repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/tree_handler.py | TreeHandler.get_parent | def get_parent(self, tree, alt=None):
"""
Get parent for given `tree` or `alt` if not found.
Args:
tree (obj): :class:`.Tree` instance, which is already stored in DB.
alt (obj, default None): Alternative value returned when `tree` is
not found.
R... | python | def get_parent(self, tree, alt=None):
"""
Get parent for given `tree` or `alt` if not found.
Args:
tree (obj): :class:`.Tree` instance, which is already stored in DB.
alt (obj, default None): Alternative value returned when `tree` is
not found.
R... | [
"def",
"get_parent",
"(",
"self",
",",
"tree",
",",
"alt",
"=",
"None",
")",
":",
"parent",
"=",
"self",
".",
"parent_db",
".",
"get",
"(",
"tree",
".",
"path",
")",
"if",
"not",
"parent",
":",
"return",
"alt",
"return",
"list",
"(",
"parent",
")",... | Get parent for given `tree` or `alt` if not found.
Args:
tree (obj): :class:`.Tree` instance, which is already stored in DB.
alt (obj, default None): Alternative value returned when `tree` is
not found.
Returns:
obj: :class:`.Tree` parent to given `t... | [
"Get",
"parent",
"for",
"given",
"tree",
"or",
"alt",
"if",
"not",
"found",
"."
] | train | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/tree_handler.py#L261-L278 |
ulf1/oxyba | oxyba/yearfrac_365q.py | yearfrac_365q | def yearfrac_365q(d1, d2):
"""date difference "d1-d2" as year fractional"""
# import modules
from datetime import date
from oxyba import date_to_datetime
# define yearfrac formula
# toyf = lambda a,b: (a - b).days / 365.2425
def toyf(a, b):
a = date_to_datetime(a) if isinstance(a, ... | python | def yearfrac_365q(d1, d2):
"""date difference "d1-d2" as year fractional"""
# import modules
from datetime import date
from oxyba import date_to_datetime
# define yearfrac formula
# toyf = lambda a,b: (a - b).days / 365.2425
def toyf(a, b):
a = date_to_datetime(a) if isinstance(a, ... | [
"def",
"yearfrac_365q",
"(",
"d1",
",",
"d2",
")",
":",
"# import modules",
"from",
"datetime",
"import",
"date",
"from",
"oxyba",
"import",
"date_to_datetime",
"# define yearfrac formula",
"# toyf = lambda a,b: (a - b).days / 365.2425",
"def",
"toyf",
"(",
"a",
",",
... | date difference "d1-d2" as year fractional | [
"date",
"difference",
"d1",
"-",
"d2",
"as",
"year",
"fractional"
] | train | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/yearfrac_365q.py#L2-L30 |
opieters/DynamicNumber | languages/python/dn.py | dn.add | def add(self, name, value, unit=None):
"""Add symbolic link to Dynamic Number list.
name -- name of the symbolic link
value -- value of the link (if not a string, conversion is done with str())
unit -- if value is a numerical value, a unit can be added to invoke the \unit{}{} LaTeX co... | python | def add(self, name, value, unit=None):
"""Add symbolic link to Dynamic Number list.
name -- name of the symbolic link
value -- value of the link (if not a string, conversion is done with str())
unit -- if value is a numerical value, a unit can be added to invoke the \unit{}{} LaTeX co... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"value",
",",
"unit",
"=",
"None",
")",
":",
"# check if unit provided",
"if",
"unit",
"is",
"not",
"None",
":",
"add_unit",
"=",
"True",
"unit",
"=",
"str",
"(",
"unit",
")",
"else",
":",
"add_unit",
"=",... | Add symbolic link to Dynamic Number list.
name -- name of the symbolic link
value -- value of the link (if not a string, conversion is done with str())
unit -- if value is a numerical value, a unit can be added to invoke the \unit{}{} LaTeX command | [
"Add",
"symbolic",
"link",
"to",
"Dynamic",
"Number",
"list",
"."
] | train | https://github.com/opieters/DynamicNumber/blob/433679e9f772a4d0e633e73bd1243ce912bb8dfc/languages/python/dn.py#L38-L61 |
Bystroushaak/zeo_connector | src/zeo_connector/zeo_wrapper_prototype.py | _init_zeo | def _init_zeo():
"""
Start asyncore thread.
"""
if not _ASYNCORE_RUNNING:
def _run_asyncore_loop():
asyncore.loop()
thread.start_new_thread(_run_asyncore_loop, ())
global _ASYNCORE_RUNNING
_ASYNCORE_RUNNING = True | python | def _init_zeo():
"""
Start asyncore thread.
"""
if not _ASYNCORE_RUNNING:
def _run_asyncore_loop():
asyncore.loop()
thread.start_new_thread(_run_asyncore_loop, ())
global _ASYNCORE_RUNNING
_ASYNCORE_RUNNING = True | [
"def",
"_init_zeo",
"(",
")",
":",
"if",
"not",
"_ASYNCORE_RUNNING",
":",
"def",
"_run_asyncore_loop",
"(",
")",
":",
"asyncore",
".",
"loop",
"(",
")",
"thread",
".",
"start_new_thread",
"(",
"_run_asyncore_loop",
",",
"(",
")",
")",
"global",
"_ASYNCORE_RU... | Start asyncore thread. | [
"Start",
"asyncore",
"thread",
"."
] | train | https://github.com/Bystroushaak/zeo_connector/blob/93f86447204efc8e33d3112907cd221daf6bce3b/src/zeo_connector/zeo_wrapper_prototype.py#L21-L32 |
Bystroushaak/zeo_connector | src/zeo_connector/zeo_wrapper_prototype.py | retry_and_reset | def retry_and_reset(fn):
"""
Decorator used to make sure, that operation on ZEO object will be retried,
if there is ``ConnectionStateError`` exception.
"""
@wraps(fn)
def retry_and_reset_decorator(*args, **kwargs):
obj = kwargs.get("self", None)
if not obj:
obj = arg... | python | def retry_and_reset(fn):
"""
Decorator used to make sure, that operation on ZEO object will be retried,
if there is ``ConnectionStateError`` exception.
"""
@wraps(fn)
def retry_and_reset_decorator(*args, **kwargs):
obj = kwargs.get("self", None)
if not obj:
obj = arg... | [
"def",
"retry_and_reset",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"retry_and_reset_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"kwargs",
".",
"get",
"(",
"\"self\"",
",",
"None",
")",
"if",
"not",
... | Decorator used to make sure, that operation on ZEO object will be retried,
if there is ``ConnectionStateError`` exception. | [
"Decorator",
"used",
"to",
"make",
"sure",
"that",
"operation",
"on",
"ZEO",
"object",
"will",
"be",
"retried",
"if",
"there",
"is",
"ConnectionStateError",
"exception",
"."
] | train | https://github.com/Bystroushaak/zeo_connector/blob/93f86447204efc8e33d3112907cd221daf6bce3b/src/zeo_connector/zeo_wrapper_prototype.py#L35-L54 |
Bystroushaak/zeo_connector | src/zeo_connector/zeo_wrapper_prototype.py | ZEOWrapperPrototype._open_connection | def _open_connection(self):
"""
Open the connection to the database based on the configuration file.
"""
if self._connection:
try:
self._connection.close()
except Exception:
pass
db = self._get_db()
self._connection... | python | def _open_connection(self):
"""
Open the connection to the database based on the configuration file.
"""
if self._connection:
try:
self._connection.close()
except Exception:
pass
db = self._get_db()
self._connection... | [
"def",
"_open_connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection",
":",
"try",
":",
"self",
".",
"_connection",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"pass",
"db",
"=",
"self",
".",
"_get_db",
"(",
")",
"self",
".",
"_c... | Open the connection to the database based on the configuration file. | [
"Open",
"the",
"connection",
"to",
"the",
"database",
"based",
"on",
"the",
"configuration",
"file",
"."
] | train | https://github.com/Bystroushaak/zeo_connector/blob/93f86447204efc8e33d3112907cd221daf6bce3b/src/zeo_connector/zeo_wrapper_prototype.py#L105-L118 |
Bystroushaak/zeo_connector | src/zeo_connector/zeo_wrapper_prototype.py | ZEOWrapperPrototype._init_zeo_root | def _init_zeo_root(self, attempts=3):
"""
Get and initialize the ZEO root object.
Args:
attempts (int, default 3): How many times to try, if the connection
was lost.
"""
try:
db_root = self._connection.root()
except ConnectionState... | python | def _init_zeo_root(self, attempts=3):
"""
Get and initialize the ZEO root object.
Args:
attempts (int, default 3): How many times to try, if the connection
was lost.
"""
try:
db_root = self._connection.root()
except ConnectionState... | [
"def",
"_init_zeo_root",
"(",
"self",
",",
"attempts",
"=",
"3",
")",
":",
"try",
":",
"db_root",
"=",
"self",
".",
"_connection",
".",
"root",
"(",
")",
"except",
"ConnectionStateError",
":",
"if",
"attempts",
"<=",
"0",
":",
"raise",
"self",
".",
"_o... | Get and initialize the ZEO root object.
Args:
attempts (int, default 3): How many times to try, if the connection
was lost. | [
"Get",
"and",
"initialize",
"the",
"ZEO",
"root",
"object",
"."
] | train | https://github.com/Bystroushaak/zeo_connector/blob/93f86447204efc8e33d3112907cd221daf6bce3b/src/zeo_connector/zeo_wrapper_prototype.py#L120-L142 |
a1ezzz/wasp-launcher | wasp_launcher/apps/log.py | WLogApp.stop | def stop(self):
""" "Uninitialize" logger. Makes :attr:`wasp_launcher.apps.WAppsGlobals.log` logger unavailable
:return: None
"""
if WAppsGlobals.log is not None and WLogApp.__log_handler__ is not None:
WAppsGlobals.log.removeHandler(WLogApp.__log_handler__)
WLogApp.__log_handler__ = None
WAppsGlobals.... | python | def stop(self):
""" "Uninitialize" logger. Makes :attr:`wasp_launcher.apps.WAppsGlobals.log` logger unavailable
:return: None
"""
if WAppsGlobals.log is not None and WLogApp.__log_handler__ is not None:
WAppsGlobals.log.removeHandler(WLogApp.__log_handler__)
WLogApp.__log_handler__ = None
WAppsGlobals.... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"WAppsGlobals",
".",
"log",
"is",
"not",
"None",
"and",
"WLogApp",
".",
"__log_handler__",
"is",
"not",
"None",
":",
"WAppsGlobals",
".",
"log",
".",
"removeHandler",
"(",
"WLogApp",
".",
"__log_handler__",
")",
... | "Uninitialize" logger. Makes :attr:`wasp_launcher.apps.WAppsGlobals.log` logger unavailable
:return: None | [
"Uninitialize",
"logger",
".",
"Makes",
":",
"attr",
":",
"wasp_launcher",
".",
"apps",
".",
"WAppsGlobals",
".",
"log",
"logger",
"unavailable"
] | train | https://github.com/a1ezzz/wasp-launcher/blob/38b476286fb422830207031935d3af1fe8da316d/wasp_launcher/apps/log.py#L54-L63 |
a1ezzz/wasp-launcher | wasp_launcher/apps/log.py | WLogApp.setup_logger | def setup_logger(cls):
""" Initialize :attr:`wasp_launcher.apps.WAppsGlobals.log` log.
:return: None
"""
if WAppsGlobals.log is None:
WAppsGlobals.log = logging.getLogger("wasp-launcher")
formatter = logging.Formatter(
'[%(name)s] [%(threadName)s] [%(levelname)s] [%(asctime)s] %(message)s',
'%Y-%... | python | def setup_logger(cls):
""" Initialize :attr:`wasp_launcher.apps.WAppsGlobals.log` log.
:return: None
"""
if WAppsGlobals.log is None:
WAppsGlobals.log = logging.getLogger("wasp-launcher")
formatter = logging.Formatter(
'[%(name)s] [%(threadName)s] [%(levelname)s] [%(asctime)s] %(message)s',
'%Y-%... | [
"def",
"setup_logger",
"(",
"cls",
")",
":",
"if",
"WAppsGlobals",
".",
"log",
"is",
"None",
":",
"WAppsGlobals",
".",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"\"wasp-launcher\"",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'[%(name)s] [%... | Initialize :attr:`wasp_launcher.apps.WAppsGlobals.log` log.
:return: None | [
"Initialize",
":",
"attr",
":",
"wasp_launcher",
".",
"apps",
".",
"WAppsGlobals",
".",
"log",
"log",
"."
] | train | https://github.com/a1ezzz/wasp-launcher/blob/38b476286fb422830207031935d3af1fe8da316d/wasp_launcher/apps/log.py#L66-L80 |
ariebovenberg/valuable | valuable/load.py | create_dataclass_loader | def create_dataclass_loader(cls, registry, field_getters):
"""create a loader for a dataclass type"""
fields = cls.__dataclass_fields__
item_loaders = map(registry, map(attrgetter('type'), fields.values()))
getters = map(field_getters.__getitem__, fields)
loaders = list(starmap(compose, zip(item_loa... | python | def create_dataclass_loader(cls, registry, field_getters):
"""create a loader for a dataclass type"""
fields = cls.__dataclass_fields__
item_loaders = map(registry, map(attrgetter('type'), fields.values()))
getters = map(field_getters.__getitem__, fields)
loaders = list(starmap(compose, zip(item_loa... | [
"def",
"create_dataclass_loader",
"(",
"cls",
",",
"registry",
",",
"field_getters",
")",
":",
"fields",
"=",
"cls",
".",
"__dataclass_fields__",
"item_loaders",
"=",
"map",
"(",
"registry",
",",
"map",
"(",
"attrgetter",
"(",
"'type'",
")",
",",
"fields",
"... | create a loader for a dataclass type | [
"create",
"a",
"loader",
"for",
"a",
"dataclass",
"type"
] | train | https://github.com/ariebovenberg/valuable/blob/72ac98b5a044233f13d14a9b9f273ce3a237d9ae/valuable/load.py#L145-L155 |
coghost/izen | izen/helper.py | num_choice | def num_choice(choices, default='1', valid_keys='', depth=1, icons='', sn_info=None,
indent=4, fg_color='green', separator='',
with_img=6, img_list=None, img_cache_dir='/tmp', use_cache=False,
extra_hints='', clear_previous=False, quit_app=True,
):
"""
... | python | def num_choice(choices, default='1', valid_keys='', depth=1, icons='', sn_info=None,
indent=4, fg_color='green', separator='',
with_img=6, img_list=None, img_cache_dir='/tmp', use_cache=False,
extra_hints='', clear_previous=False, quit_app=True,
):
"""
... | [
"def",
"num_choice",
"(",
"choices",
",",
"default",
"=",
"'1'",
",",
"valid_keys",
"=",
"''",
",",
"depth",
"=",
"1",
",",
"icons",
"=",
"''",
",",
"sn_info",
"=",
"None",
",",
"indent",
"=",
"4",
",",
"fg_color",
"=",
"'green'",
",",
"separator",
... | 传入数组, 生成待选择列表, 如果启用图片支持, 需要额外传入与数组排序一致的图片列表,
- 图片在 iterms 中显示速度较慢, 不推荐使用
.. note: 图片在 iterms 中显示速度较慢, 如果数组长度大于10, 不推荐使用
.. code:: python
sn_info = {
'align': '-', # 左右对齐
'length': 2, # 显示长度
}
:param use_cache:
:type use_cache:
... | [
"传入数组",
"生成待选择列表",
"如果启用图片支持",
"需要额外传入与数组排序一致的图片列表",
"-",
"图片在",
"iterms",
"中显示速度较慢",
"不推荐使用"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L99-L222 |
coghost/izen | izen/helper.py | yn_choice | def yn_choice(msg, indent=4, fg_color='cyan', separator=''):
"""
传入 msg , 返回 True/False
:param separator:
:type separator:
:param fg_color:
:type fg_color:
:param indent:
:type indent:
:param msg:
:type msg:
:return:
:rtype:
"""
_header, _footer = gen_separat... | python | def yn_choice(msg, indent=4, fg_color='cyan', separator=''):
"""
传入 msg , 返回 True/False
:param separator:
:type separator:
:param fg_color:
:type fg_color:
:param indent:
:type indent:
:param msg:
:type msg:
:return:
:rtype:
"""
_header, _footer = gen_separat... | [
"def",
"yn_choice",
"(",
"msg",
",",
"indent",
"=",
"4",
",",
"fg_color",
"=",
"'cyan'",
",",
"separator",
"=",
"''",
")",
":",
"_header",
",",
"_footer",
"=",
"gen_separator",
"(",
"separator",
"=",
"separator",
")",
"if",
"_header",
":",
"textui",
".... | 传入 msg , 返回 True/False
:param separator:
:type separator:
:param fg_color:
:type fg_color:
:param indent:
:type indent:
:param msg:
:type msg:
:return:
:rtype: | [
"传入",
"msg",
"返回",
"True",
"/",
"False"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L225-L252 |
coghost/izen | izen/helper.py | copy_to_clipboard | def copy_to_clipboard(dat):
"""
复制 ``dat`` 内容到 剪切板中
:return: None
"""
p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
p.stdin.write(to_bytes(dat))
p.stdin.close()
p.communicate() | python | def copy_to_clipboard(dat):
"""
复制 ``dat`` 内容到 剪切板中
:return: None
"""
p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
p.stdin.write(to_bytes(dat))
p.stdin.close()
p.communicate() | [
"def",
"copy_to_clipboard",
"(",
"dat",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'pbcopy'",
"]",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
")",
"p",
".",
"stdin",
".",
"write",
"(",
"to_bytes",
"(",
"dat",
")",
")",
"p",
".",
... | 复制 ``dat`` 内容到 剪切板中
:return: None | [
"复制",
"dat",
"内容到",
"剪切板中"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L272-L281 |
coghost/izen | izen/helper.py | cat_net_img | def cat_net_img(url='', indent=4, img_height=0, img_cache_dir='/tmp', use_cache=False):
"""
- 优先 从微博缓存目录读取图片
- 如果失败, 再从相应的url读取照片
:param use_cache: ``使用缓存``
:type use_cache:
:param img_cache_dir:
:type img_cache_dir:
:param url:
:type url:
:param indent:
:type indent... | python | def cat_net_img(url='', indent=4, img_height=0, img_cache_dir='/tmp', use_cache=False):
"""
- 优先 从微博缓存目录读取图片
- 如果失败, 再从相应的url读取照片
:param use_cache: ``使用缓存``
:type use_cache:
:param img_cache_dir:
:type img_cache_dir:
:param url:
:type url:
:param indent:
:type indent... | [
"def",
"cat_net_img",
"(",
"url",
"=",
"''",
",",
"indent",
"=",
"4",
",",
"img_height",
"=",
"0",
",",
"img_cache_dir",
"=",
"'/tmp'",
",",
"use_cache",
"=",
"False",
")",
":",
"name",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]... | - 优先 从微博缓存目录读取图片
- 如果失败, 再从相应的url读取照片
:param use_cache: ``使用缓存``
:type use_cache:
:param img_cache_dir:
:type img_cache_dir:
:param url:
:type url:
:param indent:
:type indent:
:param img_height:
:type img_height:
:return:
:rtype: | [
"-",
"优先",
"从微博缓存目录读取图片",
"-",
"如果失败",
"再从相应的url读取照片"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L284-L311 |
coghost/izen | izen/helper.py | cat_img_cnt | def cat_img_cnt(cnt_in='', img_height=0):
"""
展示图片内容
:param cnt_in:
:type cnt_in:
:param img_height: 照片占用的终端行数
:type img_height: int
:return:
:rtype:
"""
if not img_height:
img_height = 6
_head = '\x1b]1337;'
_file = 'File=name={}'.format(to_str(base64.b64enc... | python | def cat_img_cnt(cnt_in='', img_height=0):
"""
展示图片内容
:param cnt_in:
:type cnt_in:
:param img_height: 照片占用的终端行数
:type img_height: int
:return:
:rtype:
"""
if not img_height:
img_height = 6
_head = '\x1b]1337;'
_file = 'File=name={}'.format(to_str(base64.b64enc... | [
"def",
"cat_img_cnt",
"(",
"cnt_in",
"=",
"''",
",",
"img_height",
"=",
"0",
")",
":",
"if",
"not",
"img_height",
":",
"img_height",
"=",
"6",
"_head",
"=",
"'\\x1b]1337;'",
"_file",
"=",
"'File=name={}'",
".",
"format",
"(",
"to_str",
"(",
"base64",
"."... | 展示图片内容
:param cnt_in:
:type cnt_in:
:param img_height: 照片占用的终端行数
:type img_height: int
:return:
:rtype: | [
"展示图片内容"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L319-L339 |
coghost/izen | izen/helper.py | str2unixtime | def str2unixtime(ts, fmt='%Y-%m-%d %H:%M:%S'):
"""
将固定格式的字符串转换成对应的时间戳到秒级别
- 使用:
>>> str2unixtime('2016-01-01 01:01:01')
1451581261
:param ts:
:type ts:
:param fmt:
:type fmt:
:return:
:rtype:
"""
t = time.strptime(ts, fmt)
return int(time.mktime(t)) | python | def str2unixtime(ts, fmt='%Y-%m-%d %H:%M:%S'):
"""
将固定格式的字符串转换成对应的时间戳到秒级别
- 使用:
>>> str2unixtime('2016-01-01 01:01:01')
1451581261
:param ts:
:type ts:
:param fmt:
:type fmt:
:return:
:rtype:
"""
t = time.strptime(ts, fmt)
return int(time.mktime(t)) | [
"def",
"str2unixtime",
"(",
"ts",
",",
"fmt",
"=",
"'%Y-%m-%d %H:%M:%S'",
")",
":",
"t",
"=",
"time",
".",
"strptime",
"(",
"ts",
",",
"fmt",
")",
"return",
"int",
"(",
"time",
".",
"mktime",
"(",
"t",
")",
")"
] | 将固定格式的字符串转换成对应的时间戳到秒级别
- 使用:
>>> str2unixtime('2016-01-01 01:01:01')
1451581261
:param ts:
:type ts:
:param fmt:
:type fmt:
:return:
:rtype: | [
"将固定格式的字符串转换成对应的时间戳到秒级别"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L362-L379 |
coghost/izen | izen/helper.py | unixtime2str | def unixtime2str(timestamp, fmt='%Y-%m-%d %H:%M:%S'):
"""
将 ``秒级别的时间戳`` 转换成字符串
.. warning:
时间戳是以 ``秒`` 为单位的
:param timestamp: unix timestamp
:type timestamp: int
:param fmt: show format
:type fmt: str
:return:
:rtype: str
"""
dt = None
try:
timestamp = t... | python | def unixtime2str(timestamp, fmt='%Y-%m-%d %H:%M:%S'):
"""
将 ``秒级别的时间戳`` 转换成字符串
.. warning:
时间戳是以 ``秒`` 为单位的
:param timestamp: unix timestamp
:type timestamp: int
:param fmt: show format
:type fmt: str
:return:
:rtype: str
"""
dt = None
try:
timestamp = t... | [
"def",
"unixtime2str",
"(",
"timestamp",
",",
"fmt",
"=",
"'%Y-%m-%d %H:%M:%S'",
")",
":",
"dt",
"=",
"None",
"try",
":",
"timestamp",
"=",
"time",
".",
"localtime",
"(",
"timestamp",
")",
"dt",
"=",
"time",
".",
"strftime",
"(",
"fmt",
",",
"timestamp",... | 将 ``秒级别的时间戳`` 转换成字符串
.. warning:
时间戳是以 ``秒`` 为单位的
:param timestamp: unix timestamp
:type timestamp: int
:param fmt: show format
:type fmt: str
:return:
:rtype: str | [
"将",
"秒级别的时间戳",
"转换成字符串"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L382-L402 |
coghost/izen | izen/helper.py | unixtime | def unixtime(mm=False):
"""
返回当前时间的 ``unix时间戳``, 默认返回级别 ``second``
- 可设置 ``mm=True`` 来获取毫秒, 毫秒使用 ``(秒+随机数)*1000`` 来实现, 尽量防止出现相同
- 使用时间范围限制:(2001/9/9 9:46:40 ~ 2286/11/21 1:46:3)
- 样例
.. code:: python
# 标准情况直接使用秒
len(str(unixtime()))
# 输出 10
# 如果需要唯一标识, 可以... | python | def unixtime(mm=False):
"""
返回当前时间的 ``unix时间戳``, 默认返回级别 ``second``
- 可设置 ``mm=True`` 来获取毫秒, 毫秒使用 ``(秒+随机数)*1000`` 来实现, 尽量防止出现相同
- 使用时间范围限制:(2001/9/9 9:46:40 ~ 2286/11/21 1:46:3)
- 样例
.. code:: python
# 标准情况直接使用秒
len(str(unixtime()))
# 输出 10
# 如果需要唯一标识, 可以... | [
"def",
"unixtime",
"(",
"mm",
"=",
"False",
")",
":",
"if",
"mm",
":",
"return",
"int",
"(",
"(",
"time",
".",
"mktime",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"timetuple",
"(",
")",
")",
"+",
"random",
".",
"random",
"(",
... | 返回当前时间的 ``unix时间戳``, 默认返回级别 ``second``
- 可设置 ``mm=True`` 来获取毫秒, 毫秒使用 ``(秒+随机数)*1000`` 来实现, 尽量防止出现相同
- 使用时间范围限制:(2001/9/9 9:46:40 ~ 2286/11/21 1:46:3)
- 样例
.. code:: python
# 标准情况直接使用秒
len(str(unixtime()))
# 输出 10
# 如果需要唯一标识, 可以尝试使用
len(str(unixtime(True)))
... | [
"返回当前时间的",
"unix时间戳",
"默认返回级别",
"second"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L405-L428 |
coghost/izen | izen/helper.py | mkdir_p | def mkdir_p(pathin, is_dir=False):
"""
分隔pathin, 并以此创建层级目录
- ``is_dir == True``: 则将所有 ``/ 分隔`` 的pathin 当前文件夹
- 否则, 将分隔的最后一个元素当做是文件处理
>>> # 创建一个目录 /tmp/a/b/c
>>> mkdir_p('/tmp/a/b/c/001.log')
:param is_dir: ``是否目录``
:type is_dir: bool
:param pathin: ``待创建的目录或者文件路径``
:type p... | python | def mkdir_p(pathin, is_dir=False):
"""
分隔pathin, 并以此创建层级目录
- ``is_dir == True``: 则将所有 ``/ 分隔`` 的pathin 当前文件夹
- 否则, 将分隔的最后一个元素当做是文件处理
>>> # 创建一个目录 /tmp/a/b/c
>>> mkdir_p('/tmp/a/b/c/001.log')
:param is_dir: ``是否目录``
:type is_dir: bool
:param pathin: ``待创建的目录或者文件路径``
:type p... | [
"def",
"mkdir_p",
"(",
"pathin",
",",
"is_dir",
"=",
"False",
")",
":",
"h",
",",
"_",
"=",
"os",
".",
"path",
".",
"split",
"(",
"pathin",
")",
"if",
"is_dir",
":",
"h",
"=",
"pathin",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",... | 分隔pathin, 并以此创建层级目录
- ``is_dir == True``: 则将所有 ``/ 分隔`` 的pathin 当前文件夹
- 否则, 将分隔的最后一个元素当做是文件处理
>>> # 创建一个目录 /tmp/a/b/c
>>> mkdir_p('/tmp/a/b/c/001.log')
:param is_dir: ``是否目录``
:type is_dir: bool
:param pathin: ``待创建的目录或者文件路径``
:type pathin: str | [
"分隔pathin",
"并以此创建层级目录"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L434-L458 |
coghost/izen | izen/helper.py | walk_dir_with_filter | def walk_dir_with_filter(pth, prefix=None, suffix=None):
"""
默认情况下,会遍历目录下所有文件,写入数组返回.
- ``prefix`` 会过滤以 其开头的所有文件
- ``suffix`` 结尾
:param pth:
:type pth:
:param prefix:
:type prefix:
:param suffix:
:type suffix:
:return:
:rtype:
"""
if suffix is None or type(s... | python | def walk_dir_with_filter(pth, prefix=None, suffix=None):
"""
默认情况下,会遍历目录下所有文件,写入数组返回.
- ``prefix`` 会过滤以 其开头的所有文件
- ``suffix`` 结尾
:param pth:
:type pth:
:param prefix:
:type prefix:
:param suffix:
:type suffix:
:return:
:rtype:
"""
if suffix is None or type(s... | [
"def",
"walk_dir_with_filter",
"(",
"pth",
",",
"prefix",
"=",
"None",
",",
"suffix",
"=",
"None",
")",
":",
"if",
"suffix",
"is",
"None",
"or",
"type",
"(",
"suffix",
")",
"!=",
"list",
":",
"suffix",
"=",
"[",
"]",
"if",
"prefix",
"is",
"None",
"... | 默认情况下,会遍历目录下所有文件,写入数组返回.
- ``prefix`` 会过滤以 其开头的所有文件
- ``suffix`` 结尾
:param pth:
:type pth:
:param prefix:
:type prefix:
:param suffix:
:type suffix:
:return:
:rtype: | [
"默认情况下",
"会遍历目录下所有文件",
"写入数组返回",
"."
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L461-L504 |
coghost/izen | izen/helper.py | write_file | def write_file(dat, pth, append=False):
"""
将 dat 内容写入 pth 中, 如果写入成功, 返回为空, 否则返回失败信息
:type append: ``bool``
:param append: 写入模式
:type append: ``bool``
:param dat: 待写入内容
:type dat: ``str``
:param pth:
:type pth: ``str``
:return:
:rtype:
"""
err = None
_d, _nm... | python | def write_file(dat, pth, append=False):
"""
将 dat 内容写入 pth 中, 如果写入成功, 返回为空, 否则返回失败信息
:type append: ``bool``
:param append: 写入模式
:type append: ``bool``
:param dat: 待写入内容
:type dat: ``str``
:param pth:
:type pth: ``str``
:return:
:rtype:
"""
err = None
_d, _nm... | [
"def",
"write_file",
"(",
"dat",
",",
"pth",
",",
"append",
"=",
"False",
")",
":",
"err",
"=",
"None",
"_d",
",",
"_nm",
"=",
"os",
".",
"path",
".",
"split",
"(",
"pth",
")",
"if",
"_d",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
... | 将 dat 内容写入 pth 中, 如果写入成功, 返回为空, 否则返回失败信息
:type append: ``bool``
:param append: 写入模式
:type append: ``bool``
:param dat: 待写入内容
:type dat: ``str``
:param pth:
:type pth: ``str``
:return:
:rtype: | [
"将",
"dat",
"内容写入",
"pth",
"中",
"如果写入成功",
"返回为空",
"否则返回失败信息"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L507-L535 |
coghost/izen | izen/helper.py | read_file | def read_file(pth, use_str=False):
"""
读取文件, 并返回内容,
如果读取失败,返回None
:param pth:
:type pth:
:return:
:rtype:
"""
cont = None
try:
with open(u'' + pth, 'rb') as fp:
cont = fp.read()
if use_str:
cont = to_str(cont)
except Exception... | python | def read_file(pth, use_str=False):
"""
读取文件, 并返回内容,
如果读取失败,返回None
:param pth:
:type pth:
:return:
:rtype:
"""
cont = None
try:
with open(u'' + pth, 'rb') as fp:
cont = fp.read()
if use_str:
cont = to_str(cont)
except Exception... | [
"def",
"read_file",
"(",
"pth",
",",
"use_str",
"=",
"False",
")",
":",
"cont",
"=",
"None",
"try",
":",
"with",
"open",
"(",
"u''",
"+",
"pth",
",",
"'rb'",
")",
"as",
"fp",
":",
"cont",
"=",
"fp",
".",
"read",
"(",
")",
"if",
"use_str",
":",
... | 读取文件, 并返回内容,
如果读取失败,返回None
:param pth:
:type pth:
:return:
:rtype: | [
"读取文件",
"并返回内容",
"如果读取失败",
"返回None"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L538-L557 |
coghost/izen | izen/helper.py | b64_file | def b64_file(src_file):
"""
打包当前程序目录中的所有程序文件 生成 tgz 文件, 读取 base64编码后, 使用aes加密数据,并附加rsa签名
:return:
:rtype:
"""
z = None
i = 0
while not z and i < 3:
z = read_file(src_file)
time.sleep(0.1)
i += 1
if not z:
log.warning('cannot open {} '.format(src_file)... | python | def b64_file(src_file):
"""
打包当前程序目录中的所有程序文件 生成 tgz 文件, 读取 base64编码后, 使用aes加密数据,并附加rsa签名
:return:
:rtype:
"""
z = None
i = 0
while not z and i < 3:
z = read_file(src_file)
time.sleep(0.1)
i += 1
if not z:
log.warning('cannot open {} '.format(src_file)... | [
"def",
"b64_file",
"(",
"src_file",
")",
":",
"z",
"=",
"None",
"i",
"=",
"0",
"while",
"not",
"z",
"and",
"i",
"<",
"3",
":",
"z",
"=",
"read_file",
"(",
"src_file",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"i",
"+=",
"1",
"if",
"not",
"z... | 打包当前程序目录中的所有程序文件 生成 tgz 文件, 读取 base64编码后, 使用aes加密数据,并附加rsa签名
:return:
:rtype: | [
"打包当前程序目录中的所有程序文件",
"生成",
"tgz",
"文件",
"读取",
"base64编码后",
"使用aes加密数据",
"并附加rsa签名",
":",
"return",
":",
":",
"rtype",
":"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L592-L610 |
coghost/izen | izen/helper.py | pickle_m2f | def pickle_m2f(dat, pth):
"""
将 dat 内容同步到文件存储中
:param dat:
:type dat:
:param pth:
:type pth:
:return:
:rtype:
"""
mkdir_p(pth)
# 为了2与3兼容, 设置 dump 的协议为 2
with open(pth, 'wb') as f:
pickle.dump(dat, f, 2) | python | def pickle_m2f(dat, pth):
"""
将 dat 内容同步到文件存储中
:param dat:
:type dat:
:param pth:
:type pth:
:return:
:rtype:
"""
mkdir_p(pth)
# 为了2与3兼容, 设置 dump 的协议为 2
with open(pth, 'wb') as f:
pickle.dump(dat, f, 2) | [
"def",
"pickle_m2f",
"(",
"dat",
",",
"pth",
")",
":",
"mkdir_p",
"(",
"pth",
")",
"# 为了2与3兼容, 设置 dump 的协议为 2",
"with",
"open",
"(",
"pth",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"dat",
",",
"f",
",",
"2",
")"
] | 将 dat 内容同步到文件存储中
:param dat:
:type dat:
:param pth:
:type pth:
:return:
:rtype: | [
"将",
"dat",
"内容同步到文件存储中"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L613-L627 |
coghost/izen | izen/helper.py | pickle_f2m | def pickle_f2m(pth, rt=None):
"""
获取文件内容并返回, 如果文件不存在, 则返回 rt
:param pth:
:type pth:
:param rt: ``如果需要指定返回值, 请设置该值``
:type rt:
:return:
:rtype:
"""
r = rt
try:
with open(pth, 'rb') as f:
r = pickle.load(f)
except Exception as err:
sys.stder... | python | def pickle_f2m(pth, rt=None):
"""
获取文件内容并返回, 如果文件不存在, 则返回 rt
:param pth:
:type pth:
:param rt: ``如果需要指定返回值, 请设置该值``
:type rt:
:return:
:rtype:
"""
r = rt
try:
with open(pth, 'rb') as f:
r = pickle.load(f)
except Exception as err:
sys.stder... | [
"def",
"pickle_f2m",
"(",
"pth",
",",
"rt",
"=",
"None",
")",
":",
"r",
"=",
"rt",
"try",
":",
"with",
"open",
"(",
"pth",
",",
"'rb'",
")",
"as",
"f",
":",
"r",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"except",
"Exception",
"as",
"err",
"... | 获取文件内容并返回, 如果文件不存在, 则返回 rt
:param pth:
:type pth:
:param rt: ``如果需要指定返回值, 请设置该值``
:type rt:
:return:
:rtype: | [
"获取文件内容并返回",
"如果文件不存在",
"则返回",
"rt"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L630-L647 |
coghost/izen | izen/helper.py | l_endian | def l_endian(v):
""" 小端序 """
w = struct.pack('<H', v)
return str(binascii.hexlify(w), encoding='gbk') | python | def l_endian(v):
""" 小端序 """
w = struct.pack('<H', v)
return str(binascii.hexlify(w), encoding='gbk') | [
"def",
"l_endian",
"(",
"v",
")",
":",
"w",
"=",
"struct",
".",
"pack",
"(",
"'<H'",
",",
"v",
")",
"return",
"str",
"(",
"binascii",
".",
"hexlify",
"(",
"w",
")",
",",
"encoding",
"=",
"'gbk'",
")"
] | 小端序 | [
"小端序"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L670-L673 |
coghost/izen | izen/helper.py | xorsum | def xorsum(t):
"""
异或校验
:param t:
:type t:
:return:
:rtype:
"""
_b = t[0]
for i in t[1:]:
_b = _b ^ i
_b &= 0xff
return _b | python | def xorsum(t):
"""
异或校验
:param t:
:type t:
:return:
:rtype:
"""
_b = t[0]
for i in t[1:]:
_b = _b ^ i
_b &= 0xff
return _b | [
"def",
"xorsum",
"(",
"t",
")",
":",
"_b",
"=",
"t",
"[",
"0",
"]",
"for",
"i",
"in",
"t",
"[",
"1",
":",
"]",
":",
"_b",
"=",
"_b",
"^",
"i",
"_b",
"&=",
"0xff",
"return",
"_b"
] | 异或校验
:param t:
:type t:
:return:
:rtype: | [
"异或校验",
":",
"param",
"t",
":",
":",
"type",
"t",
":",
":",
"return",
":",
":",
"rtype",
":"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L682-L694 |
coghost/izen | izen/helper.py | check_sum | def check_sum(buf, csum):
"""
检查数据的校验和
:param buf:
:type buf:
:param csum:
:type csum:
:return:
:rtype:
"""
csum = csum.encode('utf-8')
_csum = ord(buf[0])
for x in buf[1:]:
_csum ^= ord(x)
_csum = binascii.b2a_hex(chr(_csum).encode('utf-8')).upper()
if _... | python | def check_sum(buf, csum):
"""
检查数据的校验和
:param buf:
:type buf:
:param csum:
:type csum:
:return:
:rtype:
"""
csum = csum.encode('utf-8')
_csum = ord(buf[0])
for x in buf[1:]:
_csum ^= ord(x)
_csum = binascii.b2a_hex(chr(_csum).encode('utf-8')).upper()
if _... | [
"def",
"check_sum",
"(",
"buf",
",",
"csum",
")",
":",
"csum",
"=",
"csum",
".",
"encode",
"(",
"'utf-8'",
")",
"_csum",
"=",
"ord",
"(",
"buf",
"[",
"0",
"]",
")",
"for",
"x",
"in",
"buf",
"[",
"1",
":",
"]",
":",
"_csum",
"^=",
"ord",
"(",
... | 检查数据的校验和
:param buf:
:type buf:
:param csum:
:type csum:
:return:
:rtype: | [
"检查数据的校验和",
":",
"param",
"buf",
":",
":",
"type",
"buf",
":",
":",
"param",
"csum",
":",
":",
"type",
"csum",
":",
":",
"return",
":",
":",
"rtype",
":"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L708-L726 |
coghost/izen | izen/helper.py | crc16 | def crc16(cmd, use_byte=False):
"""
CRC16 检验
- 启用``use_byte`` 则返回 bytes 类型.
:param cmd: 无crc检验的指令
:type cmd:
:param use_byte: 是否返回byte类型
:type use_byte:
:return: 返回crc值
:rtype:
"""
crc = 0xFFFF
# crc16 计算方法, 需要使用 byte
if hasattr(cmd, 'encode'):
cmd =... | python | def crc16(cmd, use_byte=False):
"""
CRC16 检验
- 启用``use_byte`` 则返回 bytes 类型.
:param cmd: 无crc检验的指令
:type cmd:
:param use_byte: 是否返回byte类型
:type use_byte:
:return: 返回crc值
:rtype:
"""
crc = 0xFFFF
# crc16 计算方法, 需要使用 byte
if hasattr(cmd, 'encode'):
cmd =... | [
"def",
"crc16",
"(",
"cmd",
",",
"use_byte",
"=",
"False",
")",
":",
"crc",
"=",
"0xFFFF",
"# crc16 计算方法, 需要使用 byte",
"if",
"hasattr",
"(",
"cmd",
",",
"'encode'",
")",
":",
"cmd",
"=",
"bytes",
".",
"fromhex",
"(",
"cmd",
")",
"for",
"_",
"in",
"cmd... | CRC16 检验
- 启用``use_byte`` 则返回 bytes 类型.
:param cmd: 无crc检验的指令
:type cmd:
:param use_byte: 是否返回byte类型
:type use_byte:
:return: 返回crc值
:rtype: | [
"CRC16",
"检验",
"-",
"启用",
"use_byte",
"则返回",
"bytes",
"类型",
"."
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L729-L762 |
coghost/izen | izen/helper.py | debug | def debug(users=None):
"""
是一种方便的测试模式, 用于 ``全局开启`` 或者关闭测试功能
- 如果当前用户存在在users列表中, 则设定程序运行于debug模式
"""
if not users:
return False
users = users if isinstance(users, list) else [users]
return True if getpass.getuser() in users else False | python | def debug(users=None):
"""
是一种方便的测试模式, 用于 ``全局开启`` 或者关闭测试功能
- 如果当前用户存在在users列表中, 则设定程序运行于debug模式
"""
if not users:
return False
users = users if isinstance(users, list) else [users]
return True if getpass.getuser() in users else False | [
"def",
"debug",
"(",
"users",
"=",
"None",
")",
":",
"if",
"not",
"users",
":",
"return",
"False",
"users",
"=",
"users",
"if",
"isinstance",
"(",
"users",
",",
"list",
")",
"else",
"[",
"users",
"]",
"return",
"True",
"if",
"getpass",
".",
"getuser"... | 是一种方便的测试模式, 用于 ``全局开启`` 或者关闭测试功能
- 如果当前用户存在在users列表中, 则设定程序运行于debug模式 | [
"是一种方便的测试模式",
"用于",
"全局开启",
"或者关闭测试功能"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L768-L778 |
coghost/izen | izen/helper.py | get_addr | def get_addr(iface='lo0', iface_type='link'):
"""
获取网络接口 ``iface`` 的 ``mac``
- 如果系统类型为 ``mac``, 使用 ``psutil``
- 其他使用 ``socket``
:param iface: ``网络接口``
:type iface: str
:return: ``mac地址/空``
:rtype: str/None
"""
if platform.system() in ['Darwin', 'Linux']:
if iface_ty... | python | def get_addr(iface='lo0', iface_type='link'):
"""
获取网络接口 ``iface`` 的 ``mac``
- 如果系统类型为 ``mac``, 使用 ``psutil``
- 其他使用 ``socket``
:param iface: ``网络接口``
:type iface: str
:return: ``mac地址/空``
:rtype: str/None
"""
if platform.system() in ['Darwin', 'Linux']:
if iface_ty... | [
"def",
"get_addr",
"(",
"iface",
"=",
"'lo0'",
",",
"iface_type",
"=",
"'link'",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"in",
"[",
"'Darwin'",
",",
"'Linux'",
"]",
":",
"if",
"iface_type",
"==",
"'link'",
":",
"_AF_FAMILY",
"=",
"psutil",... | 获取网络接口 ``iface`` 的 ``mac``
- 如果系统类型为 ``mac``, 使用 ``psutil``
- 其他使用 ``socket``
:param iface: ``网络接口``
:type iface: str
:return: ``mac地址/空``
:rtype: str/None | [
"获取网络接口",
"iface",
"的",
"mac"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L781-L806 |
coghost/izen | izen/helper.py | uniqid | def uniqid(iface='wlan0', is_hex=True):
"""
使用网卡的物理地址 ``默认wlan0`` 来作为标识
- 置位 ``is_hex``, 来确定返回 ``16进制/10进制格式``
:param iface: ``网络接口(默认wlan0)``
:type iface: str
:param is_hex: ``True(返回16进制)/False(10进制)``
:type is_hex: bool
:return: ``mac地址/空``
:rtype: str
"""
# return s... | python | def uniqid(iface='wlan0', is_hex=True):
"""
使用网卡的物理地址 ``默认wlan0`` 来作为标识
- 置位 ``is_hex``, 来确定返回 ``16进制/10进制格式``
:param iface: ``网络接口(默认wlan0)``
:type iface: str
:param is_hex: ``True(返回16进制)/False(10进制)``
:type is_hex: bool
:return: ``mac地址/空``
:rtype: str
"""
# return s... | [
"def",
"uniqid",
"(",
"iface",
"=",
"'wlan0'",
",",
"is_hex",
"=",
"True",
")",
":",
"# return str(appid.getnode()) if not is_hex else str(hex(appid.getnode()))[2:-1]",
"m_",
"=",
"get_addr",
"(",
"iface",
")",
"m_",
"=",
"''",
".",
"join",
"(",
"m_",
".",
"spli... | 使用网卡的物理地址 ``默认wlan0`` 来作为标识
- 置位 ``is_hex``, 来确定返回 ``16进制/10进制格式``
:param iface: ``网络接口(默认wlan0)``
:type iface: str
:param is_hex: ``True(返回16进制)/False(10进制)``
:type is_hex: bool
:return: ``mac地址/空``
:rtype: str | [
"使用网卡的物理地址",
"默认wlan0",
"来作为标识"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L809-L827 |
coghost/izen | izen/helper.py | app_id | def app_id(iface=''):
""" 依据指定的 ``iface`` 名, 来获取程序运行需要的唯一ID
- iface 为空, 则自动从系统选择第一个可用的网络接口 mac
- 顺序,自动获取编号最小的网络接口:
+ macosx: en0~n
+ linux: eth/wlan(0~n)
:param iface: ``系统中的网络接口名``
:type iface: str
:return:
:rtype:
"""
if iface:
return uniqid(iface)
if... | python | def app_id(iface=''):
""" 依据指定的 ``iface`` 名, 来获取程序运行需要的唯一ID
- iface 为空, 则自动从系统选择第一个可用的网络接口 mac
- 顺序,自动获取编号最小的网络接口:
+ macosx: en0~n
+ linux: eth/wlan(0~n)
:param iface: ``系统中的网络接口名``
:type iface: str
:return:
:rtype:
"""
if iface:
return uniqid(iface)
if... | [
"def",
"app_id",
"(",
"iface",
"=",
"''",
")",
":",
"if",
"iface",
":",
"return",
"uniqid",
"(",
"iface",
")",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Darwin'",
":",
"_ava_start",
"=",
"[",
"'en'",
"]",
"elif",
"platform",
".",
"system",
... | 依据指定的 ``iface`` 名, 来获取程序运行需要的唯一ID
- iface 为空, 则自动从系统选择第一个可用的网络接口 mac
- 顺序,自动获取编号最小的网络接口:
+ macosx: en0~n
+ linux: eth/wlan(0~n)
:param iface: ``系统中的网络接口名``
:type iface: str
:return:
:rtype: | [
"依据指定的",
"iface",
"名",
"来获取程序运行需要的唯一ID"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L830-L859 |
coghost/izen | izen/helper.py | get_sys_cmd_output | def get_sys_cmd_output(cmd):
"""
通过 ``subprocess`` 运行 ``cmd`` 获取系统输出
- ``cmd`` 为数组形式
- 需要符合 ``subprocess`` 调用标准
- 返回
- err信息,
- 使用 ``换行符\\n`` 分隔的数组
:param cmd:
:type cmd: list, str
:return:
:rtype:
"""
_e, op = None, ''
if not isinstance(cmd, list)... | python | def get_sys_cmd_output(cmd):
"""
通过 ``subprocess`` 运行 ``cmd`` 获取系统输出
- ``cmd`` 为数组形式
- 需要符合 ``subprocess`` 调用标准
- 返回
- err信息,
- 使用 ``换行符\\n`` 分隔的数组
:param cmd:
:type cmd: list, str
:return:
:rtype:
"""
_e, op = None, ''
if not isinstance(cmd, list)... | [
"def",
"get_sys_cmd_output",
"(",
"cmd",
")",
":",
"_e",
",",
"op",
"=",
"None",
",",
"''",
"if",
"not",
"isinstance",
"(",
"cmd",
",",
"list",
")",
":",
"cmd",
"=",
"cmd",
".",
"split",
"(",
"' '",
")",
"try",
":",
"op",
"=",
"subprocess",
".",
... | 通过 ``subprocess`` 运行 ``cmd`` 获取系统输出
- ``cmd`` 为数组形式
- 需要符合 ``subprocess`` 调用标准
- 返回
- err信息,
- 使用 ``换行符\\n`` 分隔的数组
:param cmd:
:type cmd: list, str
:return:
:rtype: | [
"通过",
"subprocess",
"运行",
"cmd",
"获取系统输出"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L862-L890 |
coghost/izen | izen/helper.py | block_here | def block_here(duration=0):
"""
如果 duration 为0, 则一直阻塞程序运行
:param duration:
:type duration:
:return:
:rtype:
"""
try:
while not duration:
time.sleep(0.001)
while duration:
time.sleep(0.001)
duration -= 1
except KeyboardInterrupt as ... | python | def block_here(duration=0):
"""
如果 duration 为0, 则一直阻塞程序运行
:param duration:
:type duration:
:return:
:rtype:
"""
try:
while not duration:
time.sleep(0.001)
while duration:
time.sleep(0.001)
duration -= 1
except KeyboardInterrupt as ... | [
"def",
"block_here",
"(",
"duration",
"=",
"0",
")",
":",
"try",
":",
"while",
"not",
"duration",
":",
"time",
".",
"sleep",
"(",
"0.001",
")",
"while",
"duration",
":",
"time",
".",
"sleep",
"(",
"0.001",
")",
"duration",
"-=",
"1",
"except",
"Keybo... | 如果 duration 为0, 则一直阻塞程序运行
:param duration:
:type duration:
:return:
:rtype: | [
"如果",
"duration",
"为0",
"则一直阻塞程序运行",
":",
"param",
"duration",
":",
":",
"type",
"duration",
":",
":",
"return",
":",
":",
"rtype",
":"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L911-L927 |
coghost/izen | izen/helper.py | do_get | def do_get(url, params, to=3):
"""
使用 ``request.get`` 从指定 url 获取数据
:param params: ``输入参数, 可为空``
:type params: dict
:param url: ``接口地址``
:type url:
:param to: ``响应超时返回时间``
:type to:
:return: ``接口返回的数据``
:rtype: dict
"""
try:
rs = requests.get(url, params=params, t... | python | def do_get(url, params, to=3):
"""
使用 ``request.get`` 从指定 url 获取数据
:param params: ``输入参数, 可为空``
:type params: dict
:param url: ``接口地址``
:type url:
:param to: ``响应超时返回时间``
:type to:
:return: ``接口返回的数据``
:rtype: dict
"""
try:
rs = requests.get(url, params=params, t... | [
"def",
"do_get",
"(",
"url",
",",
"params",
",",
"to",
"=",
"3",
")",
":",
"try",
":",
"rs",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
",",
"timeout",
"=",
"to",
")",
"if",
"rs",
".",
"status_code",
"==",
"200",
":"... | 使用 ``request.get`` 从指定 url 获取数据
:param params: ``输入参数, 可为空``
:type params: dict
:param url: ``接口地址``
:type url:
:param to: ``响应超时返回时间``
:type to:
:return: ``接口返回的数据``
:rtype: dict | [
"使用",
"request",
".",
"get",
"从指定",
"url",
"获取数据"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L933-L957 |
coghost/izen | izen/helper.py | do_post | def do_post(url, payload, to=3, use_json=True):
"""
使用 ``request.get`` 从指定 url 获取数据
:param use_json: 是否使用 ``json`` 格式, 如果是, 则可以直接使用字典, 否则需要先转换成字符串
:type use_json: bool
:param payload: 实际数据内容
:type payload: dict
:param url: ``接口地址``
:type url:
:param to: ``响应超时返回时间``
:type to:
... | python | def do_post(url, payload, to=3, use_json=True):
"""
使用 ``request.get`` 从指定 url 获取数据
:param use_json: 是否使用 ``json`` 格式, 如果是, 则可以直接使用字典, 否则需要先转换成字符串
:type use_json: bool
:param payload: 实际数据内容
:type payload: dict
:param url: ``接口地址``
:type url:
:param to: ``响应超时返回时间``
:type to:
... | [
"def",
"do_post",
"(",
"url",
",",
"payload",
",",
"to",
"=",
"3",
",",
"use_json",
"=",
"True",
")",
":",
"try",
":",
"if",
"use_json",
":",
"rs",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"json",
"=",
"payload",
",",
"timeout",
"=",
"to",
... | 使用 ``request.get`` 从指定 url 获取数据
:param use_json: 是否使用 ``json`` 格式, 如果是, 则可以直接使用字典, 否则需要先转换成字符串
:type use_json: bool
:param payload: 实际数据内容
:type payload: dict
:param url: ``接口地址``
:type url:
:param to: ``响应超时返回时间``
:type to:
:return: ``接口返回的数据``
:rtype: dict | [
"使用",
"request",
".",
"get",
"从指定",
"url",
"获取数据"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L960-L986 |
coghost/izen | izen/helper.py | get_domain_home_from_url | def get_domain_home_from_url(url):
""" parse url for domain and homepage
:param url: the req url
:type url: str
:return: (homepage, domain)
:rtype:
"""
p = parse.urlparse(url)
if p.netloc:
return '{}://{}'.format(p.scheme, p.netloc), p.netloc
else:
return '', '' | python | def get_domain_home_from_url(url):
""" parse url for domain and homepage
:param url: the req url
:type url: str
:return: (homepage, domain)
:rtype:
"""
p = parse.urlparse(url)
if p.netloc:
return '{}://{}'.format(p.scheme, p.netloc), p.netloc
else:
return '', '' | [
"def",
"get_domain_home_from_url",
"(",
"url",
")",
":",
"p",
"=",
"parse",
".",
"urlparse",
"(",
"url",
")",
"if",
"p",
".",
"netloc",
":",
"return",
"'{}://{}'",
".",
"format",
"(",
"p",
".",
"scheme",
",",
"p",
".",
"netloc",
")",
",",
"p",
".",... | parse url for domain and homepage
:param url: the req url
:type url: str
:return: (homepage, domain)
:rtype: | [
"parse",
"url",
"for",
"domain",
"and",
"homepage"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L989-L1001 |
coghost/izen | izen/helper.py | multi_replace | def multi_replace(original, pattens, delim='|,'):
"""
使用 ``multi_delim`` 中的所有规则来替换 ``original`` 字符串内容
>>> orig = '今天是一个好天气'
>>> multi_replace(orig, '今天|是|好天气')
'一个'
>>> multi_replace(orig, '今天,today |是,is |好天气,good weather')
'today is 一个good weather'
:param delim: 分隔符, 外层 `|` 内层 `,... | python | def multi_replace(original, pattens, delim='|,'):
"""
使用 ``multi_delim`` 中的所有规则来替换 ``original`` 字符串内容
>>> orig = '今天是一个好天气'
>>> multi_replace(orig, '今天|是|好天气')
'一个'
>>> multi_replace(orig, '今天,today |是,is |好天气,good weather')
'today is 一个good weather'
:param delim: 分隔符, 外层 `|` 内层 `,... | [
"def",
"multi_replace",
"(",
"original",
",",
"pattens",
",",
"delim",
"=",
"'|,'",
")",
":",
"if",
"not",
"original",
":",
"return",
"''",
"if",
"not",
"delim",
"or",
"len",
"(",
"delim",
")",
"!=",
"2",
":",
"delim",
"=",
"'|,'",
"# 最外层分隔符, 第二层分隔符",
... | 使用 ``multi_delim`` 中的所有规则来替换 ``original`` 字符串内容
>>> orig = '今天是一个好天气'
>>> multi_replace(orig, '今天|是|好天气')
'一个'
>>> multi_replace(orig, '今天,today |是,is |好天气,good weather')
'today is 一个good weather'
:param delim: 分隔符, 外层 `|` 内层 `,`
:type delim:
:param original: 原始字符串
:type original: ... | [
"使用",
"multi_delim",
"中的所有规则来替换",
"original",
"字符串内容"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1073-L1108 |
coghost/izen | izen/helper.py | words | def words(fpth):
"""
ww = words(os.path.join(app_root, 'ig/helper.py'))
for k, v in (ww.most_common(3)):
print(k, v)
:param fpth:
:type fpth:
:return:
:rtype:
"""
from collections import Counter
words__ = Counter()
with open(fpth) as fp:
for line in fp:
... | python | def words(fpth):
"""
ww = words(os.path.join(app_root, 'ig/helper.py'))
for k, v in (ww.most_common(3)):
print(k, v)
:param fpth:
:type fpth:
:return:
:rtype:
"""
from collections import Counter
words__ = Counter()
with open(fpth) as fp:
for line in fp:
... | [
"def",
"words",
"(",
"fpth",
")",
":",
"from",
"collections",
"import",
"Counter",
"words__",
"=",
"Counter",
"(",
")",
"with",
"open",
"(",
"fpth",
")",
"as",
"fp",
":",
"for",
"line",
"in",
"fp",
":",
"words__",
".",
"update",
"(",
"line",
".",
"... | ww = words(os.path.join(app_root, 'ig/helper.py'))
for k, v in (ww.most_common(3)):
print(k, v)
:param fpth:
:type fpth:
:return:
:rtype: | [
"ww",
"=",
"words",
"(",
"os",
".",
"path",
".",
"join",
"(",
"app_root",
"ig",
"/",
"helper",
".",
"py",
"))",
"for",
"k",
"v",
"in",
"(",
"ww",
".",
"most_common",
"(",
"3",
"))",
":",
"print",
"(",
"k",
"v",
")"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1115-L1131 |
coghost/izen | izen/helper.py | rand_block | def rand_block(minimum, scale, maximum=1):
"""
block current thread at random pareto time ``minimum < block < 15`` and return the sleep time ``seconds``
:param minimum:
:type minimum:
:param scale:
:type scale:
:param slow_mode: a tuple e.g.(2, 5)
:type slow_mode: tuple
:return:... | python | def rand_block(minimum, scale, maximum=1):
"""
block current thread at random pareto time ``minimum < block < 15`` and return the sleep time ``seconds``
:param minimum:
:type minimum:
:param scale:
:type scale:
:param slow_mode: a tuple e.g.(2, 5)
:type slow_mode: tuple
:return:... | [
"def",
"rand_block",
"(",
"minimum",
",",
"scale",
",",
"maximum",
"=",
"1",
")",
":",
"t",
"=",
"min",
"(",
"rand_pareto_float",
"(",
"minimum",
",",
"scale",
")",
",",
"maximum",
")",
"time",
".",
"sleep",
"(",
"t",
")",
"return",
"t"
] | block current thread at random pareto time ``minimum < block < 15`` and return the sleep time ``seconds``
:param minimum:
:type minimum:
:param scale:
:type scale:
:param slow_mode: a tuple e.g.(2, 5)
:type slow_mode: tuple
:return: | [
"block",
"current",
"thread",
"at",
"random",
"pareto",
"time",
"minimum",
"<",
"block",
"<",
"15",
"and",
"return",
"the",
"sleep",
"time",
"seconds"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1267-L1281 |
coghost/izen | izen/helper.py | rand_str | def rand_str(max_len=6):
""" 生成 ``max_len`` 长度的字符串
- max_len < -len(NUM_LETTER_STR) will return blank str
:param max_len:
:type max_len:
:return:
:rtype:
"""
v = [x for x in NUM_LETTER_STR]
np.random.shuffle(v)
return ''.join(v[:max_len]) | python | def rand_str(max_len=6):
""" 生成 ``max_len`` 长度的字符串
- max_len < -len(NUM_LETTER_STR) will return blank str
:param max_len:
:type max_len:
:return:
:rtype:
"""
v = [x for x in NUM_LETTER_STR]
np.random.shuffle(v)
return ''.join(v[:max_len]) | [
"def",
"rand_str",
"(",
"max_len",
"=",
"6",
")",
":",
"v",
"=",
"[",
"x",
"for",
"x",
"in",
"NUM_LETTER_STR",
"]",
"np",
".",
"random",
".",
"shuffle",
"(",
"v",
")",
"return",
"''",
".",
"join",
"(",
"v",
"[",
":",
"max_len",
"]",
")"
] | 生成 ``max_len`` 长度的字符串
- max_len < -len(NUM_LETTER_STR) will return blank str
:param max_len:
:type max_len:
:return:
:rtype: | [
"生成",
"max_len",
"长度的字符串"
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1296-L1308 |
coghost/izen | izen/helper.py | TermTable._print_divide | def _print_divide(self):
"""Prints all those table line dividers."""
for space in self.AttributesLength:
self.StrTable += "+ " + "- " * space
self.StrTable += "+" + "\n" | python | def _print_divide(self):
"""Prints all those table line dividers."""
for space in self.AttributesLength:
self.StrTable += "+ " + "- " * space
self.StrTable += "+" + "\n" | [
"def",
"_print_divide",
"(",
"self",
")",
":",
"for",
"space",
"in",
"self",
".",
"AttributesLength",
":",
"self",
".",
"StrTable",
"+=",
"\"+ \"",
"+",
"\"- \"",
"*",
"space",
"self",
".",
"StrTable",
"+=",
"\"+\"",
"+",
"\"\\n\""
] | Prints all those table line dividers. | [
"Prints",
"all",
"those",
"table",
"line",
"dividers",
"."
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1150-L1154 |
coghost/izen | izen/helper.py | TermTable.append_data | def append_data(self, attribute, values):
"""Appends the given value(s) to the attribute (column)."""
found = False
if type(values) != list:
values = [values]
for col in self.Table:
if attribute in col:
dict_values = [u"{0}".format(value) for value... | python | def append_data(self, attribute, values):
"""Appends the given value(s) to the attribute (column)."""
found = False
if type(values) != list:
values = [values]
for col in self.Table:
if attribute in col:
dict_values = [u"{0}".format(value) for value... | [
"def",
"append_data",
"(",
"self",
",",
"attribute",
",",
"values",
")",
":",
"found",
"=",
"False",
"if",
"type",
"(",
"values",
")",
"!=",
"list",
":",
"values",
"=",
"[",
"values",
"]",
"for",
"col",
"in",
"self",
".",
"Table",
":",
"if",
"attri... | Appends the given value(s) to the attribute (column). | [
"Appends",
"the",
"given",
"value",
"(",
"s",
")",
"to",
"the",
"attribute",
"(",
"column",
")",
"."
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1156-L1167 |
coghost/izen | izen/helper.py | TermTable._create_table | def _create_table(self):
"""
Creates a pretty-printed string representation of the table as
``self.StrTable``.
"""
self.StrTable = ""
self.AttributesLength = []
self.Lines_num = 0
# Prepare some values..
for col in self.Table:
# Updates... | python | def _create_table(self):
"""
Creates a pretty-printed string representation of the table as
``self.StrTable``.
"""
self.StrTable = ""
self.AttributesLength = []
self.Lines_num = 0
# Prepare some values..
for col in self.Table:
# Updates... | [
"def",
"_create_table",
"(",
"self",
")",
":",
"self",
".",
"StrTable",
"=",
"\"\"",
"self",
".",
"AttributesLength",
"=",
"[",
"]",
"self",
".",
"Lines_num",
"=",
"0",
"# Prepare some values..",
"for",
"col",
"in",
"self",
".",
"Table",
":",
"# Updates th... | Creates a pretty-printed string representation of the table as
``self.StrTable``. | [
"Creates",
"a",
"pretty",
"-",
"printed",
"string",
"representation",
"of",
"the",
"table",
"as",
"self",
".",
"StrTable",
"."
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1182-L1202 |
coghost/izen | izen/helper.py | TermTable._print_head | def _print_head(self):
"""Generates the table header."""
self._print_divide()
self.StrTable += "| "
for colwidth, attr in zip(self.AttributesLength, self.Attributes):
self.StrTable += self._pad_string(attr, colwidth * 2)
self.StrTable += "| "
self.StrTable... | python | def _print_head(self):
"""Generates the table header."""
self._print_divide()
self.StrTable += "| "
for colwidth, attr in zip(self.AttributesLength, self.Attributes):
self.StrTable += self._pad_string(attr, colwidth * 2)
self.StrTable += "| "
self.StrTable... | [
"def",
"_print_head",
"(",
"self",
")",
":",
"self",
".",
"_print_divide",
"(",
")",
"self",
".",
"StrTable",
"+=",
"\"| \"",
"for",
"colwidth",
",",
"attr",
"in",
"zip",
"(",
"self",
".",
"AttributesLength",
",",
"self",
".",
"Attributes",
")",
":",
"... | Generates the table header. | [
"Generates",
"the",
"table",
"header",
"."
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1204-L1212 |
coghost/izen | izen/helper.py | TermTable._print_value | def _print_value(self):
"""Generates the table values."""
for line in range(self.Lines_num):
for col, length in zip(self.Table, self.AttributesLength):
vals = list(col.values())[0]
val = vals[line] if len(vals) != 0 and line < len(vals) else ''
... | python | def _print_value(self):
"""Generates the table values."""
for line in range(self.Lines_num):
for col, length in zip(self.Table, self.AttributesLength):
vals = list(col.values())[0]
val = vals[line] if len(vals) != 0 and line < len(vals) else ''
... | [
"def",
"_print_value",
"(",
"self",
")",
":",
"for",
"line",
"in",
"range",
"(",
"self",
".",
"Lines_num",
")",
":",
"for",
"col",
",",
"length",
"in",
"zip",
"(",
"self",
".",
"Table",
",",
"self",
".",
"AttributesLength",
")",
":",
"vals",
"=",
"... | Generates the table values. | [
"Generates",
"the",
"table",
"values",
"."
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1214-L1223 |
coghost/izen | izen/helper.py | TermTable._disp_width | def _disp_width(self, pwcs, n=None):
"""
A wcswidth that never gives -1. Copying existing code is evil, but..
github.com/jquast/wcwidth/blob/07cea7f/wcwidth/wcwidth.py#L182-L204
"""
# pylint: disable=C0103
# Invalid argument name "n"
# TODO: Shall we consi... | python | def _disp_width(self, pwcs, n=None):
"""
A wcswidth that never gives -1. Copying existing code is evil, but..
github.com/jquast/wcwidth/blob/07cea7f/wcwidth/wcwidth.py#L182-L204
"""
# pylint: disable=C0103
# Invalid argument name "n"
# TODO: Shall we consi... | [
"def",
"_disp_width",
"(",
"self",
",",
"pwcs",
",",
"n",
"=",
"None",
")",
":",
"# pylint: disable=C0103",
"# Invalid argument name \"n\"",
"# TODO: Shall we consider things like ANSI escape seqs here?",
"# We can implement some ignore-me segment like those wrapped by",
... | A wcswidth that never gives -1. Copying existing code is evil, but..
github.com/jquast/wcwidth/blob/07cea7f/wcwidth/wcwidth.py#L182-L204 | [
"A",
"wcswidth",
"that",
"never",
"gives",
"-",
"1",
".",
"Copying",
"existing",
"code",
"is",
"evil",
"but",
"..",
"github",
".",
"com",
"/",
"jquast",
"/",
"wcwidth",
"/",
"blob",
"/",
"07cea7f",
"/",
"wcwidth",
"/",
"wcwidth",
".",
"py#L182",
"-",
... | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1225-L1240 |
coghost/izen | izen/helper.py | TermTable._pad_string | def _pad_string(self, str, colwidth):
"""Center-pads a string to the given column width using spaces."""
width = self._disp_width(str)
prefix = (colwidth - 1 - width) // 2
suffix = colwidth - prefix - width
return ' ' * prefix + str + ' ' * suffix | python | def _pad_string(self, str, colwidth):
"""Center-pads a string to the given column width using spaces."""
width = self._disp_width(str)
prefix = (colwidth - 1 - width) // 2
suffix = colwidth - prefix - width
return ' ' * prefix + str + ' ' * suffix | [
"def",
"_pad_string",
"(",
"self",
",",
"str",
",",
"colwidth",
")",
":",
"width",
"=",
"self",
".",
"_disp_width",
"(",
"str",
")",
"prefix",
"=",
"(",
"colwidth",
"-",
"1",
"-",
"width",
")",
"//",
"2",
"suffix",
"=",
"colwidth",
"-",
"prefix",
"... | Center-pads a string to the given column width using spaces. | [
"Center",
"-",
"pads",
"a",
"string",
"to",
"the",
"given",
"column",
"width",
"using",
"spaces",
"."
] | train | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1242-L1247 |
thespacedoctor/sloancone | build/lib/sloancone/image.py | image.get | def get(self):
"""
*download the image*
"""
self.log.info('starting the ``get`` method')
ra = self.ra
dec = self.dec
if self.covered == False or self.covered == 999 or self.covered == "999":
return self.covered
self._download_sdss_image()
... | python | def get(self):
"""
*download the image*
"""
self.log.info('starting the ``get`` method')
ra = self.ra
dec = self.dec
if self.covered == False or self.covered == 999 or self.covered == "999":
return self.covered
self._download_sdss_image()
... | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``get`` method'",
")",
"ra",
"=",
"self",
".",
"ra",
"dec",
"=",
"self",
".",
"dec",
"if",
"self",
".",
"covered",
"==",
"False",
"or",
"self",
".",
"covered",
... | *download the image* | [
"*",
"download",
"the",
"image",
"*"
] | train | https://github.com/thespacedoctor/sloancone/blob/106ea6533ad57f5f0ca82bf6db3053132bdb42e1/build/lib/sloancone/image.py#L120-L134 |
thespacedoctor/sloancone | build/lib/sloancone/image.py | image._download_sdss_image | def _download_sdss_image(
self):
"""*download sdss image*
"""
self.log.info('starting the ``_download_sdss_image`` method')
opt = ""
if self.grid:
opt += "G"
if self.label:
opt += "L"
if self.photocat:
opt += "P"
... | python | def _download_sdss_image(
self):
"""*download sdss image*
"""
self.log.info('starting the ``_download_sdss_image`` method')
opt = ""
if self.grid:
opt += "G"
if self.label:
opt += "L"
if self.photocat:
opt += "P"
... | [
"def",
"_download_sdss_image",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_download_sdss_image`` method'",
")",
"opt",
"=",
"\"\"",
"if",
"self",
".",
"grid",
":",
"opt",
"+=",
"\"G\"",
"if",
"self",
".",
"label",
":",
"o... | *download sdss image* | [
"*",
"download",
"sdss",
"image",
"*"
] | train | https://github.com/thespacedoctor/sloancone/blob/106ea6533ad57f5f0ca82bf6db3053132bdb42e1/build/lib/sloancone/image.py#L136-L194 |
exekias/droplet | droplet/web/wizards.py | next | def next(transport, wizard, step, data):
"""
Validate step and go to the next one (or finish the wizard)
:param transport: Transport object
:param wizard: Wizard block name
:param step: Current step number
:param data: form data for the step
"""
step = int(step)
wizard = blocks.get(... | python | def next(transport, wizard, step, data):
"""
Validate step and go to the next one (or finish the wizard)
:param transport: Transport object
:param wizard: Wizard block name
:param step: Current step number
:param data: form data for the step
"""
step = int(step)
wizard = blocks.get(... | [
"def",
"next",
"(",
"transport",
",",
"wizard",
",",
"step",
",",
"data",
")",
":",
"step",
"=",
"int",
"(",
"step",
")",
"wizard",
"=",
"blocks",
".",
"get",
"(",
"wizard",
")",
"# Retrieve form block",
"form",
"=",
"wizard",
".",
"next",
"(",
"step... | Validate step and go to the next one (or finish the wizard)
:param transport: Transport object
:param wizard: Wizard block name
:param step: Current step number
:param data: form data for the step | [
"Validate",
"step",
"and",
"go",
"to",
"the",
"next",
"one",
"(",
"or",
"finish",
"the",
"wizard",
")"
] | train | https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/web/wizards.py#L86-L111 |
ulf1/oxyba | oxyba/features_check_singular.py | features_check_singular | def features_check_singular(X, tol=1e-8):
"""Checks if a set of features/variables X result in a
ill-conditioned matrix dot(X.T,T)
Parameters:
-----------
X : ndarray
An NxM array with N observations (rows)
and M features/variables (columns).
Note: Make sure that X variable... | python | def features_check_singular(X, tol=1e-8):
"""Checks if a set of features/variables X result in a
ill-conditioned matrix dot(X.T,T)
Parameters:
-----------
X : ndarray
An NxM array with N observations (rows)
and M features/variables (columns).
Note: Make sure that X variable... | [
"def",
"features_check_singular",
"(",
"X",
",",
"tol",
"=",
"1e-8",
")",
":",
"import",
"numpy",
"as",
"np",
"_",
",",
"s",
",",
"_",
"=",
"np",
".",
"linalg",
".",
"svd",
"(",
"np",
".",
"dot",
"(",
"X",
".",
"T",
",",
"X",
")",
")",
"faile... | Checks if a set of features/variables X result in a
ill-conditioned matrix dot(X.T,T)
Parameters:
-----------
X : ndarray
An NxM array with N observations (rows)
and M features/variables (columns).
Note: Make sure that X variables are all normalized or
or scaled, e.g.
... | [
"Checks",
"if",
"a",
"set",
"of",
"features",
"/",
"variables",
"X",
"result",
"in",
"a",
"ill",
"-",
"conditioned",
"matrix",
"dot",
"(",
"X",
".",
"T",
"T",
")"
] | train | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/features_check_singular.py#L2-L43 |
Ffisegydd/whatis | whatis/_dir.py | get_dir | def get_dir(obj, **kwargs):
"""Return the type of an object. Do some regex to remove the "<class..." bit."""
attrs = list(filter(filter_dunder, dir(obj)))
if not attrs:
return "No public attributes."
s = "Attributes:"
for attr in attrs:
s += '\n - {} ({})'.format(attr, extract_type... | python | def get_dir(obj, **kwargs):
"""Return the type of an object. Do some regex to remove the "<class..." bit."""
attrs = list(filter(filter_dunder, dir(obj)))
if not attrs:
return "No public attributes."
s = "Attributes:"
for attr in attrs:
s += '\n - {} ({})'.format(attr, extract_type... | [
"def",
"get_dir",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"attrs",
"=",
"list",
"(",
"filter",
"(",
"filter_dunder",
",",
"dir",
"(",
"obj",
")",
")",
")",
"if",
"not",
"attrs",
":",
"return",
"\"No public attributes.\"",
"s",
"=",
"\"Attributes... | Return the type of an object. Do some regex to remove the "<class..." bit. | [
"Return",
"the",
"type",
"of",
"an",
"object",
".",
"Do",
"some",
"regex",
"to",
"remove",
"the",
"<class",
"...",
"bit",
"."
] | train | https://github.com/Ffisegydd/whatis/blob/eef780ced61aae6d001aeeef7574e5e27e613583/whatis/_dir.py#L6-L17 |
lehins/python-wepay | wepay/calls/account.py | Account.__find | def __find(self, **kwargs):
"""Call documentation: `/account/find
<https://www.wepay.com/developer/reference/account#find>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will s... | python | def __find(self, **kwargs):
"""Call documentation: `/account/find
<https://www.wepay.com/developer/reference/account#find>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will s... | [
"def",
"__find",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__find",
",",
"params",
",",
"kwargs",
")"
] | Call documentation: `/account/find
<https://www.wepay.com/developer/reference/account#find>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
param to ... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"find",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account#find",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",
"str",
"acc... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L40-L60 |
lehins/python-wepay | wepay/calls/account.py | Account.__create | def __create(self, name, description, **kwargs):
"""Call documentation: `/account/create
<https://www.wepay.com/developer/reference/account#create>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with `... | python | def __create(self, name, description, **kwargs):
"""Call documentation: `/account/create
<https://www.wepay.com/developer/reference/account#create>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with `... | [
"def",
"__create",
"(",
"self",
",",
"name",
",",
"description",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
",",
"'description'",
":",
"description",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__creat... | Call documentation: `/account/create
<https://www.wepay.com/developer/reference/account#create>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
param... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"create",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account#create",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",
"str",
... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L64-L87 |
lehins/python-wepay | wepay/calls/account.py | Account.__modify | def __modify(self, account_id, **kwargs):
"""Call documentation: `/account/modify
<https://www.wepay.com/developer/reference/account#modify>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_... | python | def __modify(self, account_id, **kwargs):
"""Call documentation: `/account/modify
<https://www.wepay.com/developer/reference/account#modify>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_... | [
"def",
"__modify",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'account_id'",
":",
"account_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__modify",
",",
"params",
",",
"kwargs",
")"
] | Call documentation: `/account/modify
<https://www.wepay.com/developer/reference/account#modify>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
param... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"modify",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account#modify",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",
"str",
... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L95-L117 |
lehins/python-wepay | wepay/calls/account.py | Account.__delete | def __delete(self, account_id, **kwargs):
"""Call documentation: `/account/delete
<https://www.wepay.com/developer/reference/account#delete>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_... | python | def __delete(self, account_id, **kwargs):
"""Call documentation: `/account/delete
<https://www.wepay.com/developer/reference/account#delete>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_... | [
"def",
"__delete",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'account_id'",
":",
"account_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__delete",
",",
"params",
",",
"kwargs",
")"
] | Call documentation: `/account/delete
<https://www.wepay.com/developer/reference/account#delete>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
param... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"delete",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account#delete",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",
"str",
... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L125-L147 |
lehins/python-wepay | wepay/calls/account.py | Account.__get_update_uri | def __get_update_uri(self, account_id, **kwargs):
"""Call documentation: `/account/get_update_uri
<https://www.wepay.com/developer/reference/account#update_uri>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_to... | python | def __get_update_uri(self, account_id, **kwargs):
"""Call documentation: `/account/get_update_uri
<https://www.wepay.com/developer/reference/account#update_uri>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_to... | [
"def",
"__get_update_uri",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'account_id'",
":",
"account_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__get_update_uri",
",",
"params",
",",
"kwargs"... | Call documentation: `/account/get_update_uri
<https://www.wepay.com/developer/reference/account#update_uri>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"get_update_uri",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account#update_uri",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L151-L173 |
lehins/python-wepay | wepay/calls/account.py | Account.__get_reserve_details | def __get_reserve_details(self, account_id, **kwargs):
"""Call documentation: `/account/get_reserve_details
<https://www.wepay.com/developer/reference/account#reserve>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``ac... | python | def __get_reserve_details(self, account_id, **kwargs):
"""Call documentation: `/account/get_reserve_details
<https://www.wepay.com/developer/reference/account#reserve>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``ac... | [
"def",
"__get_reserve_details",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'account_id'",
":",
"account_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__get_reserve_details",
",",
"params",
",",
... | Call documentation: `/account/get_reserve_details
<https://www.wepay.com/developer/reference/account#reserve>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"get_reserve_details",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account#reserve",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L177-L199 |
lehins/python-wepay | wepay/calls/account.py | Account.__balance | def __balance(self, account_id, **kwargs):
"""Call documentation: `/account/balance
<https://www.wepay.com/developer/reference/account-2011-01-15#balance>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``,... | python | def __balance(self, account_id, **kwargs):
"""Call documentation: `/account/balance
<https://www.wepay.com/developer/reference/account-2011-01-15#balance>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``,... | [
"def",
"__balance",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'account_id'",
":",
"account_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__balance",
",",
"params",
",",
"kwargs",
")"
] | Call documentation: `/account/balance
<https://www.wepay.com/developer/reference/account-2011-01-15#balance>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"balance",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account",
"-",
"2011",
"-",
"01",
"-",
"15#balance",
">",
"_",
"plus",
"extra",
"keyword",
"pa... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L205-L231 |
lehins/python-wepay | wepay/calls/account.py | Account.__add_bank | def __add_bank(self, account_id, **kwargs):
"""Call documentation: `/account/add_bank
<https://www.wepay.com/developer/reference/account-2011-01-15#add_bank>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token... | python | def __add_bank(self, account_id, **kwargs):
"""Call documentation: `/account/add_bank
<https://www.wepay.com/developer/reference/account-2011-01-15#add_bank>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token... | [
"def",
"__add_bank",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'account_id'",
":",
"account_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__add_bank",
",",
"params",
",",
"kwargs",
")"
] | Call documentation: `/account/add_bank
<https://www.wepay.com/developer/reference/account-2011-01-15#add_bank>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"add_bank",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account",
"-",
"2011",
"-",
"01",
"-",
"15#add_bank",
">",
"_",
"plus",
"extra",
"keyword",
"... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L235-L261 |
lehins/python-wepay | wepay/calls/account.py | Account.__set_tax | def __set_tax(self, account_id, taxes, **kwargs):
"""Call documentation: `/account/set_tax
<https://www.wepay.com/developer/reference/account-2011-01-15#set_tax>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_... | python | def __set_tax(self, account_id, taxes, **kwargs):
"""Call documentation: `/account/set_tax
<https://www.wepay.com/developer/reference/account-2011-01-15#set_tax>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_... | [
"def",
"__set_tax",
"(",
"self",
",",
"account_id",
",",
"taxes",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'account_id'",
":",
"account_id",
",",
"'taxes'",
":",
"taxes",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__set_... | Call documentation: `/account/set_tax
<https://www.wepay.com/developer/reference/account-2011-01-15#set_tax>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"set_tax",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account",
"-",
"2011",
"-",
"01",
"-",
"15#set_tax",
">",
"_",
"plus",
"extra",
"keyword",
"pa... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L265-L292 |
lehins/python-wepay | wepay/calls/account.py | Account.__get_tax | def __get_tax(self, account_id, **kwargs):
"""Call documentation: `/account/get_tax
<https://www.wepay.com/developer/reference/account-2011-01-15#get_tax>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``... | python | def __get_tax(self, account_id, **kwargs):
"""Call documentation: `/account/get_tax
<https://www.wepay.com/developer/reference/account-2011-01-15#get_tax>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``... | [
"def",
"__get_tax",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'account_id'",
":",
"account_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__get_tax",
",",
"params",
",",
"kwargs",
")"
] | Call documentation: `/account/get_tax
<https://www.wepay.com/developer/reference/account-2011-01-15#get_tax>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"get_tax",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account",
"-",
"2011",
"-",
"01",
"-",
"15#get_tax",
">",
"_",
"plus",
"extra",
"keyword",
"pa... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L296-L322 |
lehins/python-wepay | wepay/calls/account.py | Membership.__remove | def __remove(self, account_id, user_id, **kwargs):
"""Call documentation: `/account/membership/remove
<https://www.wepay.com/developer/reference/account-membership#remove>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
... | python | def __remove(self, account_id, user_id, **kwargs):
"""Call documentation: `/account/membership/remove
<https://www.wepay.com/developer/reference/account-membership#remove>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
... | [
"def",
"__remove",
"(",
"self",
",",
"account_id",
",",
"user_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'account_id'",
":",
"account_id",
",",
"'user_id'",
":",
"user_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"_... | Call documentation: `/account/membership/remove
<https://www.wepay.com/developer/reference/account-membership#remove>`_, plus extra
keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authoriza... | [
"Call",
"documentation",
":",
"/",
"account",
"/",
"membership",
"/",
"remove",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"account",
"-",
"membership#remove",
">",
"_",
"plus",
"extra",
"keyword",
"param... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/account.py#L390-L413 |
eallik/spinoff | spinoff/util/http.py | basic_auth_string | def basic_auth_string(username, password):
"""
Encode a username and password for use in an HTTP Basic Authentication
header
"""
b64 = base64.encodestring('%s:%s' % (username, password)).strip()
return 'Basic %s' % b64 | python | def basic_auth_string(username, password):
"""
Encode a username and password for use in an HTTP Basic Authentication
header
"""
b64 = base64.encodestring('%s:%s' % (username, password)).strip()
return 'Basic %s' % b64 | [
"def",
"basic_auth_string",
"(",
"username",
",",
"password",
")",
":",
"b64",
"=",
"base64",
".",
"encodestring",
"(",
"'%s:%s'",
"%",
"(",
"username",
",",
"password",
")",
")",
".",
"strip",
"(",
")",
"return",
"'Basic %s'",
"%",
"b64"
] | Encode a username and password for use in an HTTP Basic Authentication
header | [
"Encode",
"a",
"username",
"and",
"password",
"for",
"use",
"in",
"an",
"HTTP",
"Basic",
"Authentication",
"header"
] | train | https://github.com/eallik/spinoff/blob/06b00d6b86c7422c9cb8f9a4b2915906e92b7d52/spinoff/util/http.py#L80-L86 |
pydsigner/taskit | taskit/simple.py | taskit | def taskit(func):
"""
Shortcut for a standard subclass of Task(). Can be used as a decorator.
"""
class NewTask(Task):
def work(self, *args, **kw):
return func(*args, **kw)
return NewTask() | python | def taskit(func):
"""
Shortcut for a standard subclass of Task(). Can be used as a decorator.
"""
class NewTask(Task):
def work(self, *args, **kw):
return func(*args, **kw)
return NewTask() | [
"def",
"taskit",
"(",
"func",
")",
":",
"class",
"NewTask",
"(",
"Task",
")",
":",
"def",
"work",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"NewTask",
... | Shortcut for a standard subclass of Task(). Can be used as a decorator. | [
"Shortcut",
"for",
"a",
"standard",
"subclass",
"of",
"Task",
"()",
".",
"Can",
"be",
"used",
"as",
"a",
"decorator",
"."
] | train | https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/simple.py#L22-L29 |
pydsigner/taskit | taskit/simple.py | Task._do_cb | def _do_cb(self, cb, error_cb, *args, **kw):
"""
Called internally by callback(). Does cb and error_cb selection.
"""
try:
res = self.work(*args, **kw)
except Exception as e:
if error_cb is None:
show_err()
elif error_cb:
... | python | def _do_cb(self, cb, error_cb, *args, **kw):
"""
Called internally by callback(). Does cb and error_cb selection.
"""
try:
res = self.work(*args, **kw)
except Exception as e:
if error_cb is None:
show_err()
elif error_cb:
... | [
"def",
"_do_cb",
"(",
"self",
",",
"cb",
",",
"error_cb",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"work",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
... | Called internally by callback(). Does cb and error_cb selection. | [
"Called",
"internally",
"by",
"callback",
"()",
".",
"Does",
"cb",
"and",
"error_cb",
"selection",
"."
] | train | https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/simple.py#L46-L59 |
usc-isi-i2/dig-sparkutil | digSparkUtil/dictUtil.py | dict_minus | def dict_minus(d, *keys):
"""Delete key(s) from dict if exists, returning resulting dict"""
# make shallow copy
d = dict(d)
for key in keys:
try:
del d[key]
except:
pass
return d | python | def dict_minus(d, *keys):
"""Delete key(s) from dict if exists, returning resulting dict"""
# make shallow copy
d = dict(d)
for key in keys:
try:
del d[key]
except:
pass
return d | [
"def",
"dict_minus",
"(",
"d",
",",
"*",
"keys",
")",
":",
"# make shallow copy",
"d",
"=",
"dict",
"(",
"d",
")",
"for",
"key",
"in",
"keys",
":",
"try",
":",
"del",
"d",
"[",
"key",
"]",
"except",
":",
"pass",
"return",
"d"
] | Delete key(s) from dict if exists, returning resulting dict | [
"Delete",
"key",
"(",
"s",
")",
"from",
"dict",
"if",
"exists",
"returning",
"resulting",
"dict"
] | train | https://github.com/usc-isi-i2/dig-sparkutil/blob/d39c6cf957025c170753b0e02e477fea20ee3f2a/digSparkUtil/dictUtil.py#L14-L23 |
gebn/nibble | nibble/expression/lexer.py | Lexer.t_ID | def t_ID(self, t):
r'[a-zA-Z]+'
if t.value in self._RESERVED.keys():
t.type = self._RESERVED[t.value]
return t
if Information.is_valid_symbol(t.value) or \
Information.is_valid_category(t.value):
t.type = self._INFORMATION_UNIT
ret... | python | def t_ID(self, t):
r'[a-zA-Z]+'
if t.value in self._RESERVED.keys():
t.type = self._RESERVED[t.value]
return t
if Information.is_valid_symbol(t.value) or \
Information.is_valid_category(t.value):
t.type = self._INFORMATION_UNIT
ret... | [
"def",
"t_ID",
"(",
"self",
",",
"t",
")",
":",
"if",
"t",
".",
"value",
"in",
"self",
".",
"_RESERVED",
".",
"keys",
"(",
")",
":",
"t",
".",
"type",
"=",
"self",
".",
"_RESERVED",
"[",
"t",
".",
"value",
"]",
"return",
"t",
"if",
"Information... | r'[a-zA-Z]+ | [
"r",
"[",
"a",
"-",
"zA",
"-",
"Z",
"]",
"+"
] | train | https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/expression/lexer.py#L47-L63 |
gebn/nibble | nibble/expression/lexer.py | Lexer.lex | def lex(self, string):
"""
Lex a string.
:param string: The input to lex.
:return: A generator which will continue yielding tokens until the end
of the input is reached.
"""
self.lexer.input(string)
for token in self.lexer:
y... | python | def lex(self, string):
"""
Lex a string.
:param string: The input to lex.
:return: A generator which will continue yielding tokens until the end
of the input is reached.
"""
self.lexer.input(string)
for token in self.lexer:
y... | [
"def",
"lex",
"(",
"self",
",",
"string",
")",
":",
"self",
".",
"lexer",
".",
"input",
"(",
"string",
")",
"for",
"token",
"in",
"self",
".",
"lexer",
":",
"yield",
"token"
] | Lex a string.
:param string: The input to lex.
:return: A generator which will continue yielding tokens until the end
of the input is reached. | [
"Lex",
"a",
"string",
".",
":",
"param",
"string",
":",
"The",
"input",
"to",
"lex",
".",
":",
"return",
":",
"A",
"generator",
"which",
"will",
"continue",
"yielding",
"tokens",
"until",
"the",
"end",
"of",
"the",
"input",
"is",
"reached",
"."
] | train | https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/expression/lexer.py#L83-L93 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/action_plugins/fetch.py | ActionModule.run | def run(self, conn, tmp, module_name, module_args, inject):
''' handler for fetch operations '''
# load up options
options = utils.parse_kv(module_args)
source = options.get('src', None)
dest = options.get('dest', None)
if source is None or dest is None:
resu... | python | def run(self, conn, tmp, module_name, module_args, inject):
''' handler for fetch operations '''
# load up options
options = utils.parse_kv(module_args)
source = options.get('src', None)
dest = options.get('dest', None)
if source is None or dest is None:
resu... | [
"def",
"run",
"(",
"self",
",",
"conn",
",",
"tmp",
",",
"module_name",
",",
"module_args",
",",
"inject",
")",
":",
"# load up options",
"options",
"=",
"utils",
".",
"parse_kv",
"(",
"module_args",
")",
"source",
"=",
"options",
".",
"get",
"(",
"'src'... | handler for fetch operations | [
"handler",
"for",
"fetch",
"operations"
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/action_plugins/fetch.py#L36-L99 |
jamieleshaw/lurklib | lurklib/sending.py | _Sending.privmsg | def privmsg(self, target, message):
"""
Sends a PRIVMSG to someone.
Required arguments:
* target - Who to send the message to.
* message - Message to send.
"""
with self.lock:
self.send('PRIVMSG ' + target + ' :' + message)
if self.readable... | python | def privmsg(self, target, message):
"""
Sends a PRIVMSG to someone.
Required arguments:
* target - Who to send the message to.
* message - Message to send.
"""
with self.lock:
self.send('PRIVMSG ' + target + ' :' + message)
if self.readable... | [
"def",
"privmsg",
"(",
"self",
",",
"target",
",",
"message",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"send",
"(",
"'PRIVMSG '",
"+",
"target",
"+",
"' :'",
"+",
"message",
")",
"if",
"self",
".",
"readable",
"(",
")",
":",
"msg",
... | Sends a PRIVMSG to someone.
Required arguments:
* target - Who to send the message to.
* message - Message to send. | [
"Sends",
"a",
"PRIVMSG",
"to",
"someone",
".",
"Required",
"arguments",
":",
"*",
"target",
"-",
"Who",
"to",
"send",
"the",
"message",
"to",
".",
"*",
"message",
"-",
"Message",
"to",
"send",
"."
] | train | https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/sending.py#L24-L36 |
laysakura/relshell | relshell/type.py | Type.equivalent_relshell_type | def equivalent_relshell_type(val):
"""Returns `val`'s relshell compatible type.
:param val: value to check relshell equivalent type
:raises: `NotImplementedError` if val's relshell compatible type is not implemented.
"""
builtin_type = type(val)
if builtin_type not ... | python | def equivalent_relshell_type(val):
"""Returns `val`'s relshell compatible type.
:param val: value to check relshell equivalent type
:raises: `NotImplementedError` if val's relshell compatible type is not implemented.
"""
builtin_type = type(val)
if builtin_type not ... | [
"def",
"equivalent_relshell_type",
"(",
"val",
")",
":",
"builtin_type",
"=",
"type",
"(",
"val",
")",
"if",
"builtin_type",
"not",
"in",
"Type",
".",
"_typemap",
":",
"raise",
"NotImplementedError",
"(",
"\"builtin type %s is not convertible to relshell type\"",
"%",... | Returns `val`'s relshell compatible type.
:param val: value to check relshell equivalent type
:raises: `NotImplementedError` if val's relshell compatible type is not implemented. | [
"Returns",
"val",
"s",
"relshell",
"compatible",
"type",
"."
] | train | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/type.py#L53-L64 |
20c/twentyc.tools | twentyc/tools/thread.py | RunInThread.start | def start(self, *args, **kwargs):
"""
Set the arguments for the callback function and start the
thread
"""
self.runArgs = args
self.runKwargs = kwargs
Thread.start(self) | python | def start(self, *args, **kwargs):
"""
Set the arguments for the callback function and start the
thread
"""
self.runArgs = args
self.runKwargs = kwargs
Thread.start(self) | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"runArgs",
"=",
"args",
"self",
".",
"runKwargs",
"=",
"kwargs",
"Thread",
".",
"start",
"(",
"self",
")"
] | Set the arguments for the callback function and start the
thread | [
"Set",
"the",
"arguments",
"for",
"the",
"callback",
"function",
"and",
"start",
"the",
"thread"
] | train | https://github.com/20c/twentyc.tools/blob/f8f681e64f58d449bfc32646ba8bcc57db90a233/twentyc/tools/thread.py#L46-L55 |
jmgilman/Neolib | neolib/item/MainShopItem.py | MainShopItem.buy | def buy(self, price, pause=0):
""" Attempts to purchase a main shop item, returns result
Uses the item's stock id and brr to navigate to the haggle page. Auotmatically downloads
the OCR image from the haggle page and attempts to crack it. Submits the haggle form with
the given p... | python | def buy(self, price, pause=0):
""" Attempts to purchase a main shop item, returns result
Uses the item's stock id and brr to navigate to the haggle page. Auotmatically downloads
the OCR image from the haggle page and attempts to crack it. Submits the haggle form with
the given p... | [
"def",
"buy",
"(",
"self",
",",
"price",
",",
"pause",
"=",
"0",
")",
":",
"pg",
"=",
"self",
".",
"usr",
".",
"getPage",
"(",
"\"http://www.neopets.com/haggle.phtml?obj_info_id=%s&stock_id=%s&brr=%s\"",
"%",
"(",
"self",
".",
"id",
",",
"self",
".",
"stocki... | Attempts to purchase a main shop item, returns result
Uses the item's stock id and brr to navigate to the haggle page. Auotmatically downloads
the OCR image from the haggle page and attempts to crack it. Submits the haggle form with
the given price and returns if the item was successful... | [
"Attempts",
"to",
"purchase",
"a",
"main",
"shop",
"item",
"returns",
"result",
"Uses",
"the",
"item",
"s",
"stock",
"id",
"and",
"brr",
"to",
"navigate",
"to",
"the",
"haggle",
"page",
".",
"Auotmatically",
"downloads",
"the",
"OCR",
"image",
"from",
"the... | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/item/MainShopItem.py#L40-L74 |
jmgilman/Neolib | neolib/item/MainShopItem.py | MainShopItem.crackOCR | def crackOCR(self, image):
""" Attempts to crack the given OCR
Uses the "darkest pixel" method to find the darkest pixel in the image. Once
found it generates a virtual box around the rest of the pet and returns the
x and y coordinate of the middle of the virtual box. About 98.7... | python | def crackOCR(self, image):
""" Attempts to crack the given OCR
Uses the "darkest pixel" method to find the darkest pixel in the image. Once
found it generates a virtual box around the rest of the pet and returns the
x and y coordinate of the middle of the virtual box. About 98.7... | [
"def",
"crackOCR",
"(",
"self",
",",
"image",
")",
":",
"try",
":",
"im",
"=",
"Image",
".",
"open",
"(",
"image",
")",
"# Convert to greyscale, and find darkest pixel",
"im",
"=",
"im",
".",
"convert",
"(",
"\"L\"",
")",
"lo",
",",
"hi",
"=",
"im",
".... | Attempts to crack the given OCR
Uses the "darkest pixel" method to find the darkest pixel in the image. Once
found it generates a virtual box around the rest of the pet and returns the
x and y coordinate of the middle of the virtual box. About 98.7% accurate.
Paramet... | [
"Attempts",
"to",
"crack",
"the",
"given",
"OCR",
"Uses",
"the",
"darkest",
"pixel",
"method",
"to",
"find",
"the",
"darkest",
"pixel",
"in",
"the",
"image",
".",
"Once",
"found",
"it",
"generates",
"a",
"virtual",
"box",
"around",
"the",
"rest",
"of",
"... | train | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/item/MainShopItem.py#L76-L107 |
ckcollab/brains-cli | brains.py | init | def init(name, languages, run):
"""Initializes your CONFIG_FILE for the current submission"""
contents = [file_name for file_name in glob.glob("*.*") if file_name != "brains.yaml"]
with open(CONFIG_FILE, "w") as output:
output.write(yaml.safe_dump({
"run": run,
"name": name,... | python | def init(name, languages, run):
"""Initializes your CONFIG_FILE for the current submission"""
contents = [file_name for file_name in glob.glob("*.*") if file_name != "brains.yaml"]
with open(CONFIG_FILE, "w") as output:
output.write(yaml.safe_dump({
"run": run,
"name": name,... | [
"def",
"init",
"(",
"name",
",",
"languages",
",",
"run",
")",
":",
"contents",
"=",
"[",
"file_name",
"for",
"file_name",
"in",
"glob",
".",
"glob",
"(",
"\"*.*\"",
")",
"if",
"file_name",
"!=",
"\"brains.yaml\"",
"]",
"with",
"open",
"(",
"CONFIG_FILE"... | Initializes your CONFIG_FILE for the current submission | [
"Initializes",
"your",
"CONFIG_FILE",
"for",
"the",
"current",
"submission"
] | train | https://github.com/ckcollab/brains-cli/blob/8dc512c32fc83ecc3a80bf7fa2b474d142d99b0e/brains.py#L59-L77 |
ckcollab/brains-cli | brains.py | push | def push(description, datasets, wait, verbose):
"""Publish your submission to brains"""
# Loading config
config = _get_config()
file_patterns = config["contents"]
if not isinstance(file_patterns, type([])):
# put it into an array so we can iterate it, if it isn't already an array
fil... | python | def push(description, datasets, wait, verbose):
"""Publish your submission to brains"""
# Loading config
config = _get_config()
file_patterns = config["contents"]
if not isinstance(file_patterns, type([])):
# put it into an array so we can iterate it, if it isn't already an array
fil... | [
"def",
"push",
"(",
"description",
",",
"datasets",
",",
"wait",
",",
"verbose",
")",
":",
"# Loading config",
"config",
"=",
"_get_config",
"(",
")",
"file_patterns",
"=",
"config",
"[",
"\"contents\"",
"]",
"if",
"not",
"isinstance",
"(",
"file_patterns",
... | Publish your submission to brains | [
"Publish",
"your",
"submission",
"to",
"brains"
] | train | https://github.com/ckcollab/brains-cli/blob/8dc512c32fc83ecc3a80bf7fa2b474d142d99b0e/brains.py#L85-L180 |
ckcollab/brains-cli | brains.py | run | def run(dataset):
"""Run brain locally"""
config = _get_config()
if dataset:
_print("getting dataset from brains...")
cprint("done", 'green')
# check dataset cache for dataset
# if not exists
# r = requests.get('https://api.github.com/events', stream=True)
#... | python | def run(dataset):
"""Run brain locally"""
config = _get_config()
if dataset:
_print("getting dataset from brains...")
cprint("done", 'green')
# check dataset cache for dataset
# if not exists
# r = requests.get('https://api.github.com/events', stream=True)
#... | [
"def",
"run",
"(",
"dataset",
")",
":",
"config",
"=",
"_get_config",
"(",
")",
"if",
"dataset",
":",
"_print",
"(",
"\"getting dataset from brains...\"",
")",
"cprint",
"(",
"\"done\"",
",",
"'green'",
")",
"# check dataset cache for dataset",
"# if not exists",
... | Run brain locally | [
"Run",
"brain",
"locally"
] | train | https://github.com/ckcollab/brains-cli/blob/8dc512c32fc83ecc3a80bf7fa2b474d142d99b0e/brains.py#L185-L201 |
smetj/wishbone-input-disk | wishbone_input_disk/diskin.py | DiskIn.diskMonitor | def diskMonitor(self):
'''Primitive monitor which checks whether new data is added to disk.'''
while self.loop():
try:
newest = max(glob.iglob("%s/*" % (self.kwargs.directory)), key=os.path.getmtime)
except Exception:
pass
else:
... | python | def diskMonitor(self):
'''Primitive monitor which checks whether new data is added to disk.'''
while self.loop():
try:
newest = max(glob.iglob("%s/*" % (self.kwargs.directory)), key=os.path.getmtime)
except Exception:
pass
else:
... | [
"def",
"diskMonitor",
"(",
"self",
")",
":",
"while",
"self",
".",
"loop",
"(",
")",
":",
"try",
":",
"newest",
"=",
"max",
"(",
"glob",
".",
"iglob",
"(",
"\"%s/*\"",
"%",
"(",
"self",
".",
"kwargs",
".",
"directory",
")",
")",
",",
"key",
"=",
... | Primitive monitor which checks whether new data is added to disk. | [
"Primitive",
"monitor",
"which",
"checks",
"whether",
"new",
"data",
"is",
"added",
"to",
"disk",
"."
] | train | https://github.com/smetj/wishbone-input-disk/blob/c19b0df932adbbe7c04f0b76a72cee8a42463a82/wishbone_input_disk/diskin.py#L105-L118 |
exekias/droplet | droplet/models.py | ModelQuerySet.update | def update(self, **kwargs):
"""
Update selected objects with the given keyword parameters
and mark them as changed
"""
super(ModelQuerySet, self).update(_changed=True, **kwargs) | python | def update(self, **kwargs):
"""
Update selected objects with the given keyword parameters
and mark them as changed
"""
super(ModelQuerySet, self).update(_changed=True, **kwargs) | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"ModelQuerySet",
",",
"self",
")",
".",
"update",
"(",
"_changed",
"=",
"True",
",",
"*",
"*",
"kwargs",
")"
] | Update selected objects with the given keyword parameters
and mark them as changed | [
"Update",
"selected",
"objects",
"with",
"the",
"given",
"keyword",
"parameters",
"and",
"mark",
"them",
"as",
"changed"
] | train | https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/models.py#L31-L36 |
exekias/droplet | droplet/models.py | Model.commit | def commit(cls):
"""
Commit current configuration, this will:
- Unmark updated objects
- Unmark new objects
- Completely delete objects mark as deleted
"""
cls.objects.deleted().true_delete()
cls.objects.changed().true_update(_new=False, _chang... | python | def commit(cls):
"""
Commit current configuration, this will:
- Unmark updated objects
- Unmark new objects
- Completely delete objects mark as deleted
"""
cls.objects.deleted().true_delete()
cls.objects.changed().true_update(_new=False, _chang... | [
"def",
"commit",
"(",
"cls",
")",
":",
"cls",
".",
"objects",
".",
"deleted",
"(",
")",
".",
"true_delete",
"(",
")",
"cls",
".",
"objects",
".",
"changed",
"(",
")",
".",
"true_update",
"(",
"_new",
"=",
"False",
",",
"_changed",
"=",
"False",
")"... | Commit current configuration, this will:
- Unmark updated objects
- Unmark new objects
- Completely delete objects mark as deleted | [
"Commit",
"current",
"configuration",
"this",
"will",
":",
"-",
"Unmark",
"updated",
"objects",
"-",
"Unmark",
"new",
"objects",
"-",
"Completely",
"delete",
"objects",
"mark",
"as",
"deleted"
] | train | https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/models.py#L155-L163 |
exekias/droplet | droplet/network/models.py | Interface.update | def update(cls):
"""
Update rows to include known network interfaces
"""
ifaddrs = getifaddrs()
# Create new interfaces
for ifname in ifaddrs.keys():
if filter(ifname.startswith, cls.NAME_FILTER):
cls.objects.get_or_create(name=ifname)
... | python | def update(cls):
"""
Update rows to include known network interfaces
"""
ifaddrs = getifaddrs()
# Create new interfaces
for ifname in ifaddrs.keys():
if filter(ifname.startswith, cls.NAME_FILTER):
cls.objects.get_or_create(name=ifname)
... | [
"def",
"update",
"(",
"cls",
")",
":",
"ifaddrs",
"=",
"getifaddrs",
"(",
")",
"# Create new interfaces",
"for",
"ifname",
"in",
"ifaddrs",
".",
"keys",
"(",
")",
":",
"if",
"filter",
"(",
"ifname",
".",
"startswith",
",",
"cls",
".",
"NAME_FILTER",
")",... | Update rows to include known network interfaces | [
"Update",
"rows",
"to",
"include",
"known",
"network",
"interfaces"
] | train | https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/network/models.py#L56-L67 |
minhhoit/yacms | yacms/pages/views.py | admin_page_ordering | def admin_page_ordering(request):
"""
Updates the ordering of pages via AJAX from within the admin.
"""
def get_id(s):
s = s.split("_")[-1]
return int(s) if s.isdigit() else None
page = get_object_or_404(Page, id=get_id(request.POST['id']))
old_parent_id = page.parent_id
new... | python | def admin_page_ordering(request):
"""
Updates the ordering of pages via AJAX from within the admin.
"""
def get_id(s):
s = s.split("_")[-1]
return int(s) if s.isdigit() else None
page = get_object_or_404(Page, id=get_id(request.POST['id']))
old_parent_id = page.parent_id
new... | [
"def",
"admin_page_ordering",
"(",
"request",
")",
":",
"def",
"get_id",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"split",
"(",
"\"_\"",
")",
"[",
"-",
"1",
"]",
"return",
"int",
"(",
"s",
")",
"if",
"s",
".",
"isdigit",
"(",
")",
"else",
"None"... | Updates the ordering of pages via AJAX from within the admin. | [
"Updates",
"the",
"ordering",
"of",
"pages",
"via",
"AJAX",
"from",
"within",
"the",
"admin",
"."
] | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/views.py#L16-L47 |
minhhoit/yacms | yacms/pages/views.py | page | def page(request, slug, template=u"pages/page.html", extra_context=None):
"""
Select a template for a page and render it. The request
object should have a ``page`` attribute that's added via
``yacms.pages.middleware.PageMiddleware``. The page is loaded
earlier via middleware to perform various other... | python | def page(request, slug, template=u"pages/page.html", extra_context=None):
"""
Select a template for a page and render it. The request
object should have a ``page`` attribute that's added via
``yacms.pages.middleware.PageMiddleware``. The page is loaded
earlier via middleware to perform various other... | [
"def",
"page",
"(",
"request",
",",
"slug",
",",
"template",
"=",
"u\"pages/page.html\"",
",",
"extra_context",
"=",
"None",
")",
":",
"from",
"yacms",
".",
"pages",
".",
"middleware",
"import",
"PageMiddleware",
"if",
"not",
"PageMiddleware",
".",
"installed"... | Select a template for a page and render it. The request
object should have a ``page`` attribute that's added via
``yacms.pages.middleware.PageMiddleware``. The page is loaded
earlier via middleware to perform various other functions.
The urlpattern that maps to this view is a catch-all pattern, in
w... | [
"Select",
"a",
"template",
"for",
"a",
"page",
"and",
"render",
"it",
".",
"The",
"request",
"object",
"should",
"have",
"a",
"page",
"attribute",
"that",
"s",
"added",
"via",
"yacms",
".",
"pages",
".",
"middleware",
".",
"PageMiddleware",
".",
"The",
"... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/views.py#L50-L100 |
eddiejessup/spatious | spatious/vector.py | vector_unit_nonull | def vector_unit_nonull(v):
"""Return unit vectors.
Any null vectors raise an Exception.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of v
"""
if v.size == 0:
... | python | def vector_unit_nonull(v):
"""Return unit vectors.
Any null vectors raise an Exception.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of v
"""
if v.size == 0:
... | [
"def",
"vector_unit_nonull",
"(",
"v",
")",
":",
"if",
"v",
".",
"size",
"==",
"0",
":",
"return",
"v",
"return",
"v",
"/",
"vector_mag",
"(",
"v",
")",
"[",
"...",
",",
"np",
".",
"newaxis",
"]"
] | Return unit vectors.
Any null vectors raise an Exception.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of v | [
"Return",
"unit",
"vectors",
".",
"Any",
"null",
"vectors",
"raise",
"an",
"Exception",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L40-L55 |
eddiejessup/spatious | spatious/vector.py | vector_unit_nullnull | def vector_unit_nullnull(v):
"""Return unit vectors.
Any null vectors remain null vectors.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of v
"""
if v.size == 0:
... | python | def vector_unit_nullnull(v):
"""Return unit vectors.
Any null vectors remain null vectors.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of v
"""
if v.size == 0:
... | [
"def",
"vector_unit_nullnull",
"(",
"v",
")",
":",
"if",
"v",
".",
"size",
"==",
"0",
":",
"return",
"v",
"mag",
"=",
"vector_mag",
"(",
"v",
")",
"v_new",
"=",
"v",
".",
"copy",
"(",
")",
"v_new",
"[",
"mag",
">",
"0.0",
"]",
"/=",
"mag",
"[",... | Return unit vectors.
Any null vectors remain null vectors.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of v | [
"Return",
"unit",
"vectors",
".",
"Any",
"null",
"vectors",
"remain",
"null",
"vectors",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L58-L76 |
eddiejessup/spatious | spatious/vector.py | vector_unit_nullrand | def vector_unit_nullrand(v, rng=None):
"""Return unit vectors.
Any null vectors are mapped to a uniformly picked unit vector.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of ... | python | def vector_unit_nullrand(v, rng=None):
"""Return unit vectors.
Any null vectors are mapped to a uniformly picked unit vector.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of ... | [
"def",
"vector_unit_nullrand",
"(",
"v",
",",
"rng",
"=",
"None",
")",
":",
"if",
"v",
".",
"size",
"==",
"0",
":",
"return",
"v",
"mag",
"=",
"vector_mag",
"(",
"v",
")",
"v_new",
"=",
"v",
".",
"copy",
"(",
")",
"v_new",
"[",
"mag",
"==",
"0.... | Return unit vectors.
Any null vectors are mapped to a uniformly picked unit vector.
Parameters
----------
v: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
v_new: array, shape of v | [
"Return",
"unit",
"vectors",
".",
"Any",
"null",
"vectors",
"are",
"mapped",
"to",
"a",
"uniformly",
"picked",
"unit",
"vector",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L79-L98 |
eddiejessup/spatious | spatious/vector.py | vector_perp | def vector_perp(v):
"""Return vectors perpendicular to 2-dimensional vectors.
If an input vector has components (x, y), the output vector has
components (x, -y).
Parameters
----------
v: array, shape (a1, a2, ..., 2)
Returns
-------
v_perp: array, shape of v
"""
if v.shape[... | python | def vector_perp(v):
"""Return vectors perpendicular to 2-dimensional vectors.
If an input vector has components (x, y), the output vector has
components (x, -y).
Parameters
----------
v: array, shape (a1, a2, ..., 2)
Returns
-------
v_perp: array, shape of v
"""
if v.shape[... | [
"def",
"vector_perp",
"(",
"v",
")",
":",
"if",
"v",
".",
"shape",
"[",
"-",
"1",
"]",
"!=",
"2",
":",
"raise",
"Exception",
"(",
"'Can only define a unique perpendicular vector in 2d'",
")",
"v_perp",
"=",
"np",
".",
"empty_like",
"(",
"v",
")",
"v_perp",... | Return vectors perpendicular to 2-dimensional vectors.
If an input vector has components (x, y), the output vector has
components (x, -y).
Parameters
----------
v: array, shape (a1, a2, ..., 2)
Returns
-------
v_perp: array, shape of v | [
"Return",
"vectors",
"perpendicular",
"to",
"2",
"-",
"dimensional",
"vectors",
".",
"If",
"an",
"input",
"vector",
"has",
"components",
"(",
"x",
"y",
")",
"the",
"output",
"vector",
"has",
"components",
"(",
"x",
"-",
"y",
")",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L101-L119 |
eddiejessup/spatious | spatious/vector.py | polar_to_cart | def polar_to_cart(arr_p):
"""Return polar vectors in their cartesian representation.
Parameters
----------
arr_p: array, shape (a1, a2, ..., d)
Polar vectors, with last axis indexing the dimension,
using (radius, inclination, azimuth) convention.
Returns
-------
arr_c: arra... | python | def polar_to_cart(arr_p):
"""Return polar vectors in their cartesian representation.
Parameters
----------
arr_p: array, shape (a1, a2, ..., d)
Polar vectors, with last axis indexing the dimension,
using (radius, inclination, azimuth) convention.
Returns
-------
arr_c: arra... | [
"def",
"polar_to_cart",
"(",
"arr_p",
")",
":",
"if",
"arr_p",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"1",
":",
"arr_c",
"=",
"arr_p",
".",
"copy",
"(",
")",
"elif",
"arr_p",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"2",
":",
"arr_c",
"=",
"n... | Return polar vectors in their cartesian representation.
Parameters
----------
arr_p: array, shape (a1, a2, ..., d)
Polar vectors, with last axis indexing the dimension,
using (radius, inclination, azimuth) convention.
Returns
-------
arr_c: array, shape of arr_p
Cartesi... | [
"Return",
"polar",
"vectors",
"in",
"their",
"cartesian",
"representation",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L124-L153 |
eddiejessup/spatious | spatious/vector.py | cart_to_polar | def cart_to_polar(arr_c):
"""Return cartesian vectors in their polar representation.
Parameters
----------
arr_c: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
arr_p: array, shape of arr_c
Polar vectors, using (radiu... | python | def cart_to_polar(arr_c):
"""Return cartesian vectors in their polar representation.
Parameters
----------
arr_c: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
arr_p: array, shape of arr_c
Polar vectors, using (radiu... | [
"def",
"cart_to_polar",
"(",
"arr_c",
")",
":",
"if",
"arr_c",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"1",
":",
"arr_p",
"=",
"arr_c",
".",
"copy",
"(",
")",
"elif",
"arr_c",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"2",
":",
"arr_p",
"=",
"n... | Return cartesian vectors in their polar representation.
Parameters
----------
arr_c: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
arr_p: array, shape of arr_c
Polar vectors, using (radius, inclination, azimuth) conventi... | [
"Return",
"cartesian",
"vectors",
"in",
"their",
"polar",
"representation",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L156-L182 |
eddiejessup/spatious | spatious/vector.py | sphere_pick_polar | def sphere_pick_polar(d, n=1, rng=None):
"""Return vectors uniformly picked on the unit sphere.
Vectors are in a polar representation.
Parameters
----------
d: float
The number of dimensions of the space in which the sphere lives.
n: integer
Number of samples to pick.
Retur... | python | def sphere_pick_polar(d, n=1, rng=None):
"""Return vectors uniformly picked on the unit sphere.
Vectors are in a polar representation.
Parameters
----------
d: float
The number of dimensions of the space in which the sphere lives.
n: integer
Number of samples to pick.
Retur... | [
"def",
"sphere_pick_polar",
"(",
"d",
",",
"n",
"=",
"1",
",",
"rng",
"=",
"None",
")",
":",
"if",
"rng",
"is",
"None",
":",
"rng",
"=",
"np",
".",
"random",
"a",
"=",
"np",
".",
"empty",
"(",
"[",
"n",
",",
"d",
"]",
")",
"if",
"d",
"==",
... | Return vectors uniformly picked on the unit sphere.
Vectors are in a polar representation.
Parameters
----------
d: float
The number of dimensions of the space in which the sphere lives.
n: integer
Number of samples to pick.
Returns
-------
r: array, shape (n, d)
... | [
"Return",
"vectors",
"uniformly",
"picked",
"on",
"the",
"unit",
"sphere",
".",
"Vectors",
"are",
"in",
"a",
"polar",
"representation",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L185-L216 |
eddiejessup/spatious | spatious/vector.py | rejection_pick | def rejection_pick(L, n, d, valid, rng=None):
"""Return cartesian vectors uniformly picked in a space with an arbitrary
number of dimensions, which is fully enclosed by a cube of finite length,
using a supplied function which should evaluate whether a picked point lies
within this space.
The pickin... | python | def rejection_pick(L, n, d, valid, rng=None):
"""Return cartesian vectors uniformly picked in a space with an arbitrary
number of dimensions, which is fully enclosed by a cube of finite length,
using a supplied function which should evaluate whether a picked point lies
within this space.
The pickin... | [
"def",
"rejection_pick",
"(",
"L",
",",
"n",
",",
"d",
",",
"valid",
",",
"rng",
"=",
"None",
")",
":",
"if",
"rng",
"is",
"None",
":",
"rng",
"=",
"np",
".",
"random",
"rs",
"=",
"[",
"]",
"while",
"len",
"(",
"rs",
")",
"<",
"n",
":",
"r"... | Return cartesian vectors uniformly picked in a space with an arbitrary
number of dimensions, which is fully enclosed by a cube of finite length,
using a supplied function which should evaluate whether a picked point lies
within this space.
The picking is done by rejection sampling in the cube.
Par... | [
"Return",
"cartesian",
"vectors",
"uniformly",
"picked",
"in",
"a",
"space",
"with",
"an",
"arbitrary",
"number",
"of",
"dimensions",
"which",
"is",
"fully",
"enclosed",
"by",
"a",
"cube",
"of",
"finite",
"length",
"using",
"a",
"supplied",
"function",
"which"... | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L238-L267 |
eddiejessup/spatious | spatious/vector.py | ball_pick | def ball_pick(n, d, rng=None):
"""Return cartesian vectors uniformly picked on the unit ball in an
arbitrary number of dimensions.
The unit ball is the space enclosed by the unit sphere.
The picking is done by rejection sampling in the unit cube.
In 3-dimensional space, the fraction `\pi / 6 \sim... | python | def ball_pick(n, d, rng=None):
"""Return cartesian vectors uniformly picked on the unit ball in an
arbitrary number of dimensions.
The unit ball is the space enclosed by the unit sphere.
The picking is done by rejection sampling in the unit cube.
In 3-dimensional space, the fraction `\pi / 6 \sim... | [
"def",
"ball_pick",
"(",
"n",
",",
"d",
",",
"rng",
"=",
"None",
")",
":",
"def",
"valid",
"(",
"r",
")",
":",
"return",
"vector_mag_sq",
"(",
"r",
")",
"<",
"1.0",
"return",
"rejection_pick",
"(",
"L",
"=",
"2.0",
",",
"n",
"=",
"n",
",",
"d",... | Return cartesian vectors uniformly picked on the unit ball in an
arbitrary number of dimensions.
The unit ball is the space enclosed by the unit sphere.
The picking is done by rejection sampling in the unit cube.
In 3-dimensional space, the fraction `\pi / 6 \sim 0.52` points are valid.
Paramete... | [
"Return",
"cartesian",
"vectors",
"uniformly",
"picked",
"on",
"the",
"unit",
"ball",
"in",
"an",
"arbitrary",
"number",
"of",
"dimensions",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L270-L294 |
eddiejessup/spatious | spatious/vector.py | disk_pick_polar | def disk_pick_polar(n=1, rng=None):
"""Return vectors uniformly picked on the unit disk.
The unit disk is the space enclosed by the unit circle.
Vectors are in a polar representation.
Parameters
----------
n: integer
Number of points to return.
Returns
-------
r: array, sha... | python | def disk_pick_polar(n=1, rng=None):
"""Return vectors uniformly picked on the unit disk.
The unit disk is the space enclosed by the unit circle.
Vectors are in a polar representation.
Parameters
----------
n: integer
Number of points to return.
Returns
-------
r: array, sha... | [
"def",
"disk_pick_polar",
"(",
"n",
"=",
"1",
",",
"rng",
"=",
"None",
")",
":",
"if",
"rng",
"is",
"None",
":",
"rng",
"=",
"np",
".",
"random",
"a",
"=",
"np",
".",
"zeros",
"(",
"[",
"n",
",",
"2",
"]",
",",
"dtype",
"=",
"np",
".",
"flo... | Return vectors uniformly picked on the unit disk.
The unit disk is the space enclosed by the unit circle.
Vectors are in a polar representation.
Parameters
----------
n: integer
Number of points to return.
Returns
-------
r: array, shape (n, 2)
Sample vectors. | [
"Return",
"vectors",
"uniformly",
"picked",
"on",
"the",
"unit",
"disk",
".",
"The",
"unit",
"disk",
"is",
"the",
"space",
"enclosed",
"by",
"the",
"unit",
"circle",
".",
"Vectors",
"are",
"in",
"a",
"polar",
"representation",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L297-L317 |
eddiejessup/spatious | spatious/vector.py | normalise_angle | def normalise_angle(th):
"""Normalise an angle to be in the range [-pi, pi]."""
return th - (2.0 * np.pi) * np.floor((th + np.pi) / (2.0 * np.pi)) | python | def normalise_angle(th):
"""Normalise an angle to be in the range [-pi, pi]."""
return th - (2.0 * np.pi) * np.floor((th + np.pi) / (2.0 * np.pi)) | [
"def",
"normalise_angle",
"(",
"th",
")",
":",
"return",
"th",
"-",
"(",
"2.0",
"*",
"np",
".",
"pi",
")",
"*",
"np",
".",
"floor",
"(",
"(",
"th",
"+",
"np",
".",
"pi",
")",
"/",
"(",
"2.0",
"*",
"np",
".",
"pi",
")",
")"
] | Normalise an angle to be in the range [-pi, pi]. | [
"Normalise",
"an",
"angle",
"to",
"be",
"in",
"the",
"range",
"[",
"-",
"pi",
"pi",
"]",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L338-L340 |
eddiejessup/spatious | spatious/vector.py | smallest_signed_angle | def smallest_signed_angle(source, target):
"""Find the smallest angle going from angle `source` to angle `target`."""
dth = target - source
dth = (dth + np.pi) % (2.0 * np.pi) - np.pi
return dth | python | def smallest_signed_angle(source, target):
"""Find the smallest angle going from angle `source` to angle `target`."""
dth = target - source
dth = (dth + np.pi) % (2.0 * np.pi) - np.pi
return dth | [
"def",
"smallest_signed_angle",
"(",
"source",
",",
"target",
")",
":",
"dth",
"=",
"target",
"-",
"source",
"dth",
"=",
"(",
"dth",
"+",
"np",
".",
"pi",
")",
"%",
"(",
"2.0",
"*",
"np",
".",
"pi",
")",
"-",
"np",
".",
"pi",
"return",
"dth"
] | Find the smallest angle going from angle `source` to angle `target`. | [
"Find",
"the",
"smallest",
"angle",
"going",
"from",
"angle",
"source",
"to",
"angle",
"target",
"."
] | train | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L343-L347 |
cbrand/vpnchooser | src/vpnchooser/resources/vpn.py | VpnResource.put | def put(self, vpn_id: int) -> Vpn:
"""
Updates the Vpn Resource with the
name.
"""
vpn = self._get_or_abort(vpn_id)
self.update(vpn)
session.commit()
return vpn | python | def put(self, vpn_id: int) -> Vpn:
"""
Updates the Vpn Resource with the
name.
"""
vpn = self._get_or_abort(vpn_id)
self.update(vpn)
session.commit()
return vpn | [
"def",
"put",
"(",
"self",
",",
"vpn_id",
":",
"int",
")",
"->",
"Vpn",
":",
"vpn",
"=",
"self",
".",
"_get_or_abort",
"(",
"vpn_id",
")",
"self",
".",
"update",
"(",
"vpn",
")",
"session",
".",
"commit",
"(",
")",
"return",
"vpn"
] | Updates the Vpn Resource with the
name. | [
"Updates",
"the",
"Vpn",
"Resource",
"with",
"the",
"name",
"."
] | train | https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/resources/vpn.py#L88-L96 |
cbrand/vpnchooser | src/vpnchooser/resources/vpn.py | VpnResource.delete | def delete(self, vpn_id: int):
"""
Deletes the resource with the given name.
"""
vpn = self._get_or_abort(vpn_id)
session.delete(vpn)
session.commit()
return '', 204 | python | def delete(self, vpn_id: int):
"""
Deletes the resource with the given name.
"""
vpn = self._get_or_abort(vpn_id)
session.delete(vpn)
session.commit()
return '', 204 | [
"def",
"delete",
"(",
"self",
",",
"vpn_id",
":",
"int",
")",
":",
"vpn",
"=",
"self",
".",
"_get_or_abort",
"(",
"vpn_id",
")",
"session",
".",
"delete",
"(",
"vpn",
")",
"session",
".",
"commit",
"(",
")",
"return",
"''",
",",
"204"
] | Deletes the resource with the given name. | [
"Deletes",
"the",
"resource",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/resources/vpn.py#L99-L106 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.