repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
panosl/django-currencies | currencies/management/commands/currencies.py | Command.get_handler | def get_handler(self, options):
"""Return the specified handler"""
# Import the CurrencyHandler and get an instance
handler_module = import_module(sources[options[self._source_param]], self._package_name)
return handler_module.CurrencyHandler(self.log) | python | def get_handler(self, options):
"""Return the specified handler"""
# Import the CurrencyHandler and get an instance
handler_module = import_module(sources[options[self._source_param]], self._package_name)
return handler_module.CurrencyHandler(self.log) | [
"def",
"get_handler",
"(",
"self",
",",
"options",
")",
":",
"handler_module",
"=",
"import_module",
"(",
"sources",
"[",
"options",
"[",
"self",
".",
"_source_param",
"]",
"]",
",",
"self",
".",
"_package_name",
")",
"return",
"handler_module",
".",
"Curren... | Return the specified handler | [
"Return",
"the",
"specified",
"handler"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/currencies.py#L95-L99 | train |
panosl/django-currencies | currencies/management/commands/_openexchangerates.py | CurrencyHandler.check_rates | def check_rates(self, rates, base):
"""Local helper function for validating rates response"""
if "rates" not in rates:
raise RuntimeError("%s: 'rates' not found in results" % self.name)
if "base" not in rates or rates["base"] != base or base not in rates["rates"]:
self.l... | python | def check_rates(self, rates, base):
"""Local helper function for validating rates response"""
if "rates" not in rates:
raise RuntimeError("%s: 'rates' not found in results" % self.name)
if "base" not in rates or rates["base"] != base or base not in rates["rates"]:
self.l... | [
"def",
"check_rates",
"(",
"self",
",",
"rates",
",",
"base",
")",
":",
"if",
"\"rates\"",
"not",
"in",
"rates",
":",
"raise",
"RuntimeError",
"(",
"\"%s: 'rates' not found in results\"",
"%",
"self",
".",
"name",
")",
"if",
"\"base\"",
"not",
"in",
"rates",... | Local helper function for validating rates response | [
"Local",
"helper",
"function",
"for",
"validating",
"rates",
"response"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_openexchangerates.py#L48-L55 | train |
panosl/django-currencies | currencies/management/commands/_openexchangerates.py | CurrencyHandler.get_ratefactor | def get_ratefactor(self, base, code):
"""Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError"""
self.get_latestcurrencyrates(base)
try:
ratefactor = self.rates["rates"][code]
except KeyError:
raise RuntimeError("%s... | python | def get_ratefactor(self, base, code):
"""Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError"""
self.get_latestcurrencyrates(base)
try:
ratefactor = self.rates["rates"][code]
except KeyError:
raise RuntimeError("%s... | [
"def",
"get_ratefactor",
"(",
"self",
",",
"base",
",",
"code",
")",
":",
"self",
".",
"get_latestcurrencyrates",
"(",
"base",
")",
"try",
":",
"ratefactor",
"=",
"self",
".",
"rates",
"[",
"\"rates\"",
"]",
"[",
"code",
"]",
"except",
"KeyError",
":",
... | Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError | [
"Return",
"the",
"Decimal",
"currency",
"exchange",
"rate",
"factor",
"of",
"code",
"compared",
"to",
"1",
"base",
"unit",
"or",
"RuntimeError"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_openexchangerates.py#L88-L99 | train |
panosl/django-currencies | currencies/management/commands/_currencyhandler.py | BaseHandler.get_currencysymbol | def get_currencysymbol(self, code):
"""Retrieve the currency symbol from the local file"""
if not self._symbols:
symbolpath = os.path.join(self._dir, 'currencies.json')
with open(symbolpath, encoding='utf8') as df:
self._symbols = json.load(df)
return self... | python | def get_currencysymbol(self, code):
"""Retrieve the currency symbol from the local file"""
if not self._symbols:
symbolpath = os.path.join(self._dir, 'currencies.json')
with open(symbolpath, encoding='utf8') as df:
self._symbols = json.load(df)
return self... | [
"def",
"get_currencysymbol",
"(",
"self",
",",
"code",
")",
":",
"if",
"not",
"self",
".",
"_symbols",
":",
"symbolpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_dir",
",",
"'currencies.json'",
")",
"with",
"open",
"(",
"symbolpath",
"... | Retrieve the currency symbol from the local file | [
"Retrieve",
"the",
"currency",
"symbol",
"from",
"the",
"local",
"file"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_currencyhandler.py#L40-L46 | train |
panosl/django-currencies | currencies/management/commands/_currencyhandler.py | BaseHandler.ratechangebase | def ratechangebase(self, ratefactor, current_base, new_base):
"""
Local helper function for changing currency base, returns new rate in new base
Defaults to ROUND_HALF_EVEN
"""
if self._multiplier is None:
self.log(logging.WARNING, "CurrencyHandler: changing base ours... | python | def ratechangebase(self, ratefactor, current_base, new_base):
"""
Local helper function for changing currency base, returns new rate in new base
Defaults to ROUND_HALF_EVEN
"""
if self._multiplier is None:
self.log(logging.WARNING, "CurrencyHandler: changing base ours... | [
"def",
"ratechangebase",
"(",
"self",
",",
"ratefactor",
",",
"current_base",
",",
"new_base",
")",
":",
"if",
"self",
".",
"_multiplier",
"is",
"None",
":",
"self",
".",
"log",
"(",
"logging",
".",
"WARNING",
",",
"\"CurrencyHandler: changing base ourselves\"",... | Local helper function for changing currency base, returns new rate in new base
Defaults to ROUND_HALF_EVEN | [
"Local",
"helper",
"function",
"for",
"changing",
"currency",
"base",
"returns",
"new",
"rate",
"in",
"new",
"base",
"Defaults",
"to",
"ROUND_HALF_EVEN"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_currencyhandler.py#L49-L60 | train |
jmoiron/johnny-cache | johnny/cache.py | disallowed_table | def disallowed_table(*tables):
"""Returns True if a set of tables is in the blacklist or, if a whitelist is set,
any of the tables is not in the whitelist. False otherwise."""
# XXX: When using a black or white list, this has to be done EVERY query;
# It'd be nice to make this as fast as possible. In g... | python | def disallowed_table(*tables):
"""Returns True if a set of tables is in the blacklist or, if a whitelist is set,
any of the tables is not in the whitelist. False otherwise."""
# XXX: When using a black or white list, this has to be done EVERY query;
# It'd be nice to make this as fast as possible. In g... | [
"def",
"disallowed_table",
"(",
"*",
"tables",
")",
":",
"return",
"not",
"bool",
"(",
"settings",
".",
"WHITELIST",
".",
"issuperset",
"(",
"tables",
")",
")",
"if",
"settings",
".",
"WHITELIST",
"else",
"bool",
"(",
"settings",
".",
"BLACKLIST",
".",
"... | Returns True if a set of tables is in the blacklist or, if a whitelist is set,
any of the tables is not in the whitelist. False otherwise. | [
"Returns",
"True",
"if",
"a",
"set",
"of",
"tables",
"is",
"in",
"the",
"blacklist",
"or",
"if",
"a",
"whitelist",
"is",
"set",
"any",
"of",
"the",
"tables",
"is",
"not",
"in",
"the",
"whitelist",
".",
"False",
"otherwise",
"."
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L25-L34 | train |
jmoiron/johnny-cache | johnny/cache.py | invalidate | def invalidate(*tables, **kwargs):
"""Invalidate the current generation for one or more tables. The arguments
can be either strings representing database table names or models. Pass in
kwarg ``using`` to set the database."""
backend = get_backend()
db = kwargs.get('using', 'default')
if backe... | python | def invalidate(*tables, **kwargs):
"""Invalidate the current generation for one or more tables. The arguments
can be either strings representing database table names or models. Pass in
kwarg ``using`` to set the database."""
backend = get_backend()
db = kwargs.get('using', 'default')
if backe... | [
"def",
"invalidate",
"(",
"*",
"tables",
",",
"**",
"kwargs",
")",
":",
"backend",
"=",
"get_backend",
"(",
")",
"db",
"=",
"kwargs",
".",
"get",
"(",
"'using'",
",",
"'default'",
")",
"if",
"backend",
".",
"_patched",
":",
"for",
"t",
"in",
"map",
... | Invalidate the current generation for one or more tables. The arguments
can be either strings representing database table names or models. Pass in
kwarg ``using`` to set the database. | [
"Invalidate",
"the",
"current",
"generation",
"for",
"one",
"or",
"more",
"tables",
".",
"The",
"arguments",
"can",
"be",
"either",
"strings",
"representing",
"database",
"table",
"names",
"or",
"models",
".",
"Pass",
"in",
"kwarg",
"using",
"to",
"set",
"th... | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L67-L76 | train |
jmoiron/johnny-cache | johnny/cache.py | KeyGen.gen_key | def gen_key(self, *values):
"""Generate a key from one or more values."""
key = md5()
KeyGen._recursive_convert(values, key)
return key.hexdigest() | python | def gen_key(self, *values):
"""Generate a key from one or more values."""
key = md5()
KeyGen._recursive_convert(values, key)
return key.hexdigest() | [
"def",
"gen_key",
"(",
"self",
",",
"*",
"values",
")",
":",
"key",
"=",
"md5",
"(",
")",
"KeyGen",
".",
"_recursive_convert",
"(",
"values",
",",
"key",
")",
"return",
"key",
".",
"hexdigest",
"(",
")"
] | Generate a key from one or more values. | [
"Generate",
"a",
"key",
"from",
"one",
"or",
"more",
"values",
"."
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L199-L203 | train |
jmoiron/johnny-cache | johnny/cache.py | KeyHandler.get_generation | def get_generation(self, *tables, **kwargs):
"""Get the generation key for any number of tables."""
db = kwargs.get('db', 'default')
if len(tables) > 1:
return self.get_multi_generation(tables, db)
return self.get_single_generation(tables[0], db) | python | def get_generation(self, *tables, **kwargs):
"""Get the generation key for any number of tables."""
db = kwargs.get('db', 'default')
if len(tables) > 1:
return self.get_multi_generation(tables, db)
return self.get_single_generation(tables[0], db) | [
"def",
"get_generation",
"(",
"self",
",",
"*",
"tables",
",",
"**",
"kwargs",
")",
":",
"db",
"=",
"kwargs",
".",
"get",
"(",
"'db'",
",",
"'default'",
")",
"if",
"len",
"(",
"tables",
")",
">",
"1",
":",
"return",
"self",
".",
"get_multi_generation... | Get the generation key for any number of tables. | [
"Get",
"the",
"generation",
"key",
"for",
"any",
"number",
"of",
"tables",
"."
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L215-L220 | train |
jmoiron/johnny-cache | johnny/cache.py | KeyHandler.get_single_generation | def get_single_generation(self, table, db='default'):
"""Creates a random generation value for a single table name"""
key = self.keygen.gen_table_key(table, db)
val = self.cache_backend.get(key, None, db)
#if local.get('in_test', None): print force_bytes(val).ljust(32), key
if va... | python | def get_single_generation(self, table, db='default'):
"""Creates a random generation value for a single table name"""
key = self.keygen.gen_table_key(table, db)
val = self.cache_backend.get(key, None, db)
#if local.get('in_test', None): print force_bytes(val).ljust(32), key
if va... | [
"def",
"get_single_generation",
"(",
"self",
",",
"table",
",",
"db",
"=",
"'default'",
")",
":",
"key",
"=",
"self",
".",
"keygen",
".",
"gen_table_key",
"(",
"table",
",",
"db",
")",
"val",
"=",
"self",
".",
"cache_backend",
".",
"get",
"(",
"key",
... | Creates a random generation value for a single table name | [
"Creates",
"a",
"random",
"generation",
"value",
"for",
"a",
"single",
"table",
"name"
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L222-L230 | train |
jmoiron/johnny-cache | johnny/cache.py | KeyHandler.get_multi_generation | def get_multi_generation(self, tables, db='default'):
"""Takes a list of table names and returns an aggregate
value for the generation"""
generations = []
for table in tables:
generations.append(self.get_single_generation(table, db))
key = self.keygen.gen_multi_key(ge... | python | def get_multi_generation(self, tables, db='default'):
"""Takes a list of table names and returns an aggregate
value for the generation"""
generations = []
for table in tables:
generations.append(self.get_single_generation(table, db))
key = self.keygen.gen_multi_key(ge... | [
"def",
"get_multi_generation",
"(",
"self",
",",
"tables",
",",
"db",
"=",
"'default'",
")",
":",
"generations",
"=",
"[",
"]",
"for",
"table",
"in",
"tables",
":",
"generations",
".",
"append",
"(",
"self",
".",
"get_single_generation",
"(",
"table",
",",... | Takes a list of table names and returns an aggregate
value for the generation | [
"Takes",
"a",
"list",
"of",
"table",
"names",
"and",
"returns",
"an",
"aggregate",
"value",
"for",
"the",
"generation"
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L232-L244 | train |
jmoiron/johnny-cache | johnny/cache.py | KeyHandler.sql_key | def sql_key(self, generation, sql, params, order, result_type,
using='default'):
"""
Return the specific cache key for the sql query described by the
pieces of the query and the generation key.
"""
# these keys will always look pretty opaque
suffix = self.... | python | def sql_key(self, generation, sql, params, order, result_type,
using='default'):
"""
Return the specific cache key for the sql query described by the
pieces of the query and the generation key.
"""
# these keys will always look pretty opaque
suffix = self.... | [
"def",
"sql_key",
"(",
"self",
",",
"generation",
",",
"sql",
",",
"params",
",",
"order",
",",
"result_type",
",",
"using",
"=",
"'default'",
")",
":",
"suffix",
"=",
"self",
".",
"keygen",
".",
"gen_key",
"(",
"sql",
",",
"params",
",",
"order",
",... | Return the specific cache key for the sql query described by the
pieces of the query and the generation key. | [
"Return",
"the",
"specific",
"cache",
"key",
"for",
"the",
"sql",
"query",
"described",
"by",
"the",
"pieces",
"of",
"the",
"query",
"and",
"the",
"generation",
"key",
"."
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L255-L264 | train |
jmoiron/johnny-cache | johnny/cache.py | QueryCacheBackend.unpatch | def unpatch(self):
"""un-applies this patch."""
if not self._patched:
return
for func in self._read_compilers + self._write_compilers:
func.execute_sql = self._original[func]
self.cache_backend.unpatch()
self._patched = False | python | def unpatch(self):
"""un-applies this patch."""
if not self._patched:
return
for func in self._read_compilers + self._write_compilers:
func.execute_sql = self._original[func]
self.cache_backend.unpatch()
self._patched = False | [
"def",
"unpatch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_patched",
":",
"return",
"for",
"func",
"in",
"self",
".",
"_read_compilers",
"+",
"self",
".",
"_write_compilers",
":",
"func",
".",
"execute_sql",
"=",
"self",
".",
"_original",
"[",
... | un-applies this patch. | [
"un",
"-",
"applies",
"this",
"patch",
"."
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L431-L438 | train |
panosl/django-currencies | currencies/templatetags/currency.py | memoize_nullary | def memoize_nullary(f):
"""
Memoizes a function that takes no arguments. The memoization lasts only as
long as we hold a reference to the returned function.
"""
def func():
if not hasattr(func, 'retval'):
func.retval = f()
return func.retval
return func | python | def memoize_nullary(f):
"""
Memoizes a function that takes no arguments. The memoization lasts only as
long as we hold a reference to the returned function.
"""
def func():
if not hasattr(func, 'retval'):
func.retval = f()
return func.retval
return func | [
"def",
"memoize_nullary",
"(",
"f",
")",
":",
"def",
"func",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"func",
",",
"'retval'",
")",
":",
"func",
".",
"retval",
"=",
"f",
"(",
")",
"return",
"func",
".",
"retval",
"return",
"func"
] | Memoizes a function that takes no arguments. The memoization lasts only as
long as we hold a reference to the returned function. | [
"Memoizes",
"a",
"function",
"that",
"takes",
"no",
"arguments",
".",
"The",
"memoization",
"lasts",
"only",
"as",
"long",
"as",
"we",
"hold",
"a",
"reference",
"to",
"the",
"returned",
"function",
"."
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/templatetags/currency.py#L47-L56 | train |
panosl/django-currencies | currencies/templatetags/currency.py | currency_context | def currency_context(context):
"""
Use instead of context processor
Context variables are only valid within the block scope
"""
request = context['request']
currency_code = memoize_nullary(lambda: get_currency_code(request))
context['CURRENCIES'] = Currency.active.all() # querysets are alre... | python | def currency_context(context):
"""
Use instead of context processor
Context variables are only valid within the block scope
"""
request = context['request']
currency_code = memoize_nullary(lambda: get_currency_code(request))
context['CURRENCIES'] = Currency.active.all() # querysets are alre... | [
"def",
"currency_context",
"(",
"context",
")",
":",
"request",
"=",
"context",
"[",
"'request'",
"]",
"currency_code",
"=",
"memoize_nullary",
"(",
"lambda",
":",
"get_currency_code",
"(",
"request",
")",
")",
"context",
"[",
"'CURRENCIES'",
"]",
"=",
"Curren... | Use instead of context processor
Context variables are only valid within the block scope | [
"Use",
"instead",
"of",
"context",
"processor",
"Context",
"variables",
"are",
"only",
"valid",
"within",
"the",
"block",
"scope"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/templatetags/currency.py#L71-L83 | train |
panosl/django-currencies | currencies/management/commands/_openexchangerates_client.py | OpenExchangeRatesClient.currencies | def currencies(self):
"""Fetches current currency data of the service
:Example Data:
{
AED: "United Arab Emirates Dirham",
AFN: "Afghan Afghani",
ALL: "Albanian Lek",
AMD: "Armenian Dram",
ANG: "Netherlands Antillean Guilder",
... | python | def currencies(self):
"""Fetches current currency data of the service
:Example Data:
{
AED: "United Arab Emirates Dirham",
AFN: "Afghan Afghani",
ALL: "Albanian Lek",
AMD: "Armenian Dram",
ANG: "Netherlands Antillean Guilder",
... | [
"def",
"currencies",
"(",
"self",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"client",
".",
"get",
"(",
"self",
".",
"ENDPOINT_CURRENCIES",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
"as",
"e",
":",
"raise",
"OpenExchangeRa... | Fetches current currency data of the service
:Example Data:
{
AED: "United Arab Emirates Dirham",
AFN: "Afghan Afghani",
ALL: "Albanian Lek",
AMD: "Armenian Dram",
ANG: "Netherlands Antillean Guilder",
AOA: "Angolan Kwanza",
... | [
"Fetches",
"current",
"currency",
"data",
"of",
"the",
"service"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_openexchangerates_client.py#L57-L81 | train |
panosl/django-currencies | currencies/management/commands/_openexchangerates_client.py | OpenExchangeRatesClient.historical | def historical(self, date, base='USD'):
"""Fetches historical exchange rate data from service
:Example Data:
{
disclaimer: "<Disclaimer data>",
license: "<License data>",
timestamp: 1358150409,
base: "USD",
rate... | python | def historical(self, date, base='USD'):
"""Fetches historical exchange rate data from service
:Example Data:
{
disclaimer: "<Disclaimer data>",
license: "<License data>",
timestamp: 1358150409,
base: "USD",
rate... | [
"def",
"historical",
"(",
"self",
",",
"date",
",",
"base",
"=",
"'USD'",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"client",
".",
"get",
"(",
"self",
".",
"ENDPOINT_HISTORICAL",
"%",
"date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
",",
"par... | Fetches historical exchange rate data from service
:Example Data:
{
disclaimer: "<Disclaimer data>",
license: "<License data>",
timestamp: 1358150409,
base: "USD",
rates: {
AED: 3.666311,
... | [
"Fetches",
"historical",
"exchange",
"rate",
"data",
"from",
"service"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_openexchangerates_client.py#L83-L110 | train |
panosl/django-currencies | currencies/utils.py | calculate | def calculate(price, to_code, **kwargs):
"""Converts a price in the default currency to another currency"""
qs = kwargs.get('qs', get_active_currencies_qs())
kwargs['qs'] = qs
default_code = qs.default().code
return convert(price, default_code, to_code, **kwargs) | python | def calculate(price, to_code, **kwargs):
"""Converts a price in the default currency to another currency"""
qs = kwargs.get('qs', get_active_currencies_qs())
kwargs['qs'] = qs
default_code = qs.default().code
return convert(price, default_code, to_code, **kwargs) | [
"def",
"calculate",
"(",
"price",
",",
"to_code",
",",
"**",
"kwargs",
")",
":",
"qs",
"=",
"kwargs",
".",
"get",
"(",
"'qs'",
",",
"get_active_currencies_qs",
"(",
")",
")",
"kwargs",
"[",
"'qs'",
"]",
"=",
"qs",
"default_code",
"=",
"qs",
".",
"def... | Converts a price in the default currency to another currency | [
"Converts",
"a",
"price",
"in",
"the",
"default",
"currency",
"to",
"another",
"currency"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/utils.py#L11-L16 | train |
panosl/django-currencies | currencies/utils.py | convert | def convert(amount, from_code, to_code, decimals=2, qs=None):
"""Converts from any currency to any currency"""
if from_code == to_code:
return amount
if qs is None:
qs = get_active_currencies_qs()
from_, to = qs.get(code=from_code), qs.get(code=to_code)
amount = D(amount) * (to.fa... | python | def convert(amount, from_code, to_code, decimals=2, qs=None):
"""Converts from any currency to any currency"""
if from_code == to_code:
return amount
if qs is None:
qs = get_active_currencies_qs()
from_, to = qs.get(code=from_code), qs.get(code=to_code)
amount = D(amount) * (to.fa... | [
"def",
"convert",
"(",
"amount",
",",
"from_code",
",",
"to_code",
",",
"decimals",
"=",
"2",
",",
"qs",
"=",
"None",
")",
":",
"if",
"from_code",
"==",
"to_code",
":",
"return",
"amount",
"if",
"qs",
"is",
"None",
":",
"qs",
"=",
"get_active_currencie... | Converts from any currency to any currency | [
"Converts",
"from",
"any",
"currency",
"to",
"any",
"currency"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/utils.py#L19-L30 | train |
panosl/django-currencies | currencies/utils.py | price_rounding | def price_rounding(price, decimals=2):
"""Takes a decimal price and rounds to a number of decimal places"""
try:
exponent = D('.' + decimals * '0')
except InvalidOperation:
# Currencies with no decimal places, ex. JPY, HUF
exponent = D()
return price.quantize(exponent, rounding=R... | python | def price_rounding(price, decimals=2):
"""Takes a decimal price and rounds to a number of decimal places"""
try:
exponent = D('.' + decimals * '0')
except InvalidOperation:
# Currencies with no decimal places, ex. JPY, HUF
exponent = D()
return price.quantize(exponent, rounding=R... | [
"def",
"price_rounding",
"(",
"price",
",",
"decimals",
"=",
"2",
")",
":",
"try",
":",
"exponent",
"=",
"D",
"(",
"'.'",
"+",
"decimals",
"*",
"'0'",
")",
"except",
"InvalidOperation",
":",
"exponent",
"=",
"D",
"(",
")",
"return",
"price",
".",
"qu... | Takes a decimal price and rounds to a number of decimal places | [
"Takes",
"a",
"decimal",
"price",
"and",
"rounds",
"to",
"a",
"number",
"of",
"decimal",
"places"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/utils.py#L48-L55 | train |
panosl/django-currencies | currencies/management/commands/_currencyiso.py | CurrencyHandler.get_currencies | def get_currencies(self):
"""Downloads xml currency data or if not available tries to use cached file copy"""
try:
resp = get(self.endpoint)
resp.raise_for_status()
except exceptions.RequestException as e:
self.log(logging.ERROR, "%s: Problem whilst contacting... | python | def get_currencies(self):
"""Downloads xml currency data or if not available tries to use cached file copy"""
try:
resp = get(self.endpoint)
resp.raise_for_status()
except exceptions.RequestException as e:
self.log(logging.ERROR, "%s: Problem whilst contacting... | [
"def",
"get_currencies",
"(",
"self",
")",
":",
"try",
":",
"resp",
"=",
"get",
"(",
"self",
".",
"endpoint",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"exceptions",
".",
"RequestException",
"as",
"e",
":",
"self",
".",
"log",
"(",
"log... | Downloads xml currency data or if not available tries to use cached file copy | [
"Downloads",
"xml",
"currency",
"data",
"or",
"if",
"not",
"available",
"tries",
"to",
"use",
"cached",
"file",
"copy"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_currencyiso.py#L38-L54 | train |
panosl/django-currencies | currencies/management/commands/_currencyiso.py | CurrencyHandler._check_doc | def _check_doc(self, root):
"""Validates the xml tree and returns the published date"""
if (root.tag != 'ISO_4217' or
root[0].tag != 'CcyTbl' or
root[0][0].tag != 'CcyNtry' or
not root.attrib['Pblshd'] or
# Actual length in Oct 2016: 279
len(ro... | python | def _check_doc(self, root):
"""Validates the xml tree and returns the published date"""
if (root.tag != 'ISO_4217' or
root[0].tag != 'CcyTbl' or
root[0][0].tag != 'CcyNtry' or
not root.attrib['Pblshd'] or
# Actual length in Oct 2016: 279
len(ro... | [
"def",
"_check_doc",
"(",
"self",
",",
"root",
")",
":",
"if",
"(",
"root",
".",
"tag",
"!=",
"'ISO_4217'",
"or",
"root",
"[",
"0",
"]",
".",
"tag",
"!=",
"'CcyTbl'",
"or",
"root",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"tag",
"!=",
"'CcyNtry'",
"o... | Validates the xml tree and returns the published date | [
"Validates",
"the",
"xml",
"tree",
"and",
"returns",
"the",
"published",
"date"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_currencyiso.py#L56-L67 | train |
panosl/django-currencies | currencies/management/commands/_currencyiso.py | CurrencyHandler.get_allcurrencycodes | def get_allcurrencycodes(self):
"""Return an iterable of distinct 3 character ISO 4217 currency codes"""
foundcodes = []
codeelements = self.currencies[0].iter('Ccy')
for codeelement in codeelements:
code = codeelement.text
if code not in foundcodes:
... | python | def get_allcurrencycodes(self):
"""Return an iterable of distinct 3 character ISO 4217 currency codes"""
foundcodes = []
codeelements = self.currencies[0].iter('Ccy')
for codeelement in codeelements:
code = codeelement.text
if code not in foundcodes:
... | [
"def",
"get_allcurrencycodes",
"(",
"self",
")",
":",
"foundcodes",
"=",
"[",
"]",
"codeelements",
"=",
"self",
".",
"currencies",
"[",
"0",
"]",
".",
"iter",
"(",
"'Ccy'",
")",
"for",
"codeelement",
"in",
"codeelements",
":",
"code",
"=",
"codeelement",
... | Return an iterable of distinct 3 character ISO 4217 currency codes | [
"Return",
"an",
"iterable",
"of",
"distinct",
"3",
"character",
"ISO",
"4217",
"currency",
"codes"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_currencyiso.py#L69-L77 | train |
jmoiron/johnny-cache | johnny/utils.py | celery_enable_all | def celery_enable_all():
"""Enable johnny-cache in all celery tasks, clearing the local-store
after each task."""
from celery.signals import task_prerun, task_postrun, task_failure
task_prerun.connect(prerun_handler)
task_postrun.connect(postrun_handler)
# Also have to cleanup on failure.
ta... | python | def celery_enable_all():
"""Enable johnny-cache in all celery tasks, clearing the local-store
after each task."""
from celery.signals import task_prerun, task_postrun, task_failure
task_prerun.connect(prerun_handler)
task_postrun.connect(postrun_handler)
# Also have to cleanup on failure.
ta... | [
"def",
"celery_enable_all",
"(",
")",
":",
"from",
"celery",
".",
"signals",
"import",
"task_prerun",
",",
"task_postrun",
",",
"task_failure",
"task_prerun",
".",
"connect",
"(",
"prerun_handler",
")",
"task_postrun",
".",
"connect",
"(",
"postrun_handler",
")",
... | Enable johnny-cache in all celery tasks, clearing the local-store
after each task. | [
"Enable",
"johnny",
"-",
"cache",
"in",
"all",
"celery",
"tasks",
"clearing",
"the",
"local",
"-",
"store",
"after",
"each",
"task",
"."
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/utils.py#L22-L29 | train |
jmoiron/johnny-cache | johnny/utils.py | celery_task_wrapper | def celery_task_wrapper(f):
"""
Provides a task wrapper for celery that sets up cache and ensures
that the local store is cleared after completion
"""
from celery.utils import fun_takes_kwargs
@wraps(f, assigned=available_attrs(f))
def newf(*args, **kwargs):
backend = get_backend()
... | python | def celery_task_wrapper(f):
"""
Provides a task wrapper for celery that sets up cache and ensures
that the local store is cleared after completion
"""
from celery.utils import fun_takes_kwargs
@wraps(f, assigned=available_attrs(f))
def newf(*args, **kwargs):
backend = get_backend()
... | [
"def",
"celery_task_wrapper",
"(",
"f",
")",
":",
"from",
"celery",
".",
"utils",
"import",
"fun_takes_kwargs",
"@",
"wraps",
"(",
"f",
",",
"assigned",
"=",
"available_attrs",
"(",
"f",
")",
")",
"def",
"newf",
"(",
"*",
"args",
",",
"**",
"kwargs",
"... | Provides a task wrapper for celery that sets up cache and ensures
that the local store is cleared after completion | [
"Provides",
"a",
"task",
"wrapper",
"for",
"celery",
"that",
"sets",
"up",
"cache",
"and",
"ensures",
"that",
"the",
"local",
"store",
"is",
"cleared",
"after",
"completion"
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/utils.py#L31-L57 | train |
jmoiron/johnny-cache | johnny/settings.py | _get_backend | def _get_backend():
"""
Returns the actual django cache object johnny is configured to use.
This relies on the settings only; the actual active cache can
theoretically be changed at runtime.
"""
enabled = [n for n, c in sorted(CACHES.items())
if c.get('JOHNNY_CACHE', False)]
... | python | def _get_backend():
"""
Returns the actual django cache object johnny is configured to use.
This relies on the settings only; the actual active cache can
theoretically be changed at runtime.
"""
enabled = [n for n, c in sorted(CACHES.items())
if c.get('JOHNNY_CACHE', False)]
... | [
"def",
"_get_backend",
"(",
")",
":",
"enabled",
"=",
"[",
"n",
"for",
"n",
",",
"c",
"in",
"sorted",
"(",
"CACHES",
".",
"items",
"(",
")",
")",
"if",
"c",
".",
"get",
"(",
"'JOHNNY_CACHE'",
",",
"False",
")",
"]",
"if",
"len",
"(",
"enabled",
... | Returns the actual django cache object johnny is configured to use.
This relies on the settings only; the actual active cache can
theoretically be changed at runtime. | [
"Returns",
"the",
"actual",
"django",
"cache",
"object",
"johnny",
"is",
"configured",
"to",
"use",
".",
"This",
"relies",
"on",
"the",
"settings",
"only",
";",
"the",
"actual",
"active",
"cache",
"can",
"theoretically",
"be",
"changed",
"at",
"runtime",
"."... | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/settings.py#L29-L52 | train |
panosl/django-currencies | currencies/management/commands/updatecurrencies.py | Command.add_arguments | def add_arguments(self, parser):
"""Add command arguments"""
parser.add_argument(self._source_param, **self._source_kwargs)
parser.add_argument('--base', '-b', action='store',
help= 'Supply the base currency as code or a settings variable name. '
'The default is... | python | def add_arguments(self, parser):
"""Add command arguments"""
parser.add_argument(self._source_param, **self._source_kwargs)
parser.add_argument('--base', '-b', action='store',
help= 'Supply the base currency as code or a settings variable name. '
'The default is... | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"self",
".",
"_source_param",
",",
"**",
"self",
".",
"_source_kwargs",
")",
"parser",
".",
"add_argument",
"(",
"'--base'",
",",
"'-b'",
",",
"action",
"=",
... | Add command arguments | [
"Add",
"command",
"arguments"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/updatecurrencies.py#L15-L21 | train |
panosl/django-currencies | currencies/management/commands/updatecurrencies.py | Command.get_base | def get_base(self, option):
"""
Parse the base command option. Can be supplied as a 3 character code or a settings variable name
If base is not supplied, looks for settings CURRENCIES_BASE and SHOP_DEFAULT_CURRENCY
"""
if option:
if option.isupper():
i... | python | def get_base(self, option):
"""
Parse the base command option. Can be supplied as a 3 character code or a settings variable name
If base is not supplied, looks for settings CURRENCIES_BASE and SHOP_DEFAULT_CURRENCY
"""
if option:
if option.isupper():
i... | [
"def",
"get_base",
"(",
"self",
",",
"option",
")",
":",
"if",
"option",
":",
"if",
"option",
".",
"isupper",
"(",
")",
":",
"if",
"len",
"(",
"option",
")",
">",
"3",
":",
"return",
"getattr",
"(",
"settings",
",",
"option",
")",
",",
"True",
"e... | Parse the base command option. Can be supplied as a 3 character code or a settings variable name
If base is not supplied, looks for settings CURRENCIES_BASE and SHOP_DEFAULT_CURRENCY | [
"Parse",
"the",
"base",
"command",
"option",
".",
"Can",
"be",
"supplied",
"as",
"a",
"3",
"character",
"code",
"or",
"a",
"settings",
"variable",
"name",
"If",
"base",
"is",
"not",
"supplied",
"looks",
"for",
"settings",
"CURRENCIES_BASE",
"and",
"SHOP_DEFA... | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/updatecurrencies.py#L23-L40 | train |
jmoiron/johnny-cache | johnny/transaction.py | TransactionManager.set | def set(self, key, val, timeout=None, using=None):
"""
Set will be using the generational key, so if another thread
bumps this key, the localstore version will still be invalid.
If the key is bumped during a transaction it will be new
to the global cache on commit, so it will sti... | python | def set(self, key, val, timeout=None, using=None):
"""
Set will be using the generational key, so if another thread
bumps this key, the localstore version will still be invalid.
If the key is bumped during a transaction it will be new
to the global cache on commit, so it will sti... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"val",
",",
"timeout",
"=",
"None",
",",
"using",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"self",
".",
"timeout",
"if",
"self",
".",
"is_managed",
"(",
"using",
"=",
"... | Set will be using the generational key, so if another thread
bumps this key, the localstore version will still be invalid.
If the key is bumped during a transaction it will be new
to the global cache on commit, so it will still be a bump. | [
"Set",
"will",
"be",
"using",
"the",
"generational",
"key",
"so",
"if",
"another",
"thread",
"bumps",
"this",
"key",
"the",
"localstore",
"version",
"will",
"still",
"be",
"invalid",
".",
"If",
"the",
"key",
"is",
"bumped",
"during",
"a",
"transaction",
"i... | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/transaction.py#L81-L93 | train |
jmoiron/johnny-cache | johnny/transaction.py | TransactionManager._flush | def _flush(self, commit=True, using=None):
"""
Flushes the internal cache, either to the memcache or rolls back
"""
if commit:
# XXX: multi-set?
if self._uses_savepoints():
self._commit_all_savepoints(using)
c = self.local.mget('%s_%s_*... | python | def _flush(self, commit=True, using=None):
"""
Flushes the internal cache, either to the memcache or rolls back
"""
if commit:
# XXX: multi-set?
if self._uses_savepoints():
self._commit_all_savepoints(using)
c = self.local.mget('%s_%s_*... | [
"def",
"_flush",
"(",
"self",
",",
"commit",
"=",
"True",
",",
"using",
"=",
"None",
")",
":",
"if",
"commit",
":",
"if",
"self",
".",
"_uses_savepoints",
"(",
")",
":",
"self",
".",
"_commit_all_savepoints",
"(",
"using",
")",
"c",
"=",
"self",
".",... | Flushes the internal cache, either to the memcache or rolls back | [
"Flushes",
"the",
"internal",
"cache",
"either",
"to",
"the",
"memcache",
"or",
"rolls",
"back"
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/transaction.py#L99-L115 | train |
jmoiron/johnny-cache | johnny/localstore.py | LocalStore.clear | def clear(self, pat=None):
"""
Minor diversion with built-in dict here; clear can take a glob
style expression and remove keys based on that expression.
"""
if pat is None:
return self.__dict__.clear()
expr = re.compile(fnmatch.translate(pat))
for ke... | python | def clear(self, pat=None):
"""
Minor diversion with built-in dict here; clear can take a glob
style expression and remove keys based on that expression.
"""
if pat is None:
return self.__dict__.clear()
expr = re.compile(fnmatch.translate(pat))
for ke... | [
"def",
"clear",
"(",
"self",
",",
"pat",
"=",
"None",
")",
":",
"if",
"pat",
"is",
"None",
":",
"return",
"self",
".",
"__dict__",
".",
"clear",
"(",
")",
"expr",
"=",
"re",
".",
"compile",
"(",
"fnmatch",
".",
"translate",
"(",
"pat",
")",
")",
... | Minor diversion with built-in dict here; clear can take a glob
style expression and remove keys based on that expression. | [
"Minor",
"diversion",
"with",
"built",
"-",
"in",
"dict",
"here",
";",
"clear",
"can",
"take",
"a",
"glob",
"style",
"expression",
"and",
"remove",
"keys",
"based",
"on",
"that",
"expression",
"."
] | d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c | https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/localstore.py#L92-L105 | train |
panosl/django-currencies | currencies/management/commands/_yahoofinance.py | CurrencyHandler.get_bulkcurrencies | def get_bulkcurrencies(self):
"""
Get the supported currencies
Scraped from a JSON object on the html page in javascript tag
"""
start = r'YAHOO\.Finance\.CurrencyConverter\.addCurrencies\('
_json = r'\[[^\]]*\]'
try:
resp = get(self.currencies_url)
... | python | def get_bulkcurrencies(self):
"""
Get the supported currencies
Scraped from a JSON object on the html page in javascript tag
"""
start = r'YAHOO\.Finance\.CurrencyConverter\.addCurrencies\('
_json = r'\[[^\]]*\]'
try:
resp = get(self.currencies_url)
... | [
"def",
"get_bulkcurrencies",
"(",
"self",
")",
":",
"start",
"=",
"r'YAHOO\\.Finance\\.CurrencyConverter\\.addCurrencies\\('",
"_json",
"=",
"r'\\[[^\\]]*\\]'",
"try",
":",
"resp",
"=",
"get",
"(",
"self",
".",
"currencies_url",
")",
"resp",
".",
"raise_for_status",
... | Get the supported currencies
Scraped from a JSON object on the html page in javascript tag | [
"Get",
"the",
"supported",
"currencies",
"Scraped",
"from",
"a",
"JSON",
"object",
"on",
"the",
"html",
"page",
"in",
"javascript",
"tag"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_yahoofinance.py#L62-L100 | train |
panosl/django-currencies | currencies/management/commands/_yahoofinance.py | CurrencyHandler.get_bulkrates | def get_bulkrates(self):
"""Get & format the rates dict"""
try:
resp = get(self.bulk_url)
resp.raise_for_status()
except exceptions.RequestException as e:
raise RuntimeError(e)
return resp.json() | python | def get_bulkrates(self):
"""Get & format the rates dict"""
try:
resp = get(self.bulk_url)
resp.raise_for_status()
except exceptions.RequestException as e:
raise RuntimeError(e)
return resp.json() | [
"def",
"get_bulkrates",
"(",
"self",
")",
":",
"try",
":",
"resp",
"=",
"get",
"(",
"self",
".",
"bulk_url",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"exceptions",
".",
"RequestException",
"as",
"e",
":",
"raise",
"RuntimeError",
"(",
"e... | Get & format the rates dict | [
"Get",
"&",
"format",
"the",
"rates",
"dict"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_yahoofinance.py#L102-L109 | train |
panosl/django-currencies | currencies/management/commands/_yahoofinance.py | CurrencyHandler.get_singlerate | def get_singlerate(self, base, code):
"""Get a single rate, used as fallback"""
try:
url = self.onerate_url % (base, code)
resp = get(url)
resp.raise_for_status()
except exceptions.HTTPError as e:
self.log(logging.ERROR, "%s: problem with %s:\n%s",... | python | def get_singlerate(self, base, code):
"""Get a single rate, used as fallback"""
try:
url = self.onerate_url % (base, code)
resp = get(url)
resp.raise_for_status()
except exceptions.HTTPError as e:
self.log(logging.ERROR, "%s: problem with %s:\n%s",... | [
"def",
"get_singlerate",
"(",
"self",
",",
"base",
",",
"code",
")",
":",
"try",
":",
"url",
"=",
"self",
".",
"onerate_url",
"%",
"(",
"base",
",",
"code",
")",
"resp",
"=",
"get",
"(",
"url",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"excep... | Get a single rate, used as fallback | [
"Get",
"a",
"single",
"rate",
"used",
"as",
"fallback"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_yahoofinance.py#L111-L125 | train |
panosl/django-currencies | currencies/management/commands/_yahoofinance.py | CurrencyHandler.get_baserate | def get_baserate(self):
"""Helper function to populate the base rate"""
rateslist = self.rates['list']['resources']
for rate in rateslist:
rateobj = rate['resource']['fields']
if rateobj['symbol'].partition('=')[0] == rateobj['name']:
return rateobj['name'... | python | def get_baserate(self):
"""Helper function to populate the base rate"""
rateslist = self.rates['list']['resources']
for rate in rateslist:
rateobj = rate['resource']['fields']
if rateobj['symbol'].partition('=')[0] == rateobj['name']:
return rateobj['name'... | [
"def",
"get_baserate",
"(",
"self",
")",
":",
"rateslist",
"=",
"self",
".",
"rates",
"[",
"'list'",
"]",
"[",
"'resources'",
"]",
"for",
"rate",
"in",
"rateslist",
":",
"rateobj",
"=",
"rate",
"[",
"'resource'",
"]",
"[",
"'fields'",
"]",
"if",
"rateo... | Helper function to populate the base rate | [
"Helper",
"function",
"to",
"populate",
"the",
"base",
"rate"
] | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_yahoofinance.py#L185-L192 | train |
panosl/django-currencies | currencies/management/commands/_yahoofinance.py | CurrencyHandler.get_ratefactor | def get_ratefactor(self, base, code):
"""
Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError
Yahoo currently uses USD as base currency, but here we detect it with get_baserate
"""
raise RuntimeError("%s Deprecated: API withdrawn ... | python | def get_ratefactor(self, base, code):
"""
Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError
Yahoo currently uses USD as base currency, but here we detect it with get_baserate
"""
raise RuntimeError("%s Deprecated: API withdrawn ... | [
"def",
"get_ratefactor",
"(",
"self",
",",
"base",
",",
"code",
")",
":",
"raise",
"RuntimeError",
"(",
"\"%s Deprecated: API withdrawn in February 2018\"",
"%",
"self",
".",
"name",
")",
"try",
":",
"rate",
"=",
"self",
".",
"get_rate",
"(",
"code",
")",
"e... | Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError
Yahoo currently uses USD as base currency, but here we detect it with get_baserate | [
"Return",
"the",
"Decimal",
"currency",
"exchange",
"rate",
"factor",
"of",
"code",
"compared",
"to",
"1",
"base",
"unit",
"or",
"RuntimeError",
"Yahoo",
"currently",
"uses",
"USD",
"as",
"base",
"currency",
"but",
"here",
"we",
"detect",
"it",
"with",
"get_... | 8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd | https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_yahoofinance.py#L219-L237 | train |
awesmubarak/markdown_strings | markdown_strings/__init__.py | header | def header(heading_text, header_level, style="atx"):
"""Return a header of specified level.
Keyword arguments:
style -- Specifies the header style (default atx).
The "atx" style uses hash signs, and has 6 levels.
The "setext" style uses dashes or equals signs for headers of
... | python | def header(heading_text, header_level, style="atx"):
"""Return a header of specified level.
Keyword arguments:
style -- Specifies the header style (default atx).
The "atx" style uses hash signs, and has 6 levels.
The "setext" style uses dashes or equals signs for headers of
... | [
"def",
"header",
"(",
"heading_text",
",",
"header_level",
",",
"style",
"=",
"\"atx\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"header_level",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"header_level must be int\"",
")",
"if",
"style",
"not",
"in... | Return a header of specified level.
Keyword arguments:
style -- Specifies the header style (default atx).
The "atx" style uses hash signs, and has 6 levels.
The "setext" style uses dashes or equals signs for headers of
levels 1 and 2 respectively, and is limited to those... | [
"Return",
"a",
"header",
"of",
"specified",
"level",
"."
] | 569e225e7a8f23469efe8df244d3d3fd0e8c3b3e | https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L39-L69 | train |
awesmubarak/markdown_strings | markdown_strings/__init__.py | code_block | def code_block(text, language=""):
"""Return a code block.
If a language is specified a fenced code block is produced, otherwise the
block is indented by four spaces.
Keyword arguments:
language -- Specifies the language to fence the code in (default blank).
>>> code_block("This is a simple c... | python | def code_block(text, language=""):
"""Return a code block.
If a language is specified a fenced code block is produced, otherwise the
block is indented by four spaces.
Keyword arguments:
language -- Specifies the language to fence the code in (default blank).
>>> code_block("This is a simple c... | [
"def",
"code_block",
"(",
"text",
",",
"language",
"=",
"\"\"",
")",
":",
"if",
"language",
":",
"return",
"\"```\"",
"+",
"language",
"+",
"\"\\n\"",
"+",
"text",
"+",
"\"\\n```\"",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"\" \"",
"+",
"item",
... | Return a code block.
If a language is specified a fenced code block is produced, otherwise the
block is indented by four spaces.
Keyword arguments:
language -- Specifies the language to fence the code in (default blank).
>>> code_block("This is a simple codeblock.")
' This is a simple code... | [
"Return",
"a",
"code",
"block",
"."
] | 569e225e7a8f23469efe8df244d3d3fd0e8c3b3e | https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L106-L126 | train |
awesmubarak/markdown_strings | markdown_strings/__init__.py | image | def image(alt_text, link_url, title=""):
"""Return an inline image.
Keyword arguments:
title -- Specify the title of the image, as seen when hovering over it.
>>> image("This is an image", "https://tinyurl.com/bright-green-tree")
''
>>>... | python | def image(alt_text, link_url, title=""):
"""Return an inline image.
Keyword arguments:
title -- Specify the title of the image, as seen when hovering over it.
>>> image("This is an image", "https://tinyurl.com/bright-green-tree")
''
>>>... | [
"def",
"image",
"(",
"alt_text",
",",
"link_url",
",",
"title",
"=",
"\"\"",
")",
":",
"image_string",
"=",
"\"\"",
"if",
"title",
":",
"image_string",
"+=",
"' \"'"... | Return an inline image.
Keyword arguments:
title -- Specify the title of the image, as seen when hovering over it.
>>> image("This is an image", "https://tinyurl.com/bright-green-tree")
''
>>> image("This is an image", "https://tinyurl.com/... | [
"Return",
"an",
"inline",
"image",
"."
] | 569e225e7a8f23469efe8df244d3d3fd0e8c3b3e | https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L141-L155 | train |
awesmubarak/markdown_strings | markdown_strings/__init__.py | ordered_list | def ordered_list(text_array):
"""Return an ordered list from an array.
>>> ordered_list(["first", "second", "third", "fourth"])
'1. first\\n2. second\\n3. third\\n4. fourth'
"""
text_list = []
for number, item in enumerate(text_array):
text_list.append(
(esc_format(numbe... | python | def ordered_list(text_array):
"""Return an ordered list from an array.
>>> ordered_list(["first", "second", "third", "fourth"])
'1. first\\n2. second\\n3. third\\n4. fourth'
"""
text_list = []
for number, item in enumerate(text_array):
text_list.append(
(esc_format(numbe... | [
"def",
"ordered_list",
"(",
"text_array",
")",
":",
"text_list",
"=",
"[",
"]",
"for",
"number",
",",
"item",
"in",
"enumerate",
"(",
"text_array",
")",
":",
"text_list",
".",
"append",
"(",
"(",
"esc_format",
"(",
"number",
"+",
"1",
")",
"+",
"\".\""... | Return an ordered list from an array.
>>> ordered_list(["first", "second", "third", "fourth"])
'1. first\\n2. second\\n3. third\\n4. fourth' | [
"Return",
"an",
"ordered",
"list",
"from",
"an",
"array",
"."
] | 569e225e7a8f23469efe8df244d3d3fd0e8c3b3e | https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L172-L183 | train |
awesmubarak/markdown_strings | markdown_strings/__init__.py | task_list | def task_list(task_array):
"""Return a task list.
The task_array should be 2-dimensional; the first item should be the task
text, and the second the boolean completion state.
>>> task_list([["Be born", True], ["Be dead", False]])
'- [X] Be born\\n- [ ] Be dead'
When displayed using `print`, t... | python | def task_list(task_array):
"""Return a task list.
The task_array should be 2-dimensional; the first item should be the task
text, and the second the boolean completion state.
>>> task_list([["Be born", True], ["Be dead", False]])
'- [X] Be born\\n- [ ] Be dead'
When displayed using `print`, t... | [
"def",
"task_list",
"(",
"task_array",
")",
":",
"tasks",
"=",
"[",
"]",
"for",
"item",
",",
"completed",
"in",
"task_array",
":",
"task",
"=",
"\"- [ ] \"",
"+",
"esc_format",
"(",
"item",
")",
"if",
"completed",
":",
"task",
"=",
"task",
"[",
":",
... | Return a task list.
The task_array should be 2-dimensional; the first item should be the task
text, and the second the boolean completion state.
>>> task_list([["Be born", True], ["Be dead", False]])
'- [X] Be born\\n- [ ] Be dead'
When displayed using `print`, this will appear as:
- [X]... | [
"Return",
"a",
"task",
"list",
"."
] | 569e225e7a8f23469efe8df244d3d3fd0e8c3b3e | https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L231-L251 | train |
awesmubarak/markdown_strings | markdown_strings/__init__.py | table | def table(big_array):
"""Return a formatted table, generated from arrays representing columns.
The function requires a 2-dimensional array, where each array is a column
of the table. This will be used to generate a formatted table in string
format. The number of items in each columns does not need to be... | python | def table(big_array):
"""Return a formatted table, generated from arrays representing columns.
The function requires a 2-dimensional array, where each array is a column
of the table. This will be used to generate a formatted table in string
format. The number of items in each columns does not need to be... | [
"def",
"table",
"(",
"big_array",
")",
":",
"number_of_columns",
"=",
"len",
"(",
"big_array",
")",
"number_of_rows_in_column",
"=",
"[",
"len",
"(",
"column",
")",
"for",
"column",
"in",
"big_array",
"]",
"max_cell_size",
"=",
"[",
"len",
"(",
"max",
"(",... | Return a formatted table, generated from arrays representing columns.
The function requires a 2-dimensional array, where each array is a column
of the table. This will be used to generate a formatted table in string
format. The number of items in each columns does not need to be consitent.
>>> table([[... | [
"Return",
"a",
"formatted",
"table",
"generated",
"from",
"arrays",
"representing",
"columns",
".",
"The",
"function",
"requires",
"a",
"2",
"-",
"dimensional",
"array",
"where",
"each",
"array",
"is",
"a",
"column",
"of",
"the",
"table",
".",
"This",
"will"... | 569e225e7a8f23469efe8df244d3d3fd0e8c3b3e | https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L285-L324 | train |
DinoTools/python-ssdeep | src/ssdeep/__init__.py | compare | def compare(sig1, sig2):
"""
Computes the match score between two fuzzy hash signatures.
Returns a value from zero to 100 indicating the match score of the
two signatures. A match score of zero indicates the signatures
did not match.
:param Bytes|String sig1: First fuzzy hash signature
:pa... | python | def compare(sig1, sig2):
"""
Computes the match score between two fuzzy hash signatures.
Returns a value from zero to 100 indicating the match score of the
two signatures. A match score of zero indicates the signatures
did not match.
:param Bytes|String sig1: First fuzzy hash signature
:pa... | [
"def",
"compare",
"(",
"sig1",
",",
"sig2",
")",
":",
"if",
"isinstance",
"(",
"sig1",
",",
"six",
".",
"text_type",
")",
":",
"sig1",
"=",
"sig1",
".",
"encode",
"(",
"\"ascii\"",
")",
"if",
"isinstance",
"(",
"sig2",
",",
"six",
".",
"text_type",
... | Computes the match score between two fuzzy hash signatures.
Returns a value from zero to 100 indicating the match score of the
two signatures. A match score of zero indicates the signatures
did not match.
:param Bytes|String sig1: First fuzzy hash signature
:param Bytes|String sig2: Second fuzzy h... | [
"Computes",
"the",
"match",
"score",
"between",
"two",
"fuzzy",
"hash",
"signatures",
"."
] | c17b3dc0f53514afff59eca67717291ccd206b7c | https://github.com/DinoTools/python-ssdeep/blob/c17b3dc0f53514afff59eca67717291ccd206b7c/src/ssdeep/__init__.py#L150-L188 | train |
DinoTools/python-ssdeep | src/ssdeep/__init__.py | hash | def hash(buf, encoding="utf-8"):
"""
Compute the fuzzy hash of a buffer
:param String|Bytes buf: The data to be fuzzy hashed
:return: The fuzzy hash
:rtype: String
:raises InternalError: If lib returns an internal error
:raises TypeError: If buf is not String or Bytes
"""
if isins... | python | def hash(buf, encoding="utf-8"):
"""
Compute the fuzzy hash of a buffer
:param String|Bytes buf: The data to be fuzzy hashed
:return: The fuzzy hash
:rtype: String
:raises InternalError: If lib returns an internal error
:raises TypeError: If buf is not String or Bytes
"""
if isins... | [
"def",
"hash",
"(",
"buf",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"isinstance",
"(",
"buf",
",",
"six",
".",
"text_type",
")",
":",
"buf",
"=",
"buf",
".",
"encode",
"(",
"encoding",
")",
"if",
"not",
"isinstance",
"(",
"buf",
",",
"six... | Compute the fuzzy hash of a buffer
:param String|Bytes buf: The data to be fuzzy hashed
:return: The fuzzy hash
:rtype: String
:raises InternalError: If lib returns an internal error
:raises TypeError: If buf is not String or Bytes | [
"Compute",
"the",
"fuzzy",
"hash",
"of",
"a",
"buffer"
] | c17b3dc0f53514afff59eca67717291ccd206b7c | https://github.com/DinoTools/python-ssdeep/blob/c17b3dc0f53514afff59eca67717291ccd206b7c/src/ssdeep/__init__.py#L191-L217 | train |
DinoTools/python-ssdeep | src/ssdeep/__init__.py | hash_from_file | def hash_from_file(filename):
"""
Compute the fuzzy hash of a file.
Opens, reads, and hashes the contents of the file 'filename'
:param String|Bytes filename: The name of the file to be hashed
:return: The fuzzy hash of the file
:rtype: String
:raises IOError: If Python is unable to read t... | python | def hash_from_file(filename):
"""
Compute the fuzzy hash of a file.
Opens, reads, and hashes the contents of the file 'filename'
:param String|Bytes filename: The name of the file to be hashed
:return: The fuzzy hash of the file
:rtype: String
:raises IOError: If Python is unable to read t... | [
"def",
"hash_from_file",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"IOError",
"(",
"\"Path not found\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
... | Compute the fuzzy hash of a file.
Opens, reads, and hashes the contents of the file 'filename'
:param String|Bytes filename: The name of the file to be hashed
:return: The fuzzy hash of the file
:rtype: String
:raises IOError: If Python is unable to read the file
:raises InternalError: If lib ... | [
"Compute",
"the",
"fuzzy",
"hash",
"of",
"a",
"file",
"."
] | c17b3dc0f53514afff59eca67717291ccd206b7c | https://github.com/DinoTools/python-ssdeep/blob/c17b3dc0f53514afff59eca67717291ccd206b7c/src/ssdeep/__init__.py#L220-L245 | train |
DinoTools/python-ssdeep | src/ssdeep/__init__.py | Hash.digest | def digest(self, elimseq=False, notrunc=False):
"""
Obtain the fuzzy hash.
This operation does not change the state at all. It reports the hash
for the concatenation of the data previously fed using update().
:return: The fuzzy hash
:rtype: String
:raises Intern... | python | def digest(self, elimseq=False, notrunc=False):
"""
Obtain the fuzzy hash.
This operation does not change the state at all. It reports the hash
for the concatenation of the data previously fed using update().
:return: The fuzzy hash
:rtype: String
:raises Intern... | [
"def",
"digest",
"(",
"self",
",",
"elimseq",
"=",
"False",
",",
"notrunc",
"=",
"False",
")",
":",
"if",
"self",
".",
"_state",
"==",
"ffi",
".",
"NULL",
":",
"raise",
"InternalError",
"(",
"\"State object is NULL\"",
")",
"flags",
"=",
"(",
"binding",
... | Obtain the fuzzy hash.
This operation does not change the state at all. It reports the hash
for the concatenation of the data previously fed using update().
:return: The fuzzy hash
:rtype: String
:raises InternalError: If lib returns an internal error | [
"Obtain",
"the",
"fuzzy",
"hash",
"."
] | c17b3dc0f53514afff59eca67717291ccd206b7c | https://github.com/DinoTools/python-ssdeep/blob/c17b3dc0f53514afff59eca67717291ccd206b7c/src/ssdeep/__init__.py#L74-L97 | train |
Pythonity/icon-font-to-png | icon_font_to_png/icon_font.py | IconFont.load_css | def load_css(self):
"""
Creates a dict of all icons available in CSS file, and finds out
what's their common prefix.
:returns sorted icons dict, common icon prefix
"""
icons = dict()
common_prefix = None
parser = tinycss.make_parser('page3')
style... | python | def load_css(self):
"""
Creates a dict of all icons available in CSS file, and finds out
what's their common prefix.
:returns sorted icons dict, common icon prefix
"""
icons = dict()
common_prefix = None
parser = tinycss.make_parser('page3')
style... | [
"def",
"load_css",
"(",
"self",
")",
":",
"icons",
"=",
"dict",
"(",
")",
"common_prefix",
"=",
"None",
"parser",
"=",
"tinycss",
".",
"make_parser",
"(",
"'page3'",
")",
"stylesheet",
"=",
"parser",
".",
"parse_stylesheet_file",
"(",
"self",
".",
"css_fil... | Creates a dict of all icons available in CSS file, and finds out
what's their common prefix.
:returns sorted icons dict, common icon prefix | [
"Creates",
"a",
"dict",
"of",
"all",
"icons",
"available",
"in",
"CSS",
"file",
"and",
"finds",
"out",
"what",
"s",
"their",
"common",
"prefix",
"."
] | 4851fe15c077402749f843d43fbc10d28f6c655d | https://github.com/Pythonity/icon-font-to-png/blob/4851fe15c077402749f843d43fbc10d28f6c655d/icon_font_to_png/icon_font.py#L27-L76 | train |
Pythonity/icon-font-to-png | icon_font_to_png/icon_font.py | IconFont.export_icon | def export_icon(self, icon, size, color='black', scale='auto',
filename=None, export_dir='exported'):
"""
Exports given icon with provided parameters.
If the desired icon size is less than 150x150 pixels, we will first
create a 150x150 pixels image and then scale it ... | python | def export_icon(self, icon, size, color='black', scale='auto',
filename=None, export_dir='exported'):
"""
Exports given icon with provided parameters.
If the desired icon size is less than 150x150 pixels, we will first
create a 150x150 pixels image and then scale it ... | [
"def",
"export_icon",
"(",
"self",
",",
"icon",
",",
"size",
",",
"color",
"=",
"'black'",
",",
"scale",
"=",
"'auto'",
",",
"filename",
"=",
"None",
",",
"export_dir",
"=",
"'exported'",
")",
":",
"org_size",
"=",
"size",
"size",
"=",
"max",
"(",
"1... | Exports given icon with provided parameters.
If the desired icon size is less than 150x150 pixels, we will first
create a 150x150 pixels image and then scale it down, so that
it's much less likely that the edges of the icon end up cropped.
:param icon: valid icon name
:param fi... | [
"Exports",
"given",
"icon",
"with",
"provided",
"parameters",
"."
] | 4851fe15c077402749f843d43fbc10d28f6c655d | https://github.com/Pythonity/icon-font-to-png/blob/4851fe15c077402749f843d43fbc10d28f6c655d/icon_font_to_png/icon_font.py#L78-L175 | train |
alaudet/hcsr04sensor | hcsr04sensor/sensor.py | basic_distance | def basic_distance(trig_pin, echo_pin, celsius=20):
'''Return an unformatted distance in cm's as read directly from
RPi.GPIO.'''
speed_of_sound = 331.3 * math.sqrt(1+(celsius / 273.15))
GPIO.setup(trig_pin, GPIO.OUT)
GPIO.setup(echo_pin, GPIO.IN)
GPIO.output(trig_pin, GPIO.LOW)
time.sleep(0... | python | def basic_distance(trig_pin, echo_pin, celsius=20):
'''Return an unformatted distance in cm's as read directly from
RPi.GPIO.'''
speed_of_sound = 331.3 * math.sqrt(1+(celsius / 273.15))
GPIO.setup(trig_pin, GPIO.OUT)
GPIO.setup(echo_pin, GPIO.IN)
GPIO.output(trig_pin, GPIO.LOW)
time.sleep(0... | [
"def",
"basic_distance",
"(",
"trig_pin",
",",
"echo_pin",
",",
"celsius",
"=",
"20",
")",
":",
"speed_of_sound",
"=",
"331.3",
"*",
"math",
".",
"sqrt",
"(",
"1",
"+",
"(",
"celsius",
"/",
"273.15",
")",
")",
"GPIO",
".",
"setup",
"(",
"trig_pin",
"... | Return an unformatted distance in cm's as read directly from
RPi.GPIO. | [
"Return",
"an",
"unformatted",
"distance",
"in",
"cm",
"s",
"as",
"read",
"directly",
"from",
"RPi",
".",
"GPIO",
"."
] | 74caf5c825e3f700c9daa9985542c061ae04b002 | https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/hcsr04sensor/sensor.py#L127-L150 | train |
alaudet/hcsr04sensor | hcsr04sensor/sensor.py | Measurement.raw_distance | def raw_distance(self, sample_size=11, sample_wait=0.1):
'''Return an error corrected unrounded distance, in cm, of an object
adjusted for temperature in Celcius. The distance calculated
is the median value of a sample of `sample_size` readings.
Speed of readings is a result ... | python | def raw_distance(self, sample_size=11, sample_wait=0.1):
'''Return an error corrected unrounded distance, in cm, of an object
adjusted for temperature in Celcius. The distance calculated
is the median value of a sample of `sample_size` readings.
Speed of readings is a result ... | [
"def",
"raw_distance",
"(",
"self",
",",
"sample_size",
"=",
"11",
",",
"sample_wait",
"=",
"0.1",
")",
":",
"if",
"self",
".",
"unit",
"==",
"'imperial'",
":",
"self",
".",
"temperature",
"=",
"(",
"self",
".",
"temperature",
"-",
"32",
")",
"*",
"0... | Return an error corrected unrounded distance, in cm, of an object
adjusted for temperature in Celcius. The distance calculated
is the median value of a sample of `sample_size` readings.
Speed of readings is a result of two variables. The sample_size
per reading and the sampl... | [
"Return",
"an",
"error",
"corrected",
"unrounded",
"distance",
"in",
"cm",
"of",
"an",
"object",
"adjusted",
"for",
"temperature",
"in",
"Celcius",
".",
"The",
"distance",
"calculated",
"is",
"the",
"median",
"value",
"of",
"a",
"sample",
"of",
"sample_size",
... | 74caf5c825e3f700c9daa9985542c061ae04b002 | https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/hcsr04sensor/sensor.py#L36-L100 | train |
alaudet/hcsr04sensor | recipes/metric_depth.py | main | def main():
'''Calculate the depth of a liquid in centimeters using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
hole_depth = 80 # centimeters
# Create a distance reading with the hc... | python | def main():
'''Calculate the depth of a liquid in centimeters using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
hole_depth = 80 # centimeters
# Create a distance reading with the hc... | [
"def",
"main",
"(",
")",
":",
"trig_pin",
"=",
"17",
"echo_pin",
"=",
"27",
"hole_depth",
"=",
"80",
"value",
"=",
"sensor",
".",
"Measurement",
"(",
"trig_pin",
",",
"echo_pin",
")",
"raw_measurement",
"=",
"value",
".",
"raw_distance",
"(",
")",
"liqui... | Calculate the depth of a liquid in centimeters using a HCSR04 sensor
and a Raspberry Pi | [
"Calculate",
"the",
"depth",
"of",
"a",
"liquid",
"in",
"centimeters",
"using",
"a",
"HCSR04",
"sensor",
"and",
"a",
"Raspberry",
"Pi"
] | 74caf5c825e3f700c9daa9985542c061ae04b002 | https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/recipes/metric_depth.py#L6-L38 | train |
alaudet/hcsr04sensor | recipes/sample_speed.py | main | def main():
'''Calculate the distance of an object in centimeters using a HCSR04 sensor
and a Raspberry Pi. This script allows for a quicker reading by
decreasing the number of samples and forcing the readings to be
taken at quicker intervals.'''
trig_pin = 17
echo_pin = 27
# Cre... | python | def main():
'''Calculate the distance of an object in centimeters using a HCSR04 sensor
and a Raspberry Pi. This script allows for a quicker reading by
decreasing the number of samples and forcing the readings to be
taken at quicker intervals.'''
trig_pin = 17
echo_pin = 27
# Cre... | [
"def",
"main",
"(",
")",
":",
"trig_pin",
"=",
"17",
"echo_pin",
"=",
"27",
"value",
"=",
"sensor",
".",
"Measurement",
"(",
"trig_pin",
",",
"echo_pin",
")",
"raw_measurement",
"=",
"value",
".",
"raw_distance",
"(",
"sample_size",
"=",
"5",
",",
"sampl... | Calculate the distance of an object in centimeters using a HCSR04 sensor
and a Raspberry Pi. This script allows for a quicker reading by
decreasing the number of samples and forcing the readings to be
taken at quicker intervals. | [
"Calculate",
"the",
"distance",
"of",
"an",
"object",
"in",
"centimeters",
"using",
"a",
"HCSR04",
"sensor",
"and",
"a",
"Raspberry",
"Pi",
".",
"This",
"script",
"allows",
"for",
"a",
"quicker",
"reading",
"by",
"decreasing",
"the",
"number",
"of",
"samples... | 74caf5c825e3f700c9daa9985542c061ae04b002 | https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/recipes/sample_speed.py#L6-L31 | train |
alaudet/hcsr04sensor | bin/hcsr04.py | main | def main():
'''Main function to run the sensor with passed arguments'''
trig, echo, speed, samples = get_args()
print('trig pin = gpio {}'.format(trig))
print('echo pin = gpio {}'.format(echo))
print('speed = {}'.format(speed))
print('samples = {}'.format(samples))
print('')
va... | python | def main():
'''Main function to run the sensor with passed arguments'''
trig, echo, speed, samples = get_args()
print('trig pin = gpio {}'.format(trig))
print('echo pin = gpio {}'.format(echo))
print('speed = {}'.format(speed))
print('samples = {}'.format(samples))
print('')
va... | [
"def",
"main",
"(",
")",
":",
"trig",
",",
"echo",
",",
"speed",
",",
"samples",
"=",
"get_args",
"(",
")",
"print",
"(",
"'trig pin = gpio {}'",
".",
"format",
"(",
"trig",
")",
")",
"print",
"(",
"'echo pin = gpio {}'",
".",
"format",
"(",
"echo",
")... | Main function to run the sensor with passed arguments | [
"Main",
"function",
"to",
"run",
"the",
"sensor",
"with",
"passed",
"arguments"
] | 74caf5c825e3f700c9daa9985542c061ae04b002 | https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/bin/hcsr04.py#L59-L75 | train |
alaudet/hcsr04sensor | recipes/imperial_depth.py | main | def main():
'''Calculate the depth of a liquid in inches using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
hole_depth = 31.5 # inches
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
# Create a distance reading with the hcsr04 sens... | python | def main():
'''Calculate the depth of a liquid in inches using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
hole_depth = 31.5 # inches
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
# Create a distance reading with the hcsr04 sens... | [
"def",
"main",
"(",
")",
":",
"trig_pin",
"=",
"17",
"echo_pin",
"=",
"27",
"hole_depth",
"=",
"31.5",
"value",
"=",
"sensor",
".",
"Measurement",
"(",
"trig_pin",
",",
"echo_pin",
",",
"temperature",
"=",
"68",
",",
"unit",
"=",
"'imperial'",
",",
"ro... | Calculate the depth of a liquid in inches using a HCSR04 sensor
and a Raspberry Pi | [
"Calculate",
"the",
"depth",
"of",
"a",
"liquid",
"in",
"inches",
"using",
"a",
"HCSR04",
"sensor",
"and",
"a",
"Raspberry",
"Pi"
] | 74caf5c825e3f700c9daa9985542c061ae04b002 | https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/recipes/imperial_depth.py#L6-L32 | train |
alaudet/hcsr04sensor | recipes/imperial_distance.py | main | def main():
'''Calculate the distance of an object in inches using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
# Create a distance reading with the hcsr04 sensor module
# and overide ... | python | def main():
'''Calculate the distance of an object in inches using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
# Create a distance reading with the hcsr04 sensor module
# and overide ... | [
"def",
"main",
"(",
")",
":",
"trig_pin",
"=",
"17",
"echo_pin",
"=",
"27",
"value",
"=",
"sensor",
".",
"Measurement",
"(",
"trig_pin",
",",
"echo_pin",
",",
"temperature",
"=",
"68",
",",
"unit",
"=",
"'imperial'",
",",
"round_to",
"=",
"2",
")",
"... | Calculate the distance of an object in inches using a HCSR04 sensor
and a Raspberry Pi | [
"Calculate",
"the",
"distance",
"of",
"an",
"object",
"in",
"inches",
"using",
"a",
"HCSR04",
"sensor",
"and",
"a",
"Raspberry",
"Pi"
] | 74caf5c825e3f700c9daa9985542c061ae04b002 | https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/recipes/imperial_distance.py#L6-L31 | train |
vsergeev/python-periphery | periphery/led.py | LED.read | def read(self):
"""Read the brightness of the LED.
Returns:
int: Current brightness.
Raises:
LEDError: if an I/O or OS error occurs.
"""
# Read value
try:
buf = os.read(self._fd, 8)
except OSError as e:
raise LEDE... | python | def read(self):
"""Read the brightness of the LED.
Returns:
int: Current brightness.
Raises:
LEDError: if an I/O or OS error occurs.
"""
# Read value
try:
buf = os.read(self._fd, 8)
except OSError as e:
raise LEDE... | [
"def",
"read",
"(",
"self",
")",
":",
"try",
":",
"buf",
"=",
"os",
".",
"read",
"(",
"self",
".",
"_fd",
",",
"8",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"LEDError",
"(",
"e",
".",
"errno",
",",
"\"Reading LED brightness: \"",
"+",
"e"... | Read the brightness of the LED.
Returns:
int: Current brightness.
Raises:
LEDError: if an I/O or OS error occurs. | [
"Read",
"the",
"brightness",
"of",
"the",
"LED",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/led.py#L78-L100 | train |
vsergeev/python-periphery | periphery/led.py | LED.write | def write(self, brightness):
"""Set the brightness of the LED to `brightness`.
`brightness` can be a boolean for on/off, or integer value for a
specific brightness.
Args:
brightness (bool, int): Brightness value to set.
Raises:
LEDError: if an I/O or OS... | python | def write(self, brightness):
"""Set the brightness of the LED to `brightness`.
`brightness` can be a boolean for on/off, or integer value for a
specific brightness.
Args:
brightness (bool, int): Brightness value to set.
Raises:
LEDError: if an I/O or OS... | [
"def",
"write",
"(",
"self",
",",
"brightness",
")",
":",
"if",
"not",
"isinstance",
"(",
"brightness",
",",
"(",
"bool",
",",
"int",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid brightness type, should be bool or int.\"",
")",
"if",
"isinstance",
"(",... | Set the brightness of the LED to `brightness`.
`brightness` can be a boolean for on/off, or integer value for a
specific brightness.
Args:
brightness (bool, int): Brightness value to set.
Raises:
LEDError: if an I/O or OS error occurs.
TypeError: if... | [
"Set",
"the",
"brightness",
"of",
"the",
"LED",
"to",
"brightness",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/led.py#L102-L135 | train |
vsergeev/python-periphery | periphery/led.py | LED.close | def close(self):
"""Close the sysfs LED.
Raises:
LEDError: if an I/O or OS error occurs.
"""
if self._fd is None:
return
try:
os.close(self._fd)
except OSError as e:
raise LEDError(e.errno, "Closing LED: " + e.strerror)
... | python | def close(self):
"""Close the sysfs LED.
Raises:
LEDError: if an I/O or OS error occurs.
"""
if self._fd is None:
return
try:
os.close(self._fd)
except OSError as e:
raise LEDError(e.errno, "Closing LED: " + e.strerror)
... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_fd",
"is",
"None",
":",
"return",
"try",
":",
"os",
".",
"close",
"(",
"self",
".",
"_fd",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"LEDError",
"(",
"e",
".",
"errno",
",",
"... | Close the sysfs LED.
Raises:
LEDError: if an I/O or OS error occurs. | [
"Close",
"the",
"sysfs",
"LED",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/led.py#L137-L152 | train |
vsergeev/python-periphery | periphery/i2c.py | I2C.transfer | def transfer(self, address, messages):
"""Transfer `messages` to the specified I2C `address`. Modifies the
`messages` array with the results of any read transactions.
Args:
address (int): I2C address.
messages (list): list of I2C.Message messages.
Raises:
... | python | def transfer(self, address, messages):
"""Transfer `messages` to the specified I2C `address`. Modifies the
`messages` array with the results of any read transactions.
Args:
address (int): I2C address.
messages (list): list of I2C.Message messages.
Raises:
... | [
"def",
"transfer",
"(",
"self",
",",
"address",
",",
"messages",
")",
":",
"if",
"not",
"isinstance",
"(",
"messages",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid messages type, should be list of I2C.Message.\"",
")",
"elif",
"len",
"(",
"messag... | Transfer `messages` to the specified I2C `address`. Modifies the
`messages` array with the results of any read transactions.
Args:
address (int): I2C address.
messages (list): list of I2C.Message messages.
Raises:
I2CError: if an I/O or OS error occurs.
... | [
"Transfer",
"messages",
"to",
"the",
"specified",
"I2C",
"address",
".",
"Modifies",
"the",
"messages",
"array",
"with",
"the",
"results",
"of",
"any",
"read",
"transactions",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/i2c.py#L93-L149 | train |
vsergeev/python-periphery | periphery/serial.py | Serial.read | def read(self, length, timeout=None):
"""Read up to `length` number of bytes from the serial port with an
optional timeout.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking read, or negative or None for a blocking read that will
block until `length` numbe... | python | def read(self, length, timeout=None):
"""Read up to `length` number of bytes from the serial port with an
optional timeout.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking read, or negative or None for a blocking read that will
block until `length` numbe... | [
"def",
"read",
"(",
"self",
",",
"length",
",",
"timeout",
"=",
"None",
")",
":",
"data",
"=",
"b\"\"",
"while",
"True",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"(",
"rlist",
",",
"_",
",",
"_",
")",
"=",
"select",
".",
"select",
"(",
"... | Read up to `length` number of bytes from the serial port with an
optional timeout.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking read, or negative or None for a blocking read that will
block until `length` number of bytes are read. Default is a blocking
... | [
"Read",
"up",
"to",
"length",
"number",
"of",
"bytes",
"from",
"the",
"serial",
"port",
"with",
"an",
"optional",
"timeout",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L172-L216 | train |
vsergeev/python-periphery | periphery/serial.py | Serial.write | def write(self, data):
"""Write `data` to the serial port and return the number of bytes
written.
Args:
data (bytes, bytearray, list): a byte array or list of 8-bit integers to write.
Returns:
int: number of bytes written.
Raises:
SerialErro... | python | def write(self, data):
"""Write `data` to the serial port and return the number of bytes
written.
Args:
data (bytes, bytearray, list): a byte array or list of 8-bit integers to write.
Returns:
int: number of bytes written.
Raises:
SerialErro... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"bytearray",
",",
"list",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid data type, should be bytes, bytearray, or list.\"",
")",
"if",
... | Write `data` to the serial port and return the number of bytes
written.
Args:
data (bytes, bytearray, list): a byte array or list of 8-bit integers to write.
Returns:
int: number of bytes written.
Raises:
SerialError: if an I/O or OS error occurs.
... | [
"Write",
"data",
"to",
"the",
"serial",
"port",
"and",
"return",
"the",
"number",
"of",
"bytes",
"written",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L218-L243 | train |
vsergeev/python-periphery | periphery/serial.py | Serial.poll | def poll(self, timeout=None):
"""Poll for data available for reading from the serial port.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking poll, or negative or None for a blocking poll. Default is
a blocking poll.
Args:
timeout (int, float, ... | python | def poll(self, timeout=None):
"""Poll for data available for reading from the serial port.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking poll, or negative or None for a blocking poll. Default is
a blocking poll.
Args:
timeout (int, float, ... | [
"def",
"poll",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"p",
"=",
"select",
".",
"poll",
"(",
")",
"p",
".",
"register",
"(",
"self",
".",
"_fd",
",",
"select",
".",
"POLLIN",
"|",
"select",
".",
"POLLPRI",
")",
"events",
"=",
"p",
"... | Poll for data available for reading from the serial port.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking poll, or negative or None for a blocking poll. Default is
a blocking poll.
Args:
timeout (int, float, None): timeout duration in seconds.
... | [
"Poll",
"for",
"data",
"available",
"for",
"reading",
"from",
"the",
"serial",
"port",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L245-L266 | train |
vsergeev/python-periphery | periphery/serial.py | Serial.flush | def flush(self):
"""Flush the write buffer of the serial port, blocking until all bytes
are written.
Raises:
SerialError: if an I/O or OS error occurs.
"""
try:
termios.tcdrain(self._fd)
except termios.error as e:
raise SerialError(e.... | python | def flush(self):
"""Flush the write buffer of the serial port, blocking until all bytes
are written.
Raises:
SerialError: if an I/O or OS error occurs.
"""
try:
termios.tcdrain(self._fd)
except termios.error as e:
raise SerialError(e.... | [
"def",
"flush",
"(",
"self",
")",
":",
"try",
":",
"termios",
".",
"tcdrain",
"(",
"self",
".",
"_fd",
")",
"except",
"termios",
".",
"error",
"as",
"e",
":",
"raise",
"SerialError",
"(",
"e",
".",
"errno",
",",
"\"Flushing serial port: \"",
"+",
"e",
... | Flush the write buffer of the serial port, blocking until all bytes
are written.
Raises:
SerialError: if an I/O or OS error occurs. | [
"Flush",
"the",
"write",
"buffer",
"of",
"the",
"serial",
"port",
"blocking",
"until",
"all",
"bytes",
"are",
"written",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L268-L279 | train |
vsergeev/python-periphery | periphery/serial.py | Serial.input_waiting | def input_waiting(self):
"""Query the number of bytes waiting to be read from the serial port.
Returns:
int: number of bytes waiting to be read.
Raises:
SerialError: if an I/O or OS error occurs.
"""
# Get input waiting
buf = array.array('I', [0... | python | def input_waiting(self):
"""Query the number of bytes waiting to be read from the serial port.
Returns:
int: number of bytes waiting to be read.
Raises:
SerialError: if an I/O or OS error occurs.
"""
# Get input waiting
buf = array.array('I', [0... | [
"def",
"input_waiting",
"(",
"self",
")",
":",
"buf",
"=",
"array",
".",
"array",
"(",
"'I'",
",",
"[",
"0",
"]",
")",
"try",
":",
"fcntl",
".",
"ioctl",
"(",
"self",
".",
"_fd",
",",
"termios",
".",
"TIOCINQ",
",",
"buf",
",",
"True",
")",
"ex... | Query the number of bytes waiting to be read from the serial port.
Returns:
int: number of bytes waiting to be read.
Raises:
SerialError: if an I/O or OS error occurs. | [
"Query",
"the",
"number",
"of",
"bytes",
"waiting",
"to",
"be",
"read",
"from",
"the",
"serial",
"port",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L281-L298 | train |
vsergeev/python-periphery | periphery/serial.py | Serial.output_waiting | def output_waiting(self):
"""Query the number of bytes waiting to be written to the serial port.
Returns:
int: number of bytes waiting to be written.
Raises:
SerialError: if an I/O or OS error occurs.
"""
# Get input waiting
buf = array.array('I... | python | def output_waiting(self):
"""Query the number of bytes waiting to be written to the serial port.
Returns:
int: number of bytes waiting to be written.
Raises:
SerialError: if an I/O or OS error occurs.
"""
# Get input waiting
buf = array.array('I... | [
"def",
"output_waiting",
"(",
"self",
")",
":",
"buf",
"=",
"array",
".",
"array",
"(",
"'I'",
",",
"[",
"0",
"]",
")",
"try",
":",
"fcntl",
".",
"ioctl",
"(",
"self",
".",
"_fd",
",",
"termios",
".",
"TIOCOUTQ",
",",
"buf",
",",
"True",
")",
"... | Query the number of bytes waiting to be written to the serial port.
Returns:
int: number of bytes waiting to be written.
Raises:
SerialError: if an I/O or OS error occurs. | [
"Query",
"the",
"number",
"of",
"bytes",
"waiting",
"to",
"be",
"written",
"to",
"the",
"serial",
"port",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L300-L317 | train |
vsergeev/python-periphery | periphery/gpio.py | GPIO.read | def read(self):
"""Read the state of the GPIO.
Returns:
bool: ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs.
"""
# Read value
try:
buf = os.read(self._fd, 2)
except OSError ... | python | def read(self):
"""Read the state of the GPIO.
Returns:
bool: ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs.
"""
# Read value
try:
buf = os.read(self._fd, 2)
except OSError ... | [
"def",
"read",
"(",
"self",
")",
":",
"try",
":",
"buf",
"=",
"os",
".",
"read",
"(",
"self",
".",
"_fd",
",",
"2",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"GPIOError",
"(",
"e",
".",
"errno",
",",
"\"Reading GPIO: \"",
"+",
"e",
".",
... | Read the state of the GPIO.
Returns:
bool: ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs. | [
"Read",
"the",
"state",
"of",
"the",
"GPIO",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/gpio.py#L103-L130 | train |
vsergeev/python-periphery | periphery/gpio.py | GPIO.write | def write(self, value):
"""Set the state of the GPIO to `value`.
Args:
value (bool): ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs.
TypeError: if `value` type is not bool.
"""
if not isinst... | python | def write(self, value):
"""Set the state of the GPIO to `value`.
Args:
value (bool): ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs.
TypeError: if `value` type is not bool.
"""
if not isinst... | [
"def",
"write",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid value type, should be bool.\"",
")",
"try",
":",
"if",
"value",
":",
"os",
".",
"write",
"(",
"self... | Set the state of the GPIO to `value`.
Args:
value (bool): ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs.
TypeError: if `value` type is not bool. | [
"Set",
"the",
"state",
"of",
"the",
"GPIO",
"to",
"value",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/gpio.py#L132-L159 | train |
vsergeev/python-periphery | periphery/gpio.py | GPIO.poll | def poll(self, timeout=None):
"""Poll a GPIO for the edge event configured with the .edge property.
`timeout` can be a positive number for a timeout in seconds, 0 for a
non-blocking poll, or negative or None for a blocking poll. Defaults to
blocking poll.
Args:
time... | python | def poll(self, timeout=None):
"""Poll a GPIO for the edge event configured with the .edge property.
`timeout` can be a positive number for a timeout in seconds, 0 for a
non-blocking poll, or negative or None for a blocking poll. Defaults to
blocking poll.
Args:
time... | [
"def",
"poll",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"timeout",
",",
"(",
"int",
",",
"float",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid timeout type, should be integ... | Poll a GPIO for the edge event configured with the .edge property.
`timeout` can be a positive number for a timeout in seconds, 0 for a
non-blocking poll, or negative or None for a blocking poll. Defaults to
blocking poll.
Args:
timeout (int, float, None): timeout duration ... | [
"Poll",
"a",
"GPIO",
"for",
"the",
"edge",
"event",
"configured",
"with",
"the",
".",
"edge",
"property",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/gpio.py#L161-L200 | train |
vsergeev/python-periphery | periphery/mmio.py | MMIO.read32 | def read32(self, offset):
"""Read 32-bits from the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
Returns:
int: 32-bit value read.
Raises:
... | python | def read32(self, offset):
"""Read 32-bits from the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
Returns:
int: 32-bit value read.
Raises:
... | [
"def",
"read32",
"(",
"self",
",",
"offset",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid offset type, should be integer.\"",
")",
"offset",
"=",
"self",
".",
"_adjus... | Read 32-bits from the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
Returns:
int: 32-bit value read.
Raises:
TypeError: if `offset` type ... | [
"Read",
"32",
"-",
"bits",
"from",
"the",
"specified",
"offset",
"in",
"bytes",
"relative",
"to",
"the",
"base",
"physical",
"address",
"of",
"the",
"MMIO",
"region",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L84-L104 | train |
vsergeev/python-periphery | periphery/mmio.py | MMIO.read | def read(self, offset, length):
"""Read a string of bytes from the specified `offset` in bytes,
relative to the base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
length (int): number of bytes to read.
... | python | def read(self, offset, length):
"""Read a string of bytes from the specified `offset` in bytes,
relative to the base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
length (int): number of bytes to read.
... | [
"def",
"read",
"(",
"self",
",",
"offset",
",",
"length",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid offset type, should be integer.\"",
")",
"offset",
"=",
"self",... | Read a string of bytes from the specified `offset` in bytes,
relative to the base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
length (int): number of bytes to read.
Returns:
bytes: bytes read.
... | [
"Read",
"a",
"string",
"of",
"bytes",
"from",
"the",
"specified",
"offset",
"in",
"bytes",
"relative",
"to",
"the",
"base",
"physical",
"address",
"of",
"the",
"MMIO",
"region",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L150-L171 | train |
vsergeev/python-periphery | periphery/mmio.py | MMIO.write8 | def write8(self, offset, value):
"""Write 8-bits to the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
value (int, long): 8-bit value to write.
Raises:... | python | def write8(self, offset, value):
"""Write 8-bits to the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
value (int, long): 8-bit value to write.
Raises:... | [
"def",
"write8",
"(",
"self",
",",
"offset",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid offset type, should be integer.\"",
")",
"if",
"not",
"isinsta... | Write 8-bits to the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
value (int, long): 8-bit value to write.
Raises:
TypeError: if `offset` or `valu... | [
"Write",
"8",
"-",
"bits",
"to",
"the",
"specified",
"offset",
"in",
"bytes",
"relative",
"to",
"the",
"base",
"physical",
"address",
"of",
"the",
"MMIO",
"region",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L221-L243 | train |
vsergeev/python-periphery | periphery/mmio.py | MMIO.write | def write(self, offset, data):
"""Write a string of bytes to the specified `offset` in bytes, relative
to the base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
data (bytes, bytearray, list): a byte array or l... | python | def write(self, offset, data):
"""Write a string of bytes to the specified `offset` in bytes, relative
to the base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
data (bytes, bytearray, list): a byte array or l... | [
"def",
"write",
"(",
"self",
",",
"offset",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid offset type, should be integer.\"",
")",
"if",
"not",
"isinstanc... | Write a string of bytes to the specified `offset` in bytes, relative
to the base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
data (bytes, bytearray, list): a byte array or list of 8-bit
... | [
"Write",
"a",
"string",
"of",
"bytes",
"to",
"the",
"specified",
"offset",
"in",
"bytes",
"relative",
"to",
"the",
"base",
"physical",
"address",
"of",
"the",
"MMIO",
"region",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L245-L268 | train |
vsergeev/python-periphery | periphery/mmio.py | MMIO.close | def close(self):
"""Unmap the MMIO object's mapped physical memory."""
if self.mapping is None:
return
self.mapping.close()
self.mapping = None
self._fd = None | python | def close(self):
"""Unmap the MMIO object's mapped physical memory."""
if self.mapping is None:
return
self.mapping.close()
self.mapping = None
self._fd = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"mapping",
"is",
"None",
":",
"return",
"self",
".",
"mapping",
".",
"close",
"(",
")",
"self",
".",
"mapping",
"=",
"None",
"self",
".",
"_fd",
"=",
"None"
] | Unmap the MMIO object's mapped physical memory. | [
"Unmap",
"the",
"MMIO",
"object",
"s",
"mapped",
"physical",
"memory",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L270-L278 | train |
vsergeev/python-periphery | periphery/mmio.py | MMIO.pointer | def pointer(self):
"""Get a ctypes void pointer to the memory mapped region.
:type: ctypes.c_void_p
"""
return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p) | python | def pointer(self):
"""Get a ctypes void pointer to the memory mapped region.
:type: ctypes.c_void_p
"""
return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p) | [
"def",
"pointer",
"(",
"self",
")",
":",
"return",
"ctypes",
".",
"cast",
"(",
"ctypes",
".",
"pointer",
"(",
"ctypes",
".",
"c_uint8",
".",
"from_buffer",
"(",
"self",
".",
"mapping",
",",
"0",
")",
")",
",",
"ctypes",
".",
"c_void_p",
")"
] | Get a ctypes void pointer to the memory mapped region.
:type: ctypes.c_void_p | [
"Get",
"a",
"ctypes",
"void",
"pointer",
"to",
"the",
"memory",
"mapped",
"region",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L299-L304 | train |
vsergeev/python-periphery | periphery/spi.py | SPI.transfer | def transfer(self, data):
"""Shift out `data` and return shifted in data.
Args:
data (bytes, bytearray, list): a byte array or list of 8-bit integers to shift out.
Returns:
bytes, bytearray, list: data shifted in.
Raises:
SPIError: if an I/O or OS e... | python | def transfer(self, data):
"""Shift out `data` and return shifted in data.
Args:
data (bytes, bytearray, list): a byte array or list of 8-bit integers to shift out.
Returns:
bytes, bytearray, list: data shifted in.
Raises:
SPIError: if an I/O or OS e... | [
"def",
"transfer",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"bytearray",
",",
"list",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid data type, should be bytes, bytearray, or list.\"",
")",
"try"... | Shift out `data` and return shifted in data.
Args:
data (bytes, bytearray, list): a byte array or list of 8-bit integers to shift out.
Returns:
bytes, bytearray, list: data shifted in.
Raises:
SPIError: if an I/O or OS error occurs.
TypeError: i... | [
"Shift",
"out",
"data",
"and",
"return",
"shifted",
"in",
"data",
"."
] | ff4d535691a1747a76962a3d077d96d224308611 | https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/spi.py#L131-L175 | train |
pinax/pinax-referrals | pinax/referrals/utils.py | ensure_session_key | def ensure_session_key(request):
"""
Given a request return a session key that will be used. There may already
be a session key associated, but if there is not, we force the session to
create itself and persist between requests for the client behind the given
request.
"""
key = request.sessi... | python | def ensure_session_key(request):
"""
Given a request return a session key that will be used. There may already
be a session key associated, but if there is not, we force the session to
create itself and persist between requests for the client behind the given
request.
"""
key = request.sessi... | [
"def",
"ensure_session_key",
"(",
"request",
")",
":",
"key",
"=",
"request",
".",
"session",
".",
"session_key",
"if",
"key",
"is",
"None",
":",
"request",
".",
"session",
".",
"save",
"(",
")",
"request",
".",
"session",
".",
"modified",
"=",
"True",
... | Given a request return a session key that will be used. There may already
be a session key associated, but if there is not, we force the session to
create itself and persist between requests for the client behind the given
request. | [
"Given",
"a",
"request",
"return",
"a",
"session",
"key",
"that",
"will",
"be",
"used",
".",
"There",
"may",
"already",
"be",
"a",
"session",
"key",
"associated",
"but",
"if",
"there",
"is",
"not",
"we",
"force",
"the",
"session",
"to",
"create",
"itself... | 4e192afb31287c6ba426badae513555ff04a945d | https://github.com/pinax/pinax-referrals/blob/4e192afb31287c6ba426badae513555ff04a945d/pinax/referrals/utils.py#L6-L21 | train |
carsonyl/pypac | pypac/resolver.py | add_proxy_auth | def add_proxy_auth(possible_proxy_url, proxy_auth):
"""
Add a username and password to a proxy URL, if the input value is a proxy URL.
:param str possible_proxy_url: Proxy URL or ``DIRECT``.
:param requests.auth.HTTPProxyAuth proxy_auth: Proxy authentication info.
:returns: Proxy URL with auth info... | python | def add_proxy_auth(possible_proxy_url, proxy_auth):
"""
Add a username and password to a proxy URL, if the input value is a proxy URL.
:param str possible_proxy_url: Proxy URL or ``DIRECT``.
:param requests.auth.HTTPProxyAuth proxy_auth: Proxy authentication info.
:returns: Proxy URL with auth info... | [
"def",
"add_proxy_auth",
"(",
"possible_proxy_url",
",",
"proxy_auth",
")",
":",
"if",
"possible_proxy_url",
"==",
"'DIRECT'",
":",
"return",
"possible_proxy_url",
"parsed",
"=",
"urlparse",
"(",
"possible_proxy_url",
")",
"return",
"'{0}://{1}:{2}@{3}'",
".",
"format... | Add a username and password to a proxy URL, if the input value is a proxy URL.
:param str possible_proxy_url: Proxy URL or ``DIRECT``.
:param requests.auth.HTTPProxyAuth proxy_auth: Proxy authentication info.
:returns: Proxy URL with auth info added, or ``DIRECT``.
:rtype: str | [
"Add",
"a",
"username",
"and",
"password",
"to",
"a",
"proxy",
"URL",
"if",
"the",
"input",
"value",
"is",
"a",
"proxy",
"URL",
"."
] | 9e14a9e84a1ec5513a4fa819573073942fed0980 | https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/resolver.py#L112-L124 | train |
carsonyl/pypac | pypac/resolver.py | ProxyResolver.get_proxies | def get_proxies(self, url):
"""
Get the proxies that are applicable to a given URL, according to the PAC file.
:param str url: The URL for which to find appropriate proxies.
:return: All the proxies that apply to the given URL.
Can be empty, which means to abort the request.... | python | def get_proxies(self, url):
"""
Get the proxies that are applicable to a given URL, according to the PAC file.
:param str url: The URL for which to find appropriate proxies.
:return: All the proxies that apply to the given URL.
Can be empty, which means to abort the request.... | [
"def",
"get_proxies",
"(",
"self",
",",
"url",
")",
":",
"hostname",
"=",
"urlparse",
"(",
"url",
")",
".",
"hostname",
"if",
"hostname",
"is",
"None",
":",
"hostname",
"=",
"\"\"",
"value_from_js_func",
"=",
"self",
".",
"pac",
".",
"find_proxy_for_url",
... | Get the proxies that are applicable to a given URL, according to the PAC file.
:param str url: The URL for which to find appropriate proxies.
:return: All the proxies that apply to the given URL.
Can be empty, which means to abort the request.
:rtype: list[str] | [
"Get",
"the",
"proxies",
"that",
"are",
"applicable",
"to",
"a",
"given",
"URL",
"according",
"to",
"the",
"PAC",
"file",
"."
] | 9e14a9e84a1ec5513a4fa819573073942fed0980 | https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/resolver.py#L42-L66 | train |
carsonyl/pypac | pypac/resolver.py | ProxyResolver.get_proxy | def get_proxy(self, url):
"""
Get a proxy to use for a given URL, excluding any banned ones.
:param str url: The URL for which to find an appropriate proxy.
:return: A proxy to use for the URL,
or the string 'DIRECT', which means a proxy is not to be used.
Can be... | python | def get_proxy(self, url):
"""
Get a proxy to use for a given URL, excluding any banned ones.
:param str url: The URL for which to find an appropriate proxy.
:return: A proxy to use for the URL,
or the string 'DIRECT', which means a proxy is not to be used.
Can be... | [
"def",
"get_proxy",
"(",
"self",
",",
"url",
")",
":",
"proxies",
"=",
"self",
".",
"get_proxies",
"(",
"url",
")",
"for",
"proxy",
"in",
"proxies",
":",
"if",
"proxy",
"==",
"'DIRECT'",
"or",
"proxy",
"not",
"in",
"self",
".",
"_offline_proxies",
":",... | Get a proxy to use for a given URL, excluding any banned ones.
:param str url: The URL for which to find an appropriate proxy.
:return: A proxy to use for the URL,
or the string 'DIRECT', which means a proxy is not to be used.
Can be ``None``, which means to not attempt the requ... | [
"Get",
"a",
"proxy",
"to",
"use",
"for",
"a",
"given",
"URL",
"excluding",
"any",
"banned",
"ones",
"."
] | 9e14a9e84a1ec5513a4fa819573073942fed0980 | https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/resolver.py#L68-L81 | train |
carsonyl/pypac | pypac/resolver.py | ProxyResolver.get_proxy_for_requests | def get_proxy_for_requests(self, url):
"""
Get proxy configuration for a given URL, in a form ready to use with the Requests library.
:param str url: The URL for which to obtain proxy configuration.
:returns: Proxy configuration in a form recognized by Requests, for use with the ``proxi... | python | def get_proxy_for_requests(self, url):
"""
Get proxy configuration for a given URL, in a form ready to use with the Requests library.
:param str url: The URL for which to obtain proxy configuration.
:returns: Proxy configuration in a form recognized by Requests, for use with the ``proxi... | [
"def",
"get_proxy_for_requests",
"(",
"self",
",",
"url",
")",
":",
"proxy",
"=",
"self",
".",
"get_proxy",
"(",
"url",
")",
"if",
"not",
"proxy",
":",
"raise",
"ProxyConfigExhaustedError",
"(",
"url",
")",
"return",
"proxy_parameter_for_requests",
"(",
"proxy... | Get proxy configuration for a given URL, in a form ready to use with the Requests library.
:param str url: The URL for which to obtain proxy configuration.
:returns: Proxy configuration in a form recognized by Requests, for use with the ``proxies`` parameter.
:rtype: dict
:raises ProxyC... | [
"Get",
"proxy",
"configuration",
"for",
"a",
"given",
"URL",
"in",
"a",
"form",
"ready",
"to",
"use",
"with",
"the",
"Requests",
"library",
"."
] | 9e14a9e84a1ec5513a4fa819573073942fed0980 | https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/resolver.py#L83-L96 | train |
carsonyl/pypac | pypac/parser_functions.py | isInNet | def isInNet(host, pattern, mask):
"""
Pattern and mask specification is done the same way as for SOCKS configuration.
:param str host: a DNS hostname, or IP address.
If a hostname is passed, it will be resolved into an IP address by this function.
:param str pattern: an IP address pattern in th... | python | def isInNet(host, pattern, mask):
"""
Pattern and mask specification is done the same way as for SOCKS configuration.
:param str host: a DNS hostname, or IP address.
If a hostname is passed, it will be resolved into an IP address by this function.
:param str pattern: an IP address pattern in th... | [
"def",
"isInNet",
"(",
"host",
",",
"pattern",
",",
"mask",
")",
":",
"host_ip",
"=",
"host",
"if",
"is_ipv4_address",
"(",
"host",
")",
"else",
"dnsResolve",
"(",
"host",
")",
"if",
"not",
"host_ip",
"or",
"not",
"is_ipv4_address",
"(",
"pattern",
")",
... | Pattern and mask specification is done the same way as for SOCKS configuration.
:param str host: a DNS hostname, or IP address.
If a hostname is passed, it will be resolved into an IP address by this function.
:param str pattern: an IP address pattern in the dot-separated format
:param str mask: ma... | [
"Pattern",
"and",
"mask",
"specification",
"is",
"done",
"the",
"same",
"way",
"as",
"for",
"SOCKS",
"configuration",
"."
] | 9e14a9e84a1ec5513a4fa819573073942fed0980 | https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/parser_functions.py#L51-L66 | train |
althonos/fs.sshfs | fs/sshfs/sshfs.py | SSHFS._get_ssh_config | def _get_ssh_config(config_path='~/.ssh/config'):
"""Extract the configuration located at ``config_path``.
Returns:
paramiko.SSHConfig: the configuration instance.
"""
ssh_config = paramiko.SSHConfig()
try:
with open(os.path.realpath(os.path.expanduser(co... | python | def _get_ssh_config(config_path='~/.ssh/config'):
"""Extract the configuration located at ``config_path``.
Returns:
paramiko.SSHConfig: the configuration instance.
"""
ssh_config = paramiko.SSHConfig()
try:
with open(os.path.realpath(os.path.expanduser(co... | [
"def",
"_get_ssh_config",
"(",
"config_path",
"=",
"'~/.ssh/config'",
")",
":",
"ssh_config",
"=",
"paramiko",
".",
"SSHConfig",
"(",
")",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"("... | Extract the configuration located at ``config_path``.
Returns:
paramiko.SSHConfig: the configuration instance. | [
"Extract",
"the",
"configuration",
"located",
"at",
"config_path",
"."
] | 773cbdb6bceac5e00cf5785b6ffad6dc4574d29c | https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L67-L79 | train |
althonos/fs.sshfs | fs/sshfs/sshfs.py | SSHFS.openbin | def openbin(self, path, mode='r', buffering=-1, **options): # noqa: D102
"""Open a binary file-like object.
Arguments:
path (str): A path on the filesystem.
mode (str): Mode to open the file (must be a valid, non-text mode).
Since this method only opens binary f... | python | def openbin(self, path, mode='r', buffering=-1, **options): # noqa: D102
"""Open a binary file-like object.
Arguments:
path (str): A path on the filesystem.
mode (str): Mode to open the file (must be a valid, non-text mode).
Since this method only opens binary f... | [
"def",
"openbin",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"'r'",
",",
"buffering",
"=",
"-",
"1",
",",
"**",
"options",
")",
":",
"self",
".",
"check",
"(",
")",
"_path",
"=",
"self",
".",
"validatepath",
"(",
"path",
")",
"_mode",
"=",
"Mode... | Open a binary file-like object.
Arguments:
path (str): A path on the filesystem.
mode (str): Mode to open the file (must be a valid, non-text mode).
Since this method only opens binary files, the ``b`` in the mode
is implied.
buffering (int): ... | [
"Open",
"a",
"binary",
"file",
"-",
"like",
"object",
"."
] | 773cbdb6bceac5e00cf5785b6ffad6dc4574d29c | https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L177-L225 | train |
althonos/fs.sshfs | fs/sshfs/sshfs.py | SSHFS.platform | def platform(self):
"""The platform the server is running on.
Returns:
str: the platform of the remote server, as in `sys.platform`.
"""
uname_sys = self._exec_command("uname -s")
sysinfo = self._exec_command("sysinfo")
if uname_sys is not None:
i... | python | def platform(self):
"""The platform the server is running on.
Returns:
str: the platform of the remote server, as in `sys.platform`.
"""
uname_sys = self._exec_command("uname -s")
sysinfo = self._exec_command("sysinfo")
if uname_sys is not None:
i... | [
"def",
"platform",
"(",
"self",
")",
":",
"uname_sys",
"=",
"self",
".",
"_exec_command",
"(",
"\"uname -s\"",
")",
"sysinfo",
"=",
"self",
".",
"_exec_command",
"(",
"\"sysinfo\"",
")",
"if",
"uname_sys",
"is",
"not",
"None",
":",
"if",
"uname_sys",
"==",... | The platform the server is running on.
Returns:
str: the platform of the remote server, as in `sys.platform`. | [
"The",
"platform",
"the",
"server",
"is",
"running",
"on",
"."
] | 773cbdb6bceac5e00cf5785b6ffad6dc4574d29c | https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L277-L296 | train |
althonos/fs.sshfs | fs/sshfs/sshfs.py | SSHFS.locale | def locale(self):
"""The locale the server is running on.
Returns:
str: the locale of the remote server if detected, or `None`.
"""
if self.platform in ("linux", "darwin", "freebsd"):
locale = self._exec_command('echo $LANG')
if locale is not None:
... | python | def locale(self):
"""The locale the server is running on.
Returns:
str: the locale of the remote server if detected, or `None`.
"""
if self.platform in ("linux", "darwin", "freebsd"):
locale = self._exec_command('echo $LANG')
if locale is not None:
... | [
"def",
"locale",
"(",
"self",
")",
":",
"if",
"self",
".",
"platform",
"in",
"(",
"\"linux\"",
",",
"\"darwin\"",
",",
"\"freebsd\"",
")",
":",
"locale",
"=",
"self",
".",
"_exec_command",
"(",
"'echo $LANG'",
")",
"if",
"locale",
"is",
"not",
"None",
... | The locale the server is running on.
Returns:
str: the locale of the remote server if detected, or `None`. | [
"The",
"locale",
"the",
"server",
"is",
"running",
"on",
"."
] | 773cbdb6bceac5e00cf5785b6ffad6dc4574d29c | https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L299-L309 | train |
althonos/fs.sshfs | fs/sshfs/sshfs.py | SSHFS._exec_command | def _exec_command(self, cmd):
"""Run a command on the remote SSH server.
Returns:
bytes: the output of the command, if it didn't fail
None: if the error pipe of the command was not empty
"""
_, out, err = self._client.exec_command(cmd, timeout=self._timeout)
... | python | def _exec_command(self, cmd):
"""Run a command on the remote SSH server.
Returns:
bytes: the output of the command, if it didn't fail
None: if the error pipe of the command was not empty
"""
_, out, err = self._client.exec_command(cmd, timeout=self._timeout)
... | [
"def",
"_exec_command",
"(",
"self",
",",
"cmd",
")",
":",
"_",
",",
"out",
",",
"err",
"=",
"self",
".",
"_client",
".",
"exec_command",
"(",
"cmd",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"return",
"out",
".",
"read",
"(",
")",
".",
... | Run a command on the remote SSH server.
Returns:
bytes: the output of the command, if it didn't fail
None: if the error pipe of the command was not empty | [
"Run",
"a",
"command",
"on",
"the",
"remote",
"SSH",
"server",
"."
] | 773cbdb6bceac5e00cf5785b6ffad6dc4574d29c | https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L311-L319 | train |
althonos/fs.sshfs | fs/sshfs/sshfs.py | SSHFS._make_info | def _make_info(self, name, stat_result, namespaces):
"""Create an `Info` object from a stat result.
"""
info = {
'basic': {
'name': name,
'is_dir': stat.S_ISDIR(stat_result.st_mode)
}
}
if 'details' in namespaces:
... | python | def _make_info(self, name, stat_result, namespaces):
"""Create an `Info` object from a stat result.
"""
info = {
'basic': {
'name': name,
'is_dir': stat.S_ISDIR(stat_result.st_mode)
}
}
if 'details' in namespaces:
... | [
"def",
"_make_info",
"(",
"self",
",",
"name",
",",
"stat_result",
",",
"namespaces",
")",
":",
"info",
"=",
"{",
"'basic'",
":",
"{",
"'name'",
":",
"name",
",",
"'is_dir'",
":",
"stat",
".",
"S_ISDIR",
"(",
"stat_result",
".",
"st_mode",
")",
"}",
... | Create an `Info` object from a stat result. | [
"Create",
"an",
"Info",
"object",
"from",
"a",
"stat",
"result",
"."
] | 773cbdb6bceac5e00cf5785b6ffad6dc4574d29c | https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L321-L339 | train |
rroemhild/flask-ldapconn | flask_ldapconn/attribute.py | LDAPAttribute.value | def value(self):
'''Return single value or list of values from the attribute.
If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a
list with values.
'''
if len(self.__dict__['values']) == 1 and current_app.config['FORCE_ATTRIBUTE_VALUE_AS_LIST'] is False:
r... | python | def value(self):
'''Return single value or list of values from the attribute.
If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a
list with values.
'''
if len(self.__dict__['values']) == 1 and current_app.config['FORCE_ATTRIBUTE_VALUE_AS_LIST'] is False:
r... | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"__dict__",
"[",
"'values'",
"]",
")",
"==",
"1",
"and",
"current_app",
".",
"config",
"[",
"'FORCE_ATTRIBUTE_VALUE_AS_LIST'",
"]",
"is",
"False",
":",
"return",
"self",
".",
"__dict__... | Return single value or list of values from the attribute.
If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a
list with values. | [
"Return",
"single",
"value",
"or",
"list",
"of",
"values",
"from",
"the",
"attribute",
".",
"If",
"FORCE_ATTRIBUTE_VALUE_AS_LIST",
"is",
"True",
"always",
"return",
"a",
"list",
"with",
"values",
"."
] | 5295596c14538e2d874672c6b108b4b1b85dcd7e | https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/attribute.py#L68-L76 | train |
rroemhild/flask-ldapconn | flask_ldapconn/attribute.py | LDAPAttribute.append | def append(self, value):
'''Add another value to the attribute'''
if self.__dict__['values']:
self.__dict__['changetype'] = MODIFY_REPLACE
self.__dict__['values'].append(value) | python | def append(self, value):
'''Add another value to the attribute'''
if self.__dict__['values']:
self.__dict__['changetype'] = MODIFY_REPLACE
self.__dict__['values'].append(value) | [
"def",
"append",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"__dict__",
"[",
"'values'",
"]",
":",
"self",
".",
"__dict__",
"[",
"'changetype'",
"]",
"=",
"MODIFY_REPLACE",
"self",
".",
"__dict__",
"[",
"'values'",
"]",
".",
"append",
"(",... | Add another value to the attribute | [
"Add",
"another",
"value",
"to",
"the",
"attribute"
] | 5295596c14538e2d874672c6b108b4b1b85dcd7e | https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/attribute.py#L86-L91 | train |
rroemhild/flask-ldapconn | flask_ldapconn/__init__.py | LDAPConn.authenticate | def authenticate(self,
username,
password,
attribute=None,
base_dn=None,
search_filter=None,
search_scope=SUBTREE):
'''Attempts to bind a user to the LDAP server.
Args:
... | python | def authenticate(self,
username,
password,
attribute=None,
base_dn=None,
search_filter=None,
search_scope=SUBTREE):
'''Attempts to bind a user to the LDAP server.
Args:
... | [
"def",
"authenticate",
"(",
"self",
",",
"username",
",",
"password",
",",
"attribute",
"=",
"None",
",",
"base_dn",
"=",
"None",
",",
"search_filter",
"=",
"None",
",",
"search_scope",
"=",
"SUBTREE",
")",
":",
"valid_dn",
"=",
"False",
"try",
":",
"par... | Attempts to bind a user to the LDAP server.
Args:
username (str): DN or the username to attempt to bind with.
password (str): The password of the username.
attribute (str): The LDAP attribute for the username.
base_dn (str): The LDAP basedn to search on.
... | [
"Attempts",
"to",
"bind",
"a",
"user",
"to",
"the",
"LDAP",
"server",
"."
] | 5295596c14538e2d874672c6b108b4b1b85dcd7e | https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/__init__.py#L122-L171 | train |
rroemhild/flask-ldapconn | flask_ldapconn/query.py | BaseQuery.get | def get(self, ldap_dn):
'''Return an LDAP entry by DN
Args:
ldap_dn (str): LDAP DN
'''
self.base_dn = ldap_dn
self.sub_tree = BASE
return self.first() | python | def get(self, ldap_dn):
'''Return an LDAP entry by DN
Args:
ldap_dn (str): LDAP DN
'''
self.base_dn = ldap_dn
self.sub_tree = BASE
return self.first() | [
"def",
"get",
"(",
"self",
",",
"ldap_dn",
")",
":",
"self",
".",
"base_dn",
"=",
"ldap_dn",
"self",
".",
"sub_tree",
"=",
"BASE",
"return",
"self",
".",
"first",
"(",
")"
] | Return an LDAP entry by DN
Args:
ldap_dn (str): LDAP DN | [
"Return",
"an",
"LDAP",
"entry",
"by",
"DN"
] | 5295596c14538e2d874672c6b108b4b1b85dcd7e | https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/query.py#L50-L58 | train |
rroemhild/flask-ldapconn | flask_ldapconn/query.py | BaseQuery.filter | def filter(self, *query_filter):
'''Set the query filter to perform the query with
Args:
*query_filter: Simplified Query Language filter
'''
for query in query_filter:
self.query.append(query)
return self | python | def filter(self, *query_filter):
'''Set the query filter to perform the query with
Args:
*query_filter: Simplified Query Language filter
'''
for query in query_filter:
self.query.append(query)
return self | [
"def",
"filter",
"(",
"self",
",",
"*",
"query_filter",
")",
":",
"for",
"query",
"in",
"query_filter",
":",
"self",
".",
"query",
".",
"append",
"(",
"query",
")",
"return",
"self"
] | Set the query filter to perform the query with
Args:
*query_filter: Simplified Query Language filter | [
"Set",
"the",
"query",
"filter",
"to",
"perform",
"the",
"query",
"with"
] | 5295596c14538e2d874672c6b108b4b1b85dcd7e | https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/query.py#L60-L68 | train |
rroemhild/flask-ldapconn | flask_ldapconn/query.py | BaseQuery.all | def all(self, components_in_and=True):
'''Return all of the results of a query in a list'''
self.components_in_and = components_in_and
return [obj for obj in iter(self)] | python | def all(self, components_in_and=True):
'''Return all of the results of a query in a list'''
self.components_in_and = components_in_and
return [obj for obj in iter(self)] | [
"def",
"all",
"(",
"self",
",",
"components_in_and",
"=",
"True",
")",
":",
"self",
".",
"components_in_and",
"=",
"components_in_and",
"return",
"[",
"obj",
"for",
"obj",
"in",
"iter",
"(",
"self",
")",
"]"
] | Return all of the results of a query in a list | [
"Return",
"all",
"of",
"the",
"results",
"of",
"a",
"query",
"in",
"a",
"list"
] | 5295596c14538e2d874672c6b108b4b1b85dcd7e | https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/query.py#L79-L82 | train |
teffland/pytorch-monitor | build/lib/pytorch_monitor/monitor.py | set_monitor | def set_monitor(module):
""" Defines the monitor method on the module. """
def monitor(name, tensor,
track_data=True,
track_grad=True):
"""
Register the tensor under the name given (now a string)
and track it based on the track_data and track_grad argument... | python | def set_monitor(module):
""" Defines the monitor method on the module. """
def monitor(name, tensor,
track_data=True,
track_grad=True):
"""
Register the tensor under the name given (now a string)
and track it based on the track_data and track_grad argument... | [
"def",
"set_monitor",
"(",
"module",
")",
":",
"def",
"monitor",
"(",
"name",
",",
"tensor",
",",
"track_data",
"=",
"True",
",",
"track_grad",
"=",
"True",
")",
":",
"module",
".",
"monitored_vars",
"[",
"name",
"]",
"=",
"{",
"'tensor'",
":",
"tensor... | Defines the monitor method on the module. | [
"Defines",
"the",
"monitor",
"method",
"on",
"the",
"module",
"."
] | 56dce63ba85c0f9faf9df11df78161ee60f5fae9 | https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/monitor.py#L3-L17 | train |
teffland/pytorch-monitor | build/lib/pytorch_monitor/monitor.py | set_monitoring | def set_monitoring(module):
""" Defines the monitoring method on the module. """
def monitoring(is_monitoring,
track_data=None,
track_grad=None,
track_update=None,
track_update_ratio=None):
"""
Turn monitoring on or off.... | python | def set_monitoring(module):
""" Defines the monitoring method on the module. """
def monitoring(is_monitoring,
track_data=None,
track_grad=None,
track_update=None,
track_update_ratio=None):
"""
Turn monitoring on or off.... | [
"def",
"set_monitoring",
"(",
"module",
")",
":",
"def",
"monitoring",
"(",
"is_monitoring",
",",
"track_data",
"=",
"None",
",",
"track_grad",
"=",
"None",
",",
"track_update",
"=",
"None",
",",
"track_update_ratio",
"=",
"None",
")",
":",
"module",
".",
... | Defines the monitoring method on the module. | [
"Defines",
"the",
"monitoring",
"method",
"on",
"the",
"module",
"."
] | 56dce63ba85c0f9faf9df11df78161ee60f5fae9 | https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/monitor.py#L19-L35 | train |
teffland/pytorch-monitor | build/lib/pytorch_monitor/monitor.py | grad_hook | def grad_hook(module, name, writer, bins):
""" Factory for grad_hook closures """
def hook(grad):
writer.add_histogram('{}/grad'.format(name.replace('.','/')),
grad.detach().cpu().numpy(),
module.global_step-1,
bins=b... | python | def grad_hook(module, name, writer, bins):
""" Factory for grad_hook closures """
def hook(grad):
writer.add_histogram('{}/grad'.format(name.replace('.','/')),
grad.detach().cpu().numpy(),
module.global_step-1,
bins=b... | [
"def",
"grad_hook",
"(",
"module",
",",
"name",
",",
"writer",
",",
"bins",
")",
":",
"def",
"hook",
"(",
"grad",
")",
":",
"writer",
".",
"add_histogram",
"(",
"'{}/grad'",
".",
"format",
"(",
"name",
".",
"replace",
"(",
"'.'",
",",
"'/'",
")",
"... | Factory for grad_hook closures | [
"Factory",
"for",
"grad_hook",
"closures"
] | 56dce63ba85c0f9faf9df11df78161ee60f5fae9 | https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/monitor.py#L37-L44 | train |
teffland/pytorch-monitor | build/lib/pytorch_monitor/monitor.py | remove_grad_hooks | def remove_grad_hooks(module, input):
""" Remove gradient hooks to all of the parameters and monitored vars """
for hook in list(module.param_hooks.keys()):
module.param_hooks[hook].remove()
module.param_hooks.pop(hook)
for hook in list(module.var_hooks.keys()):
module.var_hooks[hook... | python | def remove_grad_hooks(module, input):
""" Remove gradient hooks to all of the parameters and monitored vars """
for hook in list(module.param_hooks.keys()):
module.param_hooks[hook].remove()
module.param_hooks.pop(hook)
for hook in list(module.var_hooks.keys()):
module.var_hooks[hook... | [
"def",
"remove_grad_hooks",
"(",
"module",
",",
"input",
")",
":",
"for",
"hook",
"in",
"list",
"(",
"module",
".",
"param_hooks",
".",
"keys",
"(",
")",
")",
":",
"module",
".",
"param_hooks",
"[",
"hook",
"]",
".",
"remove",
"(",
")",
"module",
"."... | Remove gradient hooks to all of the parameters and monitored vars | [
"Remove",
"gradient",
"hooks",
"to",
"all",
"of",
"the",
"parameters",
"and",
"monitored",
"vars"
] | 56dce63ba85c0f9faf9df11df78161ee60f5fae9 | https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/monitor.py#L46-L53 | train |
teffland/pytorch-monitor | build/lib/pytorch_monitor/monitor.py | get_monitor_forward_and_backward | def get_monitor_forward_and_backward(summary_writer, bins):
""" Get the method for monitoring the forward values of the network """
def monitor_forward_and_backward(module, input, output):
"""
Iterate over the module parameters and monitor their forward values.
Then iterate over all of t... | python | def get_monitor_forward_and_backward(summary_writer, bins):
""" Get the method for monitoring the forward values of the network """
def monitor_forward_and_backward(module, input, output):
"""
Iterate over the module parameters and monitor their forward values.
Then iterate over all of t... | [
"def",
"get_monitor_forward_and_backward",
"(",
"summary_writer",
",",
"bins",
")",
":",
"def",
"monitor_forward_and_backward",
"(",
"module",
",",
"input",
",",
"output",
")",
":",
"if",
"module",
".",
"is_monitoring",
":",
"param_names",
"=",
"[",
"name",
"for... | Get the method for monitoring the forward values of the network | [
"Get",
"the",
"method",
"for",
"monitoring",
"the",
"forward",
"values",
"of",
"the",
"network"
] | 56dce63ba85c0f9faf9df11df78161ee60f5fae9 | https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/monitor.py#L55-L107 | train |
teffland/pytorch-monitor | build/lib/pytorch_monitor/init_experiment.py | commit | def commit(experiment_name, time):
"""
Try to commit repo exactly as it is when starting the experiment for reproducibility.
"""
try:
sh.git.commit('-a',
m='"auto commit tracked files for new experiment: {} on {}"'.format(experiment_name, time),
allow_empty=True
... | python | def commit(experiment_name, time):
"""
Try to commit repo exactly as it is when starting the experiment for reproducibility.
"""
try:
sh.git.commit('-a',
m='"auto commit tracked files for new experiment: {} on {}"'.format(experiment_name, time),
allow_empty=True
... | [
"def",
"commit",
"(",
"experiment_name",
",",
"time",
")",
":",
"try",
":",
"sh",
".",
"git",
".",
"commit",
"(",
"'-a'",
",",
"m",
"=",
"'\"auto commit tracked files for new experiment: {} on {}\"'",
".",
"format",
"(",
"experiment_name",
",",
"time",
")",
",... | Try to commit repo exactly as it is when starting the experiment for reproducibility. | [
"Try",
"to",
"commit",
"repo",
"exactly",
"as",
"it",
"is",
"when",
"starting",
"the",
"experiment",
"for",
"reproducibility",
"."
] | 56dce63ba85c0f9faf9df11df78161ee60f5fae9 | https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/init_experiment.py#L13-L25 | train |
percolate/ec2-security-groups-dumper | ec2_security_groups_dumper/main.py | Firewall.json | def json(self):
"""
Output the security rules as a json string.
Return:
str
"""
return json.dumps(self.dict_rules,
sort_keys=True,
indent=2,
separators=(',', ': ')) | python | def json(self):
"""
Output the security rules as a json string.
Return:
str
"""
return json.dumps(self.dict_rules,
sort_keys=True,
indent=2,
separators=(',', ': ')) | [
"def",
"json",
"(",
"self",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"dict_rules",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"2",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")"
] | Output the security rules as a json string.
Return:
str | [
"Output",
"the",
"security",
"rules",
"as",
"a",
"json",
"string",
"."
] | f2a40d1b3802211c85767fe74281617e4dbae543 | https://github.com/percolate/ec2-security-groups-dumper/blob/f2a40d1b3802211c85767fe74281617e4dbae543/ec2_security_groups_dumper/main.py#L135-L145 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.