repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
MisterY/asset-allocation | asset_allocation/model.py | AssetAllocationModel.calculate_set_values | def calculate_set_values(self):
""" Calculate the expected totals based on set allocations """
for ac in self.asset_classes:
ac.alloc_value = self.total_amount * ac.allocation / Decimal(100) | python | def calculate_set_values(self):
""" Calculate the expected totals based on set allocations """
for ac in self.asset_classes:
ac.alloc_value = self.total_amount * ac.allocation / Decimal(100) | [
"def",
"calculate_set_values",
"(",
"self",
")",
":",
"for",
"ac",
"in",
"self",
".",
"asset_classes",
":",
"ac",
".",
"alloc_value",
"=",
"self",
".",
"total_amount",
"*",
"ac",
".",
"allocation",
"/",
"Decimal",
"(",
"100",
")"
] | Calculate the expected totals based on set allocations | [
"Calculate",
"the",
"expected",
"totals",
"based",
"on",
"set",
"allocations"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L229-L232 |
MisterY/asset-allocation | asset_allocation/model.py | AssetAllocationModel.calculate_current_allocation | def calculate_current_allocation(self):
""" Calculates the current allocation % based on the value """
for ac in self.asset_classes:
ac.curr_alloc = ac.curr_value * 100 / self.total_amount | python | def calculate_current_allocation(self):
""" Calculates the current allocation % based on the value """
for ac in self.asset_classes:
ac.curr_alloc = ac.curr_value * 100 / self.total_amount | [
"def",
"calculate_current_allocation",
"(",
"self",
")",
":",
"for",
"ac",
"in",
"self",
".",
"asset_classes",
":",
"ac",
".",
"curr_alloc",
"=",
"ac",
".",
"curr_value",
"*",
"100",
"/",
"self",
".",
"total_amount"
] | Calculates the current allocation % based on the value | [
"Calculates",
"the",
"current",
"allocation",
"%",
"based",
"on",
"the",
"value"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L234-L237 |
MisterY/asset-allocation | asset_allocation/model.py | AssetAllocationModel.calculate_current_value | def calculate_current_value(self):
""" Add all the stock values and assign to the asset classes """
# must be recursive
total = Decimal(0)
for ac in self.classes:
self.__calculate_current_value(ac)
total += ac.curr_value
self.total_amount = total | python | def calculate_current_value(self):
""" Add all the stock values and assign to the asset classes """
# must be recursive
total = Decimal(0)
for ac in self.classes:
self.__calculate_current_value(ac)
total += ac.curr_value
self.total_amount = total | [
"def",
"calculate_current_value",
"(",
"self",
")",
":",
"# must be recursive",
"total",
"=",
"Decimal",
"(",
"0",
")",
"for",
"ac",
"in",
"self",
".",
"classes",
":",
"self",
".",
"__calculate_current_value",
"(",
"ac",
")",
"total",
"+=",
"ac",
".",
"cur... | Add all the stock values and assign to the asset classes | [
"Add",
"all",
"the",
"stock",
"values",
"and",
"assign",
"to",
"the",
"asset",
"classes"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L239-L246 |
MisterY/asset-allocation | asset_allocation/model.py | AssetAllocationModel.__calculate_current_value | def __calculate_current_value(self, asset_class: AssetClass):
""" Calculate totals for asset class by adding all the children values """
# Is this the final asset class, the one with stocks?
if asset_class.stocks:
# add all the stocks
stocks_sum = Decimal(0)
f... | python | def __calculate_current_value(self, asset_class: AssetClass):
""" Calculate totals for asset class by adding all the children values """
# Is this the final asset class, the one with stocks?
if asset_class.stocks:
# add all the stocks
stocks_sum = Decimal(0)
f... | [
"def",
"__calculate_current_value",
"(",
"self",
",",
"asset_class",
":",
"AssetClass",
")",
":",
"# Is this the final asset class, the one with stocks?",
"if",
"asset_class",
".",
"stocks",
":",
"# add all the stocks",
"stocks_sum",
"=",
"Decimal",
"(",
"0",
")",
"for"... | Calculate totals for asset class by adding all the children values | [
"Calculate",
"totals",
"for",
"asset",
"class",
"by",
"adding",
"all",
"the",
"children",
"values"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L248-L264 |
MisterY/asset-allocation | asset_allocation/currency.py | CurrencyConverter.load_currency | def load_currency(self, mnemonic: str):
""" load the latest rate for the given mnemonic; expressed in the base currency """
# , base_currency: str <= ignored for now.
if self.rate and self.rate.currency == mnemonic:
# Already loaded.
return
app = PriceDbApplicati... | python | def load_currency(self, mnemonic: str):
""" load the latest rate for the given mnemonic; expressed in the base currency """
# , base_currency: str <= ignored for now.
if self.rate and self.rate.currency == mnemonic:
# Already loaded.
return
app = PriceDbApplicati... | [
"def",
"load_currency",
"(",
"self",
",",
"mnemonic",
":",
"str",
")",
":",
"# , base_currency: str <= ignored for now.",
"if",
"self",
".",
"rate",
"and",
"self",
".",
"rate",
".",
"currency",
"==",
"mnemonic",
":",
"# Already loaded.",
"return",
"app",
"=",
... | load the latest rate for the given mnemonic; expressed in the base currency | [
"load",
"the",
"latest",
"rate",
"for",
"the",
"given",
"mnemonic",
";",
"expressed",
"in",
"the",
"base",
"currency"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/currency.py#L12-L24 |
MisterY/asset-allocation | asset_allocation/cli.py | show | def show(format, full):
""" Print current allocation to the console. """
# load asset allocation
app = AppAggregate()
app.logger = logger
model = app.get_asset_allocation()
if format == "ascii":
formatter = AsciiFormatter()
elif format == "html":
formatter = HtmlFormatter
... | python | def show(format, full):
""" Print current allocation to the console. """
# load asset allocation
app = AppAggregate()
app.logger = logger
model = app.get_asset_allocation()
if format == "ascii":
formatter = AsciiFormatter()
elif format == "html":
formatter = HtmlFormatter
... | [
"def",
"show",
"(",
"format",
",",
"full",
")",
":",
"# load asset allocation",
"app",
"=",
"AppAggregate",
"(",
")",
"app",
".",
"logger",
"=",
"logger",
"model",
"=",
"app",
".",
"get_asset_allocation",
"(",
")",
"if",
"format",
"==",
"\"ascii\"",
":",
... | Print current allocation to the console. | [
"Print",
"current",
"allocation",
"to",
"the",
"console",
"."
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/cli.py#L30-L46 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.load_cash_balances | def load_cash_balances(self):
""" Loads cash balances from GnuCash book and recalculates into the default currency """
from gnucash_portfolio.accounts import AccountsAggregate, AccountAggregate
cfg = self.__get_config()
cash_root_name = cfg.get(ConfigKeys.cash_root)
# Load cash ... | python | def load_cash_balances(self):
""" Loads cash balances from GnuCash book and recalculates into the default currency """
from gnucash_portfolio.accounts import AccountsAggregate, AccountAggregate
cfg = self.__get_config()
cash_root_name = cfg.get(ConfigKeys.cash_root)
# Load cash ... | [
"def",
"load_cash_balances",
"(",
"self",
")",
":",
"from",
"gnucash_portfolio",
".",
"accounts",
"import",
"AccountsAggregate",
",",
"AccountAggregate",
"cfg",
"=",
"self",
".",
"__get_config",
"(",
")",
"cash_root_name",
"=",
"cfg",
".",
"get",
"(",
"ConfigKey... | Loads cash balances from GnuCash book and recalculates into the default currency | [
"Loads",
"cash",
"balances",
"from",
"GnuCash",
"book",
"and",
"recalculates",
"into",
"the",
"default",
"currency"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L29-L44 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.__store_cash_balances_per_currency | def __store_cash_balances_per_currency(self, cash_balances):
""" Store balance per currency as Stock records under Cash class """
cash = self.model.get_cash_asset_class()
for cur_symbol in cash_balances:
item = CashBalance(cur_symbol)
item.parent = cash
... | python | def __store_cash_balances_per_currency(self, cash_balances):
""" Store balance per currency as Stock records under Cash class """
cash = self.model.get_cash_asset_class()
for cur_symbol in cash_balances:
item = CashBalance(cur_symbol)
item.parent = cash
... | [
"def",
"__store_cash_balances_per_currency",
"(",
"self",
",",
"cash_balances",
")",
":",
"cash",
"=",
"self",
".",
"model",
".",
"get_cash_asset_class",
"(",
")",
"for",
"cur_symbol",
"in",
"cash_balances",
":",
"item",
"=",
"CashBalance",
"(",
"cur_symbol",
")... | Store balance per currency as Stock records under Cash class | [
"Store",
"balance",
"per",
"currency",
"as",
"Stock",
"records",
"under",
"Cash",
"class"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L53-L67 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.load_tree_from_db | def load_tree_from_db(self) -> AssetAllocationModel:
""" Reads the asset allocation data only, and constructs the AA tree """
self.model = AssetAllocationModel()
# currency
self.model.currency = self.__get_config().get(ConfigKeys.default_currency)
# Asset Classes
db = s... | python | def load_tree_from_db(self) -> AssetAllocationModel:
""" Reads the asset allocation data only, and constructs the AA tree """
self.model = AssetAllocationModel()
# currency
self.model.currency = self.__get_config().get(ConfigKeys.default_currency)
# Asset Classes
db = s... | [
"def",
"load_tree_from_db",
"(",
"self",
")",
"->",
"AssetAllocationModel",
":",
"self",
".",
"model",
"=",
"AssetAllocationModel",
"(",
")",
"# currency",
"self",
".",
"model",
".",
"currency",
"=",
"self",
".",
"__get_config",
"(",
")",
".",
"get",
"(",
... | Reads the asset allocation data only, and constructs the AA tree | [
"Reads",
"the",
"asset",
"allocation",
"data",
"only",
"and",
"constructs",
"the",
"AA",
"tree"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L69-L95 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.load_stock_links | def load_stock_links(self):
""" Read stock links into the model """
links = self.__get_session().query(dal.AssetClassStock).all()
for entity in links:
# log(DEBUG, f"adding {entity.symbol} to {entity.assetclassid}")
# mapping
stock: Stock = Stock(entity.symbol... | python | def load_stock_links(self):
""" Read stock links into the model """
links = self.__get_session().query(dal.AssetClassStock).all()
for entity in links:
# log(DEBUG, f"adding {entity.symbol} to {entity.assetclassid}")
# mapping
stock: Stock = Stock(entity.symbol... | [
"def",
"load_stock_links",
"(",
"self",
")",
":",
"links",
"=",
"self",
".",
"__get_session",
"(",
")",
".",
"query",
"(",
"dal",
".",
"AssetClassStock",
")",
".",
"all",
"(",
")",
"for",
"entity",
"in",
"links",
":",
"# log(DEBUG, f\"adding {entity.symbol} ... | Read stock links into the model | [
"Read",
"stock",
"links",
"into",
"the",
"model"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L97-L110 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.load_stock_quantity | def load_stock_quantity(self):
""" Loads quantities for all stocks """
info = StocksInfo(self.config)
for stock in self.model.stocks:
stock.quantity = info.load_stock_quantity(stock.symbol)
info.gc_book.close() | python | def load_stock_quantity(self):
""" Loads quantities for all stocks """
info = StocksInfo(self.config)
for stock in self.model.stocks:
stock.quantity = info.load_stock_quantity(stock.symbol)
info.gc_book.close() | [
"def",
"load_stock_quantity",
"(",
"self",
")",
":",
"info",
"=",
"StocksInfo",
"(",
"self",
".",
"config",
")",
"for",
"stock",
"in",
"self",
".",
"model",
".",
"stocks",
":",
"stock",
".",
"quantity",
"=",
"info",
".",
"load_stock_quantity",
"(",
"stoc... | Loads quantities for all stocks | [
"Loads",
"quantities",
"for",
"all",
"stocks"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L112-L117 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.load_stock_prices | def load_stock_prices(self):
""" Load latest prices for securities """
from pricedb import SecuritySymbol
info = StocksInfo(self.config)
for item in self.model.stocks:
symbol = SecuritySymbol("", "")
symbol.parse(item.symbol)
price: PriceModel = info... | python | def load_stock_prices(self):
""" Load latest prices for securities """
from pricedb import SecuritySymbol
info = StocksInfo(self.config)
for item in self.model.stocks:
symbol = SecuritySymbol("", "")
symbol.parse(item.symbol)
price: PriceModel = info... | [
"def",
"load_stock_prices",
"(",
"self",
")",
":",
"from",
"pricedb",
"import",
"SecuritySymbol",
"info",
"=",
"StocksInfo",
"(",
"self",
".",
"config",
")",
"for",
"item",
"in",
"self",
".",
"model",
".",
"stocks",
":",
"symbol",
"=",
"SecuritySymbol",
"(... | Load latest prices for securities | [
"Load",
"latest",
"prices",
"for",
"securities"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L119-L138 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.recalculate_stock_values_into_base | def recalculate_stock_values_into_base(self):
""" Loads the exchange rates and recalculates stock holding values into
base currency """
from .currency import CurrencyConverter
conv = CurrencyConverter()
cash = self.model.get_cash_asset_class()
for stock in self.model.s... | python | def recalculate_stock_values_into_base(self):
""" Loads the exchange rates and recalculates stock holding values into
base currency """
from .currency import CurrencyConverter
conv = CurrencyConverter()
cash = self.model.get_cash_asset_class()
for stock in self.model.s... | [
"def",
"recalculate_stock_values_into_base",
"(",
"self",
")",
":",
"from",
".",
"currency",
"import",
"CurrencyConverter",
"conv",
"=",
"CurrencyConverter",
"(",
")",
"cash",
"=",
"self",
".",
"model",
".",
"get_cash_asset_class",
"(",
")",
"for",
"stock",
"in"... | Loads the exchange rates and recalculates stock holding values into
base currency | [
"Loads",
"the",
"exchange",
"rates",
"and",
"recalculates",
"stock",
"holding",
"values",
"into",
"base",
"currency"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L140-L158 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.__load_child_classes | def __load_child_classes(self, ac: AssetClass):
""" Loads child classes/stocks """
# load child classes for ac
db = self.__get_session()
entities = (
db.query(dal.AssetClass)
.filter(dal.AssetClass.parentid == ac.id)
.order_by(dal.AssetClass.sortorder)... | python | def __load_child_classes(self, ac: AssetClass):
""" Loads child classes/stocks """
# load child classes for ac
db = self.__get_session()
entities = (
db.query(dal.AssetClass)
.filter(dal.AssetClass.parentid == ac.id)
.order_by(dal.AssetClass.sortorder)... | [
"def",
"__load_child_classes",
"(",
"self",
",",
"ac",
":",
"AssetClass",
")",
":",
"# load child classes for ac",
"db",
"=",
"self",
".",
"__get_session",
"(",
")",
"entities",
"=",
"(",
"db",
".",
"query",
"(",
"dal",
".",
"AssetClass",
")",
".",
"filter... | Loads child classes/stocks | [
"Loads",
"child",
"classes",
"/",
"stocks"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L161-L180 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.__map_entity | def __map_entity(self, entity: dal.AssetClass) -> AssetClass:
""" maps the entity onto the model object """
mapper = self.__get_mapper()
ac = mapper.map_entity(entity)
return ac | python | def __map_entity(self, entity: dal.AssetClass) -> AssetClass:
""" maps the entity onto the model object """
mapper = self.__get_mapper()
ac = mapper.map_entity(entity)
return ac | [
"def",
"__map_entity",
"(",
"self",
",",
"entity",
":",
"dal",
".",
"AssetClass",
")",
"->",
"AssetClass",
":",
"mapper",
"=",
"self",
".",
"__get_mapper",
"(",
")",
"ac",
"=",
"mapper",
".",
"map_entity",
"(",
"entity",
")",
"return",
"ac"
] | maps the entity onto the model object | [
"maps",
"the",
"entity",
"onto",
"the",
"model",
"object"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L182-L186 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.__get_session | def __get_session(self):
""" Opens a db session """
db_path = self.__get_config().get(ConfigKeys.asset_allocation_database_path)
self.session = dal.get_session(db_path)
return self.session | python | def __get_session(self):
""" Opens a db session """
db_path = self.__get_config().get(ConfigKeys.asset_allocation_database_path)
self.session = dal.get_session(db_path)
return self.session | [
"def",
"__get_session",
"(",
"self",
")",
":",
"db_path",
"=",
"self",
".",
"__get_config",
"(",
")",
".",
"get",
"(",
"ConfigKeys",
".",
"asset_allocation_database_path",
")",
"self",
".",
"session",
"=",
"dal",
".",
"get_session",
"(",
"db_path",
")",
"r... | Opens a db session | [
"Opens",
"a",
"db",
"session"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L194-L198 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationLoader.__load_asset_class | def __load_asset_class(self, ac_id: int):
""" Loads Asset Class entity """
# open database
db = self.__get_session()
entity = db.query(dal.AssetClass).filter(dal.AssetClass.id == ac_id).first()
return entity | python | def __load_asset_class(self, ac_id: int):
""" Loads Asset Class entity """
# open database
db = self.__get_session()
entity = db.query(dal.AssetClass).filter(dal.AssetClass.id == ac_id).first()
return entity | [
"def",
"__load_asset_class",
"(",
"self",
",",
"ac_id",
":",
"int",
")",
":",
"# open database",
"db",
"=",
"self",
".",
"__get_session",
"(",
")",
"entity",
"=",
"db",
".",
"query",
"(",
"dal",
".",
"AssetClass",
")",
".",
"filter",
"(",
"dal",
".",
... | Loads Asset Class entity | [
"Loads",
"Asset",
"Class",
"entity"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L206-L211 |
MisterY/asset-allocation | asset_allocation/loader.py | AssetAllocationAggregate.__get_by_fullname | def __get_by_fullname(self, asset_class, fullname: str):
""" Recursive function """
if asset_class.fullname == fullname:
return asset_class
if not hasattr(asset_class, "classes"):
return None
for child in asset_class.classes:
found = self.__get_by_fu... | python | def __get_by_fullname(self, asset_class, fullname: str):
""" Recursive function """
if asset_class.fullname == fullname:
return asset_class
if not hasattr(asset_class, "classes"):
return None
for child in asset_class.classes:
found = self.__get_by_fu... | [
"def",
"__get_by_fullname",
"(",
"self",
",",
"asset_class",
",",
"fullname",
":",
"str",
")",
":",
"if",
"asset_class",
".",
"fullname",
"==",
"fullname",
":",
"return",
"asset_class",
"if",
"not",
"hasattr",
"(",
"asset_class",
",",
"\"classes\"",
")",
":"... | Recursive function | [
"Recursive",
"function"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L422-L435 |
MisterY/asset-allocation | asset_allocation/dal.py | get_session | def get_session(db_path: str):
""" Creates and opens a database session """
# cfg = Config()
# db_path = cfg.get(ConfigKeys.asset_allocation_database_path)
# connection
con_str = "sqlite:///" + db_path
# Display all SQLite info with echo.
engine = create_engine(con_str, echo=False)
# c... | python | def get_session(db_path: str):
""" Creates and opens a database session """
# cfg = Config()
# db_path = cfg.get(ConfigKeys.asset_allocation_database_path)
# connection
con_str = "sqlite:///" + db_path
# Display all SQLite info with echo.
engine = create_engine(con_str, echo=False)
# c... | [
"def",
"get_session",
"(",
"db_path",
":",
"str",
")",
":",
"# cfg = Config()",
"# db_path = cfg.get(ConfigKeys.asset_allocation_database_path)",
"# connection",
"con_str",
"=",
"\"sqlite:///\"",
"+",
"db_path",
"# Display all SQLite info with echo.",
"engine",
"=",
"create_eng... | Creates and opens a database session | [
"Creates",
"and",
"opens",
"a",
"database",
"session"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/dal.py#L53-L70 |
MisterY/asset-allocation | asset_allocation/assetclass_cli.py | add | def add(name):
""" Add new Asset Class """
item = AssetClass()
item.name = name
app = AppAggregate()
app.create_asset_class(item)
print(f"Asset class {name} created.") | python | def add(name):
""" Add new Asset Class """
item = AssetClass()
item.name = name
app = AppAggregate()
app.create_asset_class(item)
print(f"Asset class {name} created.") | [
"def",
"add",
"(",
"name",
")",
":",
"item",
"=",
"AssetClass",
"(",
")",
"item",
".",
"name",
"=",
"name",
"app",
"=",
"AppAggregate",
"(",
")",
"app",
".",
"create_asset_class",
"(",
"item",
")",
"print",
"(",
"f\"Asset class {name} created.\"",
")"
] | Add new Asset Class | [
"Add",
"new",
"Asset",
"Class"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L28-L35 |
MisterY/asset-allocation | asset_allocation/assetclass_cli.py | edit | def edit(id: int, parent: int, alloc: Decimal):
""" Edit asset class """
saved = False
# load
app = AppAggregate()
item = app.get(id)
if not item:
raise KeyError("Asset Class with id %s not found.", id)
if parent:
assert parent != id, "Parent can not be set to self."
... | python | def edit(id: int, parent: int, alloc: Decimal):
""" Edit asset class """
saved = False
# load
app = AppAggregate()
item = app.get(id)
if not item:
raise KeyError("Asset Class with id %s not found.", id)
if parent:
assert parent != id, "Parent can not be set to self."
... | [
"def",
"edit",
"(",
"id",
":",
"int",
",",
"parent",
":",
"int",
",",
"alloc",
":",
"Decimal",
")",
":",
"saved",
"=",
"False",
"# load",
"app",
"=",
"AppAggregate",
"(",
")",
"item",
"=",
"app",
".",
"get",
"(",
"id",
")",
"if",
"not",
"item",
... | Edit asset class | [
"Edit",
"asset",
"class"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L50-L79 |
MisterY/asset-allocation | asset_allocation/assetclass_cli.py | my_list | def my_list():
""" Lists all asset classes """
session = AppAggregate().open_session()
classes = session.query(AssetClass).all()
for item in classes:
print(item) | python | def my_list():
""" Lists all asset classes """
session = AppAggregate().open_session()
classes = session.query(AssetClass).all()
for item in classes:
print(item) | [
"def",
"my_list",
"(",
")",
":",
"session",
"=",
"AppAggregate",
"(",
")",
".",
"open_session",
"(",
")",
"classes",
"=",
"session",
".",
"query",
"(",
"AssetClass",
")",
".",
"all",
"(",
")",
"for",
"item",
"in",
"classes",
":",
"print",
"(",
"item"... | Lists all asset classes | [
"Lists",
"all",
"asset",
"classes"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L83-L88 |
MisterY/asset-allocation | asset_allocation/assetclass_cli.py | my_import | def my_import(file):
""" Import Asset Class(es) from a .csv file """
# , help="The path to the CSV file to import. The first row must contain column names."
lines = None
with open(file) as csv_file:
lines = csv_file.readlines()
# Header, the first line.
header = lines[0]
lines.remov... | python | def my_import(file):
""" Import Asset Class(es) from a .csv file """
# , help="The path to the CSV file to import. The first row must contain column names."
lines = None
with open(file) as csv_file:
lines = csv_file.readlines()
# Header, the first line.
header = lines[0]
lines.remov... | [
"def",
"my_import",
"(",
"file",
")",
":",
"# , help=\"The path to the CSV file to import. The first row must contain column names.\"",
"lines",
"=",
"None",
"with",
"open",
"(",
"file",
")",
"as",
"csv_file",
":",
"lines",
"=",
"csv_file",
".",
"readlines",
"(",
")",... | Import Asset Class(es) from a .csv file | [
"Import",
"Asset",
"Class",
"(",
"es",
")",
"from",
"a",
".",
"csv",
"file"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L93-L121 |
MisterY/asset-allocation | asset_allocation/assetclass_cli.py | tree | def tree():
""" Display a tree of asset classes """
session = AppAggregate().open_session()
classes = session.query(AssetClass).all()
# Get the root classes
root = []
for ac in classes:
if ac.parentid is None:
root.append(ac)
# logger.debug(ac.parentid)
# header
... | python | def tree():
""" Display a tree of asset classes """
session = AppAggregate().open_session()
classes = session.query(AssetClass).all()
# Get the root classes
root = []
for ac in classes:
if ac.parentid is None:
root.append(ac)
# logger.debug(ac.parentid)
# header
... | [
"def",
"tree",
"(",
")",
":",
"session",
"=",
"AppAggregate",
"(",
")",
".",
"open_session",
"(",
")",
"classes",
"=",
"session",
".",
"query",
"(",
"AssetClass",
")",
".",
"all",
"(",
")",
"# Get the root classes",
"root",
"=",
"[",
"]",
"for",
"ac",
... | Display a tree of asset classes | [
"Display",
"a",
"tree",
"of",
"asset",
"classes"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L126-L141 |
MisterY/asset-allocation | asset_allocation/assetclass_cli.py | print_item_with_children | def print_item_with_children(ac, classes, level):
""" Print the given item and all children items """
print_row(ac.id, ac.name, f"{ac.allocation:,.2f}", level)
print_children_recursively(classes, ac, level + 1) | python | def print_item_with_children(ac, classes, level):
""" Print the given item and all children items """
print_row(ac.id, ac.name, f"{ac.allocation:,.2f}", level)
print_children_recursively(classes, ac, level + 1) | [
"def",
"print_item_with_children",
"(",
"ac",
",",
"classes",
",",
"level",
")",
":",
"print_row",
"(",
"ac",
".",
"id",
",",
"ac",
".",
"name",
",",
"f\"{ac.allocation:,.2f}\"",
",",
"level",
")",
"print_children_recursively",
"(",
"classes",
",",
"ac",
","... | Print the given item and all children items | [
"Print",
"the",
"given",
"item",
"and",
"all",
"children",
"items"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L143-L146 |
MisterY/asset-allocation | asset_allocation/assetclass_cli.py | print_children_recursively | def print_children_recursively(all_items, for_item, level):
""" Print asset classes recursively """
children = [child for child in all_items if child.parentid == for_item.id]
for child in children:
#message = f"{for_item.name}({for_item.id}) is a parent to {child.name}({child.id})"
indent = ... | python | def print_children_recursively(all_items, for_item, level):
""" Print asset classes recursively """
children = [child for child in all_items if child.parentid == for_item.id]
for child in children:
#message = f"{for_item.name}({for_item.id}) is a parent to {child.name}({child.id})"
indent = ... | [
"def",
"print_children_recursively",
"(",
"all_items",
",",
"for_item",
",",
"level",
")",
":",
"children",
"=",
"[",
"child",
"for",
"child",
"in",
"all_items",
"if",
"child",
".",
"parentid",
"==",
"for_item",
".",
"id",
"]",
"for",
"child",
"in",
"child... | Print asset classes recursively | [
"Print",
"asset",
"classes",
"recursively"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L148-L158 |
MisterY/asset-allocation | asset_allocation/assetclass_cli.py | print_row | def print_row(*argv):
""" Print one row of data """
#for i in range(0, len(argv)):
# row += f"{argv[i]}"
# columns
row = ""
# id
row += f"{argv[0]:<3}"
# name
row += f" {argv[1]:<13}"
# allocation
row += f" {argv[2]:>5}"
# level
#row += f"{argv[3]}"
print(row... | python | def print_row(*argv):
""" Print one row of data """
#for i in range(0, len(argv)):
# row += f"{argv[i]}"
# columns
row = ""
# id
row += f"{argv[0]:<3}"
# name
row += f" {argv[1]:<13}"
# allocation
row += f" {argv[2]:>5}"
# level
#row += f"{argv[3]}"
print(row... | [
"def",
"print_row",
"(",
"*",
"argv",
")",
":",
"#for i in range(0, len(argv)):",
"# row += f\"{argv[i]}\"",
"# columns",
"row",
"=",
"\"\"",
"# id",
"row",
"+=",
"f\"{argv[0]:<3}\"",
"# name",
"row",
"+=",
"f\" {argv[1]:<13}\"",
"# allocation",
"row",
"+=",
"f\" {arg... | Print one row of data | [
"Print",
"one",
"row",
"of",
"data"
] | train | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L160-L175 |
dcwatson/bbcode | bbcode.py | render_html | def render_html(input_text, **context):
"""
A module-level convenience method that creates a default bbcode parser,
and renders the input string as HTML.
"""
global g_parser
if g_parser is None:
g_parser = Parser()
return g_parser.format(input_text, **context) | python | def render_html(input_text, **context):
"""
A module-level convenience method that creates a default bbcode parser,
and renders the input string as HTML.
"""
global g_parser
if g_parser is None:
g_parser = Parser()
return g_parser.format(input_text, **context) | [
"def",
"render_html",
"(",
"input_text",
",",
"*",
"*",
"context",
")",
":",
"global",
"g_parser",
"if",
"g_parser",
"is",
"None",
":",
"g_parser",
"=",
"Parser",
"(",
")",
"return",
"g_parser",
".",
"format",
"(",
"input_text",
",",
"*",
"*",
"context",... | A module-level convenience method that creates a default bbcode parser,
and renders the input string as HTML. | [
"A",
"module",
"-",
"level",
"convenience",
"method",
"that",
"creates",
"a",
"default",
"bbcode",
"parser",
"and",
"renders",
"the",
"input",
"string",
"as",
"HTML",
"."
] | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L604-L612 |
dcwatson/bbcode | bbcode.py | Parser.add_formatter | def add_formatter(self, tag_name, render_func, **kwargs):
"""
Installs a render function for the specified tag name. The render function
should have the following signature:
def render(tag_name, value, options, parent, context)
The arguments are as follows:
tag... | python | def add_formatter(self, tag_name, render_func, **kwargs):
"""
Installs a render function for the specified tag name. The render function
should have the following signature:
def render(tag_name, value, options, parent, context)
The arguments are as follows:
tag... | [
"def",
"add_formatter",
"(",
"self",
",",
"tag_name",
",",
"render_func",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"TagOptions",
"(",
"tag_name",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"... | Installs a render function for the specified tag name. The render function
should have the following signature:
def render(tag_name, value, options, parent, context)
The arguments are as follows:
tag_name
The name of the tag being rendered.
value
... | [
"Installs",
"a",
"render",
"function",
"for",
"the",
"specified",
"tag",
"name",
".",
"The",
"render",
"function",
"should",
"have",
"the",
"following",
"signature",
":"
] | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L113-L136 |
dcwatson/bbcode | bbcode.py | Parser.add_simple_formatter | def add_simple_formatter(self, tag_name, format_string, **kwargs):
"""
Installs a formatter that takes the tag options dictionary, puts a value key
in it, and uses it as a format dictionary to the given format string.
"""
def _render(name, value, options, parent, context):
... | python | def add_simple_formatter(self, tag_name, format_string, **kwargs):
"""
Installs a formatter that takes the tag options dictionary, puts a value key
in it, and uses it as a format dictionary to the given format string.
"""
def _render(name, value, options, parent, context):
... | [
"def",
"add_simple_formatter",
"(",
"self",
",",
"tag_name",
",",
"format_string",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_render",
"(",
"name",
",",
"value",
",",
"options",
",",
"parent",
",",
"context",
")",
":",
"fmt",
"=",
"{",
"}",
"if",
"o... | Installs a formatter that takes the tag options dictionary, puts a value key
in it, and uses it as a format dictionary to the given format string. | [
"Installs",
"a",
"formatter",
"that",
"takes",
"the",
"tag",
"options",
"dictionary",
"puts",
"a",
"value",
"key",
"in",
"it",
"and",
"uses",
"it",
"as",
"a",
"format",
"dictionary",
"to",
"the",
"given",
"format",
"string",
"."
] | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L138-L149 |
dcwatson/bbcode | bbcode.py | Parser.install_default_formatters | def install_default_formatters(self):
"""
Installs default formatters for the following tags:
b, i, u, s, list (and \*), quote, code, center, color, url
"""
self.add_simple_formatter('b', '<strong>%(value)s</strong>')
self.add_simple_formatter('i', '<em>%(value)s</em... | python | def install_default_formatters(self):
"""
Installs default formatters for the following tags:
b, i, u, s, list (and \*), quote, code, center, color, url
"""
self.add_simple_formatter('b', '<strong>%(value)s</strong>')
self.add_simple_formatter('i', '<em>%(value)s</em... | [
"def",
"install_default_formatters",
"(",
"self",
")",
":",
"self",
".",
"add_simple_formatter",
"(",
"'b'",
",",
"'<strong>%(value)s</strong>'",
")",
"self",
".",
"add_simple_formatter",
"(",
"'i'",
",",
"'<em>%(value)s</em>'",
")",
"self",
".",
"add_simple_formatter... | Installs default formatters for the following tags:
b, i, u, s, list (and \*), quote, code, center, color, url | [
"Installs",
"default",
"formatters",
"for",
"the",
"following",
"tags",
":"
] | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L151-L220 |
dcwatson/bbcode | bbcode.py | Parser._replace | def _replace(self, data, replacements):
"""
Given a list of 2-tuples (find, repl) this function performs all
replacements on the input and returns the result.
"""
for find, repl in replacements:
data = data.replace(find, repl)
return data | python | def _replace(self, data, replacements):
"""
Given a list of 2-tuples (find, repl) this function performs all
replacements on the input and returns the result.
"""
for find, repl in replacements:
data = data.replace(find, repl)
return data | [
"def",
"_replace",
"(",
"self",
",",
"data",
",",
"replacements",
")",
":",
"for",
"find",
",",
"repl",
"in",
"replacements",
":",
"data",
"=",
"data",
".",
"replace",
"(",
"find",
",",
"repl",
")",
"return",
"data"
] | Given a list of 2-tuples (find, repl) this function performs all
replacements on the input and returns the result. | [
"Given",
"a",
"list",
"of",
"2",
"-",
"tuples",
"(",
"find",
"repl",
")",
"this",
"function",
"performs",
"all",
"replacements",
"on",
"the",
"input",
"and",
"returns",
"the",
"result",
"."
] | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L222-L229 |
dcwatson/bbcode | bbcode.py | Parser._newline_tokenize | def _newline_tokenize(self, data):
"""
Given a string that does not contain any tags, this function will
return a list of NEWLINE and DATA tokens such that if you concatenate
their data, you will have the original string.
"""
parts = data.split('\n')
tokens = []
... | python | def _newline_tokenize(self, data):
"""
Given a string that does not contain any tags, this function will
return a list of NEWLINE and DATA tokens such that if you concatenate
their data, you will have the original string.
"""
parts = data.split('\n')
tokens = []
... | [
"def",
"_newline_tokenize",
"(",
"self",
",",
"data",
")",
":",
"parts",
"=",
"data",
".",
"split",
"(",
"'\\n'",
")",
"tokens",
"=",
"[",
"]",
"for",
"num",
",",
"part",
"in",
"enumerate",
"(",
"parts",
")",
":",
"if",
"part",
":",
"tokens",
".",
... | Given a string that does not contain any tags, this function will
return a list of NEWLINE and DATA tokens such that if you concatenate
their data, you will have the original string. | [
"Given",
"a",
"string",
"that",
"does",
"not",
"contain",
"any",
"tags",
"this",
"function",
"will",
"return",
"a",
"list",
"of",
"NEWLINE",
"and",
"DATA",
"tokens",
"such",
"that",
"if",
"you",
"concatenate",
"their",
"data",
"you",
"will",
"have",
"the",... | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L231-L244 |
dcwatson/bbcode | bbcode.py | Parser._parse_opts | def _parse_opts(self, data):
"""
Given a tag string, this function will parse any options out of it and
return a tuple of (tag_name, options_dict). Options may be quoted in order
to preserve spaces, and free-standing options are allowed. The tag name
itself may also serve as an o... | python | def _parse_opts(self, data):
"""
Given a tag string, this function will parse any options out of it and
return a tuple of (tag_name, options_dict). Options may be quoted in order
to preserve spaces, and free-standing options are allowed. The tag name
itself may also serve as an o... | [
"def",
"_parse_opts",
"(",
"self",
",",
"data",
")",
":",
"name",
"=",
"None",
"try",
":",
"# OrderedDict is only available for 2.7+, so leave regular unsorted dicts as a fallback.",
"from",
"collections",
"import",
"OrderedDict",
"opts",
"=",
"OrderedDict",
"(",
")",
"... | Given a tag string, this function will parse any options out of it and
return a tuple of (tag_name, options_dict). Options may be quoted in order
to preserve spaces, and free-standing options are allowed. The tag name
itself may also serve as an option if it is immediately followed by an equal
... | [
"Given",
"a",
"tag",
"string",
"this",
"function",
"will",
"parse",
"any",
"options",
"out",
"of",
"it",
"and",
"return",
"a",
"tuple",
"of",
"(",
"tag_name",
"options_dict",
")",
".",
"Options",
"may",
"be",
"quoted",
"in",
"order",
"to",
"preserve",
"s... | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L246-L324 |
dcwatson/bbcode | bbcode.py | Parser._parse_tag | def _parse_tag(self, tag):
"""
Given a tag string (characters enclosed by []), this function will
parse any options and return a tuple of the form:
(valid, tag_name, closer, options)
"""
if not tag.startswith(self.tag_opener) or not tag.endswith(self.tag_closer) or ('... | python | def _parse_tag(self, tag):
"""
Given a tag string (characters enclosed by []), this function will
parse any options and return a tuple of the form:
(valid, tag_name, closer, options)
"""
if not tag.startswith(self.tag_opener) or not tag.endswith(self.tag_closer) or ('... | [
"def",
"_parse_tag",
"(",
"self",
",",
"tag",
")",
":",
"if",
"not",
"tag",
".",
"startswith",
"(",
"self",
".",
"tag_opener",
")",
"or",
"not",
"tag",
".",
"endswith",
"(",
"self",
".",
"tag_closer",
")",
"or",
"(",
"'\\n'",
"in",
"tag",
")",
"or"... | Given a tag string (characters enclosed by []), this function will
parse any options and return a tuple of the form:
(valid, tag_name, closer, options) | [
"Given",
"a",
"tag",
"string",
"(",
"characters",
"enclosed",
"by",
"[]",
")",
"this",
"function",
"will",
"parse",
"any",
"options",
"and",
"return",
"a",
"tuple",
"of",
"the",
"form",
":",
"(",
"valid",
"tag_name",
"closer",
"options",
")"
] | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L326-L345 |
dcwatson/bbcode | bbcode.py | Parser._tag_extent | def _tag_extent(self, data, start):
"""
Finds the extent of a tag, accounting for option quoting and new tags starting before the current one closes.
Returns (found_close, end_pos) where valid is False if another tag started before this one closed.
"""
in_quote = False
qu... | python | def _tag_extent(self, data, start):
"""
Finds the extent of a tag, accounting for option quoting and new tags starting before the current one closes.
Returns (found_close, end_pos) where valid is False if another tag started before this one closed.
"""
in_quote = False
qu... | [
"def",
"_tag_extent",
"(",
"self",
",",
"data",
",",
"start",
")",
":",
"in_quote",
"=",
"False",
"quotable",
"=",
"False",
"lto",
"=",
"len",
"(",
"self",
".",
"tag_opener",
")",
"ltc",
"=",
"len",
"(",
"self",
".",
"tag_closer",
")",
"for",
"i",
... | Finds the extent of a tag, accounting for option quoting and new tags starting before the current one closes.
Returns (found_close, end_pos) where valid is False if another tag started before this one closed. | [
"Finds",
"the",
"extent",
"of",
"a",
"tag",
"accounting",
"for",
"option",
"quoting",
"and",
"new",
"tags",
"starting",
"before",
"the",
"current",
"one",
"closes",
".",
"Returns",
"(",
"found_close",
"end_pos",
")",
"where",
"valid",
"is",
"False",
"if",
... | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L347-L370 |
dcwatson/bbcode | bbcode.py | Parser.tokenize | def tokenize(self, data):
"""
Tokenizes the given string. A token is a 4-tuple of the form:
(token_type, tag_name, tag_options, token_text)
token_type
One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA
tag_name
The name... | python | def tokenize(self, data):
"""
Tokenizes the given string. A token is a 4-tuple of the form:
(token_type, tag_name, tag_options, token_text)
token_type
One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA
tag_name
The name... | [
"def",
"tokenize",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"replace",
"(",
"'\\r\\n'",
",",
"'\\n'",
")",
".",
"replace",
"(",
"'\\r'",
",",
"'\\n'",
")",
"pos",
"=",
"start",
"=",
"end",
"=",
"0",
"ld",
"=",
"len",
"(",
"... | Tokenizes the given string. A token is a 4-tuple of the form:
(token_type, tag_name, tag_options, token_text)
token_type
One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA
tag_name
The name of the tag if token_type=TOKEN_TAG_*, otherwi... | [
"Tokenizes",
"the",
"given",
"string",
".",
"A",
"token",
"is",
"a",
"4",
"-",
"tuple",
"of",
"the",
"form",
":"
] | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L372-L426 |
dcwatson/bbcode | bbcode.py | Parser._find_closing_token | def _find_closing_token(self, tag, tokens, pos):
"""
Given the current tag options, a list of tokens, and the current position
in the token list, this function will find the position of the closing token
associated with the specified tag. This may be a closing tag, a newline, or
... | python | def _find_closing_token(self, tag, tokens, pos):
"""
Given the current tag options, a list of tokens, and the current position
in the token list, this function will find the position of the closing token
associated with the specified tag. This may be a closing tag, a newline, or
... | [
"def",
"_find_closing_token",
"(",
"self",
",",
"tag",
",",
"tokens",
",",
"pos",
")",
":",
"embed_count",
"=",
"0",
"block_count",
"=",
"0",
"lt",
"=",
"len",
"(",
"tokens",
")",
"while",
"pos",
"<",
"lt",
":",
"token_type",
",",
"tag_name",
",",
"t... | Given the current tag options, a list of tokens, and the current position
in the token list, this function will find the position of the closing token
associated with the specified tag. This may be a closing tag, a newline, or
simply the end of the list (to ensure tags are closed). This function... | [
"Given",
"the",
"current",
"tag",
"options",
"a",
"list",
"of",
"tokens",
"and",
"the",
"current",
"position",
"in",
"the",
"token",
"list",
"this",
"function",
"will",
"find",
"the",
"position",
"of",
"the",
"closing",
"token",
"associated",
"with",
"the",
... | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L428-L471 |
dcwatson/bbcode | bbcode.py | Parser._link_replace | def _link_replace(self, match, **context):
"""
Callback for re.sub to replace link text with markup. Turns out using a callback function
is actually faster than using backrefs, plus this lets us provide a hook for user customization.
linker_takes_context=True means that the linker gets p... | python | def _link_replace(self, match, **context):
"""
Callback for re.sub to replace link text with markup. Turns out using a callback function
is actually faster than using backrefs, plus this lets us provide a hook for user customization.
linker_takes_context=True means that the linker gets p... | [
"def",
"_link_replace",
"(",
"self",
",",
"match",
",",
"*",
"*",
"context",
")",
":",
"url",
"=",
"match",
".",
"group",
"(",
"0",
")",
"if",
"self",
".",
"linker",
":",
"if",
"self",
".",
"linker_takes_context",
":",
"return",
"self",
".",
"linker"... | Callback for re.sub to replace link text with markup. Turns out using a callback function
is actually faster than using backrefs, plus this lets us provide a hook for user customization.
linker_takes_context=True means that the linker gets passed context like a standard format function. | [
"Callback",
"for",
"re",
".",
"sub",
"to",
"replace",
"link",
"text",
"with",
"markup",
".",
"Turns",
"out",
"using",
"a",
"callback",
"function",
"is",
"actually",
"faster",
"than",
"using",
"backrefs",
"plus",
"this",
"lets",
"us",
"provide",
"a",
"hook"... | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L473-L490 |
dcwatson/bbcode | bbcode.py | Parser._transform | def _transform(self, data, escape_html, replace_links, replace_cosmetic, transform_newlines, **context):
"""
Transforms the input string based on the options specified, taking into account
whether the option is enabled globally for this parser.
"""
url_matches = {}
if sel... | python | def _transform(self, data, escape_html, replace_links, replace_cosmetic, transform_newlines, **context):
"""
Transforms the input string based on the options specified, taking into account
whether the option is enabled globally for this parser.
"""
url_matches = {}
if sel... | [
"def",
"_transform",
"(",
"self",
",",
"data",
",",
"escape_html",
",",
"replace_links",
",",
"replace_cosmetic",
",",
"transform_newlines",
",",
"*",
"*",
"context",
")",
":",
"url_matches",
"=",
"{",
"}",
"if",
"self",
".",
"replace_links",
"and",
"replace... | Transforms the input string based on the options specified, taking into account
whether the option is enabled globally for this parser. | [
"Transforms",
"the",
"input",
"string",
"based",
"on",
"the",
"options",
"specified",
"taking",
"into",
"account",
"whether",
"the",
"option",
"is",
"enabled",
"globally",
"for",
"this",
"parser",
"."
] | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L492-L523 |
dcwatson/bbcode | bbcode.py | Parser.format | def format(self, data, **context):
"""
Formats the input text using any installed renderers. Any context keyword arguments
given here will be passed along to the render functions as a context dictionary.
"""
tokens = self.tokenize(data)
full_context = self.default_context... | python | def format(self, data, **context):
"""
Formats the input text using any installed renderers. Any context keyword arguments
given here will be passed along to the render functions as a context dictionary.
"""
tokens = self.tokenize(data)
full_context = self.default_context... | [
"def",
"format",
"(",
"self",
",",
"data",
",",
"*",
"*",
"context",
")",
":",
"tokens",
"=",
"self",
".",
"tokenize",
"(",
"data",
")",
"full_context",
"=",
"self",
".",
"default_context",
".",
"copy",
"(",
")",
"full_context",
".",
"update",
"(",
"... | Formats the input text using any installed renderers. Any context keyword arguments
given here will be passed along to the render functions as a context dictionary. | [
"Formats",
"the",
"input",
"text",
"using",
"any",
"installed",
"renderers",
".",
"Any",
"context",
"keyword",
"arguments",
"given",
"here",
"will",
"be",
"passed",
"along",
"to",
"the",
"render",
"functions",
"as",
"a",
"context",
"dictionary",
"."
] | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L578-L586 |
dcwatson/bbcode | bbcode.py | Parser.strip | def strip(self, data, strip_newlines=False):
"""
Strips out any tags from the input text, using the same tokenization as the formatter.
"""
text = []
for token_type, tag_name, tag_opts, token_text in self.tokenize(data):
if token_type == self.TOKEN_DATA:
... | python | def strip(self, data, strip_newlines=False):
"""
Strips out any tags from the input text, using the same tokenization as the formatter.
"""
text = []
for token_type, tag_name, tag_opts, token_text in self.tokenize(data):
if token_type == self.TOKEN_DATA:
... | [
"def",
"strip",
"(",
"self",
",",
"data",
",",
"strip_newlines",
"=",
"False",
")",
":",
"text",
"=",
"[",
"]",
"for",
"token_type",
",",
"tag_name",
",",
"tag_opts",
",",
"token_text",
"in",
"self",
".",
"tokenize",
"(",
"data",
")",
":",
"if",
"tok... | Strips out any tags from the input text, using the same tokenization as the formatter. | [
"Strips",
"out",
"any",
"tags",
"from",
"the",
"input",
"text",
"using",
"the",
"same",
"tokenization",
"as",
"the",
"formatter",
"."
] | train | https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L588-L598 |
astroML/gatspy | gatspy/periodic/naive_multiband.py | mode_in_range | def mode_in_range(a, axis=0, tol=1E-3):
"""Find the mode of values to within a certain range"""
a_trunc = a // tol
vals, counts = mode(a_trunc, axis)
mask = (a_trunc == vals)
# mean of each row
return np.sum(a * mask, axis) / np.sum(mask, axis) | python | def mode_in_range(a, axis=0, tol=1E-3):
"""Find the mode of values to within a certain range"""
a_trunc = a // tol
vals, counts = mode(a_trunc, axis)
mask = (a_trunc == vals)
# mean of each row
return np.sum(a * mask, axis) / np.sum(mask, axis) | [
"def",
"mode_in_range",
"(",
"a",
",",
"axis",
"=",
"0",
",",
"tol",
"=",
"1E-3",
")",
":",
"a_trunc",
"=",
"a",
"//",
"tol",
"vals",
",",
"counts",
"=",
"mode",
"(",
"a_trunc",
",",
"axis",
")",
"mask",
"=",
"(",
"a_trunc",
"==",
"vals",
")",
... | Find the mode of values to within a certain range | [
"Find",
"the",
"mode",
"of",
"values",
"to",
"within",
"a",
"certain",
"range"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/naive_multiband.py#L18-L24 |
astroML/gatspy | gatspy/periodic/naive_multiband.py | NaiveMultiband.scores | def scores(self, periods):
"""Compute the scores under the various models
Parameters
----------
periods : array_like
array of periods at which to compute scores
Returns
-------
scores : dict
Dictionary of scores. Dictionary keys are the u... | python | def scores(self, periods):
"""Compute the scores under the various models
Parameters
----------
periods : array_like
array of periods at which to compute scores
Returns
-------
scores : dict
Dictionary of scores. Dictionary keys are the u... | [
"def",
"scores",
"(",
"self",
",",
"periods",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"filt",
",",
"model",
".",
"score",
"(",
"periods",
")",
")",
"for",
"(",
"filt",
",",
"model",
")",
"in",
"self",
".",
"models_",
".",
"items",
"(",
")",
... | Compute the scores under the various models
Parameters
----------
periods : array_like
array of periods at which to compute scores
Returns
-------
scores : dict
Dictionary of scores. Dictionary keys are the unique filter names
passed ... | [
"Compute",
"the",
"scores",
"under",
"the",
"various",
"models"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/naive_multiband.py#L78-L93 |
astroML/gatspy | gatspy/periodic/naive_multiband.py | NaiveMultiband.best_periods | def best_periods(self):
"""Compute the scores under the various models
Parameters
----------
periods : array_like
array of periods at which to compute scores
Returns
-------
best_periods : dict
Dictionary of best periods. Dictionary keys ... | python | def best_periods(self):
"""Compute the scores under the various models
Parameters
----------
periods : array_like
array of periods at which to compute scores
Returns
-------
best_periods : dict
Dictionary of best periods. Dictionary keys ... | [
"def",
"best_periods",
"(",
"self",
")",
":",
"for",
"(",
"key",
",",
"model",
")",
"in",
"self",
".",
"models_",
".",
"items",
"(",
")",
":",
"model",
".",
"optimizer",
"=",
"self",
".",
"optimizer",
"return",
"dict",
"(",
"(",
"filt",
",",
"model... | Compute the scores under the various models
Parameters
----------
periods : array_like
array of periods at which to compute scores
Returns
-------
best_periods : dict
Dictionary of best periods. Dictionary keys are the unique filter
n... | [
"Compute",
"the",
"scores",
"under",
"the",
"various",
"models"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/naive_multiband.py#L95-L113 |
astroML/gatspy | gatspy/periodic/modeler.py | PeriodicModeler.fit | def fit(self, t, y, dy=None):
"""Fit the multiterm Periodogram model to the data.
Parameters
----------
t : array_like, one-dimensional
sequence of observation times
y : array_like, one-dimensional
sequence of observed values
dy : float or array_l... | python | def fit(self, t, y, dy=None):
"""Fit the multiterm Periodogram model to the data.
Parameters
----------
t : array_like, one-dimensional
sequence of observation times
y : array_like, one-dimensional
sequence of observed values
dy : float or array_l... | [
"def",
"fit",
"(",
"self",
",",
"t",
",",
"y",
",",
"dy",
"=",
"None",
")",
":",
"# For linear models, dy=1 is equivalent to no errors",
"if",
"dy",
"is",
"None",
":",
"dy",
"=",
"1",
"self",
".",
"t",
",",
"self",
".",
"y",
",",
"self",
".",
"dy",
... | Fit the multiterm Periodogram model to the data.
Parameters
----------
t : array_like, one-dimensional
sequence of observation times
y : array_like, one-dimensional
sequence of observed values
dy : float or array_like (optional)
errors on obse... | [
"Fit",
"the",
"multiterm",
"Periodogram",
"model",
"to",
"the",
"data",
"."
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L27-L51 |
astroML/gatspy | gatspy/periodic/modeler.py | PeriodicModeler.predict | def predict(self, t, period=None):
"""Compute the best-fit model at ``t`` for a given period
Parameters
----------
t : float or array_like
times at which to predict
period : float (optional)
The period at which to compute the model. If not specified, it
... | python | def predict(self, t, period=None):
"""Compute the best-fit model at ``t`` for a given period
Parameters
----------
t : float or array_like
times at which to predict
period : float (optional)
The period at which to compute the model. If not specified, it
... | [
"def",
"predict",
"(",
"self",
",",
"t",
",",
"period",
"=",
"None",
")",
":",
"t",
"=",
"np",
".",
"asarray",
"(",
"t",
")",
"if",
"period",
"is",
"None",
":",
"period",
"=",
"self",
".",
"best_period",
"result",
"=",
"self",
".",
"_predict",
"(... | Compute the best-fit model at ``t`` for a given period
Parameters
----------
t : float or array_like
times at which to predict
period : float (optional)
The period at which to compute the model. If not specified, it
will be computed via the optimizer ... | [
"Compute",
"the",
"best",
"-",
"fit",
"model",
"at",
"t",
"for",
"a",
"given",
"period"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L53-L73 |
astroML/gatspy | gatspy/periodic/modeler.py | PeriodicModeler.score_frequency_grid | def score_frequency_grid(self, f0, df, N):
"""Compute the score on a frequency grid.
Some models can compute results faster if the inputs are passed in this
manner.
Parameters
----------
f0, df, N : (float, float, int)
parameters describing the frequency gri... | python | def score_frequency_grid(self, f0, df, N):
"""Compute the score on a frequency grid.
Some models can compute results faster if the inputs are passed in this
manner.
Parameters
----------
f0, df, N : (float, float, int)
parameters describing the frequency gri... | [
"def",
"score_frequency_grid",
"(",
"self",
",",
"f0",
",",
"df",
",",
"N",
")",
":",
"return",
"self",
".",
"_score_frequency_grid",
"(",
"f0",
",",
"df",
",",
"N",
")"
] | Compute the score on a frequency grid.
Some models can compute results faster if the inputs are passed in this
manner.
Parameters
----------
f0, df, N : (float, float, int)
parameters describing the frequency grid freq = f0 + df * arange(N)
Note that the... | [
"Compute",
"the",
"score",
"on",
"a",
"frequency",
"grid",
"."
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L75-L92 |
astroML/gatspy | gatspy/periodic/modeler.py | PeriodicModeler.periodogram_auto | def periodogram_auto(self, oversampling=5, nyquist_factor=3,
return_periods=True):
"""Compute the periodogram on an automatically-determined grid
This function uses heuristic arguments to choose a suitable frequency
grid for the data. Note that depending on the data win... | python | def periodogram_auto(self, oversampling=5, nyquist_factor=3,
return_periods=True):
"""Compute the periodogram on an automatically-determined grid
This function uses heuristic arguments to choose a suitable frequency
grid for the data. Note that depending on the data win... | [
"def",
"periodogram_auto",
"(",
"self",
",",
"oversampling",
"=",
"5",
",",
"nyquist_factor",
"=",
"3",
",",
"return_periods",
"=",
"True",
")",
":",
"N",
"=",
"len",
"(",
"self",
".",
"t",
")",
"T",
"=",
"np",
".",
"max",
"(",
"self",
".",
"t",
... | Compute the periodogram on an automatically-determined grid
This function uses heuristic arguments to choose a suitable frequency
grid for the data. Note that depending on the data window function,
the model may be sensitive to periodicity at higher frequencies than
this function return... | [
"Compute",
"the",
"periodogram",
"on",
"an",
"automatically",
"-",
"determined",
"grid"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L94-L127 |
astroML/gatspy | gatspy/periodic/modeler.py | PeriodicModeler.score | def score(self, periods=None):
"""Compute the periodogram for the given period or periods
Parameters
----------
periods : float or array_like
Array of periods at which to compute the periodogram.
Returns
-------
scores : np.ndarray
Array ... | python | def score(self, periods=None):
"""Compute the periodogram for the given period or periods
Parameters
----------
periods : float or array_like
Array of periods at which to compute the periodogram.
Returns
-------
scores : np.ndarray
Array ... | [
"def",
"score",
"(",
"self",
",",
"periods",
"=",
"None",
")",
":",
"periods",
"=",
"np",
".",
"asarray",
"(",
"periods",
")",
"return",
"self",
".",
"_score",
"(",
"periods",
".",
"ravel",
"(",
")",
")",
".",
"reshape",
"(",
"periods",
".",
"shape... | Compute the periodogram for the given period or periods
Parameters
----------
periods : float or array_like
Array of periods at which to compute the periodogram.
Returns
-------
scores : np.ndarray
Array of normalized powers (between 0 and 1) for... | [
"Compute",
"the",
"periodogram",
"for",
"the",
"given",
"period",
"or",
"periods"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L129-L144 |
astroML/gatspy | gatspy/periodic/modeler.py | PeriodicModeler.best_period | def best_period(self):
"""Lazy evaluation of the best period given the model"""
if self._best_period is None:
self._best_period = self._calc_best_period()
return self._best_period | python | def best_period(self):
"""Lazy evaluation of the best period given the model"""
if self._best_period is None:
self._best_period = self._calc_best_period()
return self._best_period | [
"def",
"best_period",
"(",
"self",
")",
":",
"if",
"self",
".",
"_best_period",
"is",
"None",
":",
"self",
".",
"_best_period",
"=",
"self",
".",
"_calc_best_period",
"(",
")",
"return",
"self",
".",
"_best_period"
] | Lazy evaluation of the best period given the model | [
"Lazy",
"evaluation",
"of",
"the",
"best",
"period",
"given",
"the",
"model"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L149-L153 |
astroML/gatspy | gatspy/periodic/modeler.py | PeriodicModeler.find_best_periods | def find_best_periods(self, n_periods=5, return_scores=False):
"""Find the top several best periods for the model"""
return self.optimizer.find_best_periods(self, n_periods,
return_scores=return_scores) | python | def find_best_periods(self, n_periods=5, return_scores=False):
"""Find the top several best periods for the model"""
return self.optimizer.find_best_periods(self, n_periods,
return_scores=return_scores) | [
"def",
"find_best_periods",
"(",
"self",
",",
"n_periods",
"=",
"5",
",",
"return_scores",
"=",
"False",
")",
":",
"return",
"self",
".",
"optimizer",
".",
"find_best_periods",
"(",
"self",
",",
"n_periods",
",",
"return_scores",
"=",
"return_scores",
")"
] | Find the top several best periods for the model | [
"Find",
"the",
"top",
"several",
"best",
"periods",
"for",
"the",
"model"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L155-L158 |
astroML/gatspy | gatspy/periodic/modeler.py | PeriodicModelerMultiband.fit | def fit(self, t, y, dy=None, filts=0):
"""Fit the multiterm Periodogram model to the data.
Parameters
----------
t : array_like, one-dimensional
sequence of observation times
y : array_like, one-dimensional
sequence of observed values
dy : float o... | python | def fit(self, t, y, dy=None, filts=0):
"""Fit the multiterm Periodogram model to the data.
Parameters
----------
t : array_like, one-dimensional
sequence of observation times
y : array_like, one-dimensional
sequence of observed values
dy : float o... | [
"def",
"fit",
"(",
"self",
",",
"t",
",",
"y",
",",
"dy",
"=",
"None",
",",
"filts",
"=",
"0",
")",
":",
"self",
".",
"unique_filts_",
"=",
"np",
".",
"unique",
"(",
"filts",
")",
"# For linear models, dy=1 is equivalent to no errors",
"if",
"dy",
"is",
... | Fit the multiterm Periodogram model to the data.
Parameters
----------
t : array_like, one-dimensional
sequence of observation times
y : array_like, one-dimensional
sequence of observed values
dy : float or array_like (optional)
errors on obse... | [
"Fit",
"the",
"multiterm",
"Periodogram",
"model",
"to",
"the",
"data",
"."
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L186-L214 |
astroML/gatspy | gatspy/periodic/modeler.py | PeriodicModelerMultiband.predict | def predict(self, t, filts, period=None):
"""Compute the best-fit model at ``t`` for a given period
Parameters
----------
t : float or array_like
times at which to predict
filts : array_like (optional)
the array specifying the filter/bandpass for each obs... | python | def predict(self, t, filts, period=None):
"""Compute the best-fit model at ``t`` for a given period
Parameters
----------
t : float or array_like
times at which to predict
filts : array_like (optional)
the array specifying the filter/bandpass for each obs... | [
"def",
"predict",
"(",
"self",
",",
"t",
",",
"filts",
",",
"period",
"=",
"None",
")",
":",
"unique_filts",
"=",
"set",
"(",
"np",
".",
"unique",
"(",
"filts",
")",
")",
"if",
"not",
"unique_filts",
".",
"issubset",
"(",
"self",
".",
"unique_filts_"... | Compute the best-fit model at ``t`` for a given period
Parameters
----------
t : float or array_like
times at which to predict
filts : array_like (optional)
the array specifying the filter/bandpass for each observation. This
is used only in multiband ... | [
"Compute",
"the",
"best",
"-",
"fit",
"model",
"at",
"t",
"for",
"a",
"given",
"period"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L216-L247 |
astroML/gatspy | gatspy/periodic/_least_squares_mixin.py | LeastSquaresMixin._construct_X_M | def _construct_X_M(self, omega, **kwargs):
"""Construct the weighted normal matrix of the problem"""
X = self._construct_X(omega, weighted=True, **kwargs)
M = np.dot(X.T, X)
if getattr(self, 'regularization', None) is not None:
diag = M.ravel(order='K')[::M.shape[0] + 1]
... | python | def _construct_X_M(self, omega, **kwargs):
"""Construct the weighted normal matrix of the problem"""
X = self._construct_X(omega, weighted=True, **kwargs)
M = np.dot(X.T, X)
if getattr(self, 'regularization', None) is not None:
diag = M.ravel(order='K')[::M.shape[0] + 1]
... | [
"def",
"_construct_X_M",
"(",
"self",
",",
"omega",
",",
"*",
"*",
"kwargs",
")",
":",
"X",
"=",
"self",
".",
"_construct_X",
"(",
"omega",
",",
"weighted",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"M",
"=",
"np",
".",
"dot",
"(",
"X",
".",
"... | Construct the weighted normal matrix of the problem | [
"Construct",
"the",
"weighted",
"normal",
"matrix",
"of",
"the",
"problem"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/_least_squares_mixin.py#L11-L23 |
astroML/gatspy | gatspy/periodic/_least_squares_mixin.py | LeastSquaresMixin._compute_ymean | def _compute_ymean(self, **kwargs):
"""Compute the (weighted) mean of the y data"""
y = np.asarray(kwargs.get('y', self.y))
dy = np.asarray(kwargs.get('dy', self.dy))
if dy.size == 1:
return np.mean(y)
else:
return np.average(y, weights=1 / dy ** 2) | python | def _compute_ymean(self, **kwargs):
"""Compute the (weighted) mean of the y data"""
y = np.asarray(kwargs.get('y', self.y))
dy = np.asarray(kwargs.get('dy', self.dy))
if dy.size == 1:
return np.mean(y)
else:
return np.average(y, weights=1 / dy ** 2) | [
"def",
"_compute_ymean",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"y",
"=",
"np",
".",
"asarray",
"(",
"kwargs",
".",
"get",
"(",
"'y'",
",",
"self",
".",
"y",
")",
")",
"dy",
"=",
"np",
".",
"asarray",
"(",
"kwargs",
".",
"get",
"(",
... | Compute the (weighted) mean of the y data | [
"Compute",
"the",
"(",
"weighted",
")",
"mean",
"of",
"the",
"y",
"data"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/_least_squares_mixin.py#L25-L33 |
astroML/gatspy | gatspy/periodic/lomb_scargle.py | LombScargle._construct_X | def _construct_X(self, omega, weighted=True, **kwargs):
"""Construct the design matrix for the problem"""
t = kwargs.get('t', self.t)
dy = kwargs.get('dy', self.dy)
fit_offset = kwargs.get('fit_offset', self.fit_offset)
if fit_offset:
offsets = [np.ones(len(t))]
... | python | def _construct_X(self, omega, weighted=True, **kwargs):
"""Construct the design matrix for the problem"""
t = kwargs.get('t', self.t)
dy = kwargs.get('dy', self.dy)
fit_offset = kwargs.get('fit_offset', self.fit_offset)
if fit_offset:
offsets = [np.ones(len(t))]
... | [
"def",
"_construct_X",
"(",
"self",
",",
"omega",
",",
"weighted",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"t",
"=",
"kwargs",
".",
"get",
"(",
"'t'",
",",
"self",
".",
"t",
")",
"dy",
"=",
"kwargs",
".",
"get",
"(",
"'dy'",
",",
"self"... | Construct the design matrix for the problem | [
"Construct",
"the",
"design",
"matrix",
"for",
"the",
"problem"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle.py#L92-L110 |
astroML/gatspy | gatspy/periodic/template_modeler.py | BaseTemplateModeler._interpolated_template | def _interpolated_template(self, templateid):
"""Return an interpolator for the given template"""
phase, y = self._get_template_by_id(templateid)
# double-check that phase ranges from 0 to 1
assert phase.min() >= 0
assert phase.max() <= 1
# at the start and end points, ... | python | def _interpolated_template(self, templateid):
"""Return an interpolator for the given template"""
phase, y = self._get_template_by_id(templateid)
# double-check that phase ranges from 0 to 1
assert phase.min() >= 0
assert phase.max() <= 1
# at the start and end points, ... | [
"def",
"_interpolated_template",
"(",
"self",
",",
"templateid",
")",
":",
"phase",
",",
"y",
"=",
"self",
".",
"_get_template_by_id",
"(",
"templateid",
")",
"# double-check that phase ranges from 0 to 1",
"assert",
"phase",
".",
"min",
"(",
")",
">=",
"0",
"as... | Return an interpolator for the given template | [
"Return",
"an",
"interpolator",
"for",
"the",
"given",
"template"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L39-L53 |
astroML/gatspy | gatspy/periodic/template_modeler.py | BaseTemplateModeler._eval_templates | def _eval_templates(self, period):
"""Evaluate the best template for the given period"""
theta_best = [self._optimize(period, tmpid)
for tmpid, _ in enumerate(self.templates)]
chi2 = [self._chi2(theta, period, tmpid)
for tmpid, theta in enumerate(theta_best)... | python | def _eval_templates(self, period):
"""Evaluate the best template for the given period"""
theta_best = [self._optimize(period, tmpid)
for tmpid, _ in enumerate(self.templates)]
chi2 = [self._chi2(theta, period, tmpid)
for tmpid, theta in enumerate(theta_best)... | [
"def",
"_eval_templates",
"(",
"self",
",",
"period",
")",
":",
"theta_best",
"=",
"[",
"self",
".",
"_optimize",
"(",
"period",
",",
"tmpid",
")",
"for",
"tmpid",
",",
"_",
"in",
"enumerate",
"(",
"self",
".",
"templates",
")",
"]",
"chi2",
"=",
"["... | Evaluate the best template for the given period | [
"Evaluate",
"the",
"best",
"template",
"for",
"the",
"given",
"period"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L77-L84 |
astroML/gatspy | gatspy/periodic/template_modeler.py | BaseTemplateModeler._model | def _model(self, t, theta, period, tmpid):
"""Compute model at t for the given parameters, period, & template"""
template = self.templates[tmpid]
phase = (t / period - theta[2]) % 1
return theta[0] + theta[1] * template(phase) | python | def _model(self, t, theta, period, tmpid):
"""Compute model at t for the given parameters, period, & template"""
template = self.templates[tmpid]
phase = (t / period - theta[2]) % 1
return theta[0] + theta[1] * template(phase) | [
"def",
"_model",
"(",
"self",
",",
"t",
",",
"theta",
",",
"period",
",",
"tmpid",
")",
":",
"template",
"=",
"self",
".",
"templates",
"[",
"tmpid",
"]",
"phase",
"=",
"(",
"t",
"/",
"period",
"-",
"theta",
"[",
"2",
"]",
")",
"%",
"1",
"retur... | Compute model at t for the given parameters, period, & template | [
"Compute",
"model",
"at",
"t",
"for",
"the",
"given",
"parameters",
"period",
"&",
"template"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L86-L90 |
astroML/gatspy | gatspy/periodic/template_modeler.py | BaseTemplateModeler._chi2 | def _chi2(self, theta, period, tmpid, return_gradient=False):
"""
Compute the chi2 for the given parameters, period, & template
Optionally return the gradient for faster optimization
"""
template = self.templates[tmpid]
phase = (self.t / period - theta[2]) % 1
mo... | python | def _chi2(self, theta, period, tmpid, return_gradient=False):
"""
Compute the chi2 for the given parameters, period, & template
Optionally return the gradient for faster optimization
"""
template = self.templates[tmpid]
phase = (self.t / period - theta[2]) % 1
mo... | [
"def",
"_chi2",
"(",
"self",
",",
"theta",
",",
"period",
",",
"tmpid",
",",
"return_gradient",
"=",
"False",
")",
":",
"template",
"=",
"self",
".",
"templates",
"[",
"tmpid",
"]",
"phase",
"=",
"(",
"self",
".",
"t",
"/",
"period",
"-",
"theta",
... | Compute the chi2 for the given parameters, period, & template
Optionally return the gradient for faster optimization | [
"Compute",
"the",
"chi2",
"for",
"the",
"given",
"parameters",
"period",
"&",
"template"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L92-L111 |
astroML/gatspy | gatspy/periodic/template_modeler.py | BaseTemplateModeler._optimize | def _optimize(self, period, tmpid, use_gradient=True):
"""Optimize the model for the given period & template"""
theta_0 = [self.y.min(), self.y.max() - self.y.min(), 0]
result = minimize(self._chi2, theta_0, jac=bool(use_gradient),
bounds=[(None, None), (0, None), (None... | python | def _optimize(self, period, tmpid, use_gradient=True):
"""Optimize the model for the given period & template"""
theta_0 = [self.y.min(), self.y.max() - self.y.min(), 0]
result = minimize(self._chi2, theta_0, jac=bool(use_gradient),
bounds=[(None, None), (0, None), (None... | [
"def",
"_optimize",
"(",
"self",
",",
"period",
",",
"tmpid",
",",
"use_gradient",
"=",
"True",
")",
":",
"theta_0",
"=",
"[",
"self",
".",
"y",
".",
"min",
"(",
")",
",",
"self",
".",
"y",
".",
"max",
"(",
")",
"-",
"self",
".",
"y",
".",
"m... | Optimize the model for the given period & template | [
"Optimize",
"the",
"model",
"for",
"the",
"given",
"period",
"&",
"template"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L113-L119 |
astroML/gatspy | gatspy/periodic/optimizer.py | LinearScanOptimizer.find_best_periods | def find_best_periods(self, model, n_periods=5, return_scores=False):
"""Find the `n_periods` best periods in the model"""
# compute the estimated peak width from the data range
tmin, tmax = np.min(model.t), np.max(model.t)
width = 2 * np.pi / (tmax - tmin)
# raise a ValueError... | python | def find_best_periods(self, model, n_periods=5, return_scores=False):
"""Find the `n_periods` best periods in the model"""
# compute the estimated peak width from the data range
tmin, tmax = np.min(model.t), np.max(model.t)
width = 2 * np.pi / (tmax - tmin)
# raise a ValueError... | [
"def",
"find_best_periods",
"(",
"self",
",",
"model",
",",
"n_periods",
"=",
"5",
",",
"return_scores",
"=",
"False",
")",
":",
"# compute the estimated peak width from the data range",
"tmin",
",",
"tmax",
"=",
"np",
".",
"min",
"(",
"model",
".",
"t",
")",
... | Find the `n_periods` best periods in the model | [
"Find",
"the",
"n_periods",
"best",
"periods",
"in",
"the",
"model"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/optimizer.py#L74-L156 |
astroML/gatspy | gatspy/periodic/lomb_scargle_fast.py | factorial | def factorial(N):
"""Compute the factorial of N.
If N <= 10, use a fast lookup table; otherwise use scipy.special.factorial
"""
if N < len(FACTORIALS):
return FACTORIALS[N]
else:
from scipy import special
return int(special.factorial(N)) | python | def factorial(N):
"""Compute the factorial of N.
If N <= 10, use a fast lookup table; otherwise use scipy.special.factorial
"""
if N < len(FACTORIALS):
return FACTORIALS[N]
else:
from scipy import special
return int(special.factorial(N)) | [
"def",
"factorial",
"(",
"N",
")",
":",
"if",
"N",
"<",
"len",
"(",
"FACTORIALS",
")",
":",
"return",
"FACTORIALS",
"[",
"N",
"]",
"else",
":",
"from",
"scipy",
"import",
"special",
"return",
"int",
"(",
"special",
".",
"factorial",
"(",
"N",
")",
... | Compute the factorial of N.
If N <= 10, use a fast lookup table; otherwise use scipy.special.factorial | [
"Compute",
"the",
"factorial",
"of",
"N",
".",
"If",
"N",
"<",
"=",
"10",
"use",
"a",
"fast",
"lookup",
"table",
";",
"otherwise",
"use",
"scipy",
".",
"special",
".",
"factorial"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L17-L25 |
astroML/gatspy | gatspy/periodic/lomb_scargle_fast.py | bitceil | def bitceil(N):
"""
Find the bit (i.e. power of 2) immediately greater than or equal to N
Note: this works for numbers up to 2 ** 64.
Roughly equivalent to int(2 ** np.ceil(np.log2(N)))
"""
# Note: for Python 2.7 and 3.x, this is faster:
# return 1 << int(N - 1).bit_length()
N = int(N) ... | python | def bitceil(N):
"""
Find the bit (i.e. power of 2) immediately greater than or equal to N
Note: this works for numbers up to 2 ** 64.
Roughly equivalent to int(2 ** np.ceil(np.log2(N)))
"""
# Note: for Python 2.7 and 3.x, this is faster:
# return 1 << int(N - 1).bit_length()
N = int(N) ... | [
"def",
"bitceil",
"(",
"N",
")",
":",
"# Note: for Python 2.7 and 3.x, this is faster:",
"# return 1 << int(N - 1).bit_length()",
"N",
"=",
"int",
"(",
"N",
")",
"-",
"1",
"for",
"i",
"in",
"[",
"1",
",",
"2",
",",
"4",
",",
"8",
",",
"16",
",",
"32",
"]... | Find the bit (i.e. power of 2) immediately greater than or equal to N
Note: this works for numbers up to 2 ** 64.
Roughly equivalent to int(2 ** np.ceil(np.log2(N))) | [
"Find",
"the",
"bit",
"(",
"i",
".",
"e",
".",
"power",
"of",
"2",
")",
"immediately",
"greater",
"than",
"or",
"equal",
"to",
"N",
"Note",
":",
"this",
"works",
"for",
"numbers",
"up",
"to",
"2",
"**",
"64",
"."
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L28-L40 |
astroML/gatspy | gatspy/periodic/lomb_scargle_fast.py | extirpolate | def extirpolate(x, y, N=None, M=4):
"""
Extirpolate the values (x, y) onto an integer grid range(N),
using lagrange polynomial weights on the M nearest points.
Parameters
----------
x : array_like
array of abscissas
y : array_like
array of ordinates
N : int
numbe... | python | def extirpolate(x, y, N=None, M=4):
"""
Extirpolate the values (x, y) onto an integer grid range(N),
using lagrange polynomial weights on the M nearest points.
Parameters
----------
x : array_like
array of abscissas
y : array_like
array of ordinates
N : int
numbe... | [
"def",
"extirpolate",
"(",
"x",
",",
"y",
",",
"N",
"=",
"None",
",",
"M",
"=",
"4",
")",
":",
"x",
",",
"y",
"=",
"map",
"(",
"np",
".",
"ravel",
",",
"np",
".",
"broadcast_arrays",
"(",
"x",
",",
"y",
")",
")",
"if",
"N",
"is",
"None",
... | Extirpolate the values (x, y) onto an integer grid range(N),
using lagrange polynomial weights on the M nearest points.
Parameters
----------
x : array_like
array of abscissas
y : array_like
array of ordinates
N : int
number of integer bins to use. For best performance, ... | [
"Extirpolate",
"the",
"values",
"(",
"x",
"y",
")",
"onto",
"an",
"integer",
"grid",
"range",
"(",
"N",
")",
"using",
"lagrange",
"polynomial",
"weights",
"on",
"the",
"M",
"nearest",
"points",
"."
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L43-L107 |
astroML/gatspy | gatspy/periodic/lomb_scargle_fast.py | trig_sum | def trig_sum(t, h, df, N, f0=0, freq_factor=1,
oversampling=5, use_fft=True, Mfft=4):
"""Compute (approximate) trigonometric sums for a number of frequencies
This routine computes weighted sine and cosine sums:
S_j = sum_i { h_i * sin(2 pi * f_j * t_i) }
C_j = sum_i { h_i * cos(2 ... | python | def trig_sum(t, h, df, N, f0=0, freq_factor=1,
oversampling=5, use_fft=True, Mfft=4):
"""Compute (approximate) trigonometric sums for a number of frequencies
This routine computes weighted sine and cosine sums:
S_j = sum_i { h_i * sin(2 pi * f_j * t_i) }
C_j = sum_i { h_i * cos(2 ... | [
"def",
"trig_sum",
"(",
"t",
",",
"h",
",",
"df",
",",
"N",
",",
"f0",
"=",
"0",
",",
"freq_factor",
"=",
"1",
",",
"oversampling",
"=",
"5",
",",
"use_fft",
"=",
"True",
",",
"Mfft",
"=",
"4",
")",
":",
"df",
"*=",
"freq_factor",
"f0",
"*=",
... | Compute (approximate) trigonometric sums for a number of frequencies
This routine computes weighted sine and cosine sums:
S_j = sum_i { h_i * sin(2 pi * f_j * t_i) }
C_j = sum_i { h_i * cos(2 pi * f_j * t_i) }
Where f_j = freq_factor * (f0 + j * df) for the values j in 1 ... N.
The sums c... | [
"Compute",
"(",
"approximate",
")",
"trigonometric",
"sums",
"for",
"a",
"number",
"of",
"frequencies"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L110-L187 |
astroML/gatspy | gatspy/periodic/lomb_scargle_fast.py | lomb_scargle_fast | def lomb_scargle_fast(t, y, dy=1, f0=0, df=None, Nf=None,
center_data=True, fit_offset=True,
use_fft=True, freq_oversampling=5, nyquist_factor=2,
trig_sum_kwds=None):
"""Compute a lomb-scargle periodogram for the given data
This implements both ... | python | def lomb_scargle_fast(t, y, dy=1, f0=0, df=None, Nf=None,
center_data=True, fit_offset=True,
use_fft=True, freq_oversampling=5, nyquist_factor=2,
trig_sum_kwds=None):
"""Compute a lomb-scargle periodogram for the given data
This implements both ... | [
"def",
"lomb_scargle_fast",
"(",
"t",
",",
"y",
",",
"dy",
"=",
"1",
",",
"f0",
"=",
"0",
",",
"df",
"=",
"None",
",",
"Nf",
"=",
"None",
",",
"center_data",
"=",
"True",
",",
"fit_offset",
"=",
"True",
",",
"use_fft",
"=",
"True",
",",
"freq_ove... | Compute a lomb-scargle periodogram for the given data
This implements both an O[N^2] method if use_fft==False, or an
O[NlogN] method if use_fft==True.
Parameters
----------
t, y, dy : array_like
times, values, and errors of the data points. These should be
broadcastable to the same... | [
"Compute",
"a",
"lomb",
"-",
"scargle",
"periodogram",
"for",
"the",
"given",
"data"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L190-L330 |
astroML/gatspy | gatspy/datasets/rrlyrae_generated.py | RRLyraeGenerated.observed | def observed(self, band, corrected=True):
"""Return observed values in the given band
Parameters
----------
band : str
desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z']
corrected : bool (optional)
If true, correct for extinction
Return... | python | def observed(self, band, corrected=True):
"""Return observed values in the given band
Parameters
----------
band : str
desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z']
corrected : bool (optional)
If true, correct for extinction
Return... | [
"def",
"observed",
"(",
"self",
",",
"band",
",",
"corrected",
"=",
"True",
")",
":",
"if",
"band",
"not",
"in",
"'ugriz'",
":",
"raise",
"ValueError",
"(",
"\"band='{0}' not recognized\"",
".",
"format",
"(",
"band",
")",
")",
"i",
"=",
"'ugriz'",
".",
... | Return observed values in the given band
Parameters
----------
band : str
desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z']
corrected : bool (optional)
If true, correct for extinction
Returns
-------
t, mag, dmag : ndarrays
... | [
"Return",
"observed",
"values",
"in",
"the",
"given",
"band"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae_generated.py#L77-L102 |
astroML/gatspy | gatspy/datasets/rrlyrae_generated.py | RRLyraeGenerated.generated | def generated(self, band, t, err=None, corrected=True):
"""Return generated magnitudes in the specified band
Parameters
----------
band : str
desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z']
t : array_like
array of times (in days)
err ... | python | def generated(self, band, t, err=None, corrected=True):
"""Return generated magnitudes in the specified band
Parameters
----------
band : str
desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z']
t : array_like
array of times (in days)
err ... | [
"def",
"generated",
"(",
"self",
",",
"band",
",",
"t",
",",
"err",
"=",
"None",
",",
"corrected",
"=",
"True",
")",
":",
"t",
"=",
"np",
".",
"asarray",
"(",
"t",
")",
"num",
"=",
"self",
".",
"meta",
"[",
"band",
"+",
"'T'",
"]",
"mu",
"=",... | Return generated magnitudes in the specified band
Parameters
----------
band : str
desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z']
t : array_like
array of times (in days)
err : float or array_like
gaussian error in observations
... | [
"Return",
"generated",
"magnitudes",
"in",
"the",
"specified",
"band"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae_generated.py#L104-L146 |
astroML/gatspy | gatspy/datasets/rrlyrae.py | _get_download_or_cache | def _get_download_or_cache(filename, data_home=None,
url=SESAR_RRLYRAE_URL,
force_download=False):
"""Private utility to download and/or load data from disk cache."""
# Import here so astroML is not required at package level
from astroML.datasets.tools i... | python | def _get_download_or_cache(filename, data_home=None,
url=SESAR_RRLYRAE_URL,
force_download=False):
"""Private utility to download and/or load data from disk cache."""
# Import here so astroML is not required at package level
from astroML.datasets.tools i... | [
"def",
"_get_download_or_cache",
"(",
"filename",
",",
"data_home",
"=",
"None",
",",
"url",
"=",
"SESAR_RRLYRAE_URL",
",",
"force_download",
"=",
"False",
")",
":",
"# Import here so astroML is not required at package level",
"from",
"astroML",
".",
"datasets",
".",
... | Private utility to download and/or load data from disk cache. | [
"Private",
"utility",
"to",
"download",
"and",
"/",
"or",
"load",
"data",
"from",
"disk",
"cache",
"."
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L28-L48 |
astroML/gatspy | gatspy/datasets/rrlyrae.py | fetch_rrlyrae | def fetch_rrlyrae(partial=False, **kwargs):
"""Fetch RR Lyrae light curves from Sesar 2010
Parameters
----------
partial : bool (optional)
If true, return the partial dataset (reduced to 1 band per night)
Returns
-------
rrlyrae : :class:`RRLyraeLC` object
This object conta... | python | def fetch_rrlyrae(partial=False, **kwargs):
"""Fetch RR Lyrae light curves from Sesar 2010
Parameters
----------
partial : bool (optional)
If true, return the partial dataset (reduced to 1 band per night)
Returns
-------
rrlyrae : :class:`RRLyraeLC` object
This object conta... | [
"def",
"fetch_rrlyrae",
"(",
"partial",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"partial",
":",
"return",
"PartialRRLyraeLC",
"(",
"'table1.tar.gz'",
",",
"cache_kwargs",
"=",
"kwargs",
")",
"else",
":",
"return",
"RRLyraeLC",
"(",
"'table1.ta... | Fetch RR Lyrae light curves from Sesar 2010
Parameters
----------
partial : bool (optional)
If true, return the partial dataset (reduced to 1 band per night)
Returns
-------
rrlyrae : :class:`RRLyraeLC` object
This object contains pointers to the RR Lyrae data.
Other Param... | [
"Fetch",
"RR",
"Lyrae",
"light",
"curves",
"from",
"Sesar",
"2010"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L343-L389 |
astroML/gatspy | gatspy/datasets/rrlyrae.py | fetch_rrlyrae_lc_params | def fetch_rrlyrae_lc_params(**kwargs):
"""Fetch data from table 2 of Sesar 2010
This table includes observationally-derived parameters for all the
Sesar 2010 lightcurves.
"""
save_loc = _get_download_or_cache('table2.dat.gz', **kwargs)
dtype = [('id', 'i'), ('type', 'S2'), ('P', 'f'),
... | python | def fetch_rrlyrae_lc_params(**kwargs):
"""Fetch data from table 2 of Sesar 2010
This table includes observationally-derived parameters for all the
Sesar 2010 lightcurves.
"""
save_loc = _get_download_or_cache('table2.dat.gz', **kwargs)
dtype = [('id', 'i'), ('type', 'S2'), ('P', 'f'),
... | [
"def",
"fetch_rrlyrae_lc_params",
"(",
"*",
"*",
"kwargs",
")",
":",
"save_loc",
"=",
"_get_download_or_cache",
"(",
"'table2.dat.gz'",
",",
"*",
"*",
"kwargs",
")",
"dtype",
"=",
"[",
"(",
"'id'",
",",
"'i'",
")",
",",
"(",
"'type'",
",",
"'S2'",
")",
... | Fetch data from table 2 of Sesar 2010
This table includes observationally-derived parameters for all the
Sesar 2010 lightcurves. | [
"Fetch",
"data",
"from",
"table",
"2",
"of",
"Sesar",
"2010"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L392-L407 |
astroML/gatspy | gatspy/datasets/rrlyrae.py | fetch_rrlyrae_fitdata | def fetch_rrlyrae_fitdata(**kwargs):
"""Fetch data from table 3 of Sesar 2010
This table includes parameters derived from template fits to all the
Sesar 2010 lightcurves.
"""
save_loc = _get_download_or_cache('table3.dat.gz', **kwargs)
dtype = [('id', 'i'), ('RA', 'f'), ('DEC', 'f'), ('rExt', ... | python | def fetch_rrlyrae_fitdata(**kwargs):
"""Fetch data from table 3 of Sesar 2010
This table includes parameters derived from template fits to all the
Sesar 2010 lightcurves.
"""
save_loc = _get_download_or_cache('table3.dat.gz', **kwargs)
dtype = [('id', 'i'), ('RA', 'f'), ('DEC', 'f'), ('rExt', ... | [
"def",
"fetch_rrlyrae_fitdata",
"(",
"*",
"*",
"kwargs",
")",
":",
"save_loc",
"=",
"_get_download_or_cache",
"(",
"'table3.dat.gz'",
",",
"*",
"*",
"kwargs",
")",
"dtype",
"=",
"[",
"(",
"'id'",
",",
"'i'",
")",
",",
"(",
"'RA'",
",",
"'f'",
")",
",",... | Fetch data from table 3 of Sesar 2010
This table includes parameters derived from template fits to all the
Sesar 2010 lightcurves. | [
"Fetch",
"data",
"from",
"table",
"3",
"of",
"Sesar",
"2010"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L410-L425 |
astroML/gatspy | gatspy/datasets/rrlyrae.py | RRLyraeLC.get_lightcurve | def get_lightcurve(self, star_id, return_1d=True):
"""Get the light curves for the given ID
Parameters
----------
star_id : int
A valid integer star id representing an object in the dataset
return_1d : boolean (default=True)
Specify whether to return 1D a... | python | def get_lightcurve(self, star_id, return_1d=True):
"""Get the light curves for the given ID
Parameters
----------
star_id : int
A valid integer star id representing an object in the dataset
return_1d : boolean (default=True)
Specify whether to return 1D a... | [
"def",
"get_lightcurve",
"(",
"self",
",",
"star_id",
",",
"return_1d",
"=",
"True",
")",
":",
"filename",
"=",
"'{0}/{1}.dat'",
".",
"format",
"(",
"self",
".",
"dirname",
",",
"star_id",
")",
"try",
":",
"data",
"=",
"np",
".",
"loadtxt",
"(",
"self"... | Get the light curves for the given ID
Parameters
----------
star_id : int
A valid integer star id representing an object in the dataset
return_1d : boolean (default=True)
Specify whether to return 1D arrays of (t, y, dy, filts) or
2D arrays of (t, y, ... | [
"Get",
"the",
"light",
"curves",
"for",
"the",
"given",
"ID"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L125-L173 |
astroML/gatspy | gatspy/datasets/rrlyrae.py | RRLyraeLC.get_metadata | def get_metadata(self, lcid):
"""Get the parameters derived from the fit for the given id.
This is table 2 of Sesar 2010
"""
if self._metadata is None:
self._metadata = fetch_rrlyrae_lc_params()
i = np.where(self._metadata['id'] == lcid)[0]
if len(i) == 0:
... | python | def get_metadata(self, lcid):
"""Get the parameters derived from the fit for the given id.
This is table 2 of Sesar 2010
"""
if self._metadata is None:
self._metadata = fetch_rrlyrae_lc_params()
i = np.where(self._metadata['id'] == lcid)[0]
if len(i) == 0:
... | [
"def",
"get_metadata",
"(",
"self",
",",
"lcid",
")",
":",
"if",
"self",
".",
"_metadata",
"is",
"None",
":",
"self",
".",
"_metadata",
"=",
"fetch_rrlyrae_lc_params",
"(",
")",
"i",
"=",
"np",
".",
"where",
"(",
"self",
".",
"_metadata",
"[",
"'id'",
... | Get the parameters derived from the fit for the given id.
This is table 2 of Sesar 2010 | [
"Get",
"the",
"parameters",
"derived",
"from",
"the",
"fit",
"for",
"the",
"given",
"id",
".",
"This",
"is",
"table",
"2",
"of",
"Sesar",
"2010"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L175-L184 |
astroML/gatspy | gatspy/datasets/rrlyrae.py | RRLyraeLC.get_obsmeta | def get_obsmeta(self, lcid):
"""Get the observation metadata for the given id.
This is table 3 of Sesar 2010
"""
if self._obsdata is None:
self._obsdata = fetch_rrlyrae_fitdata()
i = np.where(self._obsdata['id'] == lcid)[0]
if len(i) == 0:
raise Va... | python | def get_obsmeta(self, lcid):
"""Get the observation metadata for the given id.
This is table 3 of Sesar 2010
"""
if self._obsdata is None:
self._obsdata = fetch_rrlyrae_fitdata()
i = np.where(self._obsdata['id'] == lcid)[0]
if len(i) == 0:
raise Va... | [
"def",
"get_obsmeta",
"(",
"self",
",",
"lcid",
")",
":",
"if",
"self",
".",
"_obsdata",
"is",
"None",
":",
"self",
".",
"_obsdata",
"=",
"fetch_rrlyrae_fitdata",
"(",
")",
"i",
"=",
"np",
".",
"where",
"(",
"self",
".",
"_obsdata",
"[",
"'id'",
"]",... | Get the observation metadata for the given id.
This is table 3 of Sesar 2010 | [
"Get",
"the",
"observation",
"metadata",
"for",
"the",
"given",
"id",
".",
"This",
"is",
"table",
"3",
"of",
"Sesar",
"2010"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L186-L195 |
astroML/gatspy | gatspy/datasets/rrlyrae.py | RRLyraeTemplates.get_template | def get_template(self, template_id):
"""Get a particular lightcurve template
Parameters
----------
template_id : str
id of desired template
Returns
-------
phase : ndarray
array of phases
mag : ndarray
array of normaliz... | python | def get_template(self, template_id):
"""Get a particular lightcurve template
Parameters
----------
template_id : str
id of desired template
Returns
-------
phase : ndarray
array of phases
mag : ndarray
array of normaliz... | [
"def",
"get_template",
"(",
"self",
",",
"template_id",
")",
":",
"try",
":",
"data",
"=",
"np",
".",
"loadtxt",
"(",
"self",
".",
"data",
".",
"extractfile",
"(",
"template_id",
"+",
"'.dat'",
")",
")",
"except",
"KeyError",
":",
"raise",
"ValueError",
... | Get a particular lightcurve template
Parameters
----------
template_id : str
id of desired template
Returns
-------
phase : ndarray
array of phases
mag : ndarray
array of normalized magnitudes | [
"Get",
"a",
"particular",
"lightcurve",
"template"
] | train | https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L322-L340 |
vkurup/python-tcxparser | tcxparser/tcxparser.py | TCXParser.hr_avg | def hr_avg(self):
"""Average heart rate of the workout"""
hr_data = self.hr_values()
return int(sum(hr_data) / len(hr_data)) | python | def hr_avg(self):
"""Average heart rate of the workout"""
hr_data = self.hr_values()
return int(sum(hr_data) / len(hr_data)) | [
"def",
"hr_avg",
"(",
"self",
")",
":",
"hr_data",
"=",
"self",
".",
"hr_values",
"(",
")",
"return",
"int",
"(",
"sum",
"(",
"hr_data",
")",
"/",
"len",
"(",
"hr_data",
")",
")"
] | Average heart rate of the workout | [
"Average",
"heart",
"rate",
"of",
"the",
"workout"
] | train | https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L73-L76 |
vkurup/python-tcxparser | tcxparser/tcxparser.py | TCXParser.pace | def pace(self):
"""Average pace (mm:ss/km for the workout"""
secs_per_km = self.duration / (self.distance / 1000)
return time.strftime('%M:%S', time.gmtime(secs_per_km)) | python | def pace(self):
"""Average pace (mm:ss/km for the workout"""
secs_per_km = self.duration / (self.distance / 1000)
return time.strftime('%M:%S', time.gmtime(secs_per_km)) | [
"def",
"pace",
"(",
"self",
")",
":",
"secs_per_km",
"=",
"self",
".",
"duration",
"/",
"(",
"self",
".",
"distance",
"/",
"1000",
")",
"return",
"time",
".",
"strftime",
"(",
"'%M:%S'",
",",
"time",
".",
"gmtime",
"(",
"secs_per_km",
")",
")"
] | Average pace (mm:ss/km for the workout | [
"Average",
"pace",
"(",
"mm",
":",
"ss",
"/",
"km",
"for",
"the",
"workout"
] | train | https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L89-L92 |
vkurup/python-tcxparser | tcxparser/tcxparser.py | TCXParser.ascent | def ascent(self):
"""Returns ascent of workout in meters"""
total_ascent = 0.0
altitude_data = self.altitude_points()
for i in range(len(altitude_data) - 1):
diff = altitude_data[i+1] - altitude_data[i]
if diff > 0.0:
total_ascent += diff
r... | python | def ascent(self):
"""Returns ascent of workout in meters"""
total_ascent = 0.0
altitude_data = self.altitude_points()
for i in range(len(altitude_data) - 1):
diff = altitude_data[i+1] - altitude_data[i]
if diff > 0.0:
total_ascent += diff
r... | [
"def",
"ascent",
"(",
"self",
")",
":",
"total_ascent",
"=",
"0.0",
"altitude_data",
"=",
"self",
".",
"altitude_points",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"altitude_data",
")",
"-",
"1",
")",
":",
"diff",
"=",
"altitude_data",
"[",... | Returns ascent of workout in meters | [
"Returns",
"ascent",
"of",
"workout",
"in",
"meters"
] | train | https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L113-L121 |
vkurup/python-tcxparser | tcxparser/tcxparser.py | TCXParser.descent | def descent(self):
"""Returns descent of workout in meters"""
total_descent = 0.0
altitude_data = self.altitude_points()
for i in range(len(altitude_data) - 1):
diff = altitude_data[i+1] - altitude_data[i]
if diff < 0.0:
total_descent += abs(diff)
... | python | def descent(self):
"""Returns descent of workout in meters"""
total_descent = 0.0
altitude_data = self.altitude_points()
for i in range(len(altitude_data) - 1):
diff = altitude_data[i+1] - altitude_data[i]
if diff < 0.0:
total_descent += abs(diff)
... | [
"def",
"descent",
"(",
"self",
")",
":",
"total_descent",
"=",
"0.0",
"altitude_data",
"=",
"self",
".",
"altitude_points",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"altitude_data",
")",
"-",
"1",
")",
":",
"diff",
"=",
"altitude_data",
"[... | Returns descent of workout in meters | [
"Returns",
"descent",
"of",
"workout",
"in",
"meters"
] | train | https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L124-L132 |
uktrade/directory-validators | directory_validators/company.py | keywords_special_characters | def keywords_special_characters(keywords):
"""
Confirms that the keywords don't contain special characters
Args:
keywords (str)
Raises:
django.forms.ValidationError
"""
invalid_chars = '!\"#$%&\'()*+-./:;<=>?@[\\]^_{|}~\t\n'
if any(char in invalid_chars for char in keywords... | python | def keywords_special_characters(keywords):
"""
Confirms that the keywords don't contain special characters
Args:
keywords (str)
Raises:
django.forms.ValidationError
"""
invalid_chars = '!\"#$%&\'()*+-./:;<=>?@[\\]^_{|}~\t\n'
if any(char in invalid_chars for char in keywords... | [
"def",
"keywords_special_characters",
"(",
"keywords",
")",
":",
"invalid_chars",
"=",
"'!\\\"#$%&\\'()*+-./:;<=>?@[\\\\]^_{|}~\\t\\n'",
"if",
"any",
"(",
"char",
"in",
"invalid_chars",
"for",
"char",
"in",
"keywords",
")",
":",
"raise",
"ValidationError",
"(",
"MESSA... | Confirms that the keywords don't contain special characters
Args:
keywords (str)
Raises:
django.forms.ValidationError | [
"Confirms",
"that",
"the",
"keywords",
"don",
"t",
"contain",
"special",
"characters"
] | train | https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L45-L57 |
uktrade/directory-validators | directory_validators/company.py | image_format | def image_format(value):
"""
Confirms that the uploaded image is of supported format.
Args:
value (File): The file with an `image` property containing the image
Raises:
django.forms.ValidationError
"""
if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS:
... | python | def image_format(value):
"""
Confirms that the uploaded image is of supported format.
Args:
value (File): The file with an `image` property containing the image
Raises:
django.forms.ValidationError
"""
if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS:
... | [
"def",
"image_format",
"(",
"value",
")",
":",
"if",
"value",
".",
"image",
".",
"format",
".",
"upper",
"(",
")",
"not",
"in",
"constants",
".",
"ALLOWED_IMAGE_FORMATS",
":",
"raise",
"ValidationError",
"(",
"MESSAGE_INVALID_IMAGE_FORMAT",
")"
] | Confirms that the uploaded image is of supported format.
Args:
value (File): The file with an `image` property containing the image
Raises:
django.forms.ValidationError | [
"Confirms",
"that",
"the",
"uploaded",
"image",
"is",
"of",
"supported",
"format",
"."
] | train | https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L60-L73 |
uktrade/directory-validators | directory_validators/company.py | case_study_social_link_facebook | def case_study_social_link_facebook(value):
"""
Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError
"""
parsed = parse.urlparse(value.lower())
if not parsed.netloc.endswith('face... | python | def case_study_social_link_facebook(value):
"""
Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError
"""
parsed = parse.urlparse(value.lower())
if not parsed.netloc.endswith('face... | [
"def",
"case_study_social_link_facebook",
"(",
"value",
")",
":",
"parsed",
"=",
"parse",
".",
"urlparse",
"(",
"value",
".",
"lower",
"(",
")",
")",
"if",
"not",
"parsed",
".",
"netloc",
".",
"endswith",
"(",
"'facebook.com'",
")",
":",
"raise",
"Validati... | Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError | [
"Confirms",
"that",
"the",
"social",
"media",
"url",
"is",
"pointed",
"at",
"the",
"correct",
"domain",
"."
] | train | https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L108-L122 |
uktrade/directory-validators | directory_validators/company.py | case_study_social_link_twitter | def case_study_social_link_twitter(value):
"""
Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError
"""
parsed = parse.urlparse(value.lower())
if not parsed.netloc.endswith('twitt... | python | def case_study_social_link_twitter(value):
"""
Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError
"""
parsed = parse.urlparse(value.lower())
if not parsed.netloc.endswith('twitt... | [
"def",
"case_study_social_link_twitter",
"(",
"value",
")",
":",
"parsed",
"=",
"parse",
".",
"urlparse",
"(",
"value",
".",
"lower",
"(",
")",
")",
"if",
"not",
"parsed",
".",
"netloc",
".",
"endswith",
"(",
"'twitter.com'",
")",
":",
"raise",
"Validation... | Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError | [
"Confirms",
"that",
"the",
"social",
"media",
"url",
"is",
"pointed",
"at",
"the",
"correct",
"domain",
"."
] | train | https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L125-L139 |
uktrade/directory-validators | directory_validators/company.py | case_study_social_link_linkedin | def case_study_social_link_linkedin(value):
"""
Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError
"""
parsed = parse.urlparse(value.lower())
if not parsed.netloc.endswith('link... | python | def case_study_social_link_linkedin(value):
"""
Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError
"""
parsed = parse.urlparse(value.lower())
if not parsed.netloc.endswith('link... | [
"def",
"case_study_social_link_linkedin",
"(",
"value",
")",
":",
"parsed",
"=",
"parse",
".",
"urlparse",
"(",
"value",
".",
"lower",
"(",
")",
")",
"if",
"not",
"parsed",
".",
"netloc",
".",
"endswith",
"(",
"'linkedin.com'",
")",
":",
"raise",
"Validati... | Confirms that the social media url is pointed at the correct domain.
Args:
value (string): The url to check.
Raises:
django.forms.ValidationError | [
"Confirms",
"that",
"the",
"social",
"media",
"url",
"is",
"pointed",
"at",
"the",
"correct",
"domain",
"."
] | train | https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L142-L156 |
uktrade/directory-validators | directory_validators/company.py | no_company_with_insufficient_companies_house_data | def no_company_with_insufficient_companies_house_data(value):
"""
Confirms that the company number is not for for a company that
Companies House does not hold information on.
Args:
value (string): The company number to check.
Raises:
django.forms.ValidationError
"""
for p... | python | def no_company_with_insufficient_companies_house_data(value):
"""
Confirms that the company number is not for for a company that
Companies House does not hold information on.
Args:
value (string): The company number to check.
Raises:
django.forms.ValidationError
"""
for p... | [
"def",
"no_company_with_insufficient_companies_house_data",
"(",
"value",
")",
":",
"for",
"prefix",
",",
"name",
"in",
"company_types_with_insufficient_companies_house_data",
":",
"if",
"value",
".",
"upper",
"(",
")",
".",
"startswith",
"(",
"prefix",
")",
":",
"r... | Confirms that the company number is not for for a company that
Companies House does not hold information on.
Args:
value (string): The company number to check.
Raises:
django.forms.ValidationError | [
"Confirms",
"that",
"the",
"company",
"number",
"is",
"not",
"for",
"for",
"a",
"company",
"that",
"Companies",
"House",
"does",
"not",
"hold",
"information",
"on",
"."
] | train | https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L179-L196 |
uktrade/directory-validators | directory_validators/enrolment.py | email_domain_free | def email_domain_free(value):
"""
Confirms that the email address is not using a free service.
@param {str} value
@returns {None}
@raises AssertionError
"""
domain = helpers.get_domain_from_email_address(value)
if domain.lower() in free_domains:
raise ValidationError(MESSAGE_US... | python | def email_domain_free(value):
"""
Confirms that the email address is not using a free service.
@param {str} value
@returns {None}
@raises AssertionError
"""
domain = helpers.get_domain_from_email_address(value)
if domain.lower() in free_domains:
raise ValidationError(MESSAGE_US... | [
"def",
"email_domain_free",
"(",
"value",
")",
":",
"domain",
"=",
"helpers",
".",
"get_domain_from_email_address",
"(",
"value",
")",
"if",
"domain",
".",
"lower",
"(",
")",
"in",
"free_domains",
":",
"raise",
"ValidationError",
"(",
"MESSAGE_USE_COMPANY_EMAIL",
... | Confirms that the email address is not using a free service.
@param {str} value
@returns {None}
@raises AssertionError | [
"Confirms",
"that",
"the",
"email",
"address",
"is",
"not",
"using",
"a",
"free",
"service",
".",
"@param",
"{",
"str",
"}",
"value",
"@returns",
"{",
"None",
"}",
"@raises",
"AssertionError"
] | train | https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/enrolment.py#L43-L54 |
uktrade/directory-validators | directory_validators/enrolment.py | email_domain_disposable | def email_domain_disposable(value):
"""
Confirms that the email address is not using a disposable service.
@param {str} value
@returns {None}
@raises AssertionError
"""
domain = helpers.get_domain_from_email_address(value)
if domain.lower() in disposable_domains:
raise Validati... | python | def email_domain_disposable(value):
"""
Confirms that the email address is not using a disposable service.
@param {str} value
@returns {None}
@raises AssertionError
"""
domain = helpers.get_domain_from_email_address(value)
if domain.lower() in disposable_domains:
raise Validati... | [
"def",
"email_domain_disposable",
"(",
"value",
")",
":",
"domain",
"=",
"helpers",
".",
"get_domain_from_email_address",
"(",
"value",
")",
"if",
"domain",
".",
"lower",
"(",
")",
"in",
"disposable_domains",
":",
"raise",
"ValidationError",
"(",
"MESSAGE_USE_COMP... | Confirms that the email address is not using a disposable service.
@param {str} value
@returns {None}
@raises AssertionError | [
"Confirms",
"that",
"the",
"email",
"address",
"is",
"not",
"using",
"a",
"disposable",
"service",
".",
"@param",
"{",
"str",
"}",
"value",
"@returns",
"{",
"None",
"}",
"@raises",
"AssertionError"
] | train | https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/enrolment.py#L57-L68 |
uktrade/directory-validators | directory_validators/enrolment.py | domestic_mobile_phone_number | def domestic_mobile_phone_number(value):
"""
Confirms that the phone number is a valid UK phone number.
@param {str} value
@returns {None}
@raises AssertionError
"""
try:
parsed = phonenumbers.parse(value, 'GB')
except NumberParseException:
pass
else:
is_mob... | python | def domestic_mobile_phone_number(value):
"""
Confirms that the phone number is a valid UK phone number.
@param {str} value
@returns {None}
@raises AssertionError
"""
try:
parsed = phonenumbers.parse(value, 'GB')
except NumberParseException:
pass
else:
is_mob... | [
"def",
"domestic_mobile_phone_number",
"(",
"value",
")",
":",
"try",
":",
"parsed",
"=",
"phonenumbers",
".",
"parse",
"(",
"value",
",",
"'GB'",
")",
"except",
"NumberParseException",
":",
"pass",
"else",
":",
"is_mobile",
"=",
"carrier",
".",
"_is_mobile",
... | Confirms that the phone number is a valid UK phone number.
@param {str} value
@returns {None}
@raises AssertionError | [
"Confirms",
"that",
"the",
"phone",
"number",
"is",
"a",
"valid",
"UK",
"phone",
"number",
".",
"@param",
"{",
"str",
"}",
"value",
"@returns",
"{",
"None",
"}",
"@raises",
"AssertionError"
] | train | https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/enrolment.py#L71-L88 |
ruipgil/TrackToTrip | tracktotrip/segment.py | remove_liers | def remove_liers(points):
""" Removes obvious noise points
Checks time consistency, removing points that appear out of order
Args:
points (:obj:`list` of :obj:`Point`)
Returns:
:obj:`list` of :obj:`Point`
"""
result = [points[0]]
for i in range(1, len(points) - 2):
... | python | def remove_liers(points):
""" Removes obvious noise points
Checks time consistency, removing points that appear out of order
Args:
points (:obj:`list` of :obj:`Point`)
Returns:
:obj:`list` of :obj:`Point`
"""
result = [points[0]]
for i in range(1, len(points) - 2):
... | [
"def",
"remove_liers",
"(",
"points",
")",
":",
"result",
"=",
"[",
"points",
"[",
"0",
"]",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"points",
")",
"-",
"2",
")",
":",
"prv",
"=",
"points",
"[",
"i",
"-",
"1",
"]",
"crr",
... | Removes obvious noise points
Checks time consistency, removing points that appear out of order
Args:
points (:obj:`list` of :obj:`Point`)
Returns:
:obj:`list` of :obj:`Point` | [
"Removes",
"obvious",
"noise",
"points"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L20-L39 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.bounds | def bounds(self, thr=0, lower_index=0, upper_index=-1):
""" Computes the bounds of the segment, or part of it
Args:
lower_index (int, optional): Start index. Defaults to 0
upper_index (int, optional): End index. Defaults to 0
Returns:
:obj:`tuple` of :obj:`fl... | python | def bounds(self, thr=0, lower_index=0, upper_index=-1):
""" Computes the bounds of the segment, or part of it
Args:
lower_index (int, optional): Start index. Defaults to 0
upper_index (int, optional): End index. Defaults to 0
Returns:
:obj:`tuple` of :obj:`fl... | [
"def",
"bounds",
"(",
"self",
",",
"thr",
"=",
"0",
",",
"lower_index",
"=",
"0",
",",
"upper_index",
"=",
"-",
"1",
")",
":",
"points",
"=",
"self",
".",
"points",
"[",
"lower_index",
":",
"upper_index",
"]",
"min_lat",
"=",
"float",
"(",
"\"inf\"",... | Computes the bounds of the segment, or part of it
Args:
lower_index (int, optional): Start index. Defaults to 0
upper_index (int, optional): End index. Defaults to 0
Returns:
:obj:`tuple` of :obj:`float`: Bounds of the (sub)segment, such that
(min_lat... | [
"Computes",
"the",
"bounds",
"of",
"the",
"segment",
"or",
"part",
"of",
"it"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L65-L88 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.smooth | def smooth(self, noise, strategy=INVERSE_STRATEGY):
""" In-place smoothing
See smooth_segment function
Args:
noise (float): Noise expected
strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY
or smooth.EXTRAPOLATE_STRATEGY
Returns:
... | python | def smooth(self, noise, strategy=INVERSE_STRATEGY):
""" In-place smoothing
See smooth_segment function
Args:
noise (float): Noise expected
strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY
or smooth.EXTRAPOLATE_STRATEGY
Returns:
... | [
"def",
"smooth",
"(",
"self",
",",
"noise",
",",
"strategy",
"=",
"INVERSE_STRATEGY",
")",
":",
"if",
"strategy",
"is",
"INVERSE_STRATEGY",
":",
"self",
".",
"points",
"=",
"with_inverse",
"(",
"self",
".",
"points",
",",
"noise",
")",
"elif",
"strategy",
... | In-place smoothing
See smooth_segment function
Args:
noise (float): Noise expected
strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY
or smooth.EXTRAPOLATE_STRATEGY
Returns:
:obj:`Segment` | [
"In",
"-",
"place",
"smoothing"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L101-L119 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.simplify | def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False):
""" In-place segment simplification
See `drp` and `compression` modules
Args:
eps (float): Distance threshold for the `drp` function
max_dist_error (float): Max distance error, in meters
... | python | def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False):
""" In-place segment simplification
See `drp` and `compression` modules
Args:
eps (float): Distance threshold for the `drp` function
max_dist_error (float): Max distance error, in meters
... | [
"def",
"simplify",
"(",
"self",
",",
"eps",
",",
"max_dist_error",
",",
"max_speed_error",
",",
"topology_only",
"=",
"False",
")",
":",
"if",
"topology_only",
":",
"self",
".",
"points",
"=",
"drp",
"(",
"self",
".",
"points",
",",
"eps",
")",
"else",
... | In-place segment simplification
See `drp` and `compression` modules
Args:
eps (float): Distance threshold for the `drp` function
max_dist_error (float): Max distance error, in meters
max_speed_error (float): Max speed error, in km/h
topology_only (bool, ... | [
"In",
"-",
"place",
"segment",
"simplification"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L134-L152 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.compute_metrics | def compute_metrics(self):
""" Computes metrics for each point
Returns:
:obj:`Segment`: self
"""
for prev, point in pairwise(self.points):
point.compute_metrics(prev)
return self | python | def compute_metrics(self):
""" Computes metrics for each point
Returns:
:obj:`Segment`: self
"""
for prev, point in pairwise(self.points):
point.compute_metrics(prev)
return self | [
"def",
"compute_metrics",
"(",
"self",
")",
":",
"for",
"prev",
",",
"point",
"in",
"pairwise",
"(",
"self",
".",
"points",
")",
":",
"point",
".",
"compute_metrics",
"(",
"prev",
")",
"return",
"self"
] | Computes metrics for each point
Returns:
:obj:`Segment`: self | [
"Computes",
"metrics",
"for",
"each",
"point"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L154-L162 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.infer_location | def infer_location(
self,
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
):
"""In-place location inferring
See infer_location function
Args:
Retu... | python | def infer_location(
self,
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
):
"""In-place location inferring
See infer_location function
Args:
Retu... | [
"def",
"infer_location",
"(",
"self",
",",
"location_query",
",",
"max_distance",
",",
"google_key",
",",
"foursquare_client_id",
",",
"foursquare_client_secret",
",",
"limit",
")",
":",
"self",
".",
"location_from",
"=",
"infer_location",
"(",
"self",
".",
"point... | In-place location inferring
See infer_location function
Args:
Returns:
:obj:`Segment`: self | [
"In",
"-",
"place",
"location",
"inferring"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L164-L201 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.infer_transportation_mode | def infer_transportation_mode(self, clf, min_time):
"""In-place transportation mode inferring
See infer_transportation_mode function
Args:
Returns:
:obj:`Segment`: self
"""
self.transportation_modes = speed_clustering(clf, self.points, min_time)
retu... | python | def infer_transportation_mode(self, clf, min_time):
"""In-place transportation mode inferring
See infer_transportation_mode function
Args:
Returns:
:obj:`Segment`: self
"""
self.transportation_modes = speed_clustering(clf, self.points, min_time)
retu... | [
"def",
"infer_transportation_mode",
"(",
"self",
",",
"clf",
",",
"min_time",
")",
":",
"self",
".",
"transportation_modes",
"=",
"speed_clustering",
"(",
"clf",
",",
"self",
".",
"points",
",",
"min_time",
")",
"return",
"self"
] | In-place transportation mode inferring
See infer_transportation_mode function
Args:
Returns:
:obj:`Segment`: self | [
"In",
"-",
"place",
"transportation",
"mode",
"inferring"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L203-L213 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.merge_and_fit | def merge_and_fit(self, segment):
""" Merges another segment with this one, ordering the points based on a
distance heuristic
Args:
segment (:obj:`Segment`): Segment to merge with
Returns:
:obj:`Segment`: self
"""
self.points = sort_segment_po... | python | def merge_and_fit(self, segment):
""" Merges another segment with this one, ordering the points based on a
distance heuristic
Args:
segment (:obj:`Segment`): Segment to merge with
Returns:
:obj:`Segment`: self
"""
self.points = sort_segment_po... | [
"def",
"merge_and_fit",
"(",
"self",
",",
"segment",
")",
":",
"self",
".",
"points",
"=",
"sort_segment_points",
"(",
"self",
".",
"points",
",",
"segment",
".",
"points",
")",
"return",
"self"
] | Merges another segment with this one, ordering the points based on a
distance heuristic
Args:
segment (:obj:`Segment`): Segment to merge with
Returns:
:obj:`Segment`: self | [
"Merges",
"another",
"segment",
"with",
"this",
"one",
"ordering",
"the",
"points",
"based",
"on",
"a",
"distance",
"heuristic"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L215-L225 |
ruipgil/TrackToTrip | tracktotrip/segment.py | Segment.closest_point_to | def closest_point_to(self, point, thr=20.0):
""" Finds the closest point in the segment to a given point
Args:
point (:obj:`Point`)
thr (float, optional): Distance threshold, in meters, to be considered
the same point. Defaults to 20.0
Returns:
... | python | def closest_point_to(self, point, thr=20.0):
""" Finds the closest point in the segment to a given point
Args:
point (:obj:`Point`)
thr (float, optional): Distance threshold, in meters, to be considered
the same point. Defaults to 20.0
Returns:
... | [
"def",
"closest_point_to",
"(",
"self",
",",
"point",
",",
"thr",
"=",
"20.0",
")",
":",
"i",
"=",
"0",
"point_arr",
"=",
"point",
".",
"gen2arr",
"(",
")",
"def",
"closest_in_line",
"(",
"pointA",
",",
"pointB",
")",
":",
"temp",
"=",
"closest_point",... | Finds the closest point in the segment to a given point
Args:
point (:obj:`Point`)
thr (float, optional): Distance threshold, in meters, to be considered
the same point. Defaults to 20.0
Returns:
(int, Point): Index of the point. -1 if doesn't exist. ... | [
"Finds",
"the",
"closest",
"point",
"in",
"the",
"segment",
"to",
"a",
"given",
"point"
] | train | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L227-L255 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.