repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
MisterY/gnucash-portfolio | gnucash_portfolio/securitiesaggregate.py | SecuritiesAggregate.get_stocks | def get_stocks(self, symbols: List[str]) -> List[Commodity]:
""" loads stocks by symbol """
query = (
self.query
.filter(Commodity.mnemonic.in_(symbols))
).order_by(Commodity.namespace, Commodity.mnemonic)
return query.all() | python | def get_stocks(self, symbols: List[str]) -> List[Commodity]:
""" loads stocks by symbol """
query = (
self.query
.filter(Commodity.mnemonic.in_(symbols))
).order_by(Commodity.namespace, Commodity.mnemonic)
return query.all() | [
"def",
"get_stocks",
"(",
"self",
",",
"symbols",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Commodity",
"]",
":",
"query",
"=",
"(",
"self",
".",
"query",
".",
"filter",
"(",
"Commodity",
".",
"mnemonic",
".",
"in_",
"(",
"symbols",
")",
")",
")",
".",
"order_by",
"(",
"Commodity",
".",
"namespace",
",",
"Commodity",
".",
"mnemonic",
")",
"return",
"query",
".",
"all",
"(",
")"
] | loads stocks by symbol | [
"loads",
"stocks",
"by",
"symbol"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L420-L426 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/securitiesaggregate.py | SecuritiesAggregate.get_aggregate | def get_aggregate(self, security: Commodity) -> SecurityAggregate:
""" Returns the aggregate for the entity """
assert security is not None
assert isinstance(security, Commodity)
return SecurityAggregate(self.book, security) | python | def get_aggregate(self, security: Commodity) -> SecurityAggregate:
""" Returns the aggregate for the entity """
assert security is not None
assert isinstance(security, Commodity)
return SecurityAggregate(self.book, security) | [
"def",
"get_aggregate",
"(",
"self",
",",
"security",
":",
"Commodity",
")",
"->",
"SecurityAggregate",
":",
"assert",
"security",
"is",
"not",
"None",
"assert",
"isinstance",
"(",
"security",
",",
"Commodity",
")",
"return",
"SecurityAggregate",
"(",
"self",
".",
"book",
",",
"security",
")"
] | Returns the aggregate for the entity | [
"Returns",
"the",
"aggregate",
"for",
"the",
"entity"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L428-L433 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/securitiesaggregate.py | SecuritiesAggregate.get_aggregate_for_symbol | def get_aggregate_for_symbol(self, symbol: str) -> SecurityAggregate:
""" Returns the aggregate for the security found by full symbol """
security = self.get_by_symbol(symbol)
if not security:
raise ValueError(f"Security not found in GC book: {symbol}!")
return self.get_aggregate(security) | python | def get_aggregate_for_symbol(self, symbol: str) -> SecurityAggregate:
""" Returns the aggregate for the security found by full symbol """
security = self.get_by_symbol(symbol)
if not security:
raise ValueError(f"Security not found in GC book: {symbol}!")
return self.get_aggregate(security) | [
"def",
"get_aggregate_for_symbol",
"(",
"self",
",",
"symbol",
":",
"str",
")",
"->",
"SecurityAggregate",
":",
"security",
"=",
"self",
".",
"get_by_symbol",
"(",
"symbol",
")",
"if",
"not",
"security",
":",
"raise",
"ValueError",
"(",
"f\"Security not found in GC book: {symbol}!\"",
")",
"return",
"self",
".",
"get_aggregate",
"(",
"security",
")"
] | Returns the aggregate for the security found by full symbol | [
"Returns",
"the",
"aggregate",
"for",
"the",
"security",
"found",
"by",
"full",
"symbol"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L435-L440 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/securitiesaggregate.py | SecuritiesAggregate.query | def query(self):
""" Returns the base query which filters out data for all queries. """
query = (
self.book.session.query(Commodity)
.filter(Commodity.namespace != "CURRENCY",
Commodity.namespace != "template")
)
return query | python | def query(self):
""" Returns the base query which filters out data for all queries. """
query = (
self.book.session.query(Commodity)
.filter(Commodity.namespace != "CURRENCY",
Commodity.namespace != "template")
)
return query | [
"def",
"query",
"(",
"self",
")",
":",
"query",
"=",
"(",
"self",
".",
"book",
".",
"session",
".",
"query",
"(",
"Commodity",
")",
".",
"filter",
"(",
"Commodity",
".",
"namespace",
"!=",
"\"CURRENCY\"",
",",
"Commodity",
".",
"namespace",
"!=",
"\"template\"",
")",
")",
"return",
"query"
] | Returns the base query which filters out data for all queries. | [
"Returns",
"the",
"base",
"query",
"which",
"filters",
"out",
"data",
"for",
"all",
"queries",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L443-L450 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/bookaggregate.py | BookAggregate.book | def book(self) -> Book:
""" GnuCash Book. Opens the book or creates an database, based on settings. """
if not self.__book:
# Create/open the book.
book_uri = self.settings.database_path
self.__book = Database(book_uri).open_book(
for_writing=self.__for_writing)
return self.__book | python | def book(self) -> Book:
""" GnuCash Book. Opens the book or creates an database, based on settings. """
if not self.__book:
# Create/open the book.
book_uri = self.settings.database_path
self.__book = Database(book_uri).open_book(
for_writing=self.__for_writing)
return self.__book | [
"def",
"book",
"(",
"self",
")",
"->",
"Book",
":",
"if",
"not",
"self",
".",
"__book",
":",
"# Create/open the book.",
"book_uri",
"=",
"self",
".",
"settings",
".",
"database_path",
"self",
".",
"__book",
"=",
"Database",
"(",
"book_uri",
")",
".",
"open_book",
"(",
"for_writing",
"=",
"self",
".",
"__for_writing",
")",
"return",
"self",
".",
"__book"
] | GnuCash Book. Opens the book or creates an database, based on settings. | [
"GnuCash",
"Book",
".",
"Opens",
"the",
"book",
"or",
"creates",
"an",
"database",
"based",
"on",
"settings",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/bookaggregate.py#L54-L62 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/bookaggregate.py | BookAggregate.accounts | def accounts(self) -> AccountsAggregate:
""" Returns the Accounts aggregate """
if not self.__accounts_aggregate:
self.__accounts_aggregate = AccountsAggregate(self.book)
return self.__accounts_aggregate | python | def accounts(self) -> AccountsAggregate:
""" Returns the Accounts aggregate """
if not self.__accounts_aggregate:
self.__accounts_aggregate = AccountsAggregate(self.book)
return self.__accounts_aggregate | [
"def",
"accounts",
"(",
"self",
")",
"->",
"AccountsAggregate",
":",
"if",
"not",
"self",
".",
"__accounts_aggregate",
":",
"self",
".",
"__accounts_aggregate",
"=",
"AccountsAggregate",
"(",
"self",
".",
"book",
")",
"return",
"self",
".",
"__accounts_aggregate"
] | Returns the Accounts aggregate | [
"Returns",
"the",
"Accounts",
"aggregate"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/bookaggregate.py#L83-L87 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/bookaggregate.py | BookAggregate.currencies | def currencies(self) -> CurrenciesAggregate:
""" Returns the Currencies aggregate """
if not self.__currencies_aggregate:
self.__currencies_aggregate = CurrenciesAggregate(self.book)
return self.__currencies_aggregate | python | def currencies(self) -> CurrenciesAggregate:
""" Returns the Currencies aggregate """
if not self.__currencies_aggregate:
self.__currencies_aggregate = CurrenciesAggregate(self.book)
return self.__currencies_aggregate | [
"def",
"currencies",
"(",
"self",
")",
"->",
"CurrenciesAggregate",
":",
"if",
"not",
"self",
".",
"__currencies_aggregate",
":",
"self",
".",
"__currencies_aggregate",
"=",
"CurrenciesAggregate",
"(",
"self",
".",
"book",
")",
"return",
"self",
".",
"__currencies_aggregate"
] | Returns the Currencies aggregate | [
"Returns",
"the",
"Currencies",
"aggregate"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/bookaggregate.py#L90-L94 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/bookaggregate.py | BookAggregate.securities | def securities(self):
""" Returns securities aggregate """
if not self.__securities_aggregate:
self.__securities_aggregate = SecuritiesAggregate(self.book)
return self.__securities_aggregate | python | def securities(self):
""" Returns securities aggregate """
if not self.__securities_aggregate:
self.__securities_aggregate = SecuritiesAggregate(self.book)
return self.__securities_aggregate | [
"def",
"securities",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__securities_aggregate",
":",
"self",
".",
"__securities_aggregate",
"=",
"SecuritiesAggregate",
"(",
"self",
".",
"book",
")",
"return",
"self",
".",
"__securities_aggregate"
] | Returns securities aggregate | [
"Returns",
"securities",
"aggregate"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/bookaggregate.py#L111-L115 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/bookaggregate.py | BookAggregate.get_currency_symbols | def get_currency_symbols(self) -> List[str]:
""" Returns the used currencies' symbols as an array """
result = []
currencies = self.currencies.get_book_currencies()
for cur in currencies:
result.append(cur.mnemonic)
return result | python | def get_currency_symbols(self) -> List[str]:
""" Returns the used currencies' symbols as an array """
result = []
currencies = self.currencies.get_book_currencies()
for cur in currencies:
result.append(cur.mnemonic)
return result | [
"def",
"get_currency_symbols",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"result",
"=",
"[",
"]",
"currencies",
"=",
"self",
".",
"currencies",
".",
"get_book_currencies",
"(",
")",
"for",
"cur",
"in",
"currencies",
":",
"result",
".",
"append",
"(",
"cur",
".",
"mnemonic",
")",
"return",
"result"
] | Returns the used currencies' symbols as an array | [
"Returns",
"the",
"used",
"currencies",
"symbols",
"as",
"an",
"array"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/bookaggregate.py#L139-L145 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/templates.py | load_jinja_template | def load_jinja_template(file_name):
"""
Loads the jinja2 HTML template from the given file.
Assumes that the file is in the same directory as the script.
"""
original_script_path = sys.argv[0]
#script_path = os.path.dirname(os.path.realpath(__file__))
script_dir = os.path.dirname(original_script_path)
# file_path = os.path.join(script_path, file_name)
# with open(file_path, 'r') as template_file:
# return template_file.read()
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader(script_dir))
template = env.get_template(file_name)
return template | python | def load_jinja_template(file_name):
"""
Loads the jinja2 HTML template from the given file.
Assumes that the file is in the same directory as the script.
"""
original_script_path = sys.argv[0]
#script_path = os.path.dirname(os.path.realpath(__file__))
script_dir = os.path.dirname(original_script_path)
# file_path = os.path.join(script_path, file_name)
# with open(file_path, 'r') as template_file:
# return template_file.read()
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader(script_dir))
template = env.get_template(file_name)
return template | [
"def",
"load_jinja_template",
"(",
"file_name",
")",
":",
"original_script_path",
"=",
"sys",
".",
"argv",
"[",
"0",
"]",
"#script_path = os.path.dirname(os.path.realpath(__file__))",
"script_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"original_script_path",
")",
"# file_path = os.path.join(script_path, file_name)",
"# with open(file_path, 'r') as template_file:",
"# return template_file.read()",
"from",
"jinja2",
"import",
"Environment",
",",
"FileSystemLoader",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"FileSystemLoader",
"(",
"script_dir",
")",
")",
"template",
"=",
"env",
".",
"get_template",
"(",
"file_name",
")",
"return",
"template"
] | Loads the jinja2 HTML template from the given file.
Assumes that the file is in the same directory as the script. | [
"Loads",
"the",
"jinja2",
"HTML",
"template",
"from",
"the",
"given",
"file",
".",
"Assumes",
"that",
"the",
"file",
"is",
"in",
"the",
"same",
"directory",
"as",
"the",
"script",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/templates.py#L7-L23 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/datetimeutils.py | get_days_in_month | def get_days_in_month(year: int, month: int) -> int:
""" Returns number of days in the given month.
1-based numbers as arguments. i.e. November = 11 """
month_range = calendar.monthrange(year, month)
return month_range[1] | python | def get_days_in_month(year: int, month: int) -> int:
""" Returns number of days in the given month.
1-based numbers as arguments. i.e. November = 11 """
month_range = calendar.monthrange(year, month)
return month_range[1] | [
"def",
"get_days_in_month",
"(",
"year",
":",
"int",
",",
"month",
":",
"int",
")",
"->",
"int",
":",
"month_range",
"=",
"calendar",
".",
"monthrange",
"(",
"year",
",",
"month",
")",
"return",
"month_range",
"[",
"1",
"]"
] | Returns number of days in the given month.
1-based numbers as arguments. i.e. November = 11 | [
"Returns",
"number",
"of",
"days",
"in",
"the",
"given",
"month",
".",
"1",
"-",
"based",
"numbers",
"as",
"arguments",
".",
"i",
".",
"e",
".",
"November",
"=",
"11"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/datetimeutils.py#L8-L12 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/datetimeutils.py | get_from_gnucash26_date | def get_from_gnucash26_date(date_str: str) -> date:
""" Creates a datetime from GnuCash 2.6 date string """
date_format = "%Y%m%d"
result = datetime.strptime(date_str, date_format).date()
return result | python | def get_from_gnucash26_date(date_str: str) -> date:
""" Creates a datetime from GnuCash 2.6 date string """
date_format = "%Y%m%d"
result = datetime.strptime(date_str, date_format).date()
return result | [
"def",
"get_from_gnucash26_date",
"(",
"date_str",
":",
"str",
")",
"->",
"date",
":",
"date_format",
"=",
"\"%Y%m%d\"",
"result",
"=",
"datetime",
".",
"strptime",
"(",
"date_str",
",",
"date_format",
")",
".",
"date",
"(",
")",
"return",
"result"
] | Creates a datetime from GnuCash 2.6 date string | [
"Creates",
"a",
"datetime",
"from",
"GnuCash",
"2",
".",
"6",
"date",
"string"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/datetimeutils.py#L15-L19 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/datetimeutils.py | parse_period | def parse_period(period: str):
""" parses period from date range picker. The received values are full ISO date """
period = period.split(" - ")
date_from = Datum()
if len(period[0]) == 10:
date_from.from_iso_date_string(period[0])
else:
date_from.from_iso_long_date(period[0])
date_from.start_of_day()
date_to = Datum()
if len(period[1]) == 10:
date_to.from_iso_date_string(period[1])
else:
date_to.from_iso_long_date(period[1])
date_to.end_of_day()
return date_from.value, date_to.value | python | def parse_period(period: str):
""" parses period from date range picker. The received values are full ISO date """
period = period.split(" - ")
date_from = Datum()
if len(period[0]) == 10:
date_from.from_iso_date_string(period[0])
else:
date_from.from_iso_long_date(period[0])
date_from.start_of_day()
date_to = Datum()
if len(period[1]) == 10:
date_to.from_iso_date_string(period[1])
else:
date_to.from_iso_long_date(period[1])
date_to.end_of_day()
return date_from.value, date_to.value | [
"def",
"parse_period",
"(",
"period",
":",
"str",
")",
":",
"period",
"=",
"period",
".",
"split",
"(",
"\" - \"",
")",
"date_from",
"=",
"Datum",
"(",
")",
"if",
"len",
"(",
"period",
"[",
"0",
"]",
")",
"==",
"10",
":",
"date_from",
".",
"from_iso_date_string",
"(",
"period",
"[",
"0",
"]",
")",
"else",
":",
"date_from",
".",
"from_iso_long_date",
"(",
"period",
"[",
"0",
"]",
")",
"date_from",
".",
"start_of_day",
"(",
")",
"date_to",
"=",
"Datum",
"(",
")",
"if",
"len",
"(",
"period",
"[",
"1",
"]",
")",
"==",
"10",
":",
"date_to",
".",
"from_iso_date_string",
"(",
"period",
"[",
"1",
"]",
")",
"else",
":",
"date_to",
".",
"from_iso_long_date",
"(",
"period",
"[",
"1",
"]",
")",
"date_to",
".",
"end_of_day",
"(",
")",
"return",
"date_from",
".",
"value",
",",
"date_to",
".",
"value"
] | parses period from date range picker. The received values are full ISO date | [
"parses",
"period",
"from",
"date",
"range",
"picker",
".",
"The",
"received",
"values",
"are",
"full",
"ISO",
"date"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/datetimeutils.py#L34-L52 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/datetimeutils.py | get_period | def get_period(date_from: date, date_to: date) -> str:
""" Returns the period string from the given dates """
assert isinstance(date_from, date)
assert isinstance(date_to, date)
str_from: str = date_from.isoformat()
str_to: str = date_to.isoformat()
return str_from + " - " + str_to | python | def get_period(date_from: date, date_to: date) -> str:
""" Returns the period string from the given dates """
assert isinstance(date_from, date)
assert isinstance(date_to, date)
str_from: str = date_from.isoformat()
str_to: str = date_to.isoformat()
return str_from + " - " + str_to | [
"def",
"get_period",
"(",
"date_from",
":",
"date",
",",
"date_to",
":",
"date",
")",
"->",
"str",
":",
"assert",
"isinstance",
"(",
"date_from",
",",
"date",
")",
"assert",
"isinstance",
"(",
"date_to",
",",
"date",
")",
"str_from",
":",
"str",
"=",
"date_from",
".",
"isoformat",
"(",
")",
"str_to",
":",
"str",
"=",
"date_to",
".",
"isoformat",
"(",
")",
"return",
"str_from",
"+",
"\" - \"",
"+",
"str_to"
] | Returns the period string from the given dates | [
"Returns",
"the",
"period",
"string",
"from",
"the",
"given",
"dates"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/datetimeutils.py#L60-L68 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/generic.py | load_json_file_contents | def load_json_file_contents(path: str) -> str:
""" Loads contents from a json file """
assert isinstance(path, str)
content = None
file_path = os.path.abspath(path)
content = fileutils.read_text_from_file(file_path)
json_object = json.loads(content)
content = json.dumps(json_object, sort_keys=True, indent=4)
return content | python | def load_json_file_contents(path: str) -> str:
""" Loads contents from a json file """
assert isinstance(path, str)
content = None
file_path = os.path.abspath(path)
content = fileutils.read_text_from_file(file_path)
json_object = json.loads(content)
content = json.dumps(json_object, sort_keys=True, indent=4)
return content | [
"def",
"load_json_file_contents",
"(",
"path",
":",
"str",
")",
"->",
"str",
":",
"assert",
"isinstance",
"(",
"path",
",",
"str",
")",
"content",
"=",
"None",
"file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"content",
"=",
"fileutils",
".",
"read_text_from_file",
"(",
"file_path",
")",
"json_object",
"=",
"json",
".",
"loads",
"(",
"content",
")",
"content",
"=",
"json",
".",
"dumps",
"(",
"json_object",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")",
"return",
"content"
] | Loads contents from a json file | [
"Loads",
"contents",
"from",
"a",
"json",
"file"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L16-L26 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/generic.py | validate_json | def validate_json(data: str):
""" Validate JSON by parsing string data. Returns the json dict. """
result = None
try:
result = json.loads(data)
except ValueError as error:
log(ERROR, "invalid json: %s", error)
return result | python | def validate_json(data: str):
""" Validate JSON by parsing string data. Returns the json dict. """
result = None
try:
result = json.loads(data)
except ValueError as error:
log(ERROR, "invalid json: %s", error)
return result | [
"def",
"validate_json",
"(",
"data",
":",
"str",
")",
":",
"result",
"=",
"None",
"try",
":",
"result",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"except",
"ValueError",
"as",
"error",
":",
"log",
"(",
"ERROR",
",",
"\"invalid json: %s\"",
",",
"error",
")",
"return",
"result"
] | Validate JSON by parsing string data. Returns the json dict. | [
"Validate",
"JSON",
"by",
"parsing",
"string",
"data",
".",
"Returns",
"the",
"json",
"dict",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L28-L36 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/generic.py | get_sql | def get_sql(query):
""" Returns the sql query """
sql = str(query.statement.compile(dialect=sqlite.dialect(),
compile_kwargs={"literal_binds": True}))
return sql | python | def get_sql(query):
""" Returns the sql query """
sql = str(query.statement.compile(dialect=sqlite.dialect(),
compile_kwargs={"literal_binds": True}))
return sql | [
"def",
"get_sql",
"(",
"query",
")",
":",
"sql",
"=",
"str",
"(",
"query",
".",
"statement",
".",
"compile",
"(",
"dialect",
"=",
"sqlite",
".",
"dialect",
"(",
")",
",",
"compile_kwargs",
"=",
"{",
"\"literal_binds\"",
":",
"True",
"}",
")",
")",
"return",
"sql"
] | Returns the sql query | [
"Returns",
"the",
"sql",
"query"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L43-L47 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/generic.py | save_to_temp | def save_to_temp(content, file_name=None):
"""Save the contents into a temp file."""
#output = "results.html"
temp_dir = tempfile.gettempdir()
#tempfile.TemporaryDirectory()
#tempfile.NamedTemporaryFile(mode='w+t') as f:
out_file = os.path.join(temp_dir, file_name)
#if os.path.exists(output) and os.path.isfile(output):
file = open(out_file, 'w')
file.write(content)
file.close()
#print("results saved in results.html file.")
#return output
#output = str(pathlib.Path(f.name))
return out_file | python | def save_to_temp(content, file_name=None):
"""Save the contents into a temp file."""
#output = "results.html"
temp_dir = tempfile.gettempdir()
#tempfile.TemporaryDirectory()
#tempfile.NamedTemporaryFile(mode='w+t') as f:
out_file = os.path.join(temp_dir, file_name)
#if os.path.exists(output) and os.path.isfile(output):
file = open(out_file, 'w')
file.write(content)
file.close()
#print("results saved in results.html file.")
#return output
#output = str(pathlib.Path(f.name))
return out_file | [
"def",
"save_to_temp",
"(",
"content",
",",
"file_name",
"=",
"None",
")",
":",
"#output = \"results.html\"",
"temp_dir",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"#tempfile.TemporaryDirectory()",
"#tempfile.NamedTemporaryFile(mode='w+t') as f:",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"temp_dir",
",",
"file_name",
")",
"#if os.path.exists(output) and os.path.isfile(output):",
"file",
"=",
"open",
"(",
"out_file",
",",
"'w'",
")",
"file",
".",
"write",
"(",
"content",
")",
"file",
".",
"close",
"(",
")",
"#print(\"results saved in results.html file.\")",
"#return output",
"#output = str(pathlib.Path(f.name))",
"return",
"out_file"
] | Save the contents into a temp file. | [
"Save",
"the",
"contents",
"into",
"a",
"temp",
"file",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L49-L64 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/generic.py | read_book_uri_from_console | def read_book_uri_from_console():
""" Prompts the user to enter book url in console """
db_path: str = input("Enter book_url or leave blank for the default settings value: ")
if db_path:
# sqlite
if db_path.startswith("sqlite://"):
db_path_uri = db_path
else:
# TODO: check if file exists.
db_path_uri = "file:///" + db_path
else:
cfg = settings.Settings()
db_path_uri = cfg.database_uri
return db_path_uri | python | def read_book_uri_from_console():
""" Prompts the user to enter book url in console """
db_path: str = input("Enter book_url or leave blank for the default settings value: ")
if db_path:
# sqlite
if db_path.startswith("sqlite://"):
db_path_uri = db_path
else:
# TODO: check if file exists.
db_path_uri = "file:///" + db_path
else:
cfg = settings.Settings()
db_path_uri = cfg.database_uri
return db_path_uri | [
"def",
"read_book_uri_from_console",
"(",
")",
":",
"db_path",
":",
"str",
"=",
"input",
"(",
"\"Enter book_url or leave blank for the default settings value: \"",
")",
"if",
"db_path",
":",
"# sqlite",
"if",
"db_path",
".",
"startswith",
"(",
"\"sqlite://\"",
")",
":",
"db_path_uri",
"=",
"db_path",
"else",
":",
"# TODO: check if file exists.",
"db_path_uri",
"=",
"\"file:///\"",
"+",
"db_path",
"else",
":",
"cfg",
"=",
"settings",
".",
"Settings",
"(",
")",
"db_path_uri",
"=",
"cfg",
".",
"database_uri",
"return",
"db_path_uri"
] | Prompts the user to enter book url in console | [
"Prompts",
"the",
"user",
"to",
"enter",
"book",
"url",
"in",
"console"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L66-L80 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/generic.py | run_report_from_console | def run_report_from_console(output_file_name, callback):
"""
Runs the report from the command line. Receives the book url from the console.
"""
print("The report uses a read-only access to the book.")
print("Now enter the data or ^Z to continue:")
#report_method = kwargs["report_method"]
result = callback()
#output_file_name = kwargs["output_file_name"]
output = save_to_temp(result, output_file_name)
webbrowser.open(output) | python | def run_report_from_console(output_file_name, callback):
"""
Runs the report from the command line. Receives the book url from the console.
"""
print("The report uses a read-only access to the book.")
print("Now enter the data or ^Z to continue:")
#report_method = kwargs["report_method"]
result = callback()
#output_file_name = kwargs["output_file_name"]
output = save_to_temp(result, output_file_name)
webbrowser.open(output) | [
"def",
"run_report_from_console",
"(",
"output_file_name",
",",
"callback",
")",
":",
"print",
"(",
"\"The report uses a read-only access to the book.\"",
")",
"print",
"(",
"\"Now enter the data or ^Z to continue:\"",
")",
"#report_method = kwargs[\"report_method\"]",
"result",
"=",
"callback",
"(",
")",
"#output_file_name = kwargs[\"output_file_name\"]",
"output",
"=",
"save_to_temp",
"(",
"result",
",",
"output_file_name",
")",
"webbrowser",
".",
"open",
"(",
"output",
")"
] | Runs the report from the command line. Receives the book url from the console. | [
"Runs",
"the",
"report",
"from",
"the",
"command",
"line",
".",
"Receives",
"the",
"book",
"url",
"from",
"the",
"console",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L82-L94 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/actions/symbol_dividends.py | get_dividend_sum_for_symbol | def get_dividend_sum_for_symbol(book: Book, symbol: str):
""" Calculates all income for a symbol """
svc = SecuritiesAggregate(book)
security = svc.get_by_symbol(symbol)
sec_svc = SecurityAggregate(book, security)
accounts = sec_svc.get_income_accounts()
total = Decimal(0)
for account in accounts:
# get all dividends.
income = get_dividend_sum(book, account)
total += income
return total | python | def get_dividend_sum_for_symbol(book: Book, symbol: str):
""" Calculates all income for a symbol """
svc = SecuritiesAggregate(book)
security = svc.get_by_symbol(symbol)
sec_svc = SecurityAggregate(book, security)
accounts = sec_svc.get_income_accounts()
total = Decimal(0)
for account in accounts:
# get all dividends.
income = get_dividend_sum(book, account)
total += income
return total | [
"def",
"get_dividend_sum_for_symbol",
"(",
"book",
":",
"Book",
",",
"symbol",
":",
"str",
")",
":",
"svc",
"=",
"SecuritiesAggregate",
"(",
"book",
")",
"security",
"=",
"svc",
".",
"get_by_symbol",
"(",
"symbol",
")",
"sec_svc",
"=",
"SecurityAggregate",
"(",
"book",
",",
"security",
")",
"accounts",
"=",
"sec_svc",
".",
"get_income_accounts",
"(",
")",
"total",
"=",
"Decimal",
"(",
"0",
")",
"for",
"account",
"in",
"accounts",
":",
"# get all dividends.",
"income",
"=",
"get_dividend_sum",
"(",
"book",
",",
"account",
")",
"total",
"+=",
"income",
"return",
"total"
] | Calculates all income for a symbol | [
"Calculates",
"all",
"income",
"for",
"a",
"symbol"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/actions/symbol_dividends.py#L26-L39 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/actions/import_security_prices.py | import_file | def import_file(filename):
"""
Imports the commodity prices from the given .csv file.
"""
#file_path = os.path.relpath(filename)
file_path = os.path.abspath(filename)
log(DEBUG, "Loading prices from %s", file_path)
prices = __read_prices_from_file(file_path)
with BookAggregate(for_writing=True) as svc:
svc.prices.import_prices(prices)
print("Saving book...")
svc.book.save() | python | def import_file(filename):
"""
Imports the commodity prices from the given .csv file.
"""
#file_path = os.path.relpath(filename)
file_path = os.path.abspath(filename)
log(DEBUG, "Loading prices from %s", file_path)
prices = __read_prices_from_file(file_path)
with BookAggregate(for_writing=True) as svc:
svc.prices.import_prices(prices)
print("Saving book...")
svc.book.save() | [
"def",
"import_file",
"(",
"filename",
")",
":",
"#file_path = os.path.relpath(filename)",
"file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"log",
"(",
"DEBUG",
",",
"\"Loading prices from %s\"",
",",
"file_path",
")",
"prices",
"=",
"__read_prices_from_file",
"(",
"file_path",
")",
"with",
"BookAggregate",
"(",
"for_writing",
"=",
"True",
")",
"as",
"svc",
":",
"svc",
".",
"prices",
".",
"import_prices",
"(",
"prices",
")",
"print",
"(",
"\"Saving book...\"",
")",
"svc",
".",
"book",
".",
"save",
"(",
")"
] | Imports the commodity prices from the given .csv file. | [
"Imports",
"the",
"commodity",
"prices",
"from",
"the",
"given",
".",
"csv",
"file",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/actions/import_security_prices.py#L18-L31 | train |
MisterY/gnucash-portfolio | reports/report_portfolio_value/report_portfolio_value.py | generate_report | def generate_report(book_url):
# commodity: CommodityOption(
# section="Commodity",
# sort_tag="a",
# documentation_string="This is a stock",
# default_value="VTIP"),
# commodity_list: CommodityListOption(
# section="Commodity",
# sort_tag="a",
# documentation_string="This is a stock",
# default_value="VTIP")
#):
"""
Generates an HTML report content.
"""
# Report variables
shares_no = None
avg_price = None
stock_template = templates.load_jinja_template("stock_template.html")
stock_rows = ""
with piecash.open_book(book_url, readonly=True, open_if_lock=True) as book:
# get all commodities that are not currencies.
all_stocks = portfoliovalue.get_all_stocks(book)
for stock in all_stocks:
for_date = datetime.today().date
model = portfoliovalue.get_stock_model_from(book, stock, for_date)
stock_rows += stock_template.render(model)
# Load HTML template file.
template = templates.load_jinja_template("template.html")
# Render the full report.
#return template.format(**locals())
result = template.render(**locals())
return result | python | def generate_report(book_url):
# commodity: CommodityOption(
# section="Commodity",
# sort_tag="a",
# documentation_string="This is a stock",
# default_value="VTIP"),
# commodity_list: CommodityListOption(
# section="Commodity",
# sort_tag="a",
# documentation_string="This is a stock",
# default_value="VTIP")
#):
"""
Generates an HTML report content.
"""
# Report variables
shares_no = None
avg_price = None
stock_template = templates.load_jinja_template("stock_template.html")
stock_rows = ""
with piecash.open_book(book_url, readonly=True, open_if_lock=True) as book:
# get all commodities that are not currencies.
all_stocks = portfoliovalue.get_all_stocks(book)
for stock in all_stocks:
for_date = datetime.today().date
model = portfoliovalue.get_stock_model_from(book, stock, for_date)
stock_rows += stock_template.render(model)
# Load HTML template file.
template = templates.load_jinja_template("template.html")
# Render the full report.
#return template.format(**locals())
result = template.render(**locals())
return result | [
"def",
"generate_report",
"(",
"book_url",
")",
":",
"# commodity: CommodityOption(",
"# section=\"Commodity\",",
"# sort_tag=\"a\",",
"# documentation_string=\"This is a stock\",",
"# default_value=\"VTIP\"),",
"# commodity_list: CommodityListOption(",
"# section=\"Commodity\",",
"# sort_tag=\"a\",",
"# documentation_string=\"This is a stock\",",
"# default_value=\"VTIP\")",
"#):",
"# Report variables",
"shares_no",
"=",
"None",
"avg_price",
"=",
"None",
"stock_template",
"=",
"templates",
".",
"load_jinja_template",
"(",
"\"stock_template.html\"",
")",
"stock_rows",
"=",
"\"\"",
"with",
"piecash",
".",
"open_book",
"(",
"book_url",
",",
"readonly",
"=",
"True",
",",
"open_if_lock",
"=",
"True",
")",
"as",
"book",
":",
"# get all commodities that are not currencies.",
"all_stocks",
"=",
"portfoliovalue",
".",
"get_all_stocks",
"(",
"book",
")",
"for",
"stock",
"in",
"all_stocks",
":",
"for_date",
"=",
"datetime",
".",
"today",
"(",
")",
".",
"date",
"model",
"=",
"portfoliovalue",
".",
"get_stock_model_from",
"(",
"book",
",",
"stock",
",",
"for_date",
")",
"stock_rows",
"+=",
"stock_template",
".",
"render",
"(",
"model",
")",
"# Load HTML template file.",
"template",
"=",
"templates",
".",
"load_jinja_template",
"(",
"\"template.html\"",
")",
"# Render the full report.",
"#return template.format(**locals())",
"result",
"=",
"template",
".",
"render",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"return",
"result"
] | Generates an HTML report content. | [
"Generates",
"an",
"HTML",
"report",
"content",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/reports/report_portfolio_value/report_portfolio_value.py#L23-L58 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/actions/security_analysis.py | main | def main(symbol: str):
"""
Displays the balance for the security symbol.
"""
print("Displaying the balance for", symbol)
with BookAggregate() as svc:
security = svc.book.get(Commodity, mnemonic=symbol)
#security.transactions, security.prices
sec_svc = SecurityAggregate(svc.book, security)
# Display number of shares
shares_no = sec_svc.get_quantity()
print("Quantity:", shares_no)
# Calculate average price.
avg_price = sec_svc.get_avg_price()
print("Average price:", avg_price) | python | def main(symbol: str):
"""
Displays the balance for the security symbol.
"""
print("Displaying the balance for", symbol)
with BookAggregate() as svc:
security = svc.book.get(Commodity, mnemonic=symbol)
#security.transactions, security.prices
sec_svc = SecurityAggregate(svc.book, security)
# Display number of shares
shares_no = sec_svc.get_quantity()
print("Quantity:", shares_no)
# Calculate average price.
avg_price = sec_svc.get_avg_price()
print("Average price:", avg_price) | [
"def",
"main",
"(",
"symbol",
":",
"str",
")",
":",
"print",
"(",
"\"Displaying the balance for\"",
",",
"symbol",
")",
"with",
"BookAggregate",
"(",
")",
"as",
"svc",
":",
"security",
"=",
"svc",
".",
"book",
".",
"get",
"(",
"Commodity",
",",
"mnemonic",
"=",
"symbol",
")",
"#security.transactions, security.prices",
"sec_svc",
"=",
"SecurityAggregate",
"(",
"svc",
".",
"book",
",",
"security",
")",
"# Display number of shares",
"shares_no",
"=",
"sec_svc",
".",
"get_quantity",
"(",
")",
"print",
"(",
"\"Quantity:\"",
",",
"shares_no",
")",
"# Calculate average price.",
"avg_price",
"=",
"sec_svc",
".",
"get_avg_price",
"(",
")",
"print",
"(",
"\"Average price:\"",
",",
"avg_price",
")"
] | Displays the balance for the security symbol. | [
"Displays",
"the",
"balance",
"for",
"the",
"security",
"symbol",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/actions/security_analysis.py#L12-L30 | train |
MisterY/gnucash-portfolio | examples/report_book.py | generate_report | def generate_report(book_url):
"""
Generates the report HTML.
"""
with piecash.open_book(book_url, readonly=True, open_if_lock=True) as book:
accounts = [acc.fullname for acc in book.accounts]
return f"""<html>
<body>
Hello world from python !<br>
Book : {book_url}<br>
List of accounts : {accounts}
</body>
</html>""" | python | def generate_report(book_url):
"""
Generates the report HTML.
"""
with piecash.open_book(book_url, readonly=True, open_if_lock=True) as book:
accounts = [acc.fullname for acc in book.accounts]
return f"""<html>
<body>
Hello world from python !<br>
Book : {book_url}<br>
List of accounts : {accounts}
</body>
</html>""" | [
"def",
"generate_report",
"(",
"book_url",
")",
":",
"with",
"piecash",
".",
"open_book",
"(",
"book_url",
",",
"readonly",
"=",
"True",
",",
"open_if_lock",
"=",
"True",
")",
"as",
"book",
":",
"accounts",
"=",
"[",
"acc",
".",
"fullname",
"for",
"acc",
"in",
"book",
".",
"accounts",
"]",
"return",
"f\"\"\"<html>\n <body>\n Hello world from python !<br>\n Book : {book_url}<br>\n List of accounts : {accounts}\n </body>\n </html>\"\"\""
] | Generates the report HTML. | [
"Generates",
"the",
"report",
"HTML",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/examples/report_book.py#L18-L31 | train |
MisterY/gnucash-portfolio | setup.alt.py | get_project_files | def get_project_files():
"""Retrieve a list of project files, ignoring hidden files.
:return: sorted list of project files
:rtype: :class:`list`
"""
if is_git_project():
return get_git_project_files()
project_files = []
for top, subdirs, files in os.walk('.'):
for subdir in subdirs:
if subdir.startswith('.'):
subdirs.remove(subdir)
for f in files:
if f.startswith('.'):
continue
project_files.append(os.path.join(top, f))
return project_files | python | def get_project_files():
"""Retrieve a list of project files, ignoring hidden files.
:return: sorted list of project files
:rtype: :class:`list`
"""
if is_git_project():
return get_git_project_files()
project_files = []
for top, subdirs, files in os.walk('.'):
for subdir in subdirs:
if subdir.startswith('.'):
subdirs.remove(subdir)
for f in files:
if f.startswith('.'):
continue
project_files.append(os.path.join(top, f))
return project_files | [
"def",
"get_project_files",
"(",
")",
":",
"if",
"is_git_project",
"(",
")",
":",
"return",
"get_git_project_files",
"(",
")",
"project_files",
"=",
"[",
"]",
"for",
"top",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"'.'",
")",
":",
"for",
"subdir",
"in",
"subdirs",
":",
"if",
"subdir",
".",
"startswith",
"(",
"'.'",
")",
":",
"subdirs",
".",
"remove",
"(",
"subdir",
")",
"for",
"f",
"in",
"files",
":",
"if",
"f",
".",
"startswith",
"(",
"'.'",
")",
":",
"continue",
"project_files",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"top",
",",
"f",
")",
")",
"return",
"project_files"
] | Retrieve a list of project files, ignoring hidden files.
:return: sorted list of project files
:rtype: :class:`list` | [
"Retrieve",
"a",
"list",
"of",
"project",
"files",
"ignoring",
"hidden",
"files",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/setup.alt.py#L67-L87 | train |
MisterY/gnucash-portfolio | setup.alt.py | print_success_message | def print_success_message(message):
"""Print a message indicating success in green color to STDOUT.
:param message: the message to print
:type message: :class:`str`
"""
try:
import colorama
print(colorama.Fore.GREEN + message + colorama.Fore.RESET)
except ImportError:
print(message) | python | def print_success_message(message):
"""Print a message indicating success in green color to STDOUT.
:param message: the message to print
:type message: :class:`str`
"""
try:
import colorama
print(colorama.Fore.GREEN + message + colorama.Fore.RESET)
except ImportError:
print(message) | [
"def",
"print_success_message",
"(",
"message",
")",
":",
"try",
":",
"import",
"colorama",
"print",
"(",
"colorama",
".",
"Fore",
".",
"GREEN",
"+",
"message",
"+",
"colorama",
".",
"Fore",
".",
"RESET",
")",
"except",
"ImportError",
":",
"print",
"(",
"message",
")"
] | Print a message indicating success in green color to STDOUT.
:param message: the message to print
:type message: :class:`str` | [
"Print",
"a",
"message",
"indicating",
"success",
"in",
"green",
"color",
"to",
"STDOUT",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/setup.alt.py#L125-L136 | train |
MisterY/gnucash-portfolio | setup.alt.py | print_failure_message | def print_failure_message(message):
"""Print a message indicating failure in red color to STDERR.
:param message: the message to print
:type message: :class:`str`
"""
try:
import colorama
print(colorama.Fore.RED + message + colorama.Fore.RESET,
file=sys.stderr)
except ImportError:
print(message, file=sys.stderr) | python | def print_failure_message(message):
"""Print a message indicating failure in red color to STDERR.
:param message: the message to print
:type message: :class:`str`
"""
try:
import colorama
print(colorama.Fore.RED + message + colorama.Fore.RESET,
file=sys.stderr)
except ImportError:
print(message, file=sys.stderr) | [
"def",
"print_failure_message",
"(",
"message",
")",
":",
"try",
":",
"import",
"colorama",
"print",
"(",
"colorama",
".",
"Fore",
".",
"RED",
"+",
"message",
"+",
"colorama",
".",
"Fore",
".",
"RESET",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"except",
"ImportError",
":",
"print",
"(",
"message",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | Print a message indicating failure in red color to STDERR.
:param message: the message to print
:type message: :class:`str` | [
"Print",
"a",
"message",
"indicating",
"failure",
"in",
"red",
"color",
"to",
"STDERR",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/setup.alt.py#L139-L151 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/actions/import_exchange_rates.py | main | def main():
"""
Default entry point
"""
importer = ExchangeRatesImporter()
print("####################################")
latest_rates_json = importer.get_latest_rates()
# translate into an array of PriceModels
# TODO mapper = currencyrates.FixerioModelMapper()
mapper = None
rates = mapper.map_to_model(latest_rates_json)
print("####################################")
print("importing rates into gnucash...")
# For writing, use True below.
with BookAggregate(for_writing=False) as svc:
svc.currencies.import_fx_rates(rates)
print("####################################")
print("displaying rates from gnucash...")
importer.display_gnucash_rates() | python | def main():
"""
Default entry point
"""
importer = ExchangeRatesImporter()
print("####################################")
latest_rates_json = importer.get_latest_rates()
# translate into an array of PriceModels
# TODO mapper = currencyrates.FixerioModelMapper()
mapper = None
rates = mapper.map_to_model(latest_rates_json)
print("####################################")
print("importing rates into gnucash...")
# For writing, use True below.
with BookAggregate(for_writing=False) as svc:
svc.currencies.import_fx_rates(rates)
print("####################################")
print("displaying rates from gnucash...")
importer.display_gnucash_rates() | [
"def",
"main",
"(",
")",
":",
"importer",
"=",
"ExchangeRatesImporter",
"(",
")",
"print",
"(",
"\"####################################\"",
")",
"latest_rates_json",
"=",
"importer",
".",
"get_latest_rates",
"(",
")",
"# translate into an array of PriceModels",
"# TODO mapper = currencyrates.FixerioModelMapper()",
"mapper",
"=",
"None",
"rates",
"=",
"mapper",
".",
"map_to_model",
"(",
"latest_rates_json",
")",
"print",
"(",
"\"####################################\"",
")",
"print",
"(",
"\"importing rates into gnucash...\"",
")",
"# For writing, use True below.",
"with",
"BookAggregate",
"(",
"for_writing",
"=",
"False",
")",
"as",
"svc",
":",
"svc",
".",
"currencies",
".",
"import_fx_rates",
"(",
"rates",
")",
"print",
"(",
"\"####################################\"",
")",
"print",
"(",
"\"displaying rates from gnucash...\"",
")",
"importer",
".",
"display_gnucash_rates",
"(",
")"
] | Default entry point | [
"Default",
"entry",
"point"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/actions/import_exchange_rates.py#L68-L90 | train |
MisterY/gnucash-portfolio | reports/report_asset_allocation/report_asset_allocation.py | generate_asset_allocation_report | def generate_asset_allocation_report(book_url):
"""
The otput is generated here. Separated from the generate_report function to allow executing
from the command line.
"""
model = load_asset_allocation_model(book_url)
# load display template
template = templates.load_jinja_template("report_asset_allocation.html")
# render template
result = template.render(model=model)
# **locals()
return result | python | def generate_asset_allocation_report(book_url):
"""
The otput is generated here. Separated from the generate_report function to allow executing
from the command line.
"""
model = load_asset_allocation_model(book_url)
# load display template
template = templates.load_jinja_template("report_asset_allocation.html")
# render template
result = template.render(model=model)
# **locals()
return result | [
"def",
"generate_asset_allocation_report",
"(",
"book_url",
")",
":",
"model",
"=",
"load_asset_allocation_model",
"(",
"book_url",
")",
"# load display template",
"template",
"=",
"templates",
".",
"load_jinja_template",
"(",
"\"report_asset_allocation.html\"",
")",
"# render template",
"result",
"=",
"template",
".",
"render",
"(",
"model",
"=",
"model",
")",
"# **locals()",
"return",
"result"
] | The otput is generated here. Separated from the generate_report function to allow executing
from the command line. | [
"The",
"otput",
"is",
"generated",
"here",
".",
"Separated",
"from",
"the",
"generate_report",
"function",
"to",
"allow",
"executing",
"from",
"the",
"command",
"line",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/reports/report_asset_allocation/report_asset_allocation.py#L28-L41 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/model/price_model.py | PriceModel_Csv.parse_value | def parse_value(self, value_string: str):
"""
Parses the amount string.
"""
self.value = Decimal(value_string)
return self.value | python | def parse_value(self, value_string: str):
"""
Parses the amount string.
"""
self.value = Decimal(value_string)
return self.value | [
"def",
"parse_value",
"(",
"self",
",",
"value_string",
":",
"str",
")",
":",
"self",
".",
"value",
"=",
"Decimal",
"(",
"value_string",
")",
"return",
"self",
".",
"value"
] | Parses the amount string. | [
"Parses",
"the",
"amount",
"string",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/model/price_model.py#L27-L32 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/model/price_model.py | PriceModel_Csv.parse | def parse(self, csv_row: str):
""" Parses the .csv row into own values """
self.date = self.parse_euro_date(csv_row[2])
self.symbol = csv_row[0]
self.value = self.parse_value(csv_row[1])
return self | python | def parse(self, csv_row: str):
""" Parses the .csv row into own values """
self.date = self.parse_euro_date(csv_row[2])
self.symbol = csv_row[0]
self.value = self.parse_value(csv_row[1])
return self | [
"def",
"parse",
"(",
"self",
",",
"csv_row",
":",
"str",
")",
":",
"self",
".",
"date",
"=",
"self",
".",
"parse_euro_date",
"(",
"csv_row",
"[",
"2",
"]",
")",
"self",
".",
"symbol",
"=",
"csv_row",
"[",
"0",
"]",
"self",
".",
"value",
"=",
"self",
".",
"parse_value",
"(",
"csv_row",
"[",
"1",
"]",
")",
"return",
"self"
] | Parses the .csv row into own values | [
"Parses",
"the",
".",
"csv",
"row",
"into",
"own",
"values"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/model/price_model.py#L34-L39 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountAggregate.load_cash_balances_with_children | def load_cash_balances_with_children(self, root_account_fullname: str):
""" loads data for cash balances """
assert isinstance(root_account_fullname, str)
svc = AccountsAggregate(self.book)
root_account = svc.get_by_fullname(root_account_fullname)
if not root_account:
raise ValueError("Account not found", root_account_fullname)
accounts = self.__get_all_child_accounts_as_array(root_account)
# read cash balances
model = {}
for account in accounts:
if account.commodity.namespace != "CURRENCY" or account.placeholder:
continue
# separate per currency
currency_symbol = account.commodity.mnemonic
if not currency_symbol in model:
# Add the currency branch.
currency_record = {
"name": currency_symbol,
"total": 0,
"rows": []
}
# Append to the root.
model[currency_symbol] = currency_record
else:
currency_record = model[currency_symbol]
#acct_svc = AccountAggregate(self.book, account)
balance = account.get_balance()
row = {
"name": account.name,
"fullname": account.fullname,
"currency": currency_symbol,
"balance": balance
}
currency_record["rows"].append(row)
# add to total
total = Decimal(currency_record["total"])
total += balance
currency_record["total"] = total
return model | python | def load_cash_balances_with_children(self, root_account_fullname: str):
""" loads data for cash balances """
assert isinstance(root_account_fullname, str)
svc = AccountsAggregate(self.book)
root_account = svc.get_by_fullname(root_account_fullname)
if not root_account:
raise ValueError("Account not found", root_account_fullname)
accounts = self.__get_all_child_accounts_as_array(root_account)
# read cash balances
model = {}
for account in accounts:
if account.commodity.namespace != "CURRENCY" or account.placeholder:
continue
# separate per currency
currency_symbol = account.commodity.mnemonic
if not currency_symbol in model:
# Add the currency branch.
currency_record = {
"name": currency_symbol,
"total": 0,
"rows": []
}
# Append to the root.
model[currency_symbol] = currency_record
else:
currency_record = model[currency_symbol]
#acct_svc = AccountAggregate(self.book, account)
balance = account.get_balance()
row = {
"name": account.name,
"fullname": account.fullname,
"currency": currency_symbol,
"balance": balance
}
currency_record["rows"].append(row)
# add to total
total = Decimal(currency_record["total"])
total += balance
currency_record["total"] = total
return model | [
"def",
"load_cash_balances_with_children",
"(",
"self",
",",
"root_account_fullname",
":",
"str",
")",
":",
"assert",
"isinstance",
"(",
"root_account_fullname",
",",
"str",
")",
"svc",
"=",
"AccountsAggregate",
"(",
"self",
".",
"book",
")",
"root_account",
"=",
"svc",
".",
"get_by_fullname",
"(",
"root_account_fullname",
")",
"if",
"not",
"root_account",
":",
"raise",
"ValueError",
"(",
"\"Account not found\"",
",",
"root_account_fullname",
")",
"accounts",
"=",
"self",
".",
"__get_all_child_accounts_as_array",
"(",
"root_account",
")",
"# read cash balances",
"model",
"=",
"{",
"}",
"for",
"account",
"in",
"accounts",
":",
"if",
"account",
".",
"commodity",
".",
"namespace",
"!=",
"\"CURRENCY\"",
"or",
"account",
".",
"placeholder",
":",
"continue",
"# separate per currency",
"currency_symbol",
"=",
"account",
".",
"commodity",
".",
"mnemonic",
"if",
"not",
"currency_symbol",
"in",
"model",
":",
"# Add the currency branch.",
"currency_record",
"=",
"{",
"\"name\"",
":",
"currency_symbol",
",",
"\"total\"",
":",
"0",
",",
"\"rows\"",
":",
"[",
"]",
"}",
"# Append to the root.",
"model",
"[",
"currency_symbol",
"]",
"=",
"currency_record",
"else",
":",
"currency_record",
"=",
"model",
"[",
"currency_symbol",
"]",
"#acct_svc = AccountAggregate(self.book, account)",
"balance",
"=",
"account",
".",
"get_balance",
"(",
")",
"row",
"=",
"{",
"\"name\"",
":",
"account",
".",
"name",
",",
"\"fullname\"",
":",
"account",
".",
"fullname",
",",
"\"currency\"",
":",
"currency_symbol",
",",
"\"balance\"",
":",
"balance",
"}",
"currency_record",
"[",
"\"rows\"",
"]",
".",
"append",
"(",
"row",
")",
"# add to total",
"total",
"=",
"Decimal",
"(",
"currency_record",
"[",
"\"total\"",
"]",
")",
"total",
"+=",
"balance",
"currency_record",
"[",
"\"total\"",
"]",
"=",
"total",
"return",
"model"
] | loads data for cash balances | [
"loads",
"data",
"for",
"cash",
"balances"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L56-L102 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountAggregate.get_balance | def get_balance(self):
""" Current account balance """
on_date = Datum()
on_date.today()
return self.get_balance_on(on_date.value) | python | def get_balance(self):
""" Current account balance """
on_date = Datum()
on_date.today()
return self.get_balance_on(on_date.value) | [
"def",
"get_balance",
"(",
"self",
")",
":",
"on_date",
"=",
"Datum",
"(",
")",
"on_date",
".",
"today",
"(",
")",
"return",
"self",
".",
"get_balance_on",
"(",
"on_date",
".",
"value",
")"
] | Current account balance | [
"Current",
"account",
"balance"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L129-L133 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountAggregate.get_splits_query | def get_splits_query(self):
""" Returns all the splits in the account """
query = (
self.book.session.query(Split)
.filter(Split.account == self.account)
)
return query | python | def get_splits_query(self):
""" Returns all the splits in the account """
query = (
self.book.session.query(Split)
.filter(Split.account == self.account)
)
return query | [
"def",
"get_splits_query",
"(",
"self",
")",
":",
"query",
"=",
"(",
"self",
".",
"book",
".",
"session",
".",
"query",
"(",
"Split",
")",
".",
"filter",
"(",
"Split",
".",
"account",
"==",
"self",
".",
"account",
")",
")",
"return",
"query"
] | Returns all the splits in the account | [
"Returns",
"all",
"the",
"splits",
"in",
"the",
"account"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L164-L170 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountAggregate.get_transactions | def get_transactions(self, date_from: datetime, date_to: datetime) -> List[Transaction]:
""" Returns account transactions """
assert isinstance(date_from, datetime)
assert isinstance(date_to, datetime)
# fix up the parameters as we need datetime
dt_from = Datum()
dt_from.from_datetime(date_from)
dt_from.start_of_day()
dt_to = Datum()
dt_to.from_datetime(date_to)
dt_to.end_of_day()
query = (
self.book.session.query(Transaction)
.join(Split)
.filter(Split.account_guid == self.account.guid)
.filter(Transaction.post_date >= dt_from.date, Transaction.post_date <= dt_to.date)
.order_by(Transaction.post_date)
)
return query.all() | python | def get_transactions(self, date_from: datetime, date_to: datetime) -> List[Transaction]:
""" Returns account transactions """
assert isinstance(date_from, datetime)
assert isinstance(date_to, datetime)
# fix up the parameters as we need datetime
dt_from = Datum()
dt_from.from_datetime(date_from)
dt_from.start_of_day()
dt_to = Datum()
dt_to.from_datetime(date_to)
dt_to.end_of_day()
query = (
self.book.session.query(Transaction)
.join(Split)
.filter(Split.account_guid == self.account.guid)
.filter(Transaction.post_date >= dt_from.date, Transaction.post_date <= dt_to.date)
.order_by(Transaction.post_date)
)
return query.all() | [
"def",
"get_transactions",
"(",
"self",
",",
"date_from",
":",
"datetime",
",",
"date_to",
":",
"datetime",
")",
"->",
"List",
"[",
"Transaction",
"]",
":",
"assert",
"isinstance",
"(",
"date_from",
",",
"datetime",
")",
"assert",
"isinstance",
"(",
"date_to",
",",
"datetime",
")",
"# fix up the parameters as we need datetime",
"dt_from",
"=",
"Datum",
"(",
")",
"dt_from",
".",
"from_datetime",
"(",
"date_from",
")",
"dt_from",
".",
"start_of_day",
"(",
")",
"dt_to",
"=",
"Datum",
"(",
")",
"dt_to",
".",
"from_datetime",
"(",
"date_to",
")",
"dt_to",
".",
"end_of_day",
"(",
")",
"query",
"=",
"(",
"self",
".",
"book",
".",
"session",
".",
"query",
"(",
"Transaction",
")",
".",
"join",
"(",
"Split",
")",
".",
"filter",
"(",
"Split",
".",
"account_guid",
"==",
"self",
".",
"account",
".",
"guid",
")",
".",
"filter",
"(",
"Transaction",
".",
"post_date",
">=",
"dt_from",
".",
"date",
",",
"Transaction",
".",
"post_date",
"<=",
"dt_to",
".",
"date",
")",
".",
"order_by",
"(",
"Transaction",
".",
"post_date",
")",
")",
"return",
"query",
".",
"all",
"(",
")"
] | Returns account transactions | [
"Returns",
"account",
"transactions"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L197-L217 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountAggregate.__get_all_child_accounts_as_array | def __get_all_child_accounts_as_array(self, account: Account) -> List[Account]:
""" Returns the whole tree of child accounts in a list """
result = []
# ignore placeholders ? - what if a brokerage account has cash/stocks division?
# if not account.placeholder:
# continue
result.append(account)
for child in account.children:
sub_accounts = self.__get_all_child_accounts_as_array(child)
result += sub_accounts
return result | python | def __get_all_child_accounts_as_array(self, account: Account) -> List[Account]:
""" Returns the whole tree of child accounts in a list """
result = []
# ignore placeholders ? - what if a brokerage account has cash/stocks division?
# if not account.placeholder:
# continue
result.append(account)
for child in account.children:
sub_accounts = self.__get_all_child_accounts_as_array(child)
result += sub_accounts
return result | [
"def",
"__get_all_child_accounts_as_array",
"(",
"self",
",",
"account",
":",
"Account",
")",
"->",
"List",
"[",
"Account",
"]",
":",
"result",
"=",
"[",
"]",
"# ignore placeholders ? - what if a brokerage account has cash/stocks division?",
"# if not account.placeholder:",
"# continue",
"result",
".",
"append",
"(",
"account",
")",
"for",
"child",
"in",
"account",
".",
"children",
":",
"sub_accounts",
"=",
"self",
".",
"__get_all_child_accounts_as_array",
"(",
"child",
")",
"result",
"+=",
"sub_accounts",
"return",
"result"
] | Returns the whole tree of child accounts in a list | [
"Returns",
"the",
"whole",
"tree",
"of",
"child",
"accounts",
"in",
"a",
"list"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L222-L234 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.find_by_name | def find_by_name(self, term: str, include_placeholders: bool = False) -> List[Account]:
""" Search for account by part of the name """
query = (
self.query
.filter(Account.name.like('%' + term + '%'))
.order_by(Account.name)
)
# Exclude placeholder accounts?
if not include_placeholders:
query = query.filter(Account.placeholder == 0)
# print(generic.get_sql(query))
return query.all() | python | def find_by_name(self, term: str, include_placeholders: bool = False) -> List[Account]:
""" Search for account by part of the name """
query = (
self.query
.filter(Account.name.like('%' + term + '%'))
.order_by(Account.name)
)
# Exclude placeholder accounts?
if not include_placeholders:
query = query.filter(Account.placeholder == 0)
# print(generic.get_sql(query))
return query.all() | [
"def",
"find_by_name",
"(",
"self",
",",
"term",
":",
"str",
",",
"include_placeholders",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"Account",
"]",
":",
"query",
"=",
"(",
"self",
".",
"query",
".",
"filter",
"(",
"Account",
".",
"name",
".",
"like",
"(",
"'%'",
"+",
"term",
"+",
"'%'",
")",
")",
".",
"order_by",
"(",
"Account",
".",
"name",
")",
")",
"# Exclude placeholder accounts?",
"if",
"not",
"include_placeholders",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"Account",
".",
"placeholder",
"==",
"0",
")",
"# print(generic.get_sql(query))",
"return",
"query",
".",
"all",
"(",
")"
] | Search for account by part of the name | [
"Search",
"for",
"account",
"by",
"part",
"of",
"the",
"name"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L244-L256 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_aggregate_by_id | def get_aggregate_by_id(self, account_id: str) -> AccountAggregate:
""" Returns the aggregate for the given id """
account = self.get_by_id(account_id)
return self.get_account_aggregate(account) | python | def get_aggregate_by_id(self, account_id: str) -> AccountAggregate:
""" Returns the aggregate for the given id """
account = self.get_by_id(account_id)
return self.get_account_aggregate(account) | [
"def",
"get_aggregate_by_id",
"(",
"self",
",",
"account_id",
":",
"str",
")",
"->",
"AccountAggregate",
":",
"account",
"=",
"self",
".",
"get_by_id",
"(",
"account_id",
")",
"return",
"self",
".",
"get_account_aggregate",
"(",
"account",
")"
] | Returns the aggregate for the given id | [
"Returns",
"the",
"aggregate",
"for",
"the",
"given",
"id"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L258-L261 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_by_fullname | def get_by_fullname(self, fullname: str) -> Account:
""" Loads account by full name """
# get all accounts and iterate, comparing the fullname. :S
query = (
self.book.session.query(Account)
)
# generic.get_sql()
# print(sql)
all_accounts = query.all()
for account in all_accounts:
if account.fullname == fullname:
return account
# else
return None | python | def get_by_fullname(self, fullname: str) -> Account:
""" Loads account by full name """
# get all accounts and iterate, comparing the fullname. :S
query = (
self.book.session.query(Account)
)
# generic.get_sql()
# print(sql)
all_accounts = query.all()
for account in all_accounts:
if account.fullname == fullname:
return account
# else
return None | [
"def",
"get_by_fullname",
"(",
"self",
",",
"fullname",
":",
"str",
")",
"->",
"Account",
":",
"# get all accounts and iterate, comparing the fullname. :S",
"query",
"=",
"(",
"self",
".",
"book",
".",
"session",
".",
"query",
"(",
"Account",
")",
")",
"# generic.get_sql()",
"# print(sql)",
"all_accounts",
"=",
"query",
".",
"all",
"(",
")",
"for",
"account",
"in",
"all_accounts",
":",
"if",
"account",
".",
"fullname",
"==",
"fullname",
":",
"return",
"account",
"# else",
"return",
"None"
] | Loads account by full name | [
"Loads",
"account",
"by",
"full",
"name"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L263-L276 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_account_id_by_fullname | def get_account_id_by_fullname(self, fullname: str) -> str:
""" Locates the account by fullname """
account = self.get_by_fullname(fullname)
return account.guid | python | def get_account_id_by_fullname(self, fullname: str) -> str:
""" Locates the account by fullname """
account = self.get_by_fullname(fullname)
return account.guid | [
"def",
"get_account_id_by_fullname",
"(",
"self",
",",
"fullname",
":",
"str",
")",
"->",
"str",
":",
"account",
"=",
"self",
".",
"get_by_fullname",
"(",
"fullname",
")",
"return",
"account",
".",
"guid"
] | Locates the account by fullname | [
"Locates",
"the",
"account",
"by",
"fullname"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L278-L281 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_all_children | def get_all_children(self, fullname: str) -> List[Account]:
""" Returns the whole child account tree for the account with the given full name """
# find the account by fullname
root_acct = self.get_by_fullname(fullname)
if not root_acct:
raise NameError("Account not found in book!")
acct_agg = self.get_account_aggregate(root_acct)
result = acct_agg.get_all_child_accounts_as_array()
# for child in root_acct.children:
# log(DEBUG, "found child %s", child.fullname)
return result | python | def get_all_children(self, fullname: str) -> List[Account]:
""" Returns the whole child account tree for the account with the given full name """
# find the account by fullname
root_acct = self.get_by_fullname(fullname)
if not root_acct:
raise NameError("Account not found in book!")
acct_agg = self.get_account_aggregate(root_acct)
result = acct_agg.get_all_child_accounts_as_array()
# for child in root_acct.children:
# log(DEBUG, "found child %s", child.fullname)
return result | [
"def",
"get_all_children",
"(",
"self",
",",
"fullname",
":",
"str",
")",
"->",
"List",
"[",
"Account",
"]",
":",
"# find the account by fullname",
"root_acct",
"=",
"self",
".",
"get_by_fullname",
"(",
"fullname",
")",
"if",
"not",
"root_acct",
":",
"raise",
"NameError",
"(",
"\"Account not found in book!\"",
")",
"acct_agg",
"=",
"self",
".",
"get_account_aggregate",
"(",
"root_acct",
")",
"result",
"=",
"acct_agg",
".",
"get_all_child_accounts_as_array",
"(",
")",
"# for child in root_acct.children:",
"# log(DEBUG, \"found child %s\", child.fullname)",
"return",
"result"
] | Returns the whole child account tree for the account with the given full name | [
"Returns",
"the",
"whole",
"child",
"account",
"tree",
"for",
"the",
"account",
"with",
"the",
"given",
"full",
"name"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L283-L294 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_all | def get_all(self) -> List[Account]:
""" Returns all book accounts as a list, excluding templates. """
return [account for account in self.book.accounts if account.parent.name != "Template Root"] | python | def get_all(self) -> List[Account]:
""" Returns all book accounts as a list, excluding templates. """
return [account for account in self.book.accounts if account.parent.name != "Template Root"] | [
"def",
"get_all",
"(",
"self",
")",
"->",
"List",
"[",
"Account",
"]",
":",
"return",
"[",
"account",
"for",
"account",
"in",
"self",
".",
"book",
".",
"accounts",
"if",
"account",
".",
"parent",
".",
"name",
"!=",
"\"Template Root\"",
"]"
] | Returns all book accounts as a list, excluding templates. | [
"Returns",
"all",
"book",
"accounts",
"as",
"a",
"list",
"excluding",
"templates",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L296-L298 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_favourite_accounts | def get_favourite_accounts(self) -> List[Account]:
""" Provides a list of favourite accounts """
from gnucash_portfolio.lib.settings import Settings
settings = Settings()
favourite_accts = settings.favourite_accounts
accounts = self.get_list(favourite_accts)
return accounts | python | def get_favourite_accounts(self) -> List[Account]:
""" Provides a list of favourite accounts """
from gnucash_portfolio.lib.settings import Settings
settings = Settings()
favourite_accts = settings.favourite_accounts
accounts = self.get_list(favourite_accts)
return accounts | [
"def",
"get_favourite_accounts",
"(",
"self",
")",
"->",
"List",
"[",
"Account",
"]",
":",
"from",
"gnucash_portfolio",
".",
"lib",
".",
"settings",
"import",
"Settings",
"settings",
"=",
"Settings",
"(",
")",
"favourite_accts",
"=",
"settings",
".",
"favourite_accounts",
"accounts",
"=",
"self",
".",
"get_list",
"(",
"favourite_accts",
")",
"return",
"accounts"
] | Provides a list of favourite accounts | [
"Provides",
"a",
"list",
"of",
"favourite",
"accounts"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L304-L311 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_favourite_account_aggregates | def get_favourite_account_aggregates(self) -> List[AccountAggregate]:
""" Returns the list of aggregates for favourite accounts """
accounts = self.get_favourite_accounts()
aggregates = []
for account in accounts:
aggregate = self.get_account_aggregate(account)
aggregates.append(aggregate)
return aggregates | python | def get_favourite_account_aggregates(self) -> List[AccountAggregate]:
""" Returns the list of aggregates for favourite accounts """
accounts = self.get_favourite_accounts()
aggregates = []
for account in accounts:
aggregate = self.get_account_aggregate(account)
aggregates.append(aggregate)
return aggregates | [
"def",
"get_favourite_account_aggregates",
"(",
"self",
")",
"->",
"List",
"[",
"AccountAggregate",
"]",
":",
"accounts",
"=",
"self",
".",
"get_favourite_accounts",
"(",
")",
"aggregates",
"=",
"[",
"]",
"for",
"account",
"in",
"accounts",
":",
"aggregate",
"=",
"self",
".",
"get_account_aggregate",
"(",
"account",
")",
"aggregates",
".",
"append",
"(",
"aggregate",
")",
"return",
"aggregates"
] | Returns the list of aggregates for favourite accounts | [
"Returns",
"the",
"list",
"of",
"aggregates",
"for",
"favourite",
"accounts"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L313-L321 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_by_id | def get_by_id(self, acct_id) -> Account:
""" Loads an account entity """
return self.book.get(Account, guid=acct_id) | python | def get_by_id(self, acct_id) -> Account:
""" Loads an account entity """
return self.book.get(Account, guid=acct_id) | [
"def",
"get_by_id",
"(",
"self",
",",
"acct_id",
")",
"->",
"Account",
":",
"return",
"self",
".",
"book",
".",
"get",
"(",
"Account",
",",
"guid",
"=",
"acct_id",
")"
] | Loads an account entity | [
"Loads",
"an",
"account",
"entity"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L323-L325 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_by_name | def get_by_name(self, name: str) -> List[Account]:
""" Searches accounts by name """
# return self.query.filter(Account.name == name).all()
return self.get_by_name_from(self.book.root, name) | python | def get_by_name(self, name: str) -> List[Account]:
""" Searches accounts by name """
# return self.query.filter(Account.name == name).all()
return self.get_by_name_from(self.book.root, name) | [
"def",
"get_by_name",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"List",
"[",
"Account",
"]",
":",
"# return self.query.filter(Account.name == name).all()",
"return",
"self",
".",
"get_by_name_from",
"(",
"self",
".",
"book",
".",
"root",
",",
"name",
")"
] | Searches accounts by name | [
"Searches",
"accounts",
"by",
"name"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L327-L330 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_by_name_from | def get_by_name_from(self, root: Account, name: str) -> List[Account]:
""" Searches child accounts by name, starting from the given account """
result = []
if root.name == name:
result.append(root)
for child in root.children:
child_results = self.get_by_name_from(child, name)
result += child_results
return result | python | def get_by_name_from(self, root: Account, name: str) -> List[Account]:
""" Searches child accounts by name, starting from the given account """
result = []
if root.name == name:
result.append(root)
for child in root.children:
child_results = self.get_by_name_from(child, name)
result += child_results
return result | [
"def",
"get_by_name_from",
"(",
"self",
",",
"root",
":",
"Account",
",",
"name",
":",
"str",
")",
"->",
"List",
"[",
"Account",
"]",
":",
"result",
"=",
"[",
"]",
"if",
"root",
".",
"name",
"==",
"name",
":",
"result",
".",
"append",
"(",
"root",
")",
"for",
"child",
"in",
"root",
".",
"children",
":",
"child_results",
"=",
"self",
".",
"get_by_name_from",
"(",
"child",
",",
"name",
")",
"result",
"+=",
"child_results",
"return",
"result"
] | Searches child accounts by name, starting from the given account | [
"Searches",
"child",
"accounts",
"by",
"name",
"starting",
"from",
"the",
"given",
"account"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L332-L343 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.get_list | def get_list(self, ids: List[str]) -> List[Account]:
""" Loads accounts by the ids passed as an argument """
query = (
self.query
.filter(Account.guid.in_(ids))
)
return query.all() | python | def get_list(self, ids: List[str]) -> List[Account]:
""" Loads accounts by the ids passed as an argument """
query = (
self.query
.filter(Account.guid.in_(ids))
)
return query.all() | [
"def",
"get_list",
"(",
"self",
",",
"ids",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Account",
"]",
":",
"query",
"=",
"(",
"self",
".",
"query",
".",
"filter",
"(",
"Account",
".",
"guid",
".",
"in_",
"(",
"ids",
")",
")",
")",
"return",
"query",
".",
"all",
"(",
")"
] | Loads accounts by the ids passed as an argument | [
"Loads",
"accounts",
"by",
"the",
"ids",
"passed",
"as",
"an",
"argument"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L345-L351 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.query | def query(self):
""" Main accounts query """
query = (
self.book.session.query(Account)
.join(Commodity)
.filter(Commodity.namespace != "template")
.filter(Account.type != AccountType.root.value)
)
return query | python | def query(self):
""" Main accounts query """
query = (
self.book.session.query(Account)
.join(Commodity)
.filter(Commodity.namespace != "template")
.filter(Account.type != AccountType.root.value)
)
return query | [
"def",
"query",
"(",
"self",
")",
":",
"query",
"=",
"(",
"self",
".",
"book",
".",
"session",
".",
"query",
"(",
"Account",
")",
".",
"join",
"(",
"Commodity",
")",
".",
"filter",
"(",
"Commodity",
".",
"namespace",
"!=",
"\"template\"",
")",
".",
"filter",
"(",
"Account",
".",
"type",
"!=",
"AccountType",
".",
"root",
".",
"value",
")",
")",
"return",
"query"
] | Main accounts query | [
"Main",
"accounts",
"query"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L354-L362 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | AccountsAggregate.search | def search(self, name: str = None,
acc_type: str = None):
""" Search accounts by passing parameters.
name = exact name
name_part = part of name
parent_id = id of the parent account
type = account type
"""
query = self.query
if name is not None:
query = query.filter(Account.name == name)
if acc_type is not None:
# account type is capitalized
acc_type = acc_type.upper()
query = query.filter(Account.type == acc_type)
return query.all() | python | def search(self, name: str = None,
acc_type: str = None):
""" Search accounts by passing parameters.
name = exact name
name_part = part of name
parent_id = id of the parent account
type = account type
"""
query = self.query
if name is not None:
query = query.filter(Account.name == name)
if acc_type is not None:
# account type is capitalized
acc_type = acc_type.upper()
query = query.filter(Account.type == acc_type)
return query.all() | [
"def",
"search",
"(",
"self",
",",
"name",
":",
"str",
"=",
"None",
",",
"acc_type",
":",
"str",
"=",
"None",
")",
":",
"query",
"=",
"self",
".",
"query",
"if",
"name",
"is",
"not",
"None",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"Account",
".",
"name",
"==",
"name",
")",
"if",
"acc_type",
"is",
"not",
"None",
":",
"# account type is capitalized",
"acc_type",
"=",
"acc_type",
".",
"upper",
"(",
")",
"query",
"=",
"query",
".",
"filter",
"(",
"Account",
".",
"type",
"==",
"acc_type",
")",
"return",
"query",
".",
"all",
"(",
")"
] | Search accounts by passing parameters.
name = exact name
name_part = part of name
parent_id = id of the parent account
type = account type | [
"Search",
"accounts",
"by",
"passing",
"parameters",
".",
"name",
"=",
"exact",
"name",
"name_part",
"=",
"part",
"of",
"name",
"parent_id",
"=",
"id",
"of",
"the",
"parent",
"account",
"type",
"=",
"account",
"type"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L364-L382 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/pricesaggregate.py | PricesAggregate.get_price_as_of | def get_price_as_of(self, stock: Commodity, on_date: datetime):
""" Gets the latest price on or before the given date. """
# return self.get_price_as_of_query(stock, on_date).first()
prices = PriceDbApplication()
prices.get_prices_on(on_date.date().isoformat(), stock.namespace, stock.mnemonic) | python | def get_price_as_of(self, stock: Commodity, on_date: datetime):
""" Gets the latest price on or before the given date. """
# return self.get_price_as_of_query(stock, on_date).first()
prices = PriceDbApplication()
prices.get_prices_on(on_date.date().isoformat(), stock.namespace, stock.mnemonic) | [
"def",
"get_price_as_of",
"(",
"self",
",",
"stock",
":",
"Commodity",
",",
"on_date",
":",
"datetime",
")",
":",
"# return self.get_price_as_of_query(stock, on_date).first()",
"prices",
"=",
"PriceDbApplication",
"(",
")",
"prices",
".",
"get_prices_on",
"(",
"on_date",
".",
"date",
"(",
")",
".",
"isoformat",
"(",
")",
",",
"stock",
".",
"namespace",
",",
"stock",
".",
"mnemonic",
")"
] | Gets the latest price on or before the given date. | [
"Gets",
"the",
"latest",
"price",
"on",
"or",
"before",
"the",
"given",
"date",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/pricesaggregate.py#L36-L40 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/pricesaggregate.py | PricesAggregate.import_price | def import_price(self, price: PriceModel):
""" Import individual price """
# Handle yahoo-style symbols with extension.
symbol = price.symbol
if "." in symbol:
symbol = price.symbol.split(".")[0]
stock = SecuritiesAggregate(self.book).get_by_symbol(symbol)
# get_aggregate_for_symbol
if stock is None:
logging.warning("security %s not found in book.", price.symbol)
return False
# check if there is already a price for the date
existing_prices = stock.prices.filter(Price.date == price.datetime.date()).all()
if not existing_prices:
# Create new price for the commodity (symbol).
self.__create_price_for(stock, price)
else:
logging.warning("price already exists for %s on %s",
stock.mnemonic, price.datetime.strftime("%Y-%m-%d"))
existing_price = existing_prices[0]
# update price
existing_price.value = price.value
return True | python | def import_price(self, price: PriceModel):
""" Import individual price """
# Handle yahoo-style symbols with extension.
symbol = price.symbol
if "." in symbol:
symbol = price.symbol.split(".")[0]
stock = SecuritiesAggregate(self.book).get_by_symbol(symbol)
# get_aggregate_for_symbol
if stock is None:
logging.warning("security %s not found in book.", price.symbol)
return False
# check if there is already a price for the date
existing_prices = stock.prices.filter(Price.date == price.datetime.date()).all()
if not existing_prices:
# Create new price for the commodity (symbol).
self.__create_price_for(stock, price)
else:
logging.warning("price already exists for %s on %s",
stock.mnemonic, price.datetime.strftime("%Y-%m-%d"))
existing_price = existing_prices[0]
# update price
existing_price.value = price.value
return True | [
"def",
"import_price",
"(",
"self",
",",
"price",
":",
"PriceModel",
")",
":",
"# Handle yahoo-style symbols with extension.",
"symbol",
"=",
"price",
".",
"symbol",
"if",
"\".\"",
"in",
"symbol",
":",
"symbol",
"=",
"price",
".",
"symbol",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"stock",
"=",
"SecuritiesAggregate",
"(",
"self",
".",
"book",
")",
".",
"get_by_symbol",
"(",
"symbol",
")",
"# get_aggregate_for_symbol",
"if",
"stock",
"is",
"None",
":",
"logging",
".",
"warning",
"(",
"\"security %s not found in book.\"",
",",
"price",
".",
"symbol",
")",
"return",
"False",
"# check if there is already a price for the date",
"existing_prices",
"=",
"stock",
".",
"prices",
".",
"filter",
"(",
"Price",
".",
"date",
"==",
"price",
".",
"datetime",
".",
"date",
"(",
")",
")",
".",
"all",
"(",
")",
"if",
"not",
"existing_prices",
":",
"# Create new price for the commodity (symbol).",
"self",
".",
"__create_price_for",
"(",
"stock",
",",
"price",
")",
"else",
":",
"logging",
".",
"warning",
"(",
"\"price already exists for %s on %s\"",
",",
"stock",
".",
"mnemonic",
",",
"price",
".",
"datetime",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
")",
"existing_price",
"=",
"existing_prices",
"[",
"0",
"]",
"# update price",
"existing_price",
".",
"value",
"=",
"price",
".",
"value",
"return",
"True"
] | Import individual price | [
"Import",
"individual",
"price"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/pricesaggregate.py#L55-L81 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/pricesaggregate.py | PricesAggregate.__create_price_for | def __create_price_for(self, commodity: Commodity, price: PriceModel):
""" Creates a new Price entry in the book, for the given commodity """
logging.info("Adding a new price for %s, %s, %s",
commodity.mnemonic, price.datetime.strftime("%Y-%m-%d"), price.value)
# safety check. Compare currencies.
sec_svc = SecurityAggregate(self.book, commodity)
currency = sec_svc.get_currency()
if currency != price.currency:
raise ValueError(
"Requested currency does not match the currency previously used",
currency, price.currency)
# Description of the source field values:
# https://www.gnucash.org/docs/v2.6/C/gnucash-help/tool-price.html
new_price = Price(commodity, currency, price.datetime.date(), price.value,
source="Finance::Quote")
commodity.prices.append(new_price) | python | def __create_price_for(self, commodity: Commodity, price: PriceModel):
""" Creates a new Price entry in the book, for the given commodity """
logging.info("Adding a new price for %s, %s, %s",
commodity.mnemonic, price.datetime.strftime("%Y-%m-%d"), price.value)
# safety check. Compare currencies.
sec_svc = SecurityAggregate(self.book, commodity)
currency = sec_svc.get_currency()
if currency != price.currency:
raise ValueError(
"Requested currency does not match the currency previously used",
currency, price.currency)
# Description of the source field values:
# https://www.gnucash.org/docs/v2.6/C/gnucash-help/tool-price.html
new_price = Price(commodity, currency, price.datetime.date(), price.value,
source="Finance::Quote")
commodity.prices.append(new_price) | [
"def",
"__create_price_for",
"(",
"self",
",",
"commodity",
":",
"Commodity",
",",
"price",
":",
"PriceModel",
")",
":",
"logging",
".",
"info",
"(",
"\"Adding a new price for %s, %s, %s\"",
",",
"commodity",
".",
"mnemonic",
",",
"price",
".",
"datetime",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
",",
"price",
".",
"value",
")",
"# safety check. Compare currencies.",
"sec_svc",
"=",
"SecurityAggregate",
"(",
"self",
".",
"book",
",",
"commodity",
")",
"currency",
"=",
"sec_svc",
".",
"get_currency",
"(",
")",
"if",
"currency",
"!=",
"price",
".",
"currency",
":",
"raise",
"ValueError",
"(",
"\"Requested currency does not match the currency previously used\"",
",",
"currency",
",",
"price",
".",
"currency",
")",
"# Description of the source field values:",
"# https://www.gnucash.org/docs/v2.6/C/gnucash-help/tool-price.html",
"new_price",
"=",
"Price",
"(",
"commodity",
",",
"currency",
",",
"price",
".",
"datetime",
".",
"date",
"(",
")",
",",
"price",
".",
"value",
",",
"source",
"=",
"\"Finance::Quote\"",
")",
"commodity",
".",
"prices",
".",
"append",
"(",
"new_price",
")"
] | Creates a new Price entry in the book, for the given commodity | [
"Creates",
"a",
"new",
"Price",
"entry",
"in",
"the",
"book",
"for",
"the",
"given",
"commodity"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/pricesaggregate.py#L86-L105 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/transactionaggregate.py | TransactionAggregate.get_splits_query | def get_splits_query(self):
""" Returns the query for related splits """
query = (
self.book.session.query(Split)
# .join(Transaction)
.filter(Split.transaction_guid == self.transaction.guid)
)
return query | python | def get_splits_query(self):
""" Returns the query for related splits """
query = (
self.book.session.query(Split)
# .join(Transaction)
.filter(Split.transaction_guid == self.transaction.guid)
)
return query | [
"def",
"get_splits_query",
"(",
"self",
")",
":",
"query",
"=",
"(",
"self",
".",
"book",
".",
"session",
".",
"query",
"(",
"Split",
")",
"# .join(Transaction)",
".",
"filter",
"(",
"Split",
".",
"transaction_guid",
"==",
"self",
".",
"transaction",
".",
"guid",
")",
")",
"return",
"query"
] | Returns the query for related splits | [
"Returns",
"the",
"query",
"for",
"related",
"splits"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/transactionaggregate.py#L12-L19 | train |
MisterY/gnucash-portfolio | reports/report_vanguard_prices/report_vanguard_prices.py | generate_report | def generate_report(
book_url,
fund_ids: StringOption(
section="Funds",
sort_tag="c",
documentation_string="Comma-separated list of fund ids.",
default_value="8123,8146,8148,8147")
):
"""Generates the report output"""
return render_report(book_url, fund_ids) | python | def generate_report(
book_url,
fund_ids: StringOption(
section="Funds",
sort_tag="c",
documentation_string="Comma-separated list of fund ids.",
default_value="8123,8146,8148,8147")
):
"""Generates the report output"""
return render_report(book_url, fund_ids) | [
"def",
"generate_report",
"(",
"book_url",
",",
"fund_ids",
":",
"StringOption",
"(",
"section",
"=",
"\"Funds\"",
",",
"sort_tag",
"=",
"\"c\"",
",",
"documentation_string",
"=",
"\"Comma-separated list of fund ids.\"",
",",
"default_value",
"=",
"\"8123,8146,8148,8147\"",
")",
")",
":",
"return",
"render_report",
"(",
"book_url",
",",
"fund_ids",
")"
] | Generates the report output | [
"Generates",
"the",
"report",
"output"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/reports/report_vanguard_prices/report_vanguard_prices.py#L18-L27 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/actions/search_for_account.py | searchAccount | def searchAccount(searchTerm, book):
"""Searches through account names"""
print("Search results:\n")
found = False
# search
for account in book.accounts:
# print(account.fullname)
# name
if searchTerm.lower() in account.fullname.lower():
print(account.fullname)
found = True
if not found:
print("Search term not found in account names.") | python | def searchAccount(searchTerm, book):
"""Searches through account names"""
print("Search results:\n")
found = False
# search
for account in book.accounts:
# print(account.fullname)
# name
if searchTerm.lower() in account.fullname.lower():
print(account.fullname)
found = True
if not found:
print("Search term not found in account names.") | [
"def",
"searchAccount",
"(",
"searchTerm",
",",
"book",
")",
":",
"print",
"(",
"\"Search results:\\n\"",
")",
"found",
"=",
"False",
"# search",
"for",
"account",
"in",
"book",
".",
"accounts",
":",
"# print(account.fullname)",
"# name",
"if",
"searchTerm",
".",
"lower",
"(",
")",
"in",
"account",
".",
"fullname",
".",
"lower",
"(",
")",
":",
"print",
"(",
"account",
".",
"fullname",
")",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"print",
"(",
"\"Search term not found in account names.\"",
")"
] | Searches through account names | [
"Searches",
"through",
"account",
"names"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/actions/search_for_account.py#L21-L36 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/database.py | Database.display_db_info | def display_db_info(self):
"""Displays some basic info about the GnuCash book"""
with self.open_book() as book:
default_currency = book.default_currency
print("Default currency is ", default_currency.mnemonic) | python | def display_db_info(self):
"""Displays some basic info about the GnuCash book"""
with self.open_book() as book:
default_currency = book.default_currency
print("Default currency is ", default_currency.mnemonic) | [
"def",
"display_db_info",
"(",
"self",
")",
":",
"with",
"self",
".",
"open_book",
"(",
")",
"as",
"book",
":",
"default_currency",
"=",
"book",
".",
"default_currency",
"print",
"(",
"\"Default currency is \"",
",",
"default_currency",
".",
"mnemonic",
")"
] | Displays some basic info about the GnuCash book | [
"Displays",
"some",
"basic",
"info",
"about",
"the",
"GnuCash",
"book"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/database.py#L31-L35 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/database.py | Database.open_book | def open_book(self, for_writing=False) -> piecash.Book:
"""
Opens the database. Call this using 'with'.
If database file is not found, an in-memory database will be created.
"""
filename = None
# check if the file path is already a URL.
file_url = urllib.parse.urlparse(self.filename)
if file_url.scheme == "file" or file_url.scheme == "sqlite":
filename = file_url.path[1:]
else:
filename = self.filename
if not os.path.isfile(filename):
log(WARN, "Database %s requested but not found. Creating an in-memory book.", filename)
return self.create_book()
access_type = "read/write" if for_writing else "readonly"
log(INFO, "Using %s in %s mode.", filename, access_type)
# file_path = path.relpath(self.filename)
file_path = path.abspath(filename)
if not for_writing:
book = piecash.open_book(file_path, open_if_lock=True)
else:
book = piecash.open_book(file_path, open_if_lock=True, readonly=False)
# book = create_book()
return book | python | def open_book(self, for_writing=False) -> piecash.Book:
"""
Opens the database. Call this using 'with'.
If database file is not found, an in-memory database will be created.
"""
filename = None
# check if the file path is already a URL.
file_url = urllib.parse.urlparse(self.filename)
if file_url.scheme == "file" or file_url.scheme == "sqlite":
filename = file_url.path[1:]
else:
filename = self.filename
if not os.path.isfile(filename):
log(WARN, "Database %s requested but not found. Creating an in-memory book.", filename)
return self.create_book()
access_type = "read/write" if for_writing else "readonly"
log(INFO, "Using %s in %s mode.", filename, access_type)
# file_path = path.relpath(self.filename)
file_path = path.abspath(filename)
if not for_writing:
book = piecash.open_book(file_path, open_if_lock=True)
else:
book = piecash.open_book(file_path, open_if_lock=True, readonly=False)
# book = create_book()
return book | [
"def",
"open_book",
"(",
"self",
",",
"for_writing",
"=",
"False",
")",
"->",
"piecash",
".",
"Book",
":",
"filename",
"=",
"None",
"# check if the file path is already a URL.",
"file_url",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"self",
".",
"filename",
")",
"if",
"file_url",
".",
"scheme",
"==",
"\"file\"",
"or",
"file_url",
".",
"scheme",
"==",
"\"sqlite\"",
":",
"filename",
"=",
"file_url",
".",
"path",
"[",
"1",
":",
"]",
"else",
":",
"filename",
"=",
"self",
".",
"filename",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"log",
"(",
"WARN",
",",
"\"Database %s requested but not found. Creating an in-memory book.\"",
",",
"filename",
")",
"return",
"self",
".",
"create_book",
"(",
")",
"access_type",
"=",
"\"read/write\"",
"if",
"for_writing",
"else",
"\"readonly\"",
"log",
"(",
"INFO",
",",
"\"Using %s in %s mode.\"",
",",
"filename",
",",
"access_type",
")",
"# file_path = path.relpath(self.filename)",
"file_path",
"=",
"path",
".",
"abspath",
"(",
"filename",
")",
"if",
"not",
"for_writing",
":",
"book",
"=",
"piecash",
".",
"open_book",
"(",
"file_path",
",",
"open_if_lock",
"=",
"True",
")",
"else",
":",
"book",
"=",
"piecash",
".",
"open_book",
"(",
"file_path",
",",
"open_if_lock",
"=",
"True",
",",
"readonly",
"=",
"False",
")",
"# book = create_book()",
"return",
"book"
] | Opens the database. Call this using 'with'.
If database file is not found, an in-memory database will be created. | [
"Opens",
"the",
"database",
".",
"Call",
"this",
"using",
"with",
".",
"If",
"database",
"file",
"is",
"not",
"found",
"an",
"in",
"-",
"memory",
"database",
"will",
"be",
"created",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/database.py#L37-L65 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/fileutils.py | read_text_from_file | def read_text_from_file(path: str) -> str:
""" Reads text file contents """
with open(path) as text_file:
content = text_file.read()
return content | python | def read_text_from_file(path: str) -> str:
""" Reads text file contents """
with open(path) as text_file:
content = text_file.read()
return content | [
"def",
"read_text_from_file",
"(",
"path",
":",
"str",
")",
"->",
"str",
":",
"with",
"open",
"(",
"path",
")",
"as",
"text_file",
":",
"content",
"=",
"text_file",
".",
"read",
"(",
")",
"return",
"content"
] | Reads text file contents | [
"Reads",
"text",
"file",
"contents"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/fileutils.py#L3-L8 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/fileutils.py | save_text_to_file | def save_text_to_file(content: str, path: str):
""" Saves text to file """
with open(path, mode='w') as text_file:
text_file.write(content) | python | def save_text_to_file(content: str, path: str):
""" Saves text to file """
with open(path, mode='w') as text_file:
text_file.write(content) | [
"def",
"save_text_to_file",
"(",
"content",
":",
"str",
",",
"path",
":",
"str",
")",
":",
"with",
"open",
"(",
"path",
",",
"mode",
"=",
"'w'",
")",
"as",
"text_file",
":",
"text_file",
".",
"write",
"(",
"content",
")"
] | Saves text to file | [
"Saves",
"text",
"to",
"file"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/fileutils.py#L10-L13 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/currencies.py | CurrenciesAggregate.get_amount_in_base_currency | def get_amount_in_base_currency(self, currency: str, amount: Decimal) -> Decimal:
""" Calculates the amount in base currency """
assert isinstance(amount, Decimal)
# If this is already the base currency, do nothing.
if currency == self.get_default_currency().mnemonic:
return amount
agg = self.get_currency_aggregate_by_symbol(currency)
if not agg:
raise ValueError(f"Currency not found: {currency}!")
# TODO use pricedb for the price.
rate_to_base = agg.get_latest_price()
if not rate_to_base:
raise ValueError(f"Latest price not found for {currency}!")
assert isinstance(rate_to_base.value, Decimal)
result = amount * rate_to_base.value
return result | python | def get_amount_in_base_currency(self, currency: str, amount: Decimal) -> Decimal:
""" Calculates the amount in base currency """
assert isinstance(amount, Decimal)
# If this is already the base currency, do nothing.
if currency == self.get_default_currency().mnemonic:
return amount
agg = self.get_currency_aggregate_by_symbol(currency)
if not agg:
raise ValueError(f"Currency not found: {currency}!")
# TODO use pricedb for the price.
rate_to_base = agg.get_latest_price()
if not rate_to_base:
raise ValueError(f"Latest price not found for {currency}!")
assert isinstance(rate_to_base.value, Decimal)
result = amount * rate_to_base.value
return result | [
"def",
"get_amount_in_base_currency",
"(",
"self",
",",
"currency",
":",
"str",
",",
"amount",
":",
"Decimal",
")",
"->",
"Decimal",
":",
"assert",
"isinstance",
"(",
"amount",
",",
"Decimal",
")",
"# If this is already the base currency, do nothing.",
"if",
"currency",
"==",
"self",
".",
"get_default_currency",
"(",
")",
".",
"mnemonic",
":",
"return",
"amount",
"agg",
"=",
"self",
".",
"get_currency_aggregate_by_symbol",
"(",
"currency",
")",
"if",
"not",
"agg",
":",
"raise",
"ValueError",
"(",
"f\"Currency not found: {currency}!\"",
")",
"# TODO use pricedb for the price.",
"rate_to_base",
"=",
"agg",
".",
"get_latest_price",
"(",
")",
"if",
"not",
"rate_to_base",
":",
"raise",
"ValueError",
"(",
"f\"Latest price not found for {currency}!\"",
")",
"assert",
"isinstance",
"(",
"rate_to_base",
".",
"value",
",",
"Decimal",
")",
"result",
"=",
"amount",
"*",
"rate_to_base",
".",
"value",
"return",
"result"
] | Calculates the amount in base currency | [
"Calculates",
"the",
"amount",
"in",
"base",
"currency"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/currencies.py#L70-L89 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/currencies.py | CurrenciesAggregate.get_default_currency | def get_default_currency(self) -> Commodity:
""" returns the book default currency """
result = None
if self.default_currency:
result = self.default_currency
else:
def_currency = self.__get_default_currency()
self.default_currency = def_currency
result = def_currency
return result | python | def get_default_currency(self) -> Commodity:
""" returns the book default currency """
result = None
if self.default_currency:
result = self.default_currency
else:
def_currency = self.__get_default_currency()
self.default_currency = def_currency
result = def_currency
return result | [
"def",
"get_default_currency",
"(",
"self",
")",
"->",
"Commodity",
":",
"result",
"=",
"None",
"if",
"self",
".",
"default_currency",
":",
"result",
"=",
"self",
".",
"default_currency",
"else",
":",
"def_currency",
"=",
"self",
".",
"__get_default_currency",
"(",
")",
"self",
".",
"default_currency",
"=",
"def_currency",
"result",
"=",
"def_currency",
"return",
"result"
] | returns the book default currency | [
"returns",
"the",
"book",
"default",
"currency"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/currencies.py#L91-L102 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/currencies.py | CurrenciesAggregate.get_book_currencies | def get_book_currencies(self) -> List[Commodity]:
""" Returns currencies used in the book """
query = (
self.currencies_query
.order_by(Commodity.mnemonic)
)
return query.all() | python | def get_book_currencies(self) -> List[Commodity]:
""" Returns currencies used in the book """
query = (
self.currencies_query
.order_by(Commodity.mnemonic)
)
return query.all() | [
"def",
"get_book_currencies",
"(",
"self",
")",
"->",
"List",
"[",
"Commodity",
"]",
":",
"query",
"=",
"(",
"self",
".",
"currencies_query",
".",
"order_by",
"(",
"Commodity",
".",
"mnemonic",
")",
")",
"return",
"query",
".",
"all",
"(",
")"
] | Returns currencies used in the book | [
"Returns",
"currencies",
"used",
"in",
"the",
"book"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/currencies.py#L104-L110 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/currencies.py | CurrenciesAggregate.get_currency_aggregate_by_symbol | def get_currency_aggregate_by_symbol(self, symbol: str) -> CurrencyAggregate:
""" Creates currency aggregate for the given currency symbol """
currency = self.get_by_symbol(symbol)
result = self.get_currency_aggregate(currency)
return result | python | def get_currency_aggregate_by_symbol(self, symbol: str) -> CurrencyAggregate:
""" Creates currency aggregate for the given currency symbol """
currency = self.get_by_symbol(symbol)
result = self.get_currency_aggregate(currency)
return result | [
"def",
"get_currency_aggregate_by_symbol",
"(",
"self",
",",
"symbol",
":",
"str",
")",
"->",
"CurrencyAggregate",
":",
"currency",
"=",
"self",
".",
"get_by_symbol",
"(",
"symbol",
")",
"result",
"=",
"self",
".",
"get_currency_aggregate",
"(",
"currency",
")",
"return",
"result"
] | Creates currency aggregate for the given currency symbol | [
"Creates",
"currency",
"aggregate",
"for",
"the",
"given",
"currency",
"symbol"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/currencies.py#L116-L120 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/currencies.py | CurrenciesAggregate.get_by_symbol | def get_by_symbol(self, symbol: str) -> Commodity:
""" Loads currency by symbol """
assert isinstance(symbol, str)
query = (
self.currencies_query
.filter(Commodity.mnemonic == symbol)
)
return query.one() | python | def get_by_symbol(self, symbol: str) -> Commodity:
""" Loads currency by symbol """
assert isinstance(symbol, str)
query = (
self.currencies_query
.filter(Commodity.mnemonic == symbol)
)
return query.one() | [
"def",
"get_by_symbol",
"(",
"self",
",",
"symbol",
":",
"str",
")",
"->",
"Commodity",
":",
"assert",
"isinstance",
"(",
"symbol",
",",
"str",
")",
"query",
"=",
"(",
"self",
".",
"currencies_query",
".",
"filter",
"(",
"Commodity",
".",
"mnemonic",
"==",
"symbol",
")",
")",
"return",
"query",
".",
"one",
"(",
")"
] | Loads currency by symbol | [
"Loads",
"currency",
"by",
"symbol"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/currencies.py#L122-L130 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/currencies.py | CurrenciesAggregate.import_fx_rates | def import_fx_rates(self, rates: List[PriceModel]):
""" Imports the given prices into database. Write operation! """
have_new_rates = False
base_currency = self.get_default_currency()
for rate in rates:
assert isinstance(rate, PriceModel)
currency = self.get_by_symbol(rate.symbol)
amount = rate.value
# Do not import duplicate prices.
# todo: if the price differs, update it!
# exists_query = exists(rates_query)
has_rate = currency.prices.filter(Price.date == rate.datetime.date()).first()
# has_rate = (
# self.book.session.query(Price)
# .filter(Price.date == rate.date.date())
# .filter(Price.currency == currency)
# )
if not has_rate:
log(INFO, "Creating entry for %s, %s, %s, %s",
base_currency.mnemonic, currency.mnemonic, rate.datetime.date(), amount)
# Save the price in the exchange currency, not the default.
# Invert the rate in that case.
inverted_rate = 1 / amount
inverted_rate = inverted_rate.quantize(Decimal('.00000000'))
price = Price(commodity=currency,
currency=base_currency,
date=rate.datetime.date(),
value=str(inverted_rate))
have_new_rates = True
# Save the book after the prices have been created.
if have_new_rates:
log(INFO, "Saving new prices...")
self.book.flush()
self.book.save()
else:
log(INFO, "No prices imported.") | python | def import_fx_rates(self, rates: List[PriceModel]):
""" Imports the given prices into database. Write operation! """
have_new_rates = False
base_currency = self.get_default_currency()
for rate in rates:
assert isinstance(rate, PriceModel)
currency = self.get_by_symbol(rate.symbol)
amount = rate.value
# Do not import duplicate prices.
# todo: if the price differs, update it!
# exists_query = exists(rates_query)
has_rate = currency.prices.filter(Price.date == rate.datetime.date()).first()
# has_rate = (
# self.book.session.query(Price)
# .filter(Price.date == rate.date.date())
# .filter(Price.currency == currency)
# )
if not has_rate:
log(INFO, "Creating entry for %s, %s, %s, %s",
base_currency.mnemonic, currency.mnemonic, rate.datetime.date(), amount)
# Save the price in the exchange currency, not the default.
# Invert the rate in that case.
inverted_rate = 1 / amount
inverted_rate = inverted_rate.quantize(Decimal('.00000000'))
price = Price(commodity=currency,
currency=base_currency,
date=rate.datetime.date(),
value=str(inverted_rate))
have_new_rates = True
# Save the book after the prices have been created.
if have_new_rates:
log(INFO, "Saving new prices...")
self.book.flush()
self.book.save()
else:
log(INFO, "No prices imported.") | [
"def",
"import_fx_rates",
"(",
"self",
",",
"rates",
":",
"List",
"[",
"PriceModel",
"]",
")",
":",
"have_new_rates",
"=",
"False",
"base_currency",
"=",
"self",
".",
"get_default_currency",
"(",
")",
"for",
"rate",
"in",
"rates",
":",
"assert",
"isinstance",
"(",
"rate",
",",
"PriceModel",
")",
"currency",
"=",
"self",
".",
"get_by_symbol",
"(",
"rate",
".",
"symbol",
")",
"amount",
"=",
"rate",
".",
"value",
"# Do not import duplicate prices.",
"# todo: if the price differs, update it!",
"# exists_query = exists(rates_query)",
"has_rate",
"=",
"currency",
".",
"prices",
".",
"filter",
"(",
"Price",
".",
"date",
"==",
"rate",
".",
"datetime",
".",
"date",
"(",
")",
")",
".",
"first",
"(",
")",
"# has_rate = (",
"# self.book.session.query(Price)",
"# .filter(Price.date == rate.date.date())",
"# .filter(Price.currency == currency)",
"# )",
"if",
"not",
"has_rate",
":",
"log",
"(",
"INFO",
",",
"\"Creating entry for %s, %s, %s, %s\"",
",",
"base_currency",
".",
"mnemonic",
",",
"currency",
".",
"mnemonic",
",",
"rate",
".",
"datetime",
".",
"date",
"(",
")",
",",
"amount",
")",
"# Save the price in the exchange currency, not the default.",
"# Invert the rate in that case.",
"inverted_rate",
"=",
"1",
"/",
"amount",
"inverted_rate",
"=",
"inverted_rate",
".",
"quantize",
"(",
"Decimal",
"(",
"'.00000000'",
")",
")",
"price",
"=",
"Price",
"(",
"commodity",
"=",
"currency",
",",
"currency",
"=",
"base_currency",
",",
"date",
"=",
"rate",
".",
"datetime",
".",
"date",
"(",
")",
",",
"value",
"=",
"str",
"(",
"inverted_rate",
")",
")",
"have_new_rates",
"=",
"True",
"# Save the book after the prices have been created.",
"if",
"have_new_rates",
":",
"log",
"(",
"INFO",
",",
"\"Saving new prices...\"",
")",
"self",
".",
"book",
".",
"flush",
"(",
")",
"self",
".",
"book",
".",
"save",
"(",
")",
"else",
":",
"log",
"(",
"INFO",
",",
"\"No prices imported.\"",
")"
] | Imports the given prices into database. Write operation! | [
"Imports",
"the",
"given",
"prices",
"into",
"database",
".",
"Write",
"operation!"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/currencies.py#L132-L173 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/currencies.py | CurrenciesAggregate.__get_default_currency | def __get_default_currency(self):
"""Read the default currency from GnuCash preferences"""
# If we are on Windows, read from registry.
if sys.platform == "win32":
# read from registry
def_curr = self.book["default-currency"] = self.__get_default_currency_windows()
else:
# return the currency from locale.
# todo: Read the preferences on other operating systems.
def_curr = self.book["default-currency"] = self.__get_locale_currency()
return def_curr | python | def __get_default_currency(self):
"""Read the default currency from GnuCash preferences"""
# If we are on Windows, read from registry.
if sys.platform == "win32":
# read from registry
def_curr = self.book["default-currency"] = self.__get_default_currency_windows()
else:
# return the currency from locale.
# todo: Read the preferences on other operating systems.
def_curr = self.book["default-currency"] = self.__get_locale_currency()
return def_curr | [
"def",
"__get_default_currency",
"(",
"self",
")",
":",
"# If we are on Windows, read from registry.",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"# read from registry",
"def_curr",
"=",
"self",
".",
"book",
"[",
"\"default-currency\"",
"]",
"=",
"self",
".",
"__get_default_currency_windows",
"(",
")",
"else",
":",
"# return the currency from locale.",
"# todo: Read the preferences on other operating systems.",
"def_curr",
"=",
"self",
".",
"book",
"[",
"\"default-currency\"",
"]",
"=",
"self",
".",
"__get_locale_currency",
"(",
")",
"return",
"def_curr"
] | Read the default currency from GnuCash preferences | [
"Read",
"the",
"default",
"currency",
"from",
"GnuCash",
"preferences"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/currencies.py#L178-L189 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/currencies.py | CurrenciesAggregate.__get_registry_key | def __get_registry_key(self, key):
""" Read currency from windows registry """
import winreg
root = winreg.OpenKey(
winreg.HKEY_CURRENT_USER, r'SOFTWARE\GSettings\org\gnucash\general', 0, winreg.KEY_READ)
[pathname, regtype] = (winreg.QueryValueEx(root, key))
winreg.CloseKey(root)
return pathname | python | def __get_registry_key(self, key):
""" Read currency from windows registry """
import winreg
root = winreg.OpenKey(
winreg.HKEY_CURRENT_USER, r'SOFTWARE\GSettings\org\gnucash\general', 0, winreg.KEY_READ)
[pathname, regtype] = (winreg.QueryValueEx(root, key))
winreg.CloseKey(root)
return pathname | [
"def",
"__get_registry_key",
"(",
"self",
",",
"key",
")",
":",
"import",
"winreg",
"root",
"=",
"winreg",
".",
"OpenKey",
"(",
"winreg",
".",
"HKEY_CURRENT_USER",
",",
"r'SOFTWARE\\GSettings\\org\\gnucash\\general'",
",",
"0",
",",
"winreg",
".",
"KEY_READ",
")",
"[",
"pathname",
",",
"regtype",
"]",
"=",
"(",
"winreg",
".",
"QueryValueEx",
"(",
"root",
",",
"key",
")",
")",
"winreg",
".",
"CloseKey",
"(",
"root",
")",
"return",
"pathname"
] | Read currency from windows registry | [
"Read",
"currency",
"from",
"windows",
"registry"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/currencies.py#L209-L217 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/splitsaggregate.py | SplitsAggregate.get_for_accounts | def get_for_accounts(self, accounts: List[Account]):
''' Get all splits for the given accounts '''
account_ids = [acc.guid for acc in accounts]
query = (
self.query
.filter(Split.account_guid.in_(account_ids))
)
splits = query.all()
return splits | python | def get_for_accounts(self, accounts: List[Account]):
''' Get all splits for the given accounts '''
account_ids = [acc.guid for acc in accounts]
query = (
self.query
.filter(Split.account_guid.in_(account_ids))
)
splits = query.all()
return splits | [
"def",
"get_for_accounts",
"(",
"self",
",",
"accounts",
":",
"List",
"[",
"Account",
"]",
")",
":",
"account_ids",
"=",
"[",
"acc",
".",
"guid",
"for",
"acc",
"in",
"accounts",
"]",
"query",
"=",
"(",
"self",
".",
"query",
".",
"filter",
"(",
"Split",
".",
"account_guid",
".",
"in_",
"(",
"account_ids",
")",
")",
")",
"splits",
"=",
"query",
".",
"all",
"(",
")",
"return",
"splits"
] | Get all splits for the given accounts | [
"Get",
"all",
"splits",
"for",
"the",
"given",
"accounts"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/splitsaggregate.py#L39-L47 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/reports/portfolio_value.py | __get_model_for_portfolio_value | def __get_model_for_portfolio_value(input_model: PortfolioValueInputModel
) -> PortfolioValueViewModel:
""" loads the data for portfolio value """
result = PortfolioValueViewModel()
result.filter = input_model
ref_datum = Datum()
ref_datum.from_datetime(input_model.as_of_date)
ref_date = ref_datum.end_of_day()
result.stock_rows = []
with BookAggregate() as svc:
book = svc.book
stocks_svc = svc.securities
if input_model.stock:
symbols = input_model.stock.split(",")
stocks = stocks_svc.get_stocks(symbols)
else:
stocks = stocks_svc.get_all()
for stock in stocks:
row: StockViewModel = portfoliovalue.get_stock_model_from(
book, stock, as_of_date=ref_date)
if row and row.balance > 0:
result.stock_rows.append(row)
return result | python | def __get_model_for_portfolio_value(input_model: PortfolioValueInputModel
) -> PortfolioValueViewModel:
""" loads the data for portfolio value """
result = PortfolioValueViewModel()
result.filter = input_model
ref_datum = Datum()
ref_datum.from_datetime(input_model.as_of_date)
ref_date = ref_datum.end_of_day()
result.stock_rows = []
with BookAggregate() as svc:
book = svc.book
stocks_svc = svc.securities
if input_model.stock:
symbols = input_model.stock.split(",")
stocks = stocks_svc.get_stocks(symbols)
else:
stocks = stocks_svc.get_all()
for stock in stocks:
row: StockViewModel = portfoliovalue.get_stock_model_from(
book, stock, as_of_date=ref_date)
if row and row.balance > 0:
result.stock_rows.append(row)
return result | [
"def",
"__get_model_for_portfolio_value",
"(",
"input_model",
":",
"PortfolioValueInputModel",
")",
"->",
"PortfolioValueViewModel",
":",
"result",
"=",
"PortfolioValueViewModel",
"(",
")",
"result",
".",
"filter",
"=",
"input_model",
"ref_datum",
"=",
"Datum",
"(",
")",
"ref_datum",
".",
"from_datetime",
"(",
"input_model",
".",
"as_of_date",
")",
"ref_date",
"=",
"ref_datum",
".",
"end_of_day",
"(",
")",
"result",
".",
"stock_rows",
"=",
"[",
"]",
"with",
"BookAggregate",
"(",
")",
"as",
"svc",
":",
"book",
"=",
"svc",
".",
"book",
"stocks_svc",
"=",
"svc",
".",
"securities",
"if",
"input_model",
".",
"stock",
":",
"symbols",
"=",
"input_model",
".",
"stock",
".",
"split",
"(",
"\",\"",
")",
"stocks",
"=",
"stocks_svc",
".",
"get_stocks",
"(",
"symbols",
")",
"else",
":",
"stocks",
"=",
"stocks_svc",
".",
"get_all",
"(",
")",
"for",
"stock",
"in",
"stocks",
":",
"row",
":",
"StockViewModel",
"=",
"portfoliovalue",
".",
"get_stock_model_from",
"(",
"book",
",",
"stock",
",",
"as_of_date",
"=",
"ref_date",
")",
"if",
"row",
"and",
"row",
".",
"balance",
">",
"0",
":",
"result",
".",
"stock_rows",
".",
"append",
"(",
"row",
")",
"return",
"result"
] | loads the data for portfolio value | [
"loads",
"the",
"data",
"for",
"portfolio",
"value"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/reports/portfolio_value.py#L17-L44 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/settings.py | Settings.__load_settings | def __load_settings(self):
""" Load settings from .json file """
#file_path = path.relpath(settings_file_path)
#file_path = path.abspath(settings_file_path)
file_path = self.file_path
try:
self.data = json.load(open(file_path))
except FileNotFoundError:
print("Could not load", file_path) | python | def __load_settings(self):
""" Load settings from .json file """
#file_path = path.relpath(settings_file_path)
#file_path = path.abspath(settings_file_path)
file_path = self.file_path
try:
self.data = json.load(open(file_path))
except FileNotFoundError:
print("Could not load", file_path) | [
"def",
"__load_settings",
"(",
"self",
")",
":",
"#file_path = path.relpath(settings_file_path)",
"#file_path = path.abspath(settings_file_path)",
"file_path",
"=",
"self",
".",
"file_path",
"try",
":",
"self",
".",
"data",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"file_path",
")",
")",
"except",
"FileNotFoundError",
":",
"print",
"(",
"\"Could not load\"",
",",
"file_path",
")"
] | Load settings from .json file | [
"Load",
"settings",
"from",
".",
"json",
"file"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/settings.py#L27-L36 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/settings.py | Settings.file_exists | def file_exists(self) -> bool:
""" Check if the settings file exists or not """
cfg_path = self.file_path
assert cfg_path
return path.isfile(cfg_path) | python | def file_exists(self) -> bool:
""" Check if the settings file exists or not """
cfg_path = self.file_path
assert cfg_path
return path.isfile(cfg_path) | [
"def",
"file_exists",
"(",
"self",
")",
"->",
"bool",
":",
"cfg_path",
"=",
"self",
".",
"file_path",
"assert",
"cfg_path",
"return",
"path",
".",
"isfile",
"(",
"cfg_path",
")"
] | Check if the settings file exists or not | [
"Check",
"if",
"the",
"settings",
"file",
"exists",
"or",
"not"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/settings.py#L46-L51 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/settings.py | Settings.save | def save(self):
""" Saves the settings contents """
content = self.dumps()
fileutils.save_text_to_file(content, self.file_path) | python | def save(self):
""" Saves the settings contents """
content = self.dumps()
fileutils.save_text_to_file(content, self.file_path) | [
"def",
"save",
"(",
"self",
")",
":",
"content",
"=",
"self",
".",
"dumps",
"(",
")",
"fileutils",
".",
"save_text_to_file",
"(",
"content",
",",
"self",
".",
"file_path",
")"
] | Saves the settings contents | [
"Saves",
"the",
"settings",
"contents"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/settings.py#L53-L56 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/settings.py | Settings.database_path | def database_path(self):
"""
Full database path. Includes the default location + the database filename.
"""
filename = self.database_filename
db_path = ":memory:" if filename == ":memory:" else (
path.abspath(path.join(__file__, "../..", "..", "data", filename)))
return db_path | python | def database_path(self):
"""
Full database path. Includes the default location + the database filename.
"""
filename = self.database_filename
db_path = ":memory:" if filename == ":memory:" else (
path.abspath(path.join(__file__, "../..", "..", "data", filename)))
return db_path | [
"def",
"database_path",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"database_filename",
"db_path",
"=",
"\":memory:\"",
"if",
"filename",
"==",
"\":memory:\"",
"else",
"(",
"path",
".",
"abspath",
"(",
"path",
".",
"join",
"(",
"__file__",
",",
"\"../..\"",
",",
"\"..\"",
",",
"\"data\"",
",",
"filename",
")",
")",
")",
"return",
"db_path"
] | Full database path. Includes the default location + the database filename. | [
"Full",
"database",
"path",
".",
"Includes",
"the",
"default",
"location",
"+",
"the",
"database",
"filename",
"."
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/settings.py#L67-L74 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/settings.py | Settings.file_path | def file_path(self) -> str:
""" Settings file absolute path"""
user_dir = self.__get_user_path()
file_path = path.abspath(path.join(user_dir, self.FILENAME))
return file_path | python | def file_path(self) -> str:
""" Settings file absolute path"""
user_dir = self.__get_user_path()
file_path = path.abspath(path.join(user_dir, self.FILENAME))
return file_path | [
"def",
"file_path",
"(",
"self",
")",
"->",
"str",
":",
"user_dir",
"=",
"self",
".",
"__get_user_path",
"(",
")",
"file_path",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"join",
"(",
"user_dir",
",",
"self",
".",
"FILENAME",
")",
")",
"return",
"file_path"
] | Settings file absolute path | [
"Settings",
"file",
"absolute",
"path"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/settings.py#L89-L93 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/settings.py | Settings.dumps | def dumps(self) -> str:
""" Dumps the json content as a string """
return json.dumps(self.data, sort_keys=True, indent=4) | python | def dumps(self) -> str:
""" Dumps the json content as a string """
return json.dumps(self.data, sort_keys=True, indent=4) | [
"def",
"dumps",
"(",
"self",
")",
"->",
"str",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"data",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")"
] | Dumps the json content as a string | [
"Dumps",
"the",
"json",
"content",
"as",
"a",
"string"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/settings.py#L95-L97 | train |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/settings.py | Settings.__copy_template | def __copy_template(self):
""" Copy the settings template into the user's directory """
import shutil
template_filename = "settings.json.template"
template_path = path.abspath(
path.join(__file__, "..", "..", "config", template_filename))
settings_path = self.file_path
shutil.copyfile(template_path, settings_path)
self.__ensure_file_exists() | python | def __copy_template(self):
""" Copy the settings template into the user's directory """
import shutil
template_filename = "settings.json.template"
template_path = path.abspath(
path.join(__file__, "..", "..", "config", template_filename))
settings_path = self.file_path
shutil.copyfile(template_path, settings_path)
self.__ensure_file_exists() | [
"def",
"__copy_template",
"(",
"self",
")",
":",
"import",
"shutil",
"template_filename",
"=",
"\"settings.json.template\"",
"template_path",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"join",
"(",
"__file__",
",",
"\"..\"",
",",
"\"..\"",
",",
"\"config\"",
",",
"template_filename",
")",
")",
"settings_path",
"=",
"self",
".",
"file_path",
"shutil",
".",
"copyfile",
"(",
"template_path",
",",
"settings_path",
")",
"self",
".",
"__ensure_file_exists",
"(",
")"
] | Copy the settings template into the user's directory | [
"Copy",
"the",
"settings",
"template",
"into",
"the",
"user",
"s",
"directory"
] | bfaad8345a5479d1cd111acee1939e25c2a638c2 | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/settings.py#L117-L127 | train |
alephdata/memorious | memorious/logic/check.py | ContextCheck.is_not_empty | def is_not_empty(self, value, strict=False):
"""if value is not empty"""
value = stringify(value)
if value is not None:
return
self.shout('Value %r is empty', strict, value) | python | def is_not_empty(self, value, strict=False):
"""if value is not empty"""
value = stringify(value)
if value is not None:
return
self.shout('Value %r is empty', strict, value) | [
"def",
"is_not_empty",
"(",
"self",
",",
"value",
",",
"strict",
"=",
"False",
")",
":",
"value",
"=",
"stringify",
"(",
"value",
")",
"if",
"value",
"is",
"not",
"None",
":",
"return",
"self",
".",
"shout",
"(",
"'Value %r is empty'",
",",
"strict",
",",
"value",
")"
] | if value is not empty | [
"if",
"value",
"is",
"not",
"empty"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/check.py#L18-L23 | train |
alephdata/memorious | memorious/logic/check.py | ContextCheck.is_numeric | def is_numeric(self, value, strict=False):
"""if value is numeric"""
value = stringify(value)
if value is not None:
if value.isnumeric():
return
self.shout('value %r is not numeric', strict, value) | python | def is_numeric(self, value, strict=False):
"""if value is numeric"""
value = stringify(value)
if value is not None:
if value.isnumeric():
return
self.shout('value %r is not numeric', strict, value) | [
"def",
"is_numeric",
"(",
"self",
",",
"value",
",",
"strict",
"=",
"False",
")",
":",
"value",
"=",
"stringify",
"(",
"value",
")",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"value",
".",
"isnumeric",
"(",
")",
":",
"return",
"self",
".",
"shout",
"(",
"'value %r is not numeric'",
",",
"strict",
",",
"value",
")"
] | if value is numeric | [
"if",
"value",
"is",
"numeric"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/check.py#L25-L31 | train |
alephdata/memorious | memorious/logic/check.py | ContextCheck.is_integer | def is_integer(self, value, strict=False):
"""if value is an integer"""
if value is not None:
if isinstance(value, numbers.Number):
return
value = stringify(value)
if value is not None and value.isnumeric():
return
self.shout('value %r is not an integer', strict, value) | python | def is_integer(self, value, strict=False):
"""if value is an integer"""
if value is not None:
if isinstance(value, numbers.Number):
return
value = stringify(value)
if value is not None and value.isnumeric():
return
self.shout('value %r is not an integer', strict, value) | [
"def",
"is_integer",
"(",
"self",
",",
"value",
",",
"strict",
"=",
"False",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Number",
")",
":",
"return",
"value",
"=",
"stringify",
"(",
"value",
")",
"if",
"value",
"is",
"not",
"None",
"and",
"value",
".",
"isnumeric",
"(",
")",
":",
"return",
"self",
".",
"shout",
"(",
"'value %r is not an integer'",
",",
"strict",
",",
"value",
")"
] | if value is an integer | [
"if",
"value",
"is",
"an",
"integer"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/check.py#L33-L41 | train |
alephdata/memorious | memorious/logic/check.py | ContextCheck.match_date | def match_date(self, value, strict=False):
"""if value is a date"""
value = stringify(value)
try:
parse(value)
except Exception:
self.shout('Value %r is not a valid date', strict, value) | python | def match_date(self, value, strict=False):
"""if value is a date"""
value = stringify(value)
try:
parse(value)
except Exception:
self.shout('Value %r is not a valid date', strict, value) | [
"def",
"match_date",
"(",
"self",
",",
"value",
",",
"strict",
"=",
"False",
")",
":",
"value",
"=",
"stringify",
"(",
"value",
")",
"try",
":",
"parse",
"(",
"value",
")",
"except",
"Exception",
":",
"self",
".",
"shout",
"(",
"'Value %r is not a valid date'",
",",
"strict",
",",
"value",
")"
] | if value is a date | [
"if",
"value",
"is",
"a",
"date"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/check.py#L43-L49 | train |
alephdata/memorious | memorious/logic/check.py | ContextCheck.match_regexp | def match_regexp(self, value, q, strict=False):
"""if value matches a regexp q"""
value = stringify(value)
mr = re.compile(q)
if value is not None:
if mr.match(value):
return
self.shout('%r not matching the regexp %r', strict, value, q) | python | def match_regexp(self, value, q, strict=False):
"""if value matches a regexp q"""
value = stringify(value)
mr = re.compile(q)
if value is not None:
if mr.match(value):
return
self.shout('%r not matching the regexp %r', strict, value, q) | [
"def",
"match_regexp",
"(",
"self",
",",
"value",
",",
"q",
",",
"strict",
"=",
"False",
")",
":",
"value",
"=",
"stringify",
"(",
"value",
")",
"mr",
"=",
"re",
".",
"compile",
"(",
"q",
")",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"mr",
".",
"match",
"(",
"value",
")",
":",
"return",
"self",
".",
"shout",
"(",
"'%r not matching the regexp %r'",
",",
"strict",
",",
"value",
",",
"q",
")"
] | if value matches a regexp q | [
"if",
"value",
"matches",
"a",
"regexp",
"q"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/check.py#L51-L58 | train |
alephdata/memorious | memorious/logic/check.py | ContextCheck.has_length | def has_length(self, value, q, strict=False):
"""if value has a length of q"""
value = stringify(value)
if value is not None:
if len(value) == q:
return
self.shout('Value %r not matching length %r', strict, value, q) | python | def has_length(self, value, q, strict=False):
"""if value has a length of q"""
value = stringify(value)
if value is not None:
if len(value) == q:
return
self.shout('Value %r not matching length %r', strict, value, q) | [
"def",
"has_length",
"(",
"self",
",",
"value",
",",
"q",
",",
"strict",
"=",
"False",
")",
":",
"value",
"=",
"stringify",
"(",
"value",
")",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"value",
")",
"==",
"q",
":",
"return",
"self",
".",
"shout",
"(",
"'Value %r not matching length %r'",
",",
"strict",
",",
"value",
",",
"q",
")"
] | if value has a length of q | [
"if",
"value",
"has",
"a",
"length",
"of",
"q"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/check.py#L60-L66 | train |
alephdata/memorious | memorious/logic/check.py | ContextCheck.must_contain | def must_contain(self, value, q, strict=False):
"""if value must contain q"""
if value is not None:
if value.find(q) != -1:
return
self.shout('Value %r does not contain %r', strict, value, q) | python | def must_contain(self, value, q, strict=False):
"""if value must contain q"""
if value is not None:
if value.find(q) != -1:
return
self.shout('Value %r does not contain %r', strict, value, q) | [
"def",
"must_contain",
"(",
"self",
",",
"value",
",",
"q",
",",
"strict",
"=",
"False",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"value",
".",
"find",
"(",
"q",
")",
"!=",
"-",
"1",
":",
"return",
"self",
".",
"shout",
"(",
"'Value %r does not contain %r'",
",",
"strict",
",",
"value",
",",
"q",
")"
] | if value must contain q | [
"if",
"value",
"must",
"contain",
"q"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/check.py#L68-L73 | train |
alephdata/memorious | memorious/operations/extract.py | extract | def extract(context, data):
"""Extract a compressed file"""
with context.http.rehash(data) as result:
file_path = result.file_path
content_type = result.content_type
extract_dir = random_filename(context.work_path)
if content_type in ZIP_MIME_TYPES:
extracted_files = extract_zip(file_path, extract_dir)
elif content_type in TAR_MIME_TYPES:
extracted_files = extract_tar(file_path, extract_dir, context)
elif content_type in SEVENZIP_MIME_TYPES:
extracted_files = extract_7zip(file_path, extract_dir, context)
else:
context.log.warning(
"Unsupported archive content type: %s", content_type
)
return
extracted_content_hashes = {}
for path in extracted_files:
relative_path = os.path.relpath(path, extract_dir)
content_hash = context.store_file(path)
extracted_content_hashes[relative_path] = content_hash
data['content_hash'] = content_hash
data['file_name'] = relative_path
context.emit(data=data.copy()) | python | def extract(context, data):
"""Extract a compressed file"""
with context.http.rehash(data) as result:
file_path = result.file_path
content_type = result.content_type
extract_dir = random_filename(context.work_path)
if content_type in ZIP_MIME_TYPES:
extracted_files = extract_zip(file_path, extract_dir)
elif content_type in TAR_MIME_TYPES:
extracted_files = extract_tar(file_path, extract_dir, context)
elif content_type in SEVENZIP_MIME_TYPES:
extracted_files = extract_7zip(file_path, extract_dir, context)
else:
context.log.warning(
"Unsupported archive content type: %s", content_type
)
return
extracted_content_hashes = {}
for path in extracted_files:
relative_path = os.path.relpath(path, extract_dir)
content_hash = context.store_file(path)
extracted_content_hashes[relative_path] = content_hash
data['content_hash'] = content_hash
data['file_name'] = relative_path
context.emit(data=data.copy()) | [
"def",
"extract",
"(",
"context",
",",
"data",
")",
":",
"with",
"context",
".",
"http",
".",
"rehash",
"(",
"data",
")",
"as",
"result",
":",
"file_path",
"=",
"result",
".",
"file_path",
"content_type",
"=",
"result",
".",
"content_type",
"extract_dir",
"=",
"random_filename",
"(",
"context",
".",
"work_path",
")",
"if",
"content_type",
"in",
"ZIP_MIME_TYPES",
":",
"extracted_files",
"=",
"extract_zip",
"(",
"file_path",
",",
"extract_dir",
")",
"elif",
"content_type",
"in",
"TAR_MIME_TYPES",
":",
"extracted_files",
"=",
"extract_tar",
"(",
"file_path",
",",
"extract_dir",
",",
"context",
")",
"elif",
"content_type",
"in",
"SEVENZIP_MIME_TYPES",
":",
"extracted_files",
"=",
"extract_7zip",
"(",
"file_path",
",",
"extract_dir",
",",
"context",
")",
"else",
":",
"context",
".",
"log",
".",
"warning",
"(",
"\"Unsupported archive content type: %s\"",
",",
"content_type",
")",
"return",
"extracted_content_hashes",
"=",
"{",
"}",
"for",
"path",
"in",
"extracted_files",
":",
"relative_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"extract_dir",
")",
"content_hash",
"=",
"context",
".",
"store_file",
"(",
"path",
")",
"extracted_content_hashes",
"[",
"relative_path",
"]",
"=",
"content_hash",
"data",
"[",
"'content_hash'",
"]",
"=",
"content_hash",
"data",
"[",
"'file_name'",
"]",
"=",
"relative_path",
"context",
".",
"emit",
"(",
"data",
"=",
"data",
".",
"copy",
"(",
")",
")"
] | Extract a compressed file | [
"Extract",
"a",
"compressed",
"file"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/extract.py#L78-L102 | train |
alephdata/memorious | memorious/model/queue.py | Queue.size | def size(cls, crawler):
"""Total operations pending for this crawler"""
key = make_key('queue_pending', crawler)
return unpack_int(conn.get(key)) | python | def size(cls, crawler):
"""Total operations pending for this crawler"""
key = make_key('queue_pending', crawler)
return unpack_int(conn.get(key)) | [
"def",
"size",
"(",
"cls",
",",
"crawler",
")",
":",
"key",
"=",
"make_key",
"(",
"'queue_pending'",
",",
"crawler",
")",
"return",
"unpack_int",
"(",
"conn",
".",
"get",
"(",
"key",
")",
")"
] | Total operations pending for this crawler | [
"Total",
"operations",
"pending",
"for",
"this",
"crawler"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/model/queue.py#L71-L74 | train |
alephdata/memorious | memorious/helpers/ocr.py | read_word | def read_word(image, whitelist=None, chars=None, spaces=False):
""" OCR a single word from an image. Useful for captchas.
Image should be pre-processed to remove noise etc. """
from tesserocr import PyTessBaseAPI
api = PyTessBaseAPI()
api.SetPageSegMode(8)
if whitelist is not None:
api.SetVariable("tessedit_char_whitelist", whitelist)
api.SetImage(image)
api.Recognize()
guess = api.GetUTF8Text()
if not spaces:
guess = ''.join([c for c in guess if c != " "])
guess = guess.strip()
if chars is not None and len(guess) != chars:
return guess, None
return guess, api.MeanTextConf() | python | def read_word(image, whitelist=None, chars=None, spaces=False):
""" OCR a single word from an image. Useful for captchas.
Image should be pre-processed to remove noise etc. """
from tesserocr import PyTessBaseAPI
api = PyTessBaseAPI()
api.SetPageSegMode(8)
if whitelist is not None:
api.SetVariable("tessedit_char_whitelist", whitelist)
api.SetImage(image)
api.Recognize()
guess = api.GetUTF8Text()
if not spaces:
guess = ''.join([c for c in guess if c != " "])
guess = guess.strip()
if chars is not None and len(guess) != chars:
return guess, None
return guess, api.MeanTextConf() | [
"def",
"read_word",
"(",
"image",
",",
"whitelist",
"=",
"None",
",",
"chars",
"=",
"None",
",",
"spaces",
"=",
"False",
")",
":",
"from",
"tesserocr",
"import",
"PyTessBaseAPI",
"api",
"=",
"PyTessBaseAPI",
"(",
")",
"api",
".",
"SetPageSegMode",
"(",
"8",
")",
"if",
"whitelist",
"is",
"not",
"None",
":",
"api",
".",
"SetVariable",
"(",
"\"tessedit_char_whitelist\"",
",",
"whitelist",
")",
"api",
".",
"SetImage",
"(",
"image",
")",
"api",
".",
"Recognize",
"(",
")",
"guess",
"=",
"api",
".",
"GetUTF8Text",
"(",
")",
"if",
"not",
"spaces",
":",
"guess",
"=",
"''",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"guess",
"if",
"c",
"!=",
"\" \"",
"]",
")",
"guess",
"=",
"guess",
".",
"strip",
"(",
")",
"if",
"chars",
"is",
"not",
"None",
"and",
"len",
"(",
"guess",
")",
"!=",
"chars",
":",
"return",
"guess",
",",
"None",
"return",
"guess",
",",
"api",
".",
"MeanTextConf",
"(",
")"
] | OCR a single word from an image. Useful for captchas.
Image should be pre-processed to remove noise etc. | [
"OCR",
"a",
"single",
"word",
"from",
"an",
"image",
".",
"Useful",
"for",
"captchas",
".",
"Image",
"should",
"be",
"pre",
"-",
"processed",
"to",
"remove",
"noise",
"etc",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/helpers/ocr.py#L3-L22 | train |
alephdata/memorious | memorious/helpers/ocr.py | read_char | def read_char(image, whitelist=None):
""" OCR a single character from an image. Useful for captchas."""
from tesserocr import PyTessBaseAPI
api = PyTessBaseAPI()
api.SetPageSegMode(10)
if whitelist is not None:
api.SetVariable("tessedit_char_whitelist", whitelist)
api.SetImage(image)
api.Recognize()
return api.GetUTF8Text().strip() | python | def read_char(image, whitelist=None):
""" OCR a single character from an image. Useful for captchas."""
from tesserocr import PyTessBaseAPI
api = PyTessBaseAPI()
api.SetPageSegMode(10)
if whitelist is not None:
api.SetVariable("tessedit_char_whitelist", whitelist)
api.SetImage(image)
api.Recognize()
return api.GetUTF8Text().strip() | [
"def",
"read_char",
"(",
"image",
",",
"whitelist",
"=",
"None",
")",
":",
"from",
"tesserocr",
"import",
"PyTessBaseAPI",
"api",
"=",
"PyTessBaseAPI",
"(",
")",
"api",
".",
"SetPageSegMode",
"(",
"10",
")",
"if",
"whitelist",
"is",
"not",
"None",
":",
"api",
".",
"SetVariable",
"(",
"\"tessedit_char_whitelist\"",
",",
"whitelist",
")",
"api",
".",
"SetImage",
"(",
"image",
")",
"api",
".",
"Recognize",
"(",
")",
"return",
"api",
".",
"GetUTF8Text",
"(",
")",
".",
"strip",
"(",
")"
] | OCR a single character from an image. Useful for captchas. | [
"OCR",
"a",
"single",
"character",
"from",
"an",
"image",
".",
"Useful",
"for",
"captchas",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/helpers/ocr.py#L25-L34 | train |
alephdata/memorious | memorious/logic/context.py | Context.get | def get(self, name, default=None):
"""Get a configuration value and expand environment variables."""
value = self.params.get(name, default)
if isinstance(value, str):
value = os.path.expandvars(value)
return value | python | def get(self, name, default=None):
"""Get a configuration value and expand environment variables."""
value = self.params.get(name, default)
if isinstance(value, str):
value = os.path.expandvars(value)
return value | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"params",
".",
"get",
"(",
"name",
",",
"default",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"value",
")",
"return",
"value"
] | Get a configuration value and expand environment variables. | [
"Get",
"a",
"configuration",
"value",
"and",
"expand",
"environment",
"variables",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/context.py#L34-L39 | train |
alephdata/memorious | memorious/logic/context.py | Context.emit | def emit(self, rule='pass', stage=None, data={}, delay=None,
optional=False):
"""Invoke the next stage, either based on a handling rule, or by calling
the `pass` rule by default."""
if stage is None:
stage = self.stage.handlers.get(rule)
if optional and stage is None:
return
if stage is None or stage not in self.crawler.stages:
self.log.info("No next stage: %s (%s)" % (stage, rule))
return
state = self.dump_state()
delay = delay or self.crawler.delay
Queue.queue(stage, state, data, delay) | python | def emit(self, rule='pass', stage=None, data={}, delay=None,
optional=False):
"""Invoke the next stage, either based on a handling rule, or by calling
the `pass` rule by default."""
if stage is None:
stage = self.stage.handlers.get(rule)
if optional and stage is None:
return
if stage is None or stage not in self.crawler.stages:
self.log.info("No next stage: %s (%s)" % (stage, rule))
return
state = self.dump_state()
delay = delay or self.crawler.delay
Queue.queue(stage, state, data, delay) | [
"def",
"emit",
"(",
"self",
",",
"rule",
"=",
"'pass'",
",",
"stage",
"=",
"None",
",",
"data",
"=",
"{",
"}",
",",
"delay",
"=",
"None",
",",
"optional",
"=",
"False",
")",
":",
"if",
"stage",
"is",
"None",
":",
"stage",
"=",
"self",
".",
"stage",
".",
"handlers",
".",
"get",
"(",
"rule",
")",
"if",
"optional",
"and",
"stage",
"is",
"None",
":",
"return",
"if",
"stage",
"is",
"None",
"or",
"stage",
"not",
"in",
"self",
".",
"crawler",
".",
"stages",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"No next stage: %s (%s)\"",
"%",
"(",
"stage",
",",
"rule",
")",
")",
"return",
"state",
"=",
"self",
".",
"dump_state",
"(",
")",
"delay",
"=",
"delay",
"or",
"self",
".",
"crawler",
".",
"delay",
"Queue",
".",
"queue",
"(",
"stage",
",",
"state",
",",
"data",
",",
"delay",
")"
] | Invoke the next stage, either based on a handling rule, or by calling
the `pass` rule by default. | [
"Invoke",
"the",
"next",
"stage",
"either",
"based",
"on",
"a",
"handling",
"rule",
"or",
"by",
"calling",
"the",
"pass",
"rule",
"by",
"default",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/context.py#L41-L54 | train |
alephdata/memorious | memorious/logic/context.py | Context.recurse | def recurse(self, data={}, delay=None):
"""Have a stage invoke itself with a modified set of arguments."""
return self.emit(stage=self.stage.name,
data=data,
delay=delay) | python | def recurse(self, data={}, delay=None):
"""Have a stage invoke itself with a modified set of arguments."""
return self.emit(stage=self.stage.name,
data=data,
delay=delay) | [
"def",
"recurse",
"(",
"self",
",",
"data",
"=",
"{",
"}",
",",
"delay",
"=",
"None",
")",
":",
"return",
"self",
".",
"emit",
"(",
"stage",
"=",
"self",
".",
"stage",
".",
"name",
",",
"data",
"=",
"data",
",",
"delay",
"=",
"delay",
")"
] | Have a stage invoke itself with a modified set of arguments. | [
"Have",
"a",
"stage",
"invoke",
"itself",
"with",
"a",
"modified",
"set",
"of",
"arguments",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/context.py#L56-L60 | train |
alephdata/memorious | memorious/logic/context.py | Context.execute | def execute(self, data):
"""Execute the crawler and create a database record of having done
so."""
if Crawl.is_aborted(self.crawler, self.run_id):
return
try:
Crawl.operation_start(self.crawler, self.stage, self.run_id)
self.log.info('[%s->%s(%s)]: %s',
self.crawler.name,
self.stage.name,
self.stage.method_name,
self.run_id)
return self.stage.method(self, data)
except Exception as exc:
self.emit_exception(exc)
finally:
Crawl.operation_end(self.crawler, self.run_id)
shutil.rmtree(self.work_path) | python | def execute(self, data):
"""Execute the crawler and create a database record of having done
so."""
if Crawl.is_aborted(self.crawler, self.run_id):
return
try:
Crawl.operation_start(self.crawler, self.stage, self.run_id)
self.log.info('[%s->%s(%s)]: %s',
self.crawler.name,
self.stage.name,
self.stage.method_name,
self.run_id)
return self.stage.method(self, data)
except Exception as exc:
self.emit_exception(exc)
finally:
Crawl.operation_end(self.crawler, self.run_id)
shutil.rmtree(self.work_path) | [
"def",
"execute",
"(",
"self",
",",
"data",
")",
":",
"if",
"Crawl",
".",
"is_aborted",
"(",
"self",
".",
"crawler",
",",
"self",
".",
"run_id",
")",
":",
"return",
"try",
":",
"Crawl",
".",
"operation_start",
"(",
"self",
".",
"crawler",
",",
"self",
".",
"stage",
",",
"self",
".",
"run_id",
")",
"self",
".",
"log",
".",
"info",
"(",
"'[%s->%s(%s)]: %s'",
",",
"self",
".",
"crawler",
".",
"name",
",",
"self",
".",
"stage",
".",
"name",
",",
"self",
".",
"stage",
".",
"method_name",
",",
"self",
".",
"run_id",
")",
"return",
"self",
".",
"stage",
".",
"method",
"(",
"self",
",",
"data",
")",
"except",
"Exception",
"as",
"exc",
":",
"self",
".",
"emit_exception",
"(",
"exc",
")",
"finally",
":",
"Crawl",
".",
"operation_end",
"(",
"self",
".",
"crawler",
",",
"self",
".",
"run_id",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"work_path",
")"
] | Execute the crawler and create a database record of having done
so. | [
"Execute",
"the",
"crawler",
"and",
"create",
"a",
"database",
"record",
"of",
"having",
"done",
"so",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/context.py#L62-L80 | train |
alephdata/memorious | memorious/logic/context.py | Context.skip_incremental | def skip_incremental(self, *criteria):
"""Perform an incremental check on a set of criteria.
This can be used to execute a part of a crawler only once per an
interval (which is specified by the ``expire`` setting). If the
operation has already been performed (and should thus be skipped),
this will return ``True``. If the operation needs to be executed,
the returned value will be ``False``.
"""
if not self.incremental:
return False
# this is pure convenience, and will probably backfire at some point.
key = make_key(*criteria)
if key is None:
return False
if self.check_tag(key):
return True
self.set_tag(key, None)
return False | python | def skip_incremental(self, *criteria):
"""Perform an incremental check on a set of criteria.
This can be used to execute a part of a crawler only once per an
interval (which is specified by the ``expire`` setting). If the
operation has already been performed (and should thus be skipped),
this will return ``True``. If the operation needs to be executed,
the returned value will be ``False``.
"""
if not self.incremental:
return False
# this is pure convenience, and will probably backfire at some point.
key = make_key(*criteria)
if key is None:
return False
if self.check_tag(key):
return True
self.set_tag(key, None)
return False | [
"def",
"skip_incremental",
"(",
"self",
",",
"*",
"criteria",
")",
":",
"if",
"not",
"self",
".",
"incremental",
":",
"return",
"False",
"# this is pure convenience, and will probably backfire at some point.",
"key",
"=",
"make_key",
"(",
"*",
"criteria",
")",
"if",
"key",
"is",
"None",
":",
"return",
"False",
"if",
"self",
".",
"check_tag",
"(",
"key",
")",
":",
"return",
"True",
"self",
".",
"set_tag",
"(",
"key",
",",
"None",
")",
"return",
"False"
] | Perform an incremental check on a set of criteria.
This can be used to execute a part of a crawler only once per an
interval (which is specified by the ``expire`` setting). If the
operation has already been performed (and should thus be skipped),
this will return ``True``. If the operation needs to be executed,
the returned value will be ``False``. | [
"Perform",
"an",
"incremental",
"check",
"on",
"a",
"set",
"of",
"criteria",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/context.py#L115-L136 | train |
alephdata/memorious | memorious/logic/context.py | Context.store_data | def store_data(self, data, encoding='utf-8'):
"""Put the given content into a file, possibly encoding it as UTF-8
in the process."""
path = random_filename(self.work_path)
try:
with open(path, 'wb') as fh:
if isinstance(data, str):
data = data.encode(encoding)
if data is not None:
fh.write(data)
return self.store_file(path)
finally:
try:
os.unlink(path)
except OSError:
pass | python | def store_data(self, data, encoding='utf-8'):
"""Put the given content into a file, possibly encoding it as UTF-8
in the process."""
path = random_filename(self.work_path)
try:
with open(path, 'wb') as fh:
if isinstance(data, str):
data = data.encode(encoding)
if data is not None:
fh.write(data)
return self.store_file(path)
finally:
try:
os.unlink(path)
except OSError:
pass | [
"def",
"store_data",
"(",
"self",
",",
"data",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"path",
"=",
"random_filename",
"(",
"self",
".",
"work_path",
")",
"try",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"fh",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"encoding",
")",
"if",
"data",
"is",
"not",
"None",
":",
"fh",
".",
"write",
"(",
"data",
")",
"return",
"self",
".",
"store_file",
"(",
"path",
")",
"finally",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"path",
")",
"except",
"OSError",
":",
"pass"
] | Put the given content into a file, possibly encoding it as UTF-8
in the process. | [
"Put",
"the",
"given",
"content",
"into",
"a",
"file",
"possibly",
"encoding",
"it",
"as",
"UTF",
"-",
"8",
"in",
"the",
"process",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/context.py#L143-L158 | train |
alephdata/memorious | memorious/logic/crawler.py | Crawler.check_due | def check_due(self):
"""Check if the last execution of this crawler is older than
the scheduled interval."""
if self.disabled:
return False
if self.is_running:
return False
if self.delta is None:
return False
last_run = self.last_run
if last_run is None:
return True
now = datetime.utcnow()
if now > last_run + self.delta:
return True
return False | python | def check_due(self):
"""Check if the last execution of this crawler is older than
the scheduled interval."""
if self.disabled:
return False
if self.is_running:
return False
if self.delta is None:
return False
last_run = self.last_run
if last_run is None:
return True
now = datetime.utcnow()
if now > last_run + self.delta:
return True
return False | [
"def",
"check_due",
"(",
"self",
")",
":",
"if",
"self",
".",
"disabled",
":",
"return",
"False",
"if",
"self",
".",
"is_running",
":",
"return",
"False",
"if",
"self",
".",
"delta",
"is",
"None",
":",
"return",
"False",
"last_run",
"=",
"self",
".",
"last_run",
"if",
"last_run",
"is",
"None",
":",
"return",
"True",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"now",
">",
"last_run",
"+",
"self",
".",
"delta",
":",
"return",
"True",
"return",
"False"
] | Check if the last execution of this crawler is older than
the scheduled interval. | [
"Check",
"if",
"the",
"last",
"execution",
"of",
"this",
"crawler",
"is",
"older",
"than",
"the",
"scheduled",
"interval",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/crawler.py#L48-L63 | train |
alephdata/memorious | memorious/logic/crawler.py | Crawler.flush | def flush(self):
"""Delete all run-time data generated by this crawler."""
Queue.flush(self)
Event.delete(self)
Crawl.flush(self) | python | def flush(self):
"""Delete all run-time data generated by this crawler."""
Queue.flush(self)
Event.delete(self)
Crawl.flush(self) | [
"def",
"flush",
"(",
"self",
")",
":",
"Queue",
".",
"flush",
"(",
"self",
")",
"Event",
".",
"delete",
"(",
"self",
")",
"Crawl",
".",
"flush",
"(",
"self",
")"
] | Delete all run-time data generated by this crawler. | [
"Delete",
"all",
"run",
"-",
"time",
"data",
"generated",
"by",
"this",
"crawler",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/crawler.py#L83-L87 | train |
alephdata/memorious | memorious/logic/crawler.py | Crawler.run | def run(self, incremental=None, run_id=None):
"""Queue the execution of a particular crawler."""
state = {
'crawler': self.name,
'run_id': run_id,
'incremental': settings.INCREMENTAL
}
if incremental is not None:
state['incremental'] = incremental
# Cancel previous runs:
self.cancel()
# Flush out previous events:
Event.delete(self)
Queue.queue(self.init_stage, state, {}) | python | def run(self, incremental=None, run_id=None):
"""Queue the execution of a particular crawler."""
state = {
'crawler': self.name,
'run_id': run_id,
'incremental': settings.INCREMENTAL
}
if incremental is not None:
state['incremental'] = incremental
# Cancel previous runs:
self.cancel()
# Flush out previous events:
Event.delete(self)
Queue.queue(self.init_stage, state, {}) | [
"def",
"run",
"(",
"self",
",",
"incremental",
"=",
"None",
",",
"run_id",
"=",
"None",
")",
":",
"state",
"=",
"{",
"'crawler'",
":",
"self",
".",
"name",
",",
"'run_id'",
":",
"run_id",
",",
"'incremental'",
":",
"settings",
".",
"INCREMENTAL",
"}",
"if",
"incremental",
"is",
"not",
"None",
":",
"state",
"[",
"'incremental'",
"]",
"=",
"incremental",
"# Cancel previous runs:",
"self",
".",
"cancel",
"(",
")",
"# Flush out previous events:",
"Event",
".",
"delete",
"(",
"self",
")",
"Queue",
".",
"queue",
"(",
"self",
".",
"init_stage",
",",
"state",
",",
"{",
"}",
")"
] | Queue the execution of a particular crawler. | [
"Queue",
"the",
"execution",
"of",
"a",
"particular",
"crawler",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/crawler.py#L96-L110 | train |
alephdata/memorious | memorious/operations/fetch.py | fetch | def fetch(context, data):
"""Do an HTTP GET on the ``url`` specified in the inbound data."""
url = data.get('url')
attempt = data.pop('retry_attempt', 1)
try:
result = context.http.get(url, lazy=True)
rules = context.get('rules', {'match_all': {}})
if not Rule.get_rule(rules).apply(result):
context.log.info('Fetch skip: %r', result.url)
return
if not result.ok:
err = (result.url, result.status_code)
context.emit_warning("Fetch fail [%s]: HTTP %s" % err)
if not context.params.get('emit_errors', False):
return
else:
context.log.info("Fetched [%s]: %r",
result.status_code,
result.url)
data.update(result.serialize())
if url != result.url:
tag = make_key(context.run_id, url)
context.set_tag(tag, None)
context.emit(data=data)
except RequestException as ce:
retries = int(context.get('retry', 3))
if retries >= attempt:
context.log.warn("Retry: %s (error: %s)", url, ce)
data['retry_attempt'] = attempt + 1
context.recurse(data=data, delay=2 ** attempt)
else:
context.emit_warning("Fetch fail [%s]: %s" % (url, ce)) | python | def fetch(context, data):
"""Do an HTTP GET on the ``url`` specified in the inbound data."""
url = data.get('url')
attempt = data.pop('retry_attempt', 1)
try:
result = context.http.get(url, lazy=True)
rules = context.get('rules', {'match_all': {}})
if not Rule.get_rule(rules).apply(result):
context.log.info('Fetch skip: %r', result.url)
return
if not result.ok:
err = (result.url, result.status_code)
context.emit_warning("Fetch fail [%s]: HTTP %s" % err)
if not context.params.get('emit_errors', False):
return
else:
context.log.info("Fetched [%s]: %r",
result.status_code,
result.url)
data.update(result.serialize())
if url != result.url:
tag = make_key(context.run_id, url)
context.set_tag(tag, None)
context.emit(data=data)
except RequestException as ce:
retries = int(context.get('retry', 3))
if retries >= attempt:
context.log.warn("Retry: %s (error: %s)", url, ce)
data['retry_attempt'] = attempt + 1
context.recurse(data=data, delay=2 ** attempt)
else:
context.emit_warning("Fetch fail [%s]: %s" % (url, ce)) | [
"def",
"fetch",
"(",
"context",
",",
"data",
")",
":",
"url",
"=",
"data",
".",
"get",
"(",
"'url'",
")",
"attempt",
"=",
"data",
".",
"pop",
"(",
"'retry_attempt'",
",",
"1",
")",
"try",
":",
"result",
"=",
"context",
".",
"http",
".",
"get",
"(",
"url",
",",
"lazy",
"=",
"True",
")",
"rules",
"=",
"context",
".",
"get",
"(",
"'rules'",
",",
"{",
"'match_all'",
":",
"{",
"}",
"}",
")",
"if",
"not",
"Rule",
".",
"get_rule",
"(",
"rules",
")",
".",
"apply",
"(",
"result",
")",
":",
"context",
".",
"log",
".",
"info",
"(",
"'Fetch skip: %r'",
",",
"result",
".",
"url",
")",
"return",
"if",
"not",
"result",
".",
"ok",
":",
"err",
"=",
"(",
"result",
".",
"url",
",",
"result",
".",
"status_code",
")",
"context",
".",
"emit_warning",
"(",
"\"Fetch fail [%s]: HTTP %s\"",
"%",
"err",
")",
"if",
"not",
"context",
".",
"params",
".",
"get",
"(",
"'emit_errors'",
",",
"False",
")",
":",
"return",
"else",
":",
"context",
".",
"log",
".",
"info",
"(",
"\"Fetched [%s]: %r\"",
",",
"result",
".",
"status_code",
",",
"result",
".",
"url",
")",
"data",
".",
"update",
"(",
"result",
".",
"serialize",
"(",
")",
")",
"if",
"url",
"!=",
"result",
".",
"url",
":",
"tag",
"=",
"make_key",
"(",
"context",
".",
"run_id",
",",
"url",
")",
"context",
".",
"set_tag",
"(",
"tag",
",",
"None",
")",
"context",
".",
"emit",
"(",
"data",
"=",
"data",
")",
"except",
"RequestException",
"as",
"ce",
":",
"retries",
"=",
"int",
"(",
"context",
".",
"get",
"(",
"'retry'",
",",
"3",
")",
")",
"if",
"retries",
">=",
"attempt",
":",
"context",
".",
"log",
".",
"warn",
"(",
"\"Retry: %s (error: %s)\"",
",",
"url",
",",
"ce",
")",
"data",
"[",
"'retry_attempt'",
"]",
"=",
"attempt",
"+",
"1",
"context",
".",
"recurse",
"(",
"data",
"=",
"data",
",",
"delay",
"=",
"2",
"**",
"attempt",
")",
"else",
":",
"context",
".",
"emit_warning",
"(",
"\"Fetch fail [%s]: %s\"",
"%",
"(",
"url",
",",
"ce",
")",
")"
] | Do an HTTP GET on the ``url`` specified in the inbound data. | [
"Do",
"an",
"HTTP",
"GET",
"on",
"the",
"url",
"specified",
"in",
"the",
"inbound",
"data",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/fetch.py#L8-L41 | train |
alephdata/memorious | memorious/operations/fetch.py | dav_index | def dav_index(context, data):
"""List files in a WebDAV directory."""
# This is made to work with ownCloud/nextCloud, but some rumor has
# it they are "standards compliant" and it should thus work for
# other DAV servers.
url = data.get('url')
result = context.http.request('PROPFIND', url)
for resp in result.xml.findall('./{DAV:}response'):
href = resp.findtext('./{DAV:}href')
if href is None:
continue
rurl = urljoin(url, href)
rdata = data.copy()
rdata['url'] = rurl
rdata['foreign_id'] = rurl
if rdata['url'] == url:
continue
if resp.find('.//{DAV:}collection') is not None:
rdata['parent_foreign_id'] = rurl
context.log.info("Fetching contents of folder: %s" % rurl)
context.recurse(data=rdata)
else:
rdata['parent_foreign_id'] = url
# Do GET requests on the urls
fetch(context, rdata) | python | def dav_index(context, data):
"""List files in a WebDAV directory."""
# This is made to work with ownCloud/nextCloud, but some rumor has
# it they are "standards compliant" and it should thus work for
# other DAV servers.
url = data.get('url')
result = context.http.request('PROPFIND', url)
for resp in result.xml.findall('./{DAV:}response'):
href = resp.findtext('./{DAV:}href')
if href is None:
continue
rurl = urljoin(url, href)
rdata = data.copy()
rdata['url'] = rurl
rdata['foreign_id'] = rurl
if rdata['url'] == url:
continue
if resp.find('.//{DAV:}collection') is not None:
rdata['parent_foreign_id'] = rurl
context.log.info("Fetching contents of folder: %s" % rurl)
context.recurse(data=rdata)
else:
rdata['parent_foreign_id'] = url
# Do GET requests on the urls
fetch(context, rdata) | [
"def",
"dav_index",
"(",
"context",
",",
"data",
")",
":",
"# This is made to work with ownCloud/nextCloud, but some rumor has",
"# it they are \"standards compliant\" and it should thus work for",
"# other DAV servers.",
"url",
"=",
"data",
".",
"get",
"(",
"'url'",
")",
"result",
"=",
"context",
".",
"http",
".",
"request",
"(",
"'PROPFIND'",
",",
"url",
")",
"for",
"resp",
"in",
"result",
".",
"xml",
".",
"findall",
"(",
"'./{DAV:}response'",
")",
":",
"href",
"=",
"resp",
".",
"findtext",
"(",
"'./{DAV:}href'",
")",
"if",
"href",
"is",
"None",
":",
"continue",
"rurl",
"=",
"urljoin",
"(",
"url",
",",
"href",
")",
"rdata",
"=",
"data",
".",
"copy",
"(",
")",
"rdata",
"[",
"'url'",
"]",
"=",
"rurl",
"rdata",
"[",
"'foreign_id'",
"]",
"=",
"rurl",
"if",
"rdata",
"[",
"'url'",
"]",
"==",
"url",
":",
"continue",
"if",
"resp",
".",
"find",
"(",
"'.//{DAV:}collection'",
")",
"is",
"not",
"None",
":",
"rdata",
"[",
"'parent_foreign_id'",
"]",
"=",
"rurl",
"context",
".",
"log",
".",
"info",
"(",
"\"Fetching contents of folder: %s\"",
"%",
"rurl",
")",
"context",
".",
"recurse",
"(",
"data",
"=",
"rdata",
")",
"else",
":",
"rdata",
"[",
"'parent_foreign_id'",
"]",
"=",
"url",
"# Do GET requests on the urls",
"fetch",
"(",
"context",
",",
"rdata",
")"
] | List files in a WebDAV directory. | [
"List",
"files",
"in",
"a",
"WebDAV",
"directory",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/fetch.py#L44-L71 | train |