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 |
|---|---|---|---|---|---|---|---|---|---|---|
mrstephenneal/dirutility | dirutility/walk/walk.py | DirPaths.files | def files(self):
"""Return list of files in root directory"""
self._printer('\tFiles Walk')
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isfile(full_path):
... | python | def files(self):
"""Return list of files in root directory"""
self._printer('\tFiles Walk')
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isfile(full_path):
... | [
"def",
"files",
"(",
"self",
")",
":",
"self",
".",
"_printer",
"(",
"'\\tFiles Walk'",
")",
"for",
"directory",
"in",
"self",
".",
"directory",
":",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"full_path",
"=",
"os",
".",
... | Return list of files in root directory | [
"Return",
"list",
"of",
"files",
"in",
"root",
"directory"
] | train | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/walk.py#L216-L225 |
mrstephenneal/dirutility | dirutility/walk/walk.py | DirPaths.folders | def folders(self):
"""Return list of folders in root directory"""
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isdir(full_path):
if not path.startswith('.'):
... | python | def folders(self):
"""Return list of folders in root directory"""
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isdir(full_path):
if not path.startswith('.'):
... | [
"def",
"folders",
"(",
"self",
")",
":",
"for",
"directory",
"in",
"self",
".",
"directory",
":",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"path",
... | Return list of folders in root directory | [
"Return",
"list",
"of",
"folders",
"in",
"root",
"directory"
] | train | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/walk.py#L227-L235 |
mrstephenneal/dirutility | dirutility/walk/walk.py | DirTree.get | def get(self):
"""
Generate path, dirs, files tuple for each path in directory. Executes filters if branches are not None
:return:
"""
for path, dirs, files in os.walk(self.directory):
folders = path[self.start:].split(os.sep)
if self.branches:
... | python | def get(self):
"""
Generate path, dirs, files tuple for each path in directory. Executes filters if branches are not None
:return:
"""
for path, dirs, files in os.walk(self.directory):
folders = path[self.start:].split(os.sep)
if self.branches:
... | [
"def",
"get",
"(",
"self",
")",
":",
"for",
"path",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"self",
".",
"directory",
")",
":",
"folders",
"=",
"path",
"[",
"self",
".",
"start",
":",
"]",
".",
"split",
"(",
"os",
".",
"sep",
... | Generate path, dirs, files tuple for each path in directory. Executes filters if branches are not None
:return: | [
"Generate",
"path",
"dirs",
"files",
"tuple",
"for",
"each",
"path",
"in",
"directory",
".",
"Executes",
"filters",
"if",
"branches",
"are",
"not",
"None",
":",
"return",
":"
] | train | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/walk.py#L274-L290 |
drongo-framework/drongo | drongo/app.py | Drongo.url | def url(self, pattern, method=None, name=None):
"""Decorator to map url pattern to the callable.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Exam... | python | def url(self, pattern, method=None, name=None):
"""Decorator to map url pattern to the callable.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Exam... | [
"def",
"url",
"(",
"self",
",",
"pattern",
",",
"method",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"def",
"_inner",
"(",
"call",
")",
":",
"self",
".",
"_url_manager",
".",
"add",
"(",
"pattern",
",",
"method",
",",
"call",
",",
"name",
"... | Decorator to map url pattern to the callable.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Examples: "/", "/path/to/resource", "/resoures/{param}"
... | [
"Decorator",
"to",
"map",
"url",
"pattern",
"to",
"the",
"callable",
"."
] | train | https://github.com/drongo-framework/drongo/blob/487edb370ae329f370bcf3b433ed3f28ba4c1d8c/drongo/app.py#L86-L115 |
drongo-framework/drongo | drongo/app.py | Drongo.add_url | def add_url(self, pattern, method=None, call=None):
"""Add a url pattern.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Examples: "/", "/path/to/re... | python | def add_url(self, pattern, method=None, call=None):
"""Add a url pattern.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Examples: "/", "/path/to/re... | [
"def",
"add_url",
"(",
"self",
",",
"pattern",
",",
"method",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"self",
".",
"_url_manager",
".",
"add",
"(",
"pattern",
",",
"method",
",",
"call",
")"
] | Add a url pattern.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Examples: "/", "/path/to/resource", "/resoures/{param}"
method (:obj:`str`, :o... | [
"Add",
"a",
"url",
"pattern",
"."
] | train | https://github.com/drongo-framework/drongo/blob/487edb370ae329f370bcf3b433ed3f28ba4c1d8c/drongo/app.py#L117-L138 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | convert_other_format | def convert_other_format(filename, format):
"""
转换为png图片
:param filename: 图片文件名
:return:
"""
img = Image.open(filename)
rp = ReParser()
c_filename = rp.replace(r'\..*$', format, filename)
img.save(c_filename) | python | def convert_other_format(filename, format):
"""
转换为png图片
:param filename: 图片文件名
:return:
"""
img = Image.open(filename)
rp = ReParser()
c_filename = rp.replace(r'\..*$', format, filename)
img.save(c_filename) | [
"def",
"convert_other_format",
"(",
"filename",
",",
"format",
")",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"filename",
")",
"rp",
"=",
"ReParser",
"(",
")",
"c_filename",
"=",
"rp",
".",
"replace",
"(",
"r'\\..*$'",
",",
"format",
",",
"filename",
... | 转换为png图片
:param filename: 图片文件名
:return: | [
"转换为png图片",
":",
"param",
"filename",
":",
"图片文件名",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L34-L43 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | binarizing | def binarizing(img,threshold):
"""
二值化
:param img:
:param threshold:
:return:
"""
pixdata = img.load()
w, h = img.size
for y in range(h):
for x in range(w):
if pixdata[x, y] < threshold:
pixdata[x, y] = 0
else:
pixdata[x... | python | def binarizing(img,threshold):
"""
二值化
:param img:
:param threshold:
:return:
"""
pixdata = img.load()
w, h = img.size
for y in range(h):
for x in range(w):
if pixdata[x, y] < threshold:
pixdata[x, y] = 0
else:
pixdata[x... | [
"def",
"binarizing",
"(",
"img",
",",
"threshold",
")",
":",
"pixdata",
"=",
"img",
".",
"load",
"(",
")",
"w",
",",
"h",
"=",
"img",
".",
"size",
"for",
"y",
"in",
"range",
"(",
"h",
")",
":",
"for",
"x",
"in",
"range",
"(",
"w",
")",
":",
... | 二值化
:param img:
:param threshold:
:return: | [
"二值化",
":",
"param",
"img",
":",
":",
"param",
"threshold",
":",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L62-L77 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | remove_interference_line | def remove_interference_line(img):
"""
去除干扰线
:param img:
:return:
"""
pixdata = img.load()
w,h = img.size
for y in range(1,h-1):
for x in range(1,w-1):
count = 0
if pixdata[x,y-1] > 245:
count = count + 1
if pixdata[x,y+1] > 245... | python | def remove_interference_line(img):
"""
去除干扰线
:param img:
:return:
"""
pixdata = img.load()
w,h = img.size
for y in range(1,h-1):
for x in range(1,w-1):
count = 0
if pixdata[x,y-1] > 245:
count = count + 1
if pixdata[x,y+1] > 245... | [
"def",
"remove_interference_line",
"(",
"img",
")",
":",
"pixdata",
"=",
"img",
".",
"load",
"(",
")",
"w",
",",
"h",
"=",
"img",
".",
"size",
"for",
"y",
"in",
"range",
"(",
"1",
",",
"h",
"-",
"1",
")",
":",
"for",
"x",
"in",
"range",
"(",
... | 去除干扰线
:param img:
:return: | [
"去除干扰线",
":",
"param",
"img",
":",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L79-L100 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | create_thumbnail | def create_thumbnail(img, width, height):
"""
创建缩略图
缩略图的意思就是缩小
:param img: 图片对象
:param width: 宽
:param height: 高
:return:
"""
size = (width, height)
img.thumbnail(size)
return img | python | def create_thumbnail(img, width, height):
"""
创建缩略图
缩略图的意思就是缩小
:param img: 图片对象
:param width: 宽
:param height: 高
:return:
"""
size = (width, height)
img.thumbnail(size)
return img | [
"def",
"create_thumbnail",
"(",
"img",
",",
"width",
",",
"height",
")",
":",
"size",
"=",
"(",
"width",
",",
"height",
")",
"img",
".",
"thumbnail",
"(",
"size",
")",
"return",
"img"
] | 创建缩略图
缩略图的意思就是缩小
:param img: 图片对象
:param width: 宽
:param height: 高
:return: | [
"创建缩略图",
"缩略图的意思就是缩小",
":",
"param",
"img",
":",
"图片对象",
":",
"param",
"width",
":",
"宽",
":",
"param",
"height",
":",
"高",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L135-L146 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | cut | def cut(img, left, above, right, down):
"""
从图像中复制出一个矩形选区
box = (100, 100, 400, 400)
region = im.crop(box)
矩形选区有一个4元元组定义,分别表示左、上、右、下的坐标。这个库以左上角为坐标原点,
单位是px,所以上诉代码复制了一个 300x300 pixels 的矩形选区
:param img: 加载到内存的图片
:param left: 左
:param above: 上
:param right: 右
:param down: 下
... | python | def cut(img, left, above, right, down):
"""
从图像中复制出一个矩形选区
box = (100, 100, 400, 400)
region = im.crop(box)
矩形选区有一个4元元组定义,分别表示左、上、右、下的坐标。这个库以左上角为坐标原点,
单位是px,所以上诉代码复制了一个 300x300 pixels 的矩形选区
:param img: 加载到内存的图片
:param left: 左
:param above: 上
:param right: 右
:param down: 下
... | [
"def",
"cut",
"(",
"img",
",",
"left",
",",
"above",
",",
"right",
",",
"down",
")",
":",
"box",
"=",
"(",
"left",
",",
"above",
",",
"right",
",",
"down",
")",
"region",
"=",
"img",
".",
"crop",
"(",
"box",
")",
"return",
"region"
] | 从图像中复制出一个矩形选区
box = (100, 100, 400, 400)
region = im.crop(box)
矩形选区有一个4元元组定义,分别表示左、上、右、下的坐标。这个库以左上角为坐标原点,
单位是px,所以上诉代码复制了一个 300x300 pixels 的矩形选区
:param img: 加载到内存的图片
:param left: 左
:param above: 上
:param right: 右
:param down: 下
:return: | [
"从图像中复制出一个矩形选区"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L148-L166 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | paste | def paste(region, img, left, above, right, down):
"""
将扣的图粘贴到制定图片上
当你粘贴矩形选区的时候必须保证尺寸一致。此外,矩形选区不能在图像外。然而你不必保证矩形选区和原图的颜色模式一致,
因为矩形选区会被自动转换颜色,遗憾的是,只能扣矩形图。
:param region: 扣出的图
:param img: 指定图片
:param left: 左
:param above: 上
:param right: 右
:param down: 下
:return: 被修改过的图片对象,还在内存中... | python | def paste(region, img, left, above, right, down):
"""
将扣的图粘贴到制定图片上
当你粘贴矩形选区的时候必须保证尺寸一致。此外,矩形选区不能在图像外。然而你不必保证矩形选区和原图的颜色模式一致,
因为矩形选区会被自动转换颜色,遗憾的是,只能扣矩形图。
:param region: 扣出的图
:param img: 指定图片
:param left: 左
:param above: 上
:param right: 右
:param down: 下
:return: 被修改过的图片对象,还在内存中... | [
"def",
"paste",
"(",
"region",
",",
"img",
",",
"left",
",",
"above",
",",
"right",
",",
"down",
")",
":",
"region",
"=",
"region",
".",
"transpose",
"(",
"Image",
".",
"ROTATE_180",
")",
"box",
"=",
"(",
"left",
",",
"above",
",",
"right",
",",
... | 将扣的图粘贴到制定图片上
当你粘贴矩形选区的时候必须保证尺寸一致。此外,矩形选区不能在图像外。然而你不必保证矩形选区和原图的颜色模式一致,
因为矩形选区会被自动转换颜色,遗憾的是,只能扣矩形图。
:param region: 扣出的图
:param img: 指定图片
:param left: 左
:param above: 上
:param right: 右
:param down: 下
:return: 被修改过的图片对象,还在内存中,未保存。 | [
"将扣的图粘贴到制定图片上",
"当你粘贴矩形选区的时候必须保证尺寸一致。此外,矩形选区不能在图像外。然而你不必保证矩形选区和原图的颜色模式一致,",
"因为矩形选区会被自动转换颜色,遗憾的是,只能扣矩形图。"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L168-L185 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | resize | def resize(img, width, height):
"""
更改图片大小,只能更改磁盘空间的大小。
:param img:
:param width:
:param height:
:return: 更改后的图片
"""
return img.resize((width, height), Image.ANTIALIAS) | python | def resize(img, width, height):
"""
更改图片大小,只能更改磁盘空间的大小。
:param img:
:param width:
:param height:
:return: 更改后的图片
"""
return img.resize((width, height), Image.ANTIALIAS) | [
"def",
"resize",
"(",
"img",
",",
"width",
",",
"height",
")",
":",
"return",
"img",
".",
"resize",
"(",
"(",
"width",
",",
"height",
")",
",",
"Image",
".",
"ANTIALIAS",
")"
] | 更改图片大小,只能更改磁盘空间的大小。
:param img:
:param width:
:param height:
:return: 更改后的图片 | [
"更改图片大小,只能更改磁盘空间的大小。",
":",
"param",
"img",
":",
":",
"param",
"width",
":",
":",
"param",
"height",
":",
":",
"return",
":",
"更改后的图片"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L204-L212 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | GPS.get_exif_data | def get_exif_data(self, image):
"""Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
exif_data = {}
info = image._getexif()
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decod... | python | def get_exif_data(self, image):
"""Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
exif_data = {}
info = image._getexif()
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decod... | [
"def",
"get_exif_data",
"(",
"self",
",",
"image",
")",
":",
"exif_data",
"=",
"{",
"}",
"info",
"=",
"image",
".",
"_getexif",
"(",
")",
"if",
"info",
":",
"for",
"tag",
",",
"value",
"in",
"info",
".",
"items",
"(",
")",
":",
"decoded",
"=",
"T... | Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags | [
"Returns",
"a",
"dictionary",
"from",
"the",
"exif",
"data",
"of",
"an",
"PIL",
"Image",
"item",
".",
"Also",
"converts",
"the",
"GPS",
"Tags"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L236-L253 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | GPS._convert_to_degress | def _convert_to_degress(self, value):
"""Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"""
d0 = value[0][0]
d1 = value[0][1]
d = float(d0) / float(d1)
m0 = value[1][0]
m1 = value[1][1]
m = float(m0) / float(m1)
... | python | def _convert_to_degress(self, value):
"""Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"""
d0 = value[0][0]
d1 = value[0][1]
d = float(d0) / float(d1)
m0 = value[1][0]
m1 = value[1][1]
m = float(m0) / float(m1)
... | [
"def",
"_convert_to_degress",
"(",
"self",
",",
"value",
")",
":",
"d0",
"=",
"value",
"[",
"0",
"]",
"[",
"0",
"]",
"d1",
"=",
"value",
"[",
"0",
"]",
"[",
"1",
"]",
"d",
"=",
"float",
"(",
"d0",
")",
"/",
"float",
"(",
"d1",
")",
"m0",
"=... | Helper function to convert the GPS coordinates stored in the EXIF to degress in float format | [
"Helper",
"function",
"to",
"convert",
"the",
"GPS",
"coordinates",
"stored",
"in",
"the",
"EXIF",
"to",
"degress",
"in",
"float",
"format"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L261-L275 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | GPS.get_lat_lon | def get_lat_lon(self, exif_data):
"""Returns the latitude and longitude, if available, from the provided exif_data (obtained through get_exif_data above)"""
lat = None
lon = None
if "GPSInfo" in exif_data:
gps_info = exif_data["GPSInfo"]
gps_latitude = self._get... | python | def get_lat_lon(self, exif_data):
"""Returns the latitude and longitude, if available, from the provided exif_data (obtained through get_exif_data above)"""
lat = None
lon = None
if "GPSInfo" in exif_data:
gps_info = exif_data["GPSInfo"]
gps_latitude = self._get... | [
"def",
"get_lat_lon",
"(",
"self",
",",
"exif_data",
")",
":",
"lat",
"=",
"None",
"lon",
"=",
"None",
"if",
"\"GPSInfo\"",
"in",
"exif_data",
":",
"gps_info",
"=",
"exif_data",
"[",
"\"GPSInfo\"",
"]",
"gps_latitude",
"=",
"self",
".",
"_get_if_exist",
"(... | Returns the latitude and longitude, if available, from the provided exif_data (obtained through get_exif_data above) | [
"Returns",
"the",
"latitude",
"and",
"longitude",
"if",
"available",
"from",
"the",
"provided",
"exif_data",
"(",
"obtained",
"through",
"get_exif_data",
"above",
")"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L277-L299 |
shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | GPS.get_gps | def get_gps(self, image):
"""获取经度,纬度"""
exif_data = self.get_exif_data(image)
return self.get_lat_lon(exif_data) | python | def get_gps(self, image):
"""获取经度,纬度"""
exif_data = self.get_exif_data(image)
return self.get_lat_lon(exif_data) | [
"def",
"get_gps",
"(",
"self",
",",
"image",
")",
":",
"exif_data",
"=",
"self",
".",
"get_exif_data",
"(",
"image",
")",
"return",
"self",
".",
"get_lat_lon",
"(",
"exif_data",
")"
] | 获取经度,纬度 | [
"获取经度,纬度"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L301-L304 |
asyncdef/interfaces | asyncdef/interfaces/engine/iselector.py | ISelector.add_reader | def add_reader(
self,
fd: IFileLike,
callback: typing.Callable[[IFileLike], typing.Any],
) -> None:
"""Add a file descriptor to the processor and wait for READ.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
return... | python | def add_reader(
self,
fd: IFileLike,
callback: typing.Callable[[IFileLike], typing.Any],
) -> None:
"""Add a file descriptor to the processor and wait for READ.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
return... | [
"def",
"add_reader",
"(",
"self",
",",
"fd",
":",
"IFileLike",
",",
"callback",
":",
"typing",
".",
"Callable",
"[",
"[",
"IFileLike",
"]",
",",
"typing",
".",
"Any",
"]",
",",
")",
"->",
"None",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Add a file descriptor to the processor and wait for READ.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
returns a valid file descriptor integer.
callback (typing.Callable[[IFileLike], typing.Any]): A function
that consumes the IFileL... | [
"Add",
"a",
"file",
"descriptor",
"to",
"the",
"processor",
"and",
"wait",
"for",
"READ",
"."
] | train | https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/iselector.py#L25-L39 |
robertchase/ergaleia | ergaleia/config.py | Config._load | def _load(self, path='config', filetype=None, relaxed=False, ignore=False):
""" load key value pairs from a file
Parameters:
path - path to configuration data (see Note 1)
filetype - type component of dot-delimited path
relaxed - if True, define ... | python | def _load(self, path='config', filetype=None, relaxed=False, ignore=False):
""" load key value pairs from a file
Parameters:
path - path to configuration data (see Note 1)
filetype - type component of dot-delimited path
relaxed - if True, define ... | [
"def",
"_load",
"(",
"self",
",",
"path",
"=",
"'config'",
",",
"filetype",
"=",
"None",
",",
"relaxed",
"=",
"False",
",",
"ignore",
"=",
"False",
")",
":",
"for",
"num",
",",
"line",
"in",
"enumerate",
"(",
"un_comment",
"(",
"load_lines_from_path",
... | load key value pairs from a file
Parameters:
path - path to configuration data (see Note 1)
filetype - type component of dot-delimited path
relaxed - if True, define keys on the fly (see Note 2)
ignore - if True, ignore undefined keys i... | [
"load",
"key",
"value",
"pairs",
"from",
"a",
"file"
] | train | https://github.com/robertchase/ergaleia/blob/df8e9a4b18c563022a503faa27e822c9a5755490/ergaleia/config.py#L155-L208 |
robertchase/ergaleia | ergaleia/config.py | _item.load | def load(self, value):
""" enforce env > value when loading from file """
self.reset(
value,
validator=self.__dict__.get('validator'),
env=self.__dict__.get('env'),
) | python | def load(self, value):
""" enforce env > value when loading from file """
self.reset(
value,
validator=self.__dict__.get('validator'),
env=self.__dict__.get('env'),
) | [
"def",
"load",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"reset",
"(",
"value",
",",
"validator",
"=",
"self",
".",
"__dict__",
".",
"get",
"(",
"'validator'",
")",
",",
"env",
"=",
"self",
".",
"__dict__",
".",
"get",
"(",
"'env'",
")",
... | enforce env > value when loading from file | [
"enforce",
"env",
">",
"value",
"when",
"loading",
"from",
"file"
] | train | https://github.com/robertchase/ergaleia/blob/df8e9a4b18c563022a503faa27e822c9a5755490/ergaleia/config.py#L245-L251 |
tBaxter/tango-shared-core | build/lib/tango_shared/models.py | set_img_path | def set_img_path(instance, filename):
"""
Sets upload_to dynamically
"""
upload_path = '/'.join(
['img', instance._meta.app_label, str(now.year), str(now.month), filename]
)
return upload_path | python | def set_img_path(instance, filename):
"""
Sets upload_to dynamically
"""
upload_path = '/'.join(
['img', instance._meta.app_label, str(now.year), str(now.month), filename]
)
return upload_path | [
"def",
"set_img_path",
"(",
"instance",
",",
"filename",
")",
":",
"upload_path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'img'",
",",
"instance",
".",
"_meta",
".",
"app_label",
",",
"str",
"(",
"now",
".",
"year",
")",
",",
"str",
"(",
"now",
".",
"m... | Sets upload_to dynamically | [
"Sets",
"upload_to",
"dynamically"
] | train | https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/models.py#L24-L31 |
tBaxter/tango-shared-core | build/lib/tango_shared/models.py | BaseUserContentModel.save | def save(self, *args, **kwargs):
"""
Clean text and save formatted version.
"""
self.text = clean_text(self.text)
self.text_formatted = format_text(self.text)
super(BaseUserContentModel, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
Clean text and save formatted version.
"""
self.text = clean_text(self.text)
self.text_formatted = format_text(self.text)
super(BaseUserContentModel, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"text",
"=",
"clean_text",
"(",
"self",
".",
"text",
")",
"self",
".",
"text_formatted",
"=",
"format_text",
"(",
"self",
".",
"text",
")",
"super",
"(",
... | Clean text and save formatted version. | [
"Clean",
"text",
"and",
"save",
"formatted",
"version",
"."
] | train | https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/models.py#L151-L157 |
tBaxter/tango-shared-core | build/lib/tango_shared/models.py | ContentImage.save | def save(self, *args, **kwargs):
"""
We want to do dimension checks and/or resizing BEFORE the original image is saved.
Note that if we can't get image dimensions, it's considered an invalid image
and we return without saving.
If the image has changed, sets self.thumb to None, tr... | python | def save(self, *args, **kwargs):
"""
We want to do dimension checks and/or resizing BEFORE the original image is saved.
Note that if we can't get image dimensions, it's considered an invalid image
and we return without saving.
If the image has changed, sets self.thumb to None, tr... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"img",
"=",
"self",
".",
"image",
"# Check if this is an already existing photo",
"try",
":",
"old_self",
"=",
"self",
".",
"__class__",
".",
"objects",
".",
"get",
"(",
"id... | We want to do dimension checks and/or resizing BEFORE the original image is saved.
Note that if we can't get image dimensions, it's considered an invalid image
and we return without saving.
If the image has changed, sets self.thumb to None, triggering post_save thumbnailer. | [
"We",
"want",
"to",
"do",
"dimension",
"checks",
"and",
"/",
"or",
"resizing",
"BEFORE",
"the",
"original",
"image",
"is",
"saved",
".",
"Note",
"that",
"if",
"we",
"can",
"t",
"get",
"image",
"dimensions",
"it",
"s",
"considered",
"an",
"invalid",
"imag... | train | https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/models.py#L198-L240 |
Apitax/Apitax | apitax/api/controllers/migrations/developers_controller.py | create_script | def create_script(create=None): # noqa: E501
"""Create a new script
Create a new script # noqa: E501
:param Scripts: The data needed to create this script
:type Scripts: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
create = Create.from_dict(connexion.request.ge... | python | def create_script(create=None): # noqa: E501
"""Create a new script
Create a new script # noqa: E501
:param Scripts: The data needed to create this script
:type Scripts: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
create = Create.from_dict(connexion.request.ge... | [
"def",
"create_script",
"(",
"create",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"create",
"=",
"Create",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501... | Create a new script
Create a new script # noqa: E501
:param Scripts: The data needed to create this script
:type Scripts: dict | bytes
:rtype: Response | [
"Create",
"a",
"new",
"script"
] | train | https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/developers_controller.py#L23-L41 |
Apitax/Apitax | apitax/api/controllers/migrations/developers_controller.py | delete_script | def delete_script(delete=None): # noqa: E501
"""Delete a script
Delete a script # noqa: E501
:param delete: The data needed to delete this script
:type delete: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
delete = Delete.from_dict(connexion.request.get_json()) ... | python | def delete_script(delete=None): # noqa: E501
"""Delete a script
Delete a script # noqa: E501
:param delete: The data needed to delete this script
:type delete: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
delete = Delete.from_dict(connexion.request.get_json()) ... | [
"def",
"delete_script",
"(",
"delete",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"delete",
"=",
"Delete",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501... | Delete a script
Delete a script # noqa: E501
:param delete: The data needed to delete this script
:type delete: dict | bytes
:rtype: Response | [
"Delete",
"a",
"script"
] | train | https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/developers_controller.py#L45-L63 |
Apitax/Apitax | apitax/api/controllers/migrations/developers_controller.py | rename_script | def rename_script(rename=None): # noqa: E501
"""Rename a script
Rename a script # noqa: E501
:param rename: The data needed to save this script
:type rename: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
rename = Rename.from_dict(connexion.request.get_json()) #... | python | def rename_script(rename=None): # noqa: E501
"""Rename a script
Rename a script # noqa: E501
:param rename: The data needed to save this script
:type rename: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
rename = Rename.from_dict(connexion.request.get_json()) #... | [
"def",
"rename_script",
"(",
"rename",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"rename",
"=",
"Rename",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501... | Rename a script
Rename a script # noqa: E501
:param rename: The data needed to save this script
:type rename: dict | bytes
:rtype: Response | [
"Rename",
"a",
"script"
] | train | https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/developers_controller.py#L83-L102 |
Apitax/Apitax | apitax/api/controllers/migrations/developers_controller.py | save_script | def save_script(save=None): # noqa: E501
"""Save a script
Save a script # noqa: E501
:param Scripts: The data needed to save this script
:type Scripts: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
save = Save.from_dict(connexion.request.get_json()) # noqa: E50... | python | def save_script(save=None): # noqa: E501
"""Save a script
Save a script # noqa: E501
:param Scripts: The data needed to save this script
:type Scripts: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
save = Save.from_dict(connexion.request.get_json()) # noqa: E50... | [
"def",
"save_script",
"(",
"save",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"save",
"=",
"Save",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501",
"if... | Save a script
Save a script # noqa: E501
:param Scripts: The data needed to save this script
:type Scripts: dict | bytes
:rtype: Response | [
"Save",
"a",
"script"
] | train | https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/developers_controller.py#L106-L124 |
treystout/Agner | agner/queue.py | Queue.enqueue | def enqueue(self, job):
"""Enqueue a job for later processing, returns the new length of the queue
"""
if job.queue_name():
raise EnqueueError("job %s already queued!" % job.job_id)
new_len = self.redis.lpush(self.queue_name, job.serialize())
job.notify_queued(self)
return new_len | python | def enqueue(self, job):
"""Enqueue a job for later processing, returns the new length of the queue
"""
if job.queue_name():
raise EnqueueError("job %s already queued!" % job.job_id)
new_len = self.redis.lpush(self.queue_name, job.serialize())
job.notify_queued(self)
return new_len | [
"def",
"enqueue",
"(",
"self",
",",
"job",
")",
":",
"if",
"job",
".",
"queue_name",
"(",
")",
":",
"raise",
"EnqueueError",
"(",
"\"job %s already queued!\"",
"%",
"job",
".",
"job_id",
")",
"new_len",
"=",
"self",
".",
"redis",
".",
"lpush",
"(",
"se... | Enqueue a job for later processing, returns the new length of the queue | [
"Enqueue",
"a",
"job",
"for",
"later",
"processing",
"returns",
"the",
"new",
"length",
"of",
"the",
"queue"
] | train | https://github.com/treystout/Agner/blob/db29db9ceed8732e6ffdfc4f4fc1a42bd10b8c85/agner/queue.py#L34-L41 |
treystout/Agner | agner/queue.py | Queue.next_job | def next_job(self, timeout_seconds=None):
"""Retuns the next job in the queue, or None if is nothing there
"""
if timeout_seconds is not None:
timeout = timeout_seconds
else:
timeout = BLOCK_SECONDS
response = self.lua_next(keys=[self.queue_name])
if not response:
return
... | python | def next_job(self, timeout_seconds=None):
"""Retuns the next job in the queue, or None if is nothing there
"""
if timeout_seconds is not None:
timeout = timeout_seconds
else:
timeout = BLOCK_SECONDS
response = self.lua_next(keys=[self.queue_name])
if not response:
return
... | [
"def",
"next_job",
"(",
"self",
",",
"timeout_seconds",
"=",
"None",
")",
":",
"if",
"timeout_seconds",
"is",
"not",
"None",
":",
"timeout",
"=",
"timeout_seconds",
"else",
":",
"timeout",
"=",
"BLOCK_SECONDS",
"response",
"=",
"self",
".",
"lua_next",
"(",
... | Retuns the next job in the queue, or None if is nothing there | [
"Retuns",
"the",
"next",
"job",
"in",
"the",
"queue",
"or",
"None",
"if",
"is",
"nothing",
"there"
] | train | https://github.com/treystout/Agner/blob/db29db9ceed8732e6ffdfc4f4fc1a42bd10b8c85/agner/queue.py#L43-L58 |
maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | generate_headline_from_description | def generate_headline_from_description(sender, instance, *args, **kwargs):
'''
Auto generate the headline of the node from the first lines of the description.
'''
lines = instance.description.split('\n')
headline = truncatewords(lines[0], 20)
if headline[:-3] == '...':
headline = truncat... | python | def generate_headline_from_description(sender, instance, *args, **kwargs):
'''
Auto generate the headline of the node from the first lines of the description.
'''
lines = instance.description.split('\n')
headline = truncatewords(lines[0], 20)
if headline[:-3] == '...':
headline = truncat... | [
"def",
"generate_headline_from_description",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lines",
"=",
"instance",
".",
"description",
".",
"split",
"(",
"'\\n'",
")",
"headline",
"=",
"truncatewords",
"(",
"lines",
... | Auto generate the headline of the node from the first lines of the description. | [
"Auto",
"generate",
"the",
"headline",
"of",
"the",
"node",
"from",
"the",
"first",
"lines",
"of",
"the",
"description",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L22-L32 |
maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | story_root_for_new_outline | def story_root_for_new_outline(sender, instance, created, *args, **kwargs):
'''
If a new instance of a Outline is created, also create
the root node of the story tree.
'''
if created and isinstance(instance, Outline):
streeroot = StoryElementNode.add_root(outline=instance, story_element_type... | python | def story_root_for_new_outline(sender, instance, created, *args, **kwargs):
'''
If a new instance of a Outline is created, also create
the root node of the story tree.
'''
if created and isinstance(instance, Outline):
streeroot = StoryElementNode.add_root(outline=instance, story_element_type... | [
"def",
"story_root_for_new_outline",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
"and",
"isinstance",
"(",
"instance",
",",
"Outline",
")",
":",
"streeroot",
"=",
"StoryElementNode",
... | If a new instance of a Outline is created, also create
the root node of the story tree. | [
"If",
"a",
"new",
"instance",
"of",
"a",
"Outline",
"is",
"created",
"also",
"create",
"the",
"root",
"node",
"of",
"the",
"story",
"tree",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L36-L44 |
maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | arc_node_edit_add_missing_characters_and_locations_to_related_story_node | def arc_node_edit_add_missing_characters_and_locations_to_related_story_node(
sender,
instance,
action,
reverse,
pk_set,
*args,
**kwargs
):
'''
If an arc_element is modified and it's characters/locations are not already in the story node, add them.
We ... | python | def arc_node_edit_add_missing_characters_and_locations_to_related_story_node(
sender,
instance,
action,
reverse,
pk_set,
*args,
**kwargs
):
'''
If an arc_element is modified and it's characters/locations are not already in the story node, add them.
We ... | [
"def",
"arc_node_edit_add_missing_characters_and_locations_to_related_story_node",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"pk_set",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'post_add'",
":",
"logger",... | If an arc_element is modified and it's characters/locations are not already in the story node, add them.
We don't assume that removing the arc element would change the characters or locations as of yet.
This takes up a little more space in the database, but the additional flexibility for users is
worth it. | [
"If",
"an",
"arc_element",
"is",
"modified",
"and",
"it",
"s",
"characters",
"/",
"locations",
"are",
"not",
"already",
"in",
"the",
"story",
"node",
"add",
"them",
".",
"We",
"don",
"t",
"assume",
"that",
"removing",
"the",
"arc",
"element",
"would",
"c... | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L49-L92 |
maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | story_node_add_arc_element_update_characters_locations | def story_node_add_arc_element_update_characters_locations(sender, instance, created, *args, **kwargs):
'''
If an arc element is added to a story element node, add any missing elements or locations.
'''
arc_node = ArcElementNode.objects.get(pk=instance.pk)
logger.debug('Scanning arc_node %s' % arc_n... | python | def story_node_add_arc_element_update_characters_locations(sender, instance, created, *args, **kwargs):
'''
If an arc element is added to a story element node, add any missing elements or locations.
'''
arc_node = ArcElementNode.objects.get(pk=instance.pk)
logger.debug('Scanning arc_node %s' % arc_n... | [
"def",
"story_node_add_arc_element_update_characters_locations",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"arc_node",
"=",
"ArcElementNode",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"instance",
"."... | If an arc element is added to a story element node, add any missing elements or locations. | [
"If",
"an",
"arc",
"element",
"is",
"added",
"to",
"a",
"story",
"element",
"node",
"add",
"any",
"missing",
"elements",
"or",
"locations",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L96-L117 |
maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_arc_links_same_outline | def validate_arc_links_same_outline(sender, instance, *args, **kwargs):
'''
Evaluates attempts to link an arc to a story node from another outline.
'''
if instance.story_element_node:
if instance.story_element_node.outline != instance.parent_outline:
raise IntegrityError(_('An arc ca... | python | def validate_arc_links_same_outline(sender, instance, *args, **kwargs):
'''
Evaluates attempts to link an arc to a story node from another outline.
'''
if instance.story_element_node:
if instance.story_element_node.outline != instance.parent_outline:
raise IntegrityError(_('An arc ca... | [
"def",
"validate_arc_links_same_outline",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"story_element_node",
":",
"if",
"instance",
".",
"story_element_node",
".",
"outline",
"!=",
"instance",
".",... | Evaluates attempts to link an arc to a story node from another outline. | [
"Evaluates",
"attempts",
"to",
"link",
"an",
"arc",
"to",
"a",
"story",
"node",
"from",
"another",
"outline",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L121-L127 |
maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_character_instance_valid_for_arc | def validate_character_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluate attempts to assign a character instance to ensure it is from same
outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
... | python | def validate_character_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluate attempts to assign a character instance to ensure it is from same
outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
... | [
"def",
"validate_character_instance_valid_for_arc",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"pk_set",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'pre_add'",
":",
"if",
"reverse",
":",
"# Fetch arc ... | Evaluate attempts to assign a character instance to ensure it is from same
outline. | [
"Evaluate",
"attempts",
"to",
"assign",
"a",
"character",
"instance",
"to",
"ensure",
"it",
"is",
"from",
"same",
"outline",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L131-L147 |
maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_location_instance_valid_for_arc | def validate_location_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluates attempts to add location instances to arc, ensuring they are from same outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
... | python | def validate_location_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluates attempts to add location instances to arc, ensuring they are from same outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
... | [
"def",
"validate_location_instance_valid_for_arc",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"pk_set",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'pre_add'",
":",
"if",
"reverse",
":",
"# Fetch arc d... | Evaluates attempts to add location instances to arc, ensuring they are from same outline. | [
"Evaluates",
"attempts",
"to",
"add",
"location",
"instances",
"to",
"arc",
"ensuring",
"they",
"are",
"from",
"same",
"outline",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L151-L166 |
maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_character_for_story_element | def validate_character_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that character is from the same outline as the story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.obje... | python | def validate_character_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that character is from the same outline as the story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.obje... | [
"def",
"validate_character_for_story_element",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"pk_set",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'pre_add'",
":",
"if",
"reverse",
":",
"for",
"spk",
... | Validates that character is from the same outline as the story node. | [
"Validates",
"that",
"character",
"is",
"from",
"the",
"same",
"outline",
"as",
"the",
"story",
"node",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L170-L184 |
maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_location_for_story_element | def validate_location_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that location is from same outline as story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.objects.get(pk... | python | def validate_location_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that location is from same outline as story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.objects.get(pk... | [
"def",
"validate_location_for_story_element",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"pk_set",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'pre_add'",
":",
"if",
"reverse",
":",
"for",
"spk",
"... | Validates that location is from same outline as story node. | [
"Validates",
"that",
"location",
"is",
"from",
"same",
"outline",
"as",
"story",
"node",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L188-L202 |
maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_generations_for_story_elements | def validate_generations_for_story_elements(
sender,
instance,
action,
target_node_type=None,
target_node=None,
pos=None,
*args,
**kwargs
):
'''
Unlike arc nodes, for which we just warn about structure, the story tree
allowed parent/child rules... | python | def validate_generations_for_story_elements(
sender,
instance,
action,
target_node_type=None,
target_node=None,
pos=None,
*args,
**kwargs
):
'''
Unlike arc nodes, for which we just warn about structure, the story tree
allowed parent/child rules... | [
"def",
"validate_generations_for_story_elements",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"target_node_type",
"=",
"None",
",",
"target_node",
"=",
"None",
",",
"pos",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"act... | Unlike arc nodes, for which we just warn about structure, the story tree
allowed parent/child rules must be strictly enforced. | [
"Unlike",
"arc",
"nodes",
"for",
"which",
"we",
"just",
"warn",
"about",
"structure",
"the",
"story",
"tree",
"allowed",
"parent",
"/",
"child",
"rules",
"must",
"be",
"strictly",
"enforced",
"."
] | train | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L206-L253 |
rsalmaso/django-fluo | fluo/views/base.py | View.options | def options(self, request, *args, **kwargs):
"""
Handles responding to requests for the OPTIONS HTTP verb
"""
response = HttpResponse()
response['Allow'] = ', '.join(self.allowed_methods)
response['Content-Length'] = 0
return response | python | def options(self, request, *args, **kwargs):
"""
Handles responding to requests for the OPTIONS HTTP verb
"""
response = HttpResponse()
response['Allow'] = ', '.join(self.allowed_methods)
response['Content-Length'] = 0
return response | [
"def",
"options",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"HttpResponse",
"(",
")",
"response",
"[",
"'Allow'",
"]",
"=",
"', '",
".",
"join",
"(",
"self",
".",
"allowed_methods",
")",
"respo... | Handles responding to requests for the OPTIONS HTTP verb | [
"Handles",
"responding",
"to",
"requests",
"for",
"the",
"OPTIONS",
"HTTP",
"verb"
] | train | https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/views/base.py#L75-L82 |
rsalmaso/django-fluo | fluo/views/base.py | RedirectView.get_redirect_url | def get_redirect_url(self, request, **kwargs):
"""
Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method.
"""
if self.url:
url = self.url % kwargs
args = reque... | python | def get_redirect_url(self, request, **kwargs):
"""
Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method.
"""
if self.url:
url = self.url % kwargs
args = reque... | [
"def",
"get_redirect_url",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"url",
":",
"url",
"=",
"self",
".",
"url",
"%",
"kwargs",
"args",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'QUERY_STRING'",
",",
"'... | Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method. | [
"Return",
"the",
"URL",
"redirect",
"to",
".",
"Keyword",
"arguments",
"from",
"the",
"URL",
"pattern",
"match",
"generating",
"the",
"redirect",
"request",
"are",
"provided",
"as",
"kwargs",
"to",
"this",
"method",
"."
] | train | https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/views/base.py#L132-L145 |
DasIch/argvard | argvard/utils.py | is_python2_identifier | def is_python2_identifier(possible_identifier):
"""
Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 2.
"""
match = _python2_identifier_re.match(possible_identifier)
return bool(match) and not iskeyword(possible_identifier) | python | def is_python2_identifier(possible_identifier):
"""
Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 2.
"""
match = _python2_identifier_re.match(possible_identifier)
return bool(match) and not iskeyword(possible_identifier) | [
"def",
"is_python2_identifier",
"(",
"possible_identifier",
")",
":",
"match",
"=",
"_python2_identifier_re",
".",
"match",
"(",
"possible_identifier",
")",
"return",
"bool",
"(",
"match",
")",
"and",
"not",
"iskeyword",
"(",
"possible_identifier",
")"
] | Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 2. | [
"Returns",
"True",
"if",
"the",
"given",
"possible_identifier",
"can",
"be",
"used",
"as",
"an",
"identifier",
"in",
"Python",
"2",
"."
] | train | https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/utils.py#L43-L49 |
DasIch/argvard | argvard/utils.py | is_python3_identifier | def is_python3_identifier(possible_identifier):
"""
Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 3.
"""
possible_identifier = unicodedata.normalize('NFKC', possible_identifier)
return (
bool(possible_identifier) and
_is_in_id_start(poss... | python | def is_python3_identifier(possible_identifier):
"""
Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 3.
"""
possible_identifier = unicodedata.normalize('NFKC', possible_identifier)
return (
bool(possible_identifier) and
_is_in_id_start(poss... | [
"def",
"is_python3_identifier",
"(",
"possible_identifier",
")",
":",
"possible_identifier",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKC'",
",",
"possible_identifier",
")",
"return",
"(",
"bool",
"(",
"possible_identifier",
")",
"and",
"_is_in_id_start",
"(",
... | Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 3. | [
"Returns",
"True",
"if",
"the",
"given",
"possible_identifier",
"can",
"be",
"used",
"as",
"an",
"identifier",
"in",
"Python",
"3",
"."
] | train | https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/utils.py#L52-L62 |
DasIch/argvard | argvard/utils.py | unique | def unique(iterable):
"""
Returns an iterator that yields the first occurence of a hashable item in
`iterable`.
"""
seen = set()
for obj in iterable:
if obj not in seen:
yield obj
seen.add(obj) | python | def unique(iterable):
"""
Returns an iterator that yields the first occurence of a hashable item in
`iterable`.
"""
seen = set()
for obj in iterable:
if obj not in seen:
yield obj
seen.add(obj) | [
"def",
"unique",
"(",
"iterable",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"obj",
"in",
"iterable",
":",
"if",
"obj",
"not",
"in",
"seen",
":",
"yield",
"obj",
"seen",
".",
"add",
"(",
"obj",
")"
] | Returns an iterator that yields the first occurence of a hashable item in
`iterable`. | [
"Returns",
"an",
"iterator",
"that",
"yields",
"the",
"first",
"occurence",
"of",
"a",
"hashable",
"item",
"in",
"iterable",
"."
] | train | https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/utils.py#L87-L96 |
krinj/k-util | k_util/region.py | Region.contains | def contains(self, x, y) -> bool:
"""" Checks if the given x, y position is within the area of this region. """
if x < self._left or x > self._right or y < self._top or y > self._bottom:
return False
return True | python | def contains(self, x, y) -> bool:
"""" Checks if the given x, y position is within the area of this region. """
if x < self._left or x > self._right or y < self._top or y > self._bottom:
return False
return True | [
"def",
"contains",
"(",
"self",
",",
"x",
",",
"y",
")",
"->",
"bool",
":",
"if",
"x",
"<",
"self",
".",
"_left",
"or",
"x",
">",
"self",
".",
"_right",
"or",
"y",
"<",
"self",
".",
"_top",
"or",
"y",
">",
"self",
".",
"_bottom",
":",
"return... | Checks if the given x, y position is within the area of this region. | [
"Checks",
"if",
"the",
"given",
"x",
"y",
"position",
"is",
"within",
"the",
"area",
"of",
"this",
"region",
"."
] | train | https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L72-L76 |
krinj/k-util | k_util/region.py | Region.is_in_bounds | def is_in_bounds(self, width, height) -> bool:
""" Check if this entire region is contained within the bounds of a given stage size."""
if self._top < 0 \
or self._bottom > height \
or self._left < 0 \
or self._right > width:
return False
... | python | def is_in_bounds(self, width, height) -> bool:
""" Check if this entire region is contained within the bounds of a given stage size."""
if self._top < 0 \
or self._bottom > height \
or self._left < 0 \
or self._right > width:
return False
... | [
"def",
"is_in_bounds",
"(",
"self",
",",
"width",
",",
"height",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_top",
"<",
"0",
"or",
"self",
".",
"_bottom",
">",
"height",
"or",
"self",
".",
"_left",
"<",
"0",
"or",
"self",
".",
"_right",
">",
"wi... | Check if this entire region is contained within the bounds of a given stage size. | [
"Check",
"if",
"this",
"entire",
"region",
"is",
"contained",
"within",
"the",
"bounds",
"of",
"a",
"given",
"stage",
"size",
"."
] | train | https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L78-L85 |
krinj/k-util | k_util/region.py | Region.canvas_resize | def canvas_resize(self, scale):
""" Resize this region against the entire axis space. """
self._top *= scale
self._bottom *= scale
self._left *= scale
self._right *= scale
self._calibrate_to_rect() | python | def canvas_resize(self, scale):
""" Resize this region against the entire axis space. """
self._top *= scale
self._bottom *= scale
self._left *= scale
self._right *= scale
self._calibrate_to_rect() | [
"def",
"canvas_resize",
"(",
"self",
",",
"scale",
")",
":",
"self",
".",
"_top",
"*=",
"scale",
"self",
".",
"_bottom",
"*=",
"scale",
"self",
".",
"_left",
"*=",
"scale",
"self",
".",
"_right",
"*=",
"scale",
"self",
".",
"_calibrate_to_rect",
"(",
"... | Resize this region against the entire axis space. | [
"Resize",
"this",
"region",
"against",
"the",
"entire",
"axis",
"space",
"."
] | train | https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L97-L103 |
krinj/k-util | k_util/region.py | Region.distance | def distance(r1: 'Region', r2: 'Region'):
""" Calculate distance between the x and y of the two regions."""
return math.sqrt((r2.x - r1.x) ** 2 + (r2.y - r1.y) ** 2) | python | def distance(r1: 'Region', r2: 'Region'):
""" Calculate distance between the x and y of the two regions."""
return math.sqrt((r2.x - r1.x) ** 2 + (r2.y - r1.y) ** 2) | [
"def",
"distance",
"(",
"r1",
":",
"'Region'",
",",
"r2",
":",
"'Region'",
")",
":",
"return",
"math",
".",
"sqrt",
"(",
"(",
"r2",
".",
"x",
"-",
"r1",
".",
"x",
")",
"**",
"2",
"+",
"(",
"r2",
".",
"y",
"-",
"r1",
".",
"y",
")",
"**",
"... | Calculate distance between the x and y of the two regions. | [
"Calculate",
"distance",
"between",
"the",
"x",
"and",
"y",
"of",
"the",
"two",
"regions",
"."
] | train | https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L240-L242 |
krinj/k-util | k_util/region.py | Region.fast_distance | def fast_distance(r1: 'Region', r2: 'Region'):
""" A quicker way of calculating approximate distance. Lower accuracy but faster results."""
return abs(r1.x - r2.x) + abs(r1.y - r2.y) | python | def fast_distance(r1: 'Region', r2: 'Region'):
""" A quicker way of calculating approximate distance. Lower accuracy but faster results."""
return abs(r1.x - r2.x) + abs(r1.y - r2.y) | [
"def",
"fast_distance",
"(",
"r1",
":",
"'Region'",
",",
"r2",
":",
"'Region'",
")",
":",
"return",
"abs",
"(",
"r1",
".",
"x",
"-",
"r2",
".",
"x",
")",
"+",
"abs",
"(",
"r1",
".",
"y",
"-",
"r2",
".",
"y",
")"
] | A quicker way of calculating approximate distance. Lower accuracy but faster results. | [
"A",
"quicker",
"way",
"of",
"calculating",
"approximate",
"distance",
".",
"Lower",
"accuracy",
"but",
"faster",
"results",
"."
] | train | https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L245-L247 |
hobson/pug-invest | pug/invest/util.py | rms | def rms(x):
""""Root Mean Square"
Arguments:
x (seq of float): A sequence of numerical values
Returns:
The square root of the average of the squares of the values
math.sqrt(sum(x_i**2 for x_i in x) / len(x))
or
return (np.array(x) ** 2).mean() ** 0.5
>>> rms... | python | def rms(x):
""""Root Mean Square"
Arguments:
x (seq of float): A sequence of numerical values
Returns:
The square root of the average of the squares of the values
math.sqrt(sum(x_i**2 for x_i in x) / len(x))
or
return (np.array(x) ** 2).mean() ** 0.5
>>> rms... | [
"def",
"rms",
"(",
"x",
")",
":",
"try",
":",
"return",
"(",
"np",
".",
"array",
"(",
"x",
")",
"**",
"2",
")",
".",
"mean",
"(",
")",
"**",
"0.5",
"except",
":",
"x",
"=",
"np",
".",
"array",
"(",
"dropna",
"(",
"x",
")",
")",
"invN",
"=... | Root Mean Square"
Arguments:
x (seq of float): A sequence of numerical values
Returns:
The square root of the average of the squares of the values
math.sqrt(sum(x_i**2 for x_i in x) / len(x))
or
return (np.array(x) ** 2).mean() ** 0.5
>>> rms([0, 2, 4, 4])
3... | [
"Root",
"Mean",
"Square"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L34-L57 |
hobson/pug-invest | pug/invest/util.py | rmse | def rmse(target, prediction, relative=False, percent=False):
"""Root Mean Square Error
This seems like a simple formula that you'd never need to create a function for.
But my mistakes on coding challenges have convinced me that I do need it,
as a reminder of important tweaks, if nothing else.
>>> ... | python | def rmse(target, prediction, relative=False, percent=False):
"""Root Mean Square Error
This seems like a simple formula that you'd never need to create a function for.
But my mistakes on coding challenges have convinced me that I do need it,
as a reminder of important tweaks, if nothing else.
>>> ... | [
"def",
"rmse",
"(",
"target",
",",
"prediction",
",",
"relative",
"=",
"False",
",",
"percent",
"=",
"False",
")",
":",
"relative",
"=",
"relative",
"or",
"percent",
"prediction",
"=",
"pd",
".",
"np",
".",
"array",
"(",
"prediction",
")",
"target",
"=... | Root Mean Square Error
This seems like a simple formula that you'd never need to create a function for.
But my mistakes on coding challenges have convinced me that I do need it,
as a reminder of important tweaks, if nothing else.
>>> rmse([0, 1, 4, 3], [2, 1, 0, -1])
3.0
>>> rmse([0, 1, 4, 3],... | [
"Root",
"Mean",
"Square",
"Error"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L60-L87 |
hobson/pug-invest | pug/invest/util.py | clean_dataframe | def clean_dataframe(df):
"""Fill NaNs with the previous value, the next value or if all are NaN then 1.0"""
df = df.fillna(method='ffill')
df = df.fillna(0.0)
return df | python | def clean_dataframe(df):
"""Fill NaNs with the previous value, the next value or if all are NaN then 1.0"""
df = df.fillna(method='ffill')
df = df.fillna(0.0)
return df | [
"def",
"clean_dataframe",
"(",
"df",
")",
":",
"df",
"=",
"df",
".",
"fillna",
"(",
"method",
"=",
"'ffill'",
")",
"df",
"=",
"df",
".",
"fillna",
"(",
"0.0",
")",
"return",
"df"
] | Fill NaNs with the previous value, the next value or if all are NaN then 1.0 | [
"Fill",
"NaNs",
"with",
"the",
"previous",
"value",
"the",
"next",
"value",
"or",
"if",
"all",
"are",
"NaN",
"then",
"1",
".",
"0"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L106-L110 |
hobson/pug-invest | pug/invest/util.py | clean_dataframes | def clean_dataframes(dfs):
"""Fill NaNs with the previous value, the next value or if all are NaN then 1.0
TODO:
Linear interpolation and extrapolation
Arguments:
dfs (list of dataframes): list of dataframes that contain NaNs to be removed
Returns:
list of dataframes: list of datafr... | python | def clean_dataframes(dfs):
"""Fill NaNs with the previous value, the next value or if all are NaN then 1.0
TODO:
Linear interpolation and extrapolation
Arguments:
dfs (list of dataframes): list of dataframes that contain NaNs to be removed
Returns:
list of dataframes: list of datafr... | [
"def",
"clean_dataframes",
"(",
"dfs",
")",
":",
"if",
"isinstance",
"(",
"dfs",
",",
"(",
"list",
")",
")",
":",
"for",
"df",
"in",
"dfs",
":",
"df",
"=",
"clean_dataframe",
"(",
"df",
")",
"return",
"dfs",
"else",
":",
"return",
"[",
"clean_datafra... | Fill NaNs with the previous value, the next value or if all are NaN then 1.0
TODO:
Linear interpolation and extrapolation
Arguments:
dfs (list of dataframes): list of dataframes that contain NaNs to be removed
Returns:
list of dataframes: list of dataframes with NaNs replaced by interpo... | [
"Fill",
"NaNs",
"with",
"the",
"previous",
"value",
"the",
"next",
"value",
"or",
"if",
"all",
"are",
"NaN",
"then",
"1",
".",
"0"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L113-L130 |
hobson/pug-invest | pug/invest/util.py | get_symbols_from_list | def get_symbols_from_list(list_name):
"""Retrieve a named (symbol list name) list of strings (symbols)
If you've installed the QSTK Quantitative analysis toolkit
`get_symbols_from_list('sp5002012')` will produce a list of the symbols that
were members of the S&P 500 in 2012.
Otherwise an im... | python | def get_symbols_from_list(list_name):
"""Retrieve a named (symbol list name) list of strings (symbols)
If you've installed the QSTK Quantitative analysis toolkit
`get_symbols_from_list('sp5002012')` will produce a list of the symbols that
were members of the S&P 500 in 2012.
Otherwise an im... | [
"def",
"get_symbols_from_list",
"(",
"list_name",
")",
":",
"try",
":",
"# quant software toolkit has a method for retrieving lists of symbols like S&P500 for 2012 with 'sp5002012'",
"import",
"QSTK",
".",
"qstkutil",
".",
"DataAccess",
"as",
"da",
"dataobj",
"=",
"da",
".",
... | Retrieve a named (symbol list name) list of strings (symbols)
If you've installed the QSTK Quantitative analysis toolkit
`get_symbols_from_list('sp5002012')` will produce a list of the symbols that
were members of the S&P 500 in 2012.
Otherwise an import error exception will be raised.
... | [
"Retrieve",
"a",
"named",
"(",
"symbol",
"list",
"name",
")",
"list",
"of",
"strings",
"(",
"symbols",
")"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L133-L157 |
hobson/pug-invest | pug/invest/util.py | make_symbols | def make_symbols(symbols, *args):
"""Return a list of uppercase strings like "GOOG", "$SPX, "XOM"...
Arguments:
symbols (str or list of str): list of market ticker symbols to normalize
If `symbols` is a str a get_symbols_from_list() call is used to retrieve the list of symbols
Returns:
... | python | def make_symbols(symbols, *args):
"""Return a list of uppercase strings like "GOOG", "$SPX, "XOM"...
Arguments:
symbols (str or list of str): list of market ticker symbols to normalize
If `symbols` is a str a get_symbols_from_list() call is used to retrieve the list of symbols
Returns:
... | [
"def",
"make_symbols",
"(",
"symbols",
",",
"*",
"args",
")",
":",
"if",
"(",
"hasattr",
"(",
"symbols",
",",
"'__iter__'",
")",
"and",
"not",
"any",
"(",
"symbols",
")",
")",
"or",
"(",
"isinstance",
"(",
"symbols",
",",
"(",
"list",
",",
"tuple",
... | Return a list of uppercase strings like "GOOG", "$SPX, "XOM"...
Arguments:
symbols (str or list of str): list of market ticker symbols to normalize
If `symbols` is a str a get_symbols_from_list() call is used to retrieve the list of symbols
Returns:
list of str: list of cananical ticker sy... | [
"Return",
"a",
"list",
"of",
"uppercase",
"strings",
"like",
"GOOG",
"$SPX",
"XOM",
"..."
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L160-L197 |
hobson/pug-invest | pug/invest/util.py | make_time_series | def make_time_series(x, t=pd.Timestamp(datetime.datetime(1970, 1, 1)), freq=None):
"""Convert a 2-D array of time/value pairs (or pair of time/value vectors) into a pd.Series time-series
>>> make_time_series(range(3), freq='15min') # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
1970-01-01 00:00:00 NaN
... | python | def make_time_series(x, t=pd.Timestamp(datetime.datetime(1970, 1, 1)), freq=None):
"""Convert a 2-D array of time/value pairs (or pair of time/value vectors) into a pd.Series time-series
>>> make_time_series(range(3), freq='15min') # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
1970-01-01 00:00:00 NaN
... | [
"def",
"make_time_series",
"(",
"x",
",",
"t",
"=",
"pd",
".",
"Timestamp",
"(",
"datetime",
".",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
")",
",",
"freq",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"pd",
".",
"DataFrame"... | Convert a 2-D array of time/value pairs (or pair of time/value vectors) into a pd.Series time-series
>>> make_time_series(range(3), freq='15min') # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
1970-01-01 00:00:00 NaN
1970-01-01 00:15:00 NaN
1970-01-01 00:30:00 NaN
dtype: float64 | [
"Convert",
"a",
"2",
"-",
"D",
"array",
"of",
"time",
"/",
"value",
"pairs",
"(",
"or",
"pair",
"of",
"time",
"/",
"value",
"vectors",
")",
"into",
"a",
"pd",
".",
"Series",
"time",
"-",
"series"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L200-L243 |
hobson/pug-invest | pug/invest/util.py | pandas_mesh | def pandas_mesh(df):
"""Create numpy 2-D "meshgrid" from 3+ columns in a Pandas DataFrame
Arguments:
df (DataFrame): Must have 3 or 4 columns of numerical data
Returns:
OrderedDict: column labels from the data frame are the keys, values are 2-D matrices
All matrices have shape NxM, whe... | python | def pandas_mesh(df):
"""Create numpy 2-D "meshgrid" from 3+ columns in a Pandas DataFrame
Arguments:
df (DataFrame): Must have 3 or 4 columns of numerical data
Returns:
OrderedDict: column labels from the data frame are the keys, values are 2-D matrices
All matrices have shape NxM, whe... | [
"def",
"pandas_mesh",
"(",
"df",
")",
":",
"xyz",
"=",
"[",
"df",
"[",
"c",
"]",
".",
"values",
"for",
"c",
"in",
"df",
".",
"columns",
"]",
"index",
"=",
"pd",
".",
"MultiIndex",
".",
"from_tuples",
"(",
"zip",
"(",
"xyz",
"[",
"0",
"]",
",",
... | Create numpy 2-D "meshgrid" from 3+ columns in a Pandas DataFrame
Arguments:
df (DataFrame): Must have 3 or 4 columns of numerical data
Returns:
OrderedDict: column labels from the data frame are the keys, values are 2-D matrices
All matrices have shape NxM, where N = len(set(df.iloc[:,0])... | [
"Create",
"numpy",
"2",
"-",
"D",
"meshgrid",
"from",
"3",
"+",
"columns",
"in",
"a",
"Pandas",
"DataFrame"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L246-L292 |
hobson/pug-invest | pug/invest/util.py | integrated_change | def integrated_change(ts, integrator=integrate.trapz, clip_floor=None, clip_ceil=float('inf')):
"""Total value * time above the starting value within a TimeSeries"""
integrator = get_integrator(integrator)
if clip_floor is None:
clip_floor = ts[0]
if clip_ceil < clip_floor:
polarity = -1... | python | def integrated_change(ts, integrator=integrate.trapz, clip_floor=None, clip_ceil=float('inf')):
"""Total value * time above the starting value within a TimeSeries"""
integrator = get_integrator(integrator)
if clip_floor is None:
clip_floor = ts[0]
if clip_ceil < clip_floor:
polarity = -1... | [
"def",
"integrated_change",
"(",
"ts",
",",
"integrator",
"=",
"integrate",
".",
"trapz",
",",
"clip_floor",
"=",
"None",
",",
"clip_ceil",
"=",
"float",
"(",
"'inf'",
")",
")",
":",
"integrator",
"=",
"get_integrator",
"(",
"integrator",
")",
"if",
"clip_... | Total value * time above the starting value within a TimeSeries | [
"Total",
"value",
"*",
"time",
"above",
"the",
"starting",
"value",
"within",
"a",
"TimeSeries"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L295-L313 |
hobson/pug-invest | pug/invest/util.py | insert_crossings | def insert_crossings(ts, thresh):
"""Insert/append threshold crossing points (time and value) into a timeseries (pd.Series)
Arguments:
ts (pandas.Series): Time series of values to be interpolated at `thresh` crossings
thresh (float or np.float64):
"""
# import time
# tic0 = time.clock()... | python | def insert_crossings(ts, thresh):
"""Insert/append threshold crossing points (time and value) into a timeseries (pd.Series)
Arguments:
ts (pandas.Series): Time series of values to be interpolated at `thresh` crossings
thresh (float or np.float64):
"""
# import time
# tic0 = time.clock()... | [
"def",
"insert_crossings",
"(",
"ts",
",",
"thresh",
")",
":",
"# import time",
"# tic0 = time.clock(); tic = tic0",
"# int64 for fast processing, pandas.DatetimeIndex is 5-10x slower, 0.3 ms",
"index",
"=",
"ts",
".",
"index",
"index_type",
"=",
"type",
"(",
"index",
")",
... | Insert/append threshold crossing points (time and value) into a timeseries (pd.Series)
Arguments:
ts (pandas.Series): Time series of values to be interpolated at `thresh` crossings
thresh (float or np.float64): | [
"Insert",
"/",
"append",
"threshold",
"crossing",
"points",
"(",
"time",
"and",
"value",
")",
"into",
"a",
"timeseries",
"(",
"pd",
".",
"Series",
")"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L316-L397 |
hobson/pug-invest | pug/invest/util.py | get_integrator | def get_integrator(integrator):
"""Return the scipy.integrator indicated by an index, name, or integrator_function
>> get_integrator(0)
"""
integrator_types = set(['trapz', 'cumtrapz', 'simps', 'romb'])
integrator_funcs = [integrate.trapz, integrate.cumtrapz, integrate.simps, integrate.romb]
i... | python | def get_integrator(integrator):
"""Return the scipy.integrator indicated by an index, name, or integrator_function
>> get_integrator(0)
"""
integrator_types = set(['trapz', 'cumtrapz', 'simps', 'romb'])
integrator_funcs = [integrate.trapz, integrate.cumtrapz, integrate.simps, integrate.romb]
i... | [
"def",
"get_integrator",
"(",
"integrator",
")",
":",
"integrator_types",
"=",
"set",
"(",
"[",
"'trapz'",
",",
"'cumtrapz'",
",",
"'simps'",
",",
"'romb'",
"]",
")",
"integrator_funcs",
"=",
"[",
"integrate",
".",
"trapz",
",",
"integrate",
".",
"cumtrapz",... | Return the scipy.integrator indicated by an index, name, or integrator_function
>> get_integrator(0) | [
"Return",
"the",
"scipy",
".",
"integrator",
"indicated",
"by",
"an",
"index",
"name",
"or",
"integrator_function"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L400-L418 |
hobson/pug-invest | pug/invest/util.py | clipped_area | def clipped_area(ts, thresh=0, integrator=integrate.trapz):
"""Total value * time above the starting value within a TimeSeries
Arguments:
ts (pandas.Series): Time series to be integrated.
thresh (float): Value to clip the tops off at (crossings will be interpolated)
References:
http://nb... | python | def clipped_area(ts, thresh=0, integrator=integrate.trapz):
"""Total value * time above the starting value within a TimeSeries
Arguments:
ts (pandas.Series): Time series to be integrated.
thresh (float): Value to clip the tops off at (crossings will be interpolated)
References:
http://nb... | [
"def",
"clipped_area",
"(",
"ts",
",",
"thresh",
"=",
"0",
",",
"integrator",
"=",
"integrate",
".",
"trapz",
")",
":",
"integrator",
"=",
"get_integrator",
"(",
"integrator",
"or",
"0",
")",
"ts",
"=",
"insert_crossings",
"(",
"ts",
",",
"thresh",
")",
... | Total value * time above the starting value within a TimeSeries
Arguments:
ts (pandas.Series): Time series to be integrated.
thresh (float): Value to clip the tops off at (crossings will be interpolated)
References:
http://nbviewer.ipython.org/gist/kermit666/5720498
>>> t = ['2014-12-09... | [
"Total",
"value",
"*",
"time",
"above",
"the",
"starting",
"value",
"within",
"a",
"TimeSeries"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L421-L447 |
hobson/pug-invest | pug/invest/util.py | clipping_params | def clipping_params(ts, capacity=100, rate_limit=float('inf'), method=None, max_attempts=100):
"""Start, end, and threshold that clips the value of a time series the most, given a limitted "capacity" and "rate"
Assumes that signal can be linearly interpolated between points (trapezoidal integration)
Argum... | python | def clipping_params(ts, capacity=100, rate_limit=float('inf'), method=None, max_attempts=100):
"""Start, end, and threshold that clips the value of a time series the most, given a limitted "capacity" and "rate"
Assumes that signal can be linearly interpolated between points (trapezoidal integration)
Argum... | [
"def",
"clipping_params",
"(",
"ts",
",",
"capacity",
"=",
"100",
",",
"rate_limit",
"=",
"float",
"(",
"'inf'",
")",
",",
"method",
"=",
"None",
",",
"max_attempts",
"=",
"100",
")",
":",
"VALID_METHODS",
"=",
"[",
"'L-BFGS-B'",
",",
"'TNC'",
",",
"'S... | Start, end, and threshold that clips the value of a time series the most, given a limitted "capacity" and "rate"
Assumes that signal can be linearly interpolated between points (trapezoidal integration)
Arguments:
ts (TimeSeries): Time series to attempt to clip to as low a max value as possible
ca... | [
"Start",
"end",
"and",
"threshold",
"that",
"clips",
"the",
"value",
"of",
"a",
"time",
"series",
"the",
"most",
"given",
"a",
"limitted",
"capacity",
"and",
"rate"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L450-L514 |
hobson/pug-invest | pug/invest/util.py | discrete_clipping_params | def discrete_clipping_params(ts, capacity=100, rate_limit=float('inf')):
"""Start, end, and threshold that clips the value of a time series the most, given a limitted "capacity" and "rate"
Assumes that the integrated maximum includes the peak (instantaneous maximum).
Assumes that the threshold can only set... | python | def discrete_clipping_params(ts, capacity=100, rate_limit=float('inf')):
"""Start, end, and threshold that clips the value of a time series the most, given a limitted "capacity" and "rate"
Assumes that the integrated maximum includes the peak (instantaneous maximum).
Assumes that the threshold can only set... | [
"def",
"discrete_clipping_params",
"(",
"ts",
",",
"capacity",
"=",
"100",
",",
"rate_limit",
"=",
"float",
"(",
"'inf'",
")",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Doesn't work. Returns incorrect, overly conservative threshold values.\"",
")",
"#index_type = ... | Start, end, and threshold that clips the value of a time series the most, given a limitted "capacity" and "rate"
Assumes that the integrated maximum includes the peak (instantaneous maximum).
Assumes that the threshold can only set to one of the values of the Series.
Arguments:
ts (TimeSeries): Time... | [
"Start",
"end",
"and",
"threshold",
"that",
"clips",
"the",
"value",
"of",
"a",
"time",
"series",
"the",
"most",
"given",
"a",
"limitted",
"capacity",
"and",
"rate"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L519-L569 |
hobson/pug-invest | pug/invest/util.py | square_off | def square_off(series, time_delta=None, transition_seconds=1):
"""Insert samples in regularly sampled data to produce stairsteps from ramps when plotted.
New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting
>>> square_off(pd.Series(range(3), index=pd.date_rang... | python | def square_off(series, time_delta=None, transition_seconds=1):
"""Insert samples in regularly sampled data to produce stairsteps from ramps when plotted.
New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting
>>> square_off(pd.Series(range(3), index=pd.date_rang... | [
"def",
"square_off",
"(",
"series",
",",
"time_delta",
"=",
"None",
",",
"transition_seconds",
"=",
"1",
")",
":",
"if",
"time_delta",
":",
"# int, float means delta is in seconds (not years!)",
"if",
"isinstance",
"(",
"time_delta",
",",
"(",
"int",
",",
"float",... | Insert samples in regularly sampled data to produce stairsteps from ramps when plotted.
New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting
>>> square_off(pd.Series(range(3), index=pd.date_range('2014-01-01', periods=3, freq='15m')),
... time_delta... | [
"Insert",
"samples",
"in",
"regularly",
"sampled",
"data",
"to",
"produce",
"stairsteps",
"from",
"ramps",
"when",
"plotted",
"."
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L572-L604 |
hobson/pug-invest | pug/invest/util.py | clipping_threshold | def clipping_threshold(ts, capacity=100, rate_limit=10):
"""Start and end index (datetime) that clips the price/value of a time series the most
Assumes that the integrated maximum includes the peak (instantaneous maximum).
Arguments:
ts (TimeSeries): Time series of prices or power readings to be "cl... | python | def clipping_threshold(ts, capacity=100, rate_limit=10):
"""Start and end index (datetime) that clips the price/value of a time series the most
Assumes that the integrated maximum includes the peak (instantaneous maximum).
Arguments:
ts (TimeSeries): Time series of prices or power readings to be "cl... | [
"def",
"clipping_threshold",
"(",
"ts",
",",
"capacity",
"=",
"100",
",",
"rate_limit",
"=",
"10",
")",
":",
"params",
"=",
"clipping_params",
"(",
"ts",
",",
"capacity",
"=",
"capacity",
",",
"rate_limit",
"=",
"rate_limit",
")",
"if",
"params",
":",
"r... | Start and end index (datetime) that clips the price/value of a time series the most
Assumes that the integrated maximum includes the peak (instantaneous maximum).
Arguments:
ts (TimeSeries): Time series of prices or power readings to be "clipped" as much as possible.
capacity (float): Total "funds... | [
"Start",
"and",
"end",
"index",
"(",
"datetime",
")",
"that",
"clips",
"the",
"price",
"/",
"value",
"of",
"a",
"time",
"series",
"the",
"most"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L607-L634 |
hobson/pug-invest | pug/invest/util.py | join_time_series | def join_time_series(serieses, ignore_year=False, T_s=None, aggregator='mean'):
"""Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling
FIXME:
For ignore_year and multi-year data, the index (in seconds) is computed assuming
366 days per year (leap year). So 3 ou... | python | def join_time_series(serieses, ignore_year=False, T_s=None, aggregator='mean'):
"""Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling
FIXME:
For ignore_year and multi-year data, the index (in seconds) is computed assuming
366 days per year (leap year). So 3 ou... | [
"def",
"join_time_series",
"(",
"serieses",
",",
"ignore_year",
"=",
"False",
",",
"T_s",
"=",
"None",
",",
"aggregator",
"=",
"'mean'",
")",
":",
"if",
"ignore_year",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"for",
"name",
",",
"ts",
"in",
... | Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling
FIXME:
For ignore_year and multi-year data, the index (in seconds) is computed assuming
366 days per year (leap year). So 3 out of 4 years will have a 1-day (86400 s) gap
Arguments:
series (dict of Seri... | [
"Combine",
"a",
"dict",
"of",
"pd",
".",
"Series",
"objects",
"into",
"a",
"single",
"pd",
".",
"DataFrame",
"with",
"optional",
"downsampling"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L637-L677 |
hobson/pug-invest | pug/invest/util.py | simulate | def simulate(t=1000, poly=(0.,), sinusoids=None, sigma=0, rw=0, irw=0, rrw=0):
"""Simulate a random signal with seasonal (sinusoids), linear and quadratic trend, RW, IRW, and RRW
Arguments:
t (int or list of float): number of samples or time vector, default = 1000
poly (list of float): polynomial c... | python | def simulate(t=1000, poly=(0.,), sinusoids=None, sigma=0, rw=0, irw=0, rrw=0):
"""Simulate a random signal with seasonal (sinusoids), linear and quadratic trend, RW, IRW, and RRW
Arguments:
t (int or list of float): number of samples or time vector, default = 1000
poly (list of float): polynomial c... | [
"def",
"simulate",
"(",
"t",
"=",
"1000",
",",
"poly",
"=",
"(",
"0.",
",",
")",
",",
"sinusoids",
"=",
"None",
",",
"sigma",
"=",
"0",
",",
"rw",
"=",
"0",
",",
"irw",
"=",
"0",
",",
"rrw",
"=",
"0",
")",
":",
"if",
"t",
"and",
"isinstance... | Simulate a random signal with seasonal (sinusoids), linear and quadratic trend, RW, IRW, and RRW
Arguments:
t (int or list of float): number of samples or time vector, default = 1000
poly (list of float): polynomial coefficients (in decreasing "order") passed to `numpy.polyval`
i.e. poly[0]*x*... | [
"Simulate",
"a",
"random",
"signal",
"with",
"seasonal",
"(",
"sinusoids",
")",
"linear",
"and",
"quadratic",
"trend",
"RW",
"IRW",
"and",
"RRW"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L680-L743 |
hobson/pug-invest | pug/invest/util.py | normalize_symbols | def normalize_symbols(symbols, *args, **kwargs):
"""Coerce into a list of uppercase strings like "GOOG", "$SPX, "XOM"
Flattens nested lists in `symbols` and converts all list elements to strings
Arguments:
symbols (str or list of str): list of market ticker symbols to normalize
If `symbols` ... | python | def normalize_symbols(symbols, *args, **kwargs):
"""Coerce into a list of uppercase strings like "GOOG", "$SPX, "XOM"
Flattens nested lists in `symbols` and converts all list elements to strings
Arguments:
symbols (str or list of str): list of market ticker symbols to normalize
If `symbols` ... | [
"def",
"normalize_symbols",
"(",
"symbols",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"postprocess",
"=",
"kwargs",
".",
"get",
"(",
"'postprocess'",
",",
"None",
")",
"or",
"str",
".",
"upper",
"if",
"(",
"(",
"hasattr",
"(",
"symbols",
"... | Coerce into a list of uppercase strings like "GOOG", "$SPX, "XOM"
Flattens nested lists in `symbols` and converts all list elements to strings
Arguments:
symbols (str or list of str): list of market ticker symbols to normalize
If `symbols` is a str a get_symbols_from_list() call is used to retri... | [
"Coerce",
"into",
"a",
"list",
"of",
"uppercase",
"strings",
"like",
"GOOG",
"$SPX",
"XOM"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L746-L790 |
hobson/pug-invest | pug/invest/util.py | smooth | def smooth(x, window_len=11, window='hanning', fill='reflect'):
"""smooth the data using a window with requested size.
Convolve a normalized window with the signal.
input:
x: signal to be smoothed
window_len: the width of the smoothing window
window: the type of window from 'flat',... | python | def smooth(x, window_len=11, window='hanning', fill='reflect'):
"""smooth the data using a window with requested size.
Convolve a normalized window with the signal.
input:
x: signal to be smoothed
window_len: the width of the smoothing window
window: the type of window from 'flat',... | [
"def",
"smooth",
"(",
"x",
",",
"window_len",
"=",
"11",
",",
"window",
"=",
"'hanning'",
",",
"fill",
"=",
"'reflect'",
")",
":",
"# force window_len to be an odd integer so it can be symmetrically applied",
"window_len",
"=",
"int",
"(",
"window_len",
")",
"window... | smooth the data using a window with requested size.
Convolve a normalized window with the signal.
input:
x: signal to be smoothed
window_len: the width of the smoothing window
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window w... | [
"smooth",
"the",
"data",
"using",
"a",
"window",
"with",
"requested",
"size",
"."
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L846-L907 |
hobson/pug-invest | pug/invest/util.py | estimate_shift | def estimate_shift(x, y, smoother=None, w=None, index_and_value=False, ignore_edge=1/3.,
method='valid'):
"""Estimate the time shift between two signals based on their cross correlation
Arguements:
smoother: Smoothing function applied to correlation values before finding peak
w:... | python | def estimate_shift(x, y, smoother=None, w=None, index_and_value=False, ignore_edge=1/3.,
method='valid'):
"""Estimate the time shift between two signals based on their cross correlation
Arguements:
smoother: Smoothing function applied to correlation values before finding peak
w:... | [
"def",
"estimate_shift",
"(",
"x",
",",
"y",
",",
"smoother",
"=",
"None",
",",
"w",
"=",
"None",
",",
"index_and_value",
"=",
"False",
",",
"ignore_edge",
"=",
"1",
"/",
"3.",
",",
"method",
"=",
"'valid'",
")",
":",
"return",
"NotImplementedError",
"... | Estimate the time shift between two signals based on their cross correlation
Arguements:
smoother: Smoothing function applied to correlation values before finding peak
w: Window. Sequence of values between 0 and 1 for wind centered on 0-shift
to weight correlation by before fi... | [
"Estimate",
"the",
"time",
"shift",
"between",
"two",
"signals",
"based",
"on",
"their",
"cross",
"correlation"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L910-L1004 |
hobson/pug-invest | pug/invest/util.py | fuzzy_index_match | def fuzzy_index_match(possiblities, label, **kwargs):
"""Find the closest matching column label, key, or integer indexed value
Returns:
type(label): sequence of immutable objects corresponding to best matches to each object in label
if label is an int returns the object (value) in the list ... | python | def fuzzy_index_match(possiblities, label, **kwargs):
"""Find the closest matching column label, key, or integer indexed value
Returns:
type(label): sequence of immutable objects corresponding to best matches to each object in label
if label is an int returns the object (value) in the list ... | [
"def",
"fuzzy_index_match",
"(",
"possiblities",
",",
"label",
",",
"*",
"*",
"kwargs",
")",
":",
"possibilities",
"=",
"list",
"(",
"possiblities",
")",
"if",
"isinstance",
"(",
"label",
",",
"basestring",
")",
":",
"return",
"fuzzy_get",
"(",
"possibilitie... | Find the closest matching column label, key, or integer indexed value
Returns:
type(label): sequence of immutable objects corresponding to best matches to each object in label
if label is an int returns the object (value) in the list of possibilities at that index
if label is a st... | [
"Find",
"the",
"closest",
"matching",
"column",
"label",
"key",
"or",
"integer",
"indexed",
"value"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L1008-L1034 |
hobson/pug-invest | pug/invest/util.py | get_column_labels | def get_column_labels(obj):
"""Retrieve the column labels/keys from any DataFrame or QuerySet-like table object
>>> from collections import OrderedDict
>>> get_column_labels(OrderedDict(zip('ABC', pd.np.arange(12).reshape((3,4)))))
['A', 'B', 'C']
"""
if not isinstance(obj, (list, tuple, pd.np.... | python | def get_column_labels(obj):
"""Retrieve the column labels/keys from any DataFrame or QuerySet-like table object
>>> from collections import OrderedDict
>>> get_column_labels(OrderedDict(zip('ABC', pd.np.arange(12).reshape((3,4)))))
['A', 'B', 'C']
"""
if not isinstance(obj, (list, tuple, pd.np.... | [
"def",
"get_column_labels",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
",",
"pd",
".",
"np",
".",
"ndarray",
")",
")",
":",
"try",
":",
"labels",
"=",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"o... | Retrieve the column labels/keys from any DataFrame or QuerySet-like table object
>>> from collections import OrderedDict
>>> get_column_labels(OrderedDict(zip('ABC', pd.np.arange(12).reshape((3,4)))))
['A', 'B', 'C'] | [
"Retrieve",
"the",
"column",
"labels",
"/",
"keys",
"from",
"any",
"DataFrame",
"or",
"QuerySet",
"-",
"like",
"table",
"object"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L1037-L1059 |
hobson/pug-invest | pug/invest/util.py | make_dataframe | def make_dataframe(obj, columns=None, exclude=None, limit=1e8):
"""Coerce an iterable, queryset, list or rows, dict of columns, etc into a Pandas DataFrame"""
try:
obj = obj.objects.all()[:limit]
except:
pass
if isinstance(obj, (pd.Series, list, tuple)):
return make_dataframe(pd.... | python | def make_dataframe(obj, columns=None, exclude=None, limit=1e8):
"""Coerce an iterable, queryset, list or rows, dict of columns, etc into a Pandas DataFrame"""
try:
obj = obj.objects.all()[:limit]
except:
pass
if isinstance(obj, (pd.Series, list, tuple)):
return make_dataframe(pd.... | [
"def",
"make_dataframe",
"(",
"obj",
",",
"columns",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"limit",
"=",
"1e8",
")",
":",
"try",
":",
"obj",
"=",
"obj",
".",
"objects",
".",
"all",
"(",
")",
"[",
":",
"limit",
"]",
"except",
":",
"pass",... | Coerce an iterable, queryset, list or rows, dict of columns, etc into a Pandas DataFrame | [
"Coerce",
"an",
"iterable",
"queryset",
"list",
"or",
"rows",
"dict",
"of",
"columns",
"etc",
"into",
"a",
"Pandas",
"DataFrame"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L1062-L1084 |
hobson/pug-invest | pug/invest/util.py | hist | def hist(table, field=-1, class_column=None,
title='', verbosity=2, **kwargs):
"""Plot discrete PDFs
>>> df = pd.DataFrame(pd.np.random.randn(99,3), columns=list('ABC'))
>>> df['Class'] = pd.np.array((pd.np.matrix([1,1,1])*pd.np.matrix(df).T).T > 0)
>>> len(hist(df, verbosity=0, class_column='... | python | def hist(table, field=-1, class_column=None,
title='', verbosity=2, **kwargs):
"""Plot discrete PDFs
>>> df = pd.DataFrame(pd.np.random.randn(99,3), columns=list('ABC'))
>>> df['Class'] = pd.np.array((pd.np.matrix([1,1,1])*pd.np.matrix(df).T).T > 0)
>>> len(hist(df, verbosity=0, class_column='... | [
"def",
"hist",
"(",
"table",
",",
"field",
"=",
"-",
"1",
",",
"class_column",
"=",
"None",
",",
"title",
"=",
"''",
",",
"verbosity",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"field",
"=",
"fuzzy_index_match",
"(",
"table",
",",
"field",
")",
... | Plot discrete PDFs
>>> df = pd.DataFrame(pd.np.random.randn(99,3), columns=list('ABC'))
>>> df['Class'] = pd.np.array((pd.np.matrix([1,1,1])*pd.np.matrix(df).T).T > 0)
>>> len(hist(df, verbosity=0, class_column='Class'))
3 | [
"Plot",
"discrete",
"PDFs"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L1087-L1172 |
mariocesar/pengbot | src/pengbot/utils.py | colorize | def colorize(fg=None, bg=None, attr=None, stream=None):
"""Colorize stdout"""
stdout = stream or sys.stdout
ansi_codes = []
if attr:
ansi_codes.append(color_codes['attr'][attr])
if fg:
ansi_codes.append(color_codes['fg'][fg])
if bg:
ansi_codes.append(color_codes['bg'][bg... | python | def colorize(fg=None, bg=None, attr=None, stream=None):
"""Colorize stdout"""
stdout = stream or sys.stdout
ansi_codes = []
if attr:
ansi_codes.append(color_codes['attr'][attr])
if fg:
ansi_codes.append(color_codes['fg'][fg])
if bg:
ansi_codes.append(color_codes['bg'][bg... | [
"def",
"colorize",
"(",
"fg",
"=",
"None",
",",
"bg",
"=",
"None",
",",
"attr",
"=",
"None",
",",
"stream",
"=",
"None",
")",
":",
"stdout",
"=",
"stream",
"or",
"sys",
".",
"stdout",
"ansi_codes",
"=",
"[",
"]",
"if",
"attr",
":",
"ansi_codes",
... | Colorize stdout | [
"Colorize",
"stdout"
] | train | https://github.com/mariocesar/pengbot/blob/070854f92ac1314ee56f7f6cb9d27430b8f0fda8/src/pengbot/utils.py#L168-L183 |
armstrong/armstrong.apps.related_content | armstrong/apps/related_content/managers.py | RelatedContentQuerySet.filter | def filter(self, destination_object=None, source_object=None, **kwargs):
"""
See ``QuerySet.filter`` for full documentation
This adds support for ``destination_object`` and ``source_object``
as kwargs. This converts those objects into the values necessary
to handle the ``Generi... | python | def filter(self, destination_object=None, source_object=None, **kwargs):
"""
See ``QuerySet.filter`` for full documentation
This adds support for ``destination_object`` and ``source_object``
as kwargs. This converts those objects into the values necessary
to handle the ``Generi... | [
"def",
"filter",
"(",
"self",
",",
"destination_object",
"=",
"None",
",",
"source_object",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"destination_object",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"destination_id\"",
":",
"destination_object",
"... | See ``QuerySet.filter`` for full documentation
This adds support for ``destination_object`` and ``source_object``
as kwargs. This converts those objects into the values necessary
to handle the ``GenericForeignKey`` fields. | [
"See",
"QuerySet",
".",
"filter",
"for",
"full",
"documentation"
] | train | https://github.com/armstrong/armstrong.apps.related_content/blob/f57b6908d3c76c4a44b2241c676ab5d86391106c/armstrong/apps/related_content/managers.py#L9-L27 |
AliGhahraei/verarandom | verarandom/_build_utils.py | _set_module_names_for_sphinx | def _set_module_names_for_sphinx(modules: List, new_name: str):
""" Trick sphinx into displaying the desired module in these objects' documentation. """
for obj in modules:
obj.__module__ = new_name | python | def _set_module_names_for_sphinx(modules: List, new_name: str):
""" Trick sphinx into displaying the desired module in these objects' documentation. """
for obj in modules:
obj.__module__ = new_name | [
"def",
"_set_module_names_for_sphinx",
"(",
"modules",
":",
"List",
",",
"new_name",
":",
"str",
")",
":",
"for",
"obj",
"in",
"modules",
":",
"obj",
".",
"__module__",
"=",
"new_name"
] | Trick sphinx into displaying the desired module in these objects' documentation. | [
"Trick",
"sphinx",
"into",
"displaying",
"the",
"desired",
"module",
"in",
"these",
"objects",
"documentation",
"."
] | train | https://github.com/AliGhahraei/verarandom/blob/63d9a5bd2776e40368933f54e58c3f4b4f333f03/verarandom/_build_utils.py#L4-L7 |
political-memory/django-representatives | representatives/migrations/0021_update_fr_committees.py | update_kinds | def update_kinds(apps, schema_editor):
"""
Downgrade FR special committees to delegations
"""
# Get model managers
Group = apps.get_model("representatives", "Group")
qs = Group.objects.filter(
models.Q(name__iregex=ur'^commission d\'enquête') |
models.Q(name__iregex=ur'^commiss... | python | def update_kinds(apps, schema_editor):
"""
Downgrade FR special committees to delegations
"""
# Get model managers
Group = apps.get_model("representatives", "Group")
qs = Group.objects.filter(
models.Q(name__iregex=ur'^commission d\'enquête') |
models.Q(name__iregex=ur'^commiss... | [
"def",
"update_kinds",
"(",
"apps",
",",
"schema_editor",
")",
":",
"# Get model managers",
"Group",
"=",
"apps",
".",
"get_model",
"(",
"\"representatives\"",
",",
"\"Group\"",
")",
"qs",
"=",
"Group",
".",
"objects",
".",
"filter",
"(",
"models",
".",
"Q",... | Downgrade FR special committees to delegations | [
"Downgrade",
"FR",
"special",
"committees",
"to",
"delegations"
] | train | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/migrations/0021_update_fr_committees.py#L7-L22 |
political-memory/django-representatives | representatives/migrations/0021_update_fr_committees.py | update_abbreviations | def update_abbreviations(apps, schema_editor):
"""
Migrate to new FR committee abbreviations
"""
# Get model managers
Group = apps.get_model("representatives", "Group")
# Abbreviation mapping
amap = {
u'SenComCult': u'Culture',
u'SenComEco': u'Économie',
u'SenComDef... | python | def update_abbreviations(apps, schema_editor):
"""
Migrate to new FR committee abbreviations
"""
# Get model managers
Group = apps.get_model("representatives", "Group")
# Abbreviation mapping
amap = {
u'SenComCult': u'Culture',
u'SenComEco': u'Économie',
u'SenComDef... | [
"def",
"update_abbreviations",
"(",
"apps",
",",
"schema_editor",
")",
":",
"# Get model managers",
"Group",
"=",
"apps",
".",
"get_model",
"(",
"\"representatives\"",
",",
"\"Group\"",
")",
"# Abbreviation mapping",
"amap",
"=",
"{",
"u'SenComCult'",
":",
"u'Cultur... | Migrate to new FR committee abbreviations | [
"Migrate",
"to",
"new",
"FR",
"committee",
"abbreviations"
] | train | https://github.com/political-memory/django-representatives/blob/811c90d0250149e913e6196f0ab11c97d396be39/representatives/migrations/0021_update_fr_committees.py#L25-L59 |
EnigmaBridge/client.py | ebclient/eb_utils.py | EBUtils.build_api_object | def build_api_object(uo=None, api_key=None, uo_id=None, uo_type=None):
"""
Builds API object identifier
:return:
"""
if uo is not None:
api_key = uo.resolve_api_key() if uo.resolve_api_key() is not None else api_key
uo_id = uo.uo_id if uo.uo_id is not None... | python | def build_api_object(uo=None, api_key=None, uo_id=None, uo_type=None):
"""
Builds API object identifier
:return:
"""
if uo is not None:
api_key = uo.resolve_api_key() if uo.resolve_api_key() is not None else api_key
uo_id = uo.uo_id if uo.uo_id is not None... | [
"def",
"build_api_object",
"(",
"uo",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"uo_id",
"=",
"None",
",",
"uo_type",
"=",
"None",
")",
":",
"if",
"uo",
"is",
"not",
"None",
":",
"api_key",
"=",
"uo",
".",
"resolve_api_key",
"(",
")",
"if",
"u... | Builds API object identifier
:return: | [
"Builds",
"API",
"object",
"identifier",
":",
"return",
":"
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_utils.py#L47-L60 |
EnigmaBridge/client.py | ebclient/eb_utils.py | EBUtils.get_request_type | def get_request_type(type_in):
"""
Constructs request type string for ProcessData packet from the UOtype of UO object
:param type_in:
:return:
"""
uo_type = None
if isinstance(type_in, (int, long)):
uo_type = int(type_in)
elif isinstance(type_i... | python | def get_request_type(type_in):
"""
Constructs request type string for ProcessData packet from the UOtype of UO object
:param type_in:
:return:
"""
uo_type = None
if isinstance(type_in, (int, long)):
uo_type = int(type_in)
elif isinstance(type_i... | [
"def",
"get_request_type",
"(",
"type_in",
")",
":",
"uo_type",
"=",
"None",
"if",
"isinstance",
"(",
"type_in",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"uo_type",
"=",
"int",
"(",
"type_in",
")",
"elif",
"isinstance",
"(",
"type_in",
",",
"UO",
... | Constructs request type string for ProcessData packet from the UOtype of UO object
:param type_in:
:return: | [
"Constructs",
"request",
"type",
"string",
"for",
"ProcessData",
"packet",
"from",
"the",
"UOtype",
"of",
"UO",
"object",
":",
"param",
"type_in",
":",
":",
"return",
":"
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_utils.py#L63-L74 |
EnigmaBridge/client.py | ebclient/eb_utils.py | EBUtils.merge | def merge(final, update, path=None):
"""
Deep merges dictionary object b into a.
:param final:
:param update:
:param path:
:return:
"""
if final is None:
return None
if update is None:
return final
if path is None:
... | python | def merge(final, update, path=None):
"""
Deep merges dictionary object b into a.
:param final:
:param update:
:param path:
:return:
"""
if final is None:
return None
if update is None:
return final
if path is None:
... | [
"def",
"merge",
"(",
"final",
",",
"update",
",",
"path",
"=",
"None",
")",
":",
"if",
"final",
"is",
"None",
":",
"return",
"None",
"if",
"update",
"is",
"None",
":",
"return",
"final",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"fo... | Deep merges dictionary object b into a.
:param final:
:param update:
:param path:
:return: | [
"Deep",
"merges",
"dictionary",
"object",
"b",
"into",
"a",
".",
":",
"param",
"final",
":",
":",
"param",
"update",
":",
":",
"param",
"path",
":",
":",
"return",
":"
] | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_utils.py#L95-L120 |
EnigmaBridge/client.py | ebclient/eb_utils.py | EBUtils.update | def update(dest, variation, path=None):
"""
Deep merges dictionary object variation into dest, dest keys in variation will be assigned new values
from variation
:param dest:
:param variation:
:param path:
:return:
"""
if dest is None:
r... | python | def update(dest, variation, path=None):
"""
Deep merges dictionary object variation into dest, dest keys in variation will be assigned new values
from variation
:param dest:
:param variation:
:param path:
:return:
"""
if dest is None:
r... | [
"def",
"update",
"(",
"dest",
",",
"variation",
",",
"path",
"=",
"None",
")",
":",
"if",
"dest",
"is",
"None",
":",
"return",
"None",
"if",
"variation",
"is",
"None",
":",
"return",
"dest",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
... | Deep merges dictionary object variation into dest, dest keys in variation will be assigned new values
from variation
:param dest:
:param variation:
:param path:
:return: | [
"Deep",
"merges",
"dictionary",
"object",
"variation",
"into",
"dest",
"dest",
"keys",
"in",
"variation",
"will",
"be",
"assigned",
"new",
"values",
"from",
"variation",
":",
"param",
"dest",
":",
":",
"param",
"variation",
":",
":",
"param",
"path",
":",
... | train | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_utils.py#L123-L150 |
Archived-Object/ligament | ligament/ligament.py | run_skeleton | def run_skeleton(skeleton_path, tasks, watch=True):
"""loads and executes tasks from a given skeleton file
skeleton_path:
path to the skeleton file
tasks:
a list of string identifiers of tasks to be executed
watch:
boolean flag of if the skeleton should... | python | def run_skeleton(skeleton_path, tasks, watch=True):
"""loads and executes tasks from a given skeleton file
skeleton_path:
path to the skeleton file
tasks:
a list of string identifiers of tasks to be executed
watch:
boolean flag of if the skeleton should... | [
"def",
"run_skeleton",
"(",
"skeleton_path",
",",
"tasks",
",",
"watch",
"=",
"True",
")",
":",
"build_context",
"=",
"load_context_from_skeleton",
"(",
"skeleton_path",
")",
"# for t in build_context.tasks:",
"# print t, str(build_context.tasks[t])",
"for",
"task",
"... | loads and executes tasks from a given skeleton file
skeleton_path:
path to the skeleton file
tasks:
a list of string identifiers of tasks to be executed
watch:
boolean flag of if the skeleton should be watched for changes and
automatically updat... | [
"loads",
"and",
"executes",
"tasks",
"from",
"a",
"given",
"skeleton",
"file"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/ligament.py#L50-L118 |
tBaxter/tango-shared-core | build/lib/tango_shared/templatetags/tango_site_tags.py | get_fresh_content | def get_fresh_content(top=4, additional=10, featured=False):
"""
Requires articles, photos and video packages to be installed.
Returns published *Featured* content (articles, galleries, video, etc)
and an additional batch of fresh regular (featured or not) content.
The number of objects returned i... | python | def get_fresh_content(top=4, additional=10, featured=False):
"""
Requires articles, photos and video packages to be installed.
Returns published *Featured* content (articles, galleries, video, etc)
and an additional batch of fresh regular (featured or not) content.
The number of objects returned i... | [
"def",
"get_fresh_content",
"(",
"top",
"=",
"4",
",",
"additional",
"=",
"10",
",",
"featured",
"=",
"False",
")",
":",
"from",
"articles",
".",
"models",
"import",
"Article",
"from",
"photos",
".",
"models",
"import",
"Gallery",
"from",
"video",
".",
"... | Requires articles, photos and video packages to be installed.
Returns published *Featured* content (articles, galleries, video, etc)
and an additional batch of fresh regular (featured or not) content.
The number of objects returned is defined when the tag is called.
The top item type is defined in th... | [
"Requires",
"articles",
"photos",
"and",
"video",
"packages",
"to",
"be",
"installed",
"."
] | train | https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/templatetags/tango_site_tags.py#L28-L101 |
tBaxter/tango-shared-core | build/lib/tango_shared/templatetags/tango_site_tags.py | markdown | def markdown(value, arg=''):
"""
Runs Markdown over a given value, optionally using various
extensions python-markdown supports.
Derived from django.contrib.markdown, which was deprecated from django.
ALWAYS CLEAN INPUT BEFORE TRUSTING IT.
Syntax::
{{ value|markdown:"extension1_name,... | python | def markdown(value, arg=''):
"""
Runs Markdown over a given value, optionally using various
extensions python-markdown supports.
Derived from django.contrib.markdown, which was deprecated from django.
ALWAYS CLEAN INPUT BEFORE TRUSTING IT.
Syntax::
{{ value|markdown:"extension1_name,... | [
"def",
"markdown",
"(",
"value",
",",
"arg",
"=",
"''",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"'The markdown filter has been deprecated'",
",",
"category",
"=",
"DeprecationWarning",
")",
"try",
":",
"import",
"markdown",
"except",
"Impor... | Runs Markdown over a given value, optionally using various
extensions python-markdown supports.
Derived from django.contrib.markdown, which was deprecated from django.
ALWAYS CLEAN INPUT BEFORE TRUSTING IT.
Syntax::
{{ value|markdown:"extension1_name,extension2_name..." }}
To enable saf... | [
"Runs",
"Markdown",
"over",
"a",
"given",
"value",
"optionally",
"using",
"various",
"extensions",
"python",
"-",
"markdown",
"supports",
"."
] | train | https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/templatetags/tango_site_tags.py#L105-L156 |
bretth/djset | djset/backends.py | UnencryptedKeyring.file_path | def file_path(self):
"""
The path to the file where passwords are stored. This property
may be overridden by the subclass or at the instance level.
"""
return os.path.join(keyring.util.platform.data_root(), self.filename) | python | def file_path(self):
"""
The path to the file where passwords are stored. This property
may be overridden by the subclass or at the instance level.
"""
return os.path.join(keyring.util.platform.data_root(), self.filename) | [
"def",
"file_path",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"keyring",
".",
"util",
".",
"platform",
".",
"data_root",
"(",
")",
",",
"self",
".",
"filename",
")"
] | The path to the file where passwords are stored. This property
may be overridden by the subclass or at the instance level. | [
"The",
"path",
"to",
"the",
"file",
"where",
"passwords",
"are",
"stored",
".",
"This",
"property",
"may",
"be",
"overridden",
"by",
"the",
"subclass",
"or",
"at",
"the",
"instance",
"level",
"."
] | train | https://github.com/bretth/djset/blob/e04cbcadc311f6edec50a718415d0004aa304034/djset/backends.py#L20-L25 |
bretth/djset | djset/backends.py | UnencryptedKeyring.get_password | def get_password(self, service, username):
"""Read the password from the file.
"""
service = escape_for_ini(service)
username = escape_for_ini(username)
# load the passwords from the file
config = configparser.RawConfigParser()
if os.path.exists(self.file_path):
... | python | def get_password(self, service, username):
"""Read the password from the file.
"""
service = escape_for_ini(service)
username = escape_for_ini(username)
# load the passwords from the file
config = configparser.RawConfigParser()
if os.path.exists(self.file_path):
... | [
"def",
"get_password",
"(",
"self",
",",
"service",
",",
"username",
")",
":",
"service",
"=",
"escape_for_ini",
"(",
"service",
")",
"username",
"=",
"escape_for_ini",
"(",
"username",
")",
"# load the passwords from the file",
"config",
"=",
"configparser",
".",... | Read the password from the file. | [
"Read",
"the",
"password",
"from",
"the",
"file",
"."
] | train | https://github.com/bretth/djset/blob/e04cbcadc311f6edec50a718415d0004aa304034/djset/backends.py#L37-L54 |
bretth/djset | djset/backends.py | UnencryptedKeyring.set_password | def set_password(self, service, username, password):
"""Write the password in the file.
"""
service = escape_for_ini(service)
username = escape_for_ini(username)
# ensure the file exists
self._ensure_file_path()
# load the keyring from the disk
config = ... | python | def set_password(self, service, username, password):
"""Write the password in the file.
"""
service = escape_for_ini(service)
username = escape_for_ini(username)
# ensure the file exists
self._ensure_file_path()
# load the keyring from the disk
config = ... | [
"def",
"set_password",
"(",
"self",
",",
"service",
",",
"username",
",",
"password",
")",
":",
"service",
"=",
"escape_for_ini",
"(",
"service",
")",
"username",
"=",
"escape_for_ini",
"(",
"username",
")",
"# ensure the file exists",
"self",
".",
"_ensure_file... | Write the password in the file. | [
"Write",
"the",
"password",
"in",
"the",
"file",
"."
] | train | https://github.com/bretth/djset/blob/e04cbcadc311f6edec50a718415d0004aa304034/djset/backends.py#L56-L79 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.account | def account(self, account=None):
''' Fetches account information and stores the
result in a class variable. Returns that variable
if the account has not changed.
'''
for num_of_retries in range(default.max_retry):
if account is None:
account = self.mai... | python | def account(self, account=None):
''' Fetches account information and stores the
result in a class variable. Returns that variable
if the account has not changed.
'''
for num_of_retries in range(default.max_retry):
if account is None:
account = self.mai... | [
"def",
"account",
"(",
"self",
",",
"account",
"=",
"None",
")",
":",
"for",
"num_of_retries",
"in",
"range",
"(",
"default",
".",
"max_retry",
")",
":",
"if",
"account",
"is",
"None",
":",
"account",
"=",
"self",
".",
"mainaccount",
"if",
"account",
"... | Fetches account information and stores the
result in a class variable. Returns that variable
if the account has not changed. | [
"Fetches",
"account",
"information",
"and",
"stores",
"the",
"result",
"in",
"a",
"class",
"variable",
".",
"Returns",
"that",
"variable",
"if",
"the",
"account",
"has",
"not",
"changed",
"."
] | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L92-L114 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.steem_instance | def steem_instance(self):
''' Returns the steem instance if it already exists
otherwise uses the goodnode method to fetch a node
and instantiate the Steem class.
'''
if self.s:
return self.s
for num_of_retries in range(default.max_retry):
node = se... | python | def steem_instance(self):
''' Returns the steem instance if it already exists
otherwise uses the goodnode method to fetch a node
and instantiate the Steem class.
'''
if self.s:
return self.s
for num_of_retries in range(default.max_retry):
node = se... | [
"def",
"steem_instance",
"(",
"self",
")",
":",
"if",
"self",
".",
"s",
":",
"return",
"self",
".",
"s",
"for",
"num_of_retries",
"in",
"range",
"(",
"default",
".",
"max_retry",
")",
":",
"node",
"=",
"self",
".",
"util",
".",
"goodnode",
"(",
"self... | Returns the steem instance if it already exists
otherwise uses the goodnode method to fetch a node
and instantiate the Steem class. | [
"Returns",
"the",
"steem",
"instance",
"if",
"it",
"already",
"exists",
"otherwise",
"uses",
"the",
"goodnode",
"method",
"to",
"fetch",
"a",
"node",
"and",
"instantiate",
"the",
"Steem",
"class",
"."
] | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L117-L135 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.verify_key | def verify_key (self, acctname=None, tokenkey=None):
''' This can be used to verify either a private
posting key or to verify a steemconnect refresh
token and retreive the access token.
'''
if (re.match( r'^[A-Za-z0-9]+$', tokenkey)
and tokenkey is not Non... | python | def verify_key (self, acctname=None, tokenkey=None):
''' This can be used to verify either a private
posting key or to verify a steemconnect refresh
token and retreive the access token.
'''
if (re.match( r'^[A-Za-z0-9]+$', tokenkey)
and tokenkey is not Non... | [
"def",
"verify_key",
"(",
"self",
",",
"acctname",
"=",
"None",
",",
"tokenkey",
"=",
"None",
")",
":",
"if",
"(",
"re",
".",
"match",
"(",
"r'^[A-Za-z0-9]+$'",
",",
"tokenkey",
")",
"and",
"tokenkey",
"is",
"not",
"None",
"and",
"len",
"(",
"tokenkey"... | This can be used to verify either a private
posting key or to verify a steemconnect refresh
token and retreive the access token. | [
"This",
"can",
"be",
"used",
"to",
"verify",
"either",
"a",
"private",
"posting",
"key",
"or",
"to",
"verify",
"a",
"steemconnect",
"refresh",
"token",
"and",
"retreive",
"the",
"access",
"token",
"."
] | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L147-L178 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.reward_pool_balances | def reward_pool_balances(self):
''' Fetches and returns the 3 values
needed to calculate the reward pool
and other associated values such as rshares.
Returns the reward balance, all recent claims
and the current price of steem.
'''
if self.reward_balance > 0:
... | python | def reward_pool_balances(self):
''' Fetches and returns the 3 values
needed to calculate the reward pool
and other associated values such as rshares.
Returns the reward balance, all recent claims
and the current price of steem.
'''
if self.reward_balance > 0:
... | [
"def",
"reward_pool_balances",
"(",
"self",
")",
":",
"if",
"self",
".",
"reward_balance",
">",
"0",
":",
"return",
"self",
".",
"reward_balance",
"else",
":",
"reward_fund",
"=",
"self",
".",
"steem_instance",
"(",
")",
".",
"get_reward_fund",
"(",
")",
"... | Fetches and returns the 3 values
needed to calculate the reward pool
and other associated values such as rshares.
Returns the reward balance, all recent claims
and the current price of steem. | [
"Fetches",
"and",
"returns",
"the",
"3",
"values",
"needed",
"to",
"calculate",
"the",
"reward",
"pool",
"and",
"other",
"associated",
"values",
"such",
"as",
"rshares",
".",
"Returns",
"the",
"reward",
"balance",
"all",
"recent",
"claims",
"and",
"the",
"cu... | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L181-L199 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.rshares_to_steem | def rshares_to_steem (self, rshares):
''' Gets the reward pool balances
then calculates rshares to steem
'''
self.reward_pool_balances()
return round(
rshares
* self.reward_balance
/ self.recent_claims
* self.base, 4) | python | def rshares_to_steem (self, rshares):
''' Gets the reward pool balances
then calculates rshares to steem
'''
self.reward_pool_balances()
return round(
rshares
* self.reward_balance
/ self.recent_claims
* self.base, 4) | [
"def",
"rshares_to_steem",
"(",
"self",
",",
"rshares",
")",
":",
"self",
".",
"reward_pool_balances",
"(",
")",
"return",
"round",
"(",
"rshares",
"*",
"self",
".",
"reward_balance",
"/",
"self",
".",
"recent_claims",
"*",
"self",
".",
"base",
",",
"4",
... | Gets the reward pool balances
then calculates rshares to steem | [
"Gets",
"the",
"reward",
"pool",
"balances",
"then",
"calculates",
"rshares",
"to",
"steem"
] | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L202-L211 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.global_props | def global_props(self):
''' Retrieves the global properties
used to determine rates used for calculations
in converting steempower to vests etc.
Stores these in the Utilities class as that
is where the conversions take place, however
SimpleSteem is the class that contains... | python | def global_props(self):
''' Retrieves the global properties
used to determine rates used for calculations
in converting steempower to vests etc.
Stores these in the Utilities class as that
is where the conversions take place, however
SimpleSteem is the class that contains... | [
"def",
"global_props",
"(",
"self",
")",
":",
"if",
"self",
".",
"util",
".",
"info",
"is",
"None",
":",
"self",
".",
"util",
".",
"info",
"=",
"self",
".",
"steem_instance",
"(",
")",
".",
"get_dynamic_global_properties",
"(",
")",
"self",
".",
"util"... | Retrieves the global properties
used to determine rates used for calculations
in converting steempower to vests etc.
Stores these in the Utilities class as that
is where the conversions take place, however
SimpleSteem is the class that contains
steem_instance, so to to pr... | [
"Retrieves",
"the",
"global",
"properties",
"used",
"to",
"determine",
"rates",
"used",
"for",
"calculations",
"in",
"converting",
"steempower",
"to",
"vests",
"etc",
".",
"Stores",
"these",
"in",
"the",
"Utilities",
"class",
"as",
"that",
"is",
"where",
"the"... | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L214-L230 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.current_vote_value | def current_vote_value(self, **kwargs):
''' Ensures the needed variables are
created and set to defaults although
a variable number of variables are given.
'''
try:
kwargs.items()
except:
pass
else:
for key, value in kwargs.item... | python | def current_vote_value(self, **kwargs):
''' Ensures the needed variables are
created and set to defaults although
a variable number of variables are given.
'''
try:
kwargs.items()
except:
pass
else:
for key, value in kwargs.item... | [
"def",
"current_vote_value",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"kwargs",
".",
"items",
"(",
")",
"except",
":",
"pass",
"else",
":",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
... | Ensures the needed variables are
created and set to defaults although
a variable number of variables are given. | [
"Ensures",
"the",
"needed",
"variables",
"are",
"created",
"and",
"set",
"to",
"defaults",
"although",
"a",
"variable",
"number",
"of",
"variables",
"are",
"given",
"."
] | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L233-L283 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.check_balances | def check_balances(self, account=None):
''' Fetches an account balance and makes
necessary conversions
'''
a = self.account(account)
if a is not False and a is not None:
self.sbdbal = Amount(a['sbd_balance']).amount
self.steembal = Amount(a['balance']).amo... | python | def check_balances(self, account=None):
''' Fetches an account balance and makes
necessary conversions
'''
a = self.account(account)
if a is not False and a is not None:
self.sbdbal = Amount(a['sbd_balance']).amount
self.steembal = Amount(a['balance']).amo... | [
"def",
"check_balances",
"(",
"self",
",",
"account",
"=",
"None",
")",
":",
"a",
"=",
"self",
".",
"account",
"(",
"account",
")",
"if",
"a",
"is",
"not",
"False",
"and",
"a",
"is",
"not",
"None",
":",
"self",
".",
"sbdbal",
"=",
"Amount",
"(",
... | Fetches an account balance and makes
necessary conversions | [
"Fetches",
"an",
"account",
"balance",
"and",
"makes",
"necessary",
"conversions"
] | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L286-L310 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.transfer_funds | def transfer_funds(self, to, amount, denom, msg):
''' Transfer SBD or STEEM to the given account
'''
try:
self.steem_instance().commit.transfer(to,
float(amount), denom, msg, self.mainaccount)
except Exception as e:
self.msg.error_message(e)
... | python | def transfer_funds(self, to, amount, denom, msg):
''' Transfer SBD or STEEM to the given account
'''
try:
self.steem_instance().commit.transfer(to,
float(amount), denom, msg, self.mainaccount)
except Exception as e:
self.msg.error_message(e)
... | [
"def",
"transfer_funds",
"(",
"self",
",",
"to",
",",
"amount",
",",
"denom",
",",
"msg",
")",
":",
"try",
":",
"self",
".",
"steem_instance",
"(",
")",
".",
"commit",
".",
"transfer",
"(",
"to",
",",
"float",
"(",
"amount",
")",
",",
"denom",
",",... | Transfer SBD or STEEM to the given account | [
"Transfer",
"SBD",
"or",
"STEEM",
"to",
"the",
"given",
"account"
] | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L313-L323 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.get_my_history | def get_my_history(self, account=None, limit=10000):
''' Fetches the account history from
most recent back
'''
if not account:
account = self.mainaccount
try:
h = self.steem_instance().get_account_history(
account, -1, limit)
except... | python | def get_my_history(self, account=None, limit=10000):
''' Fetches the account history from
most recent back
'''
if not account:
account = self.mainaccount
try:
h = self.steem_instance().get_account_history(
account, -1, limit)
except... | [
"def",
"get_my_history",
"(",
"self",
",",
"account",
"=",
"None",
",",
"limit",
"=",
"10000",
")",
":",
"if",
"not",
"account",
":",
"account",
"=",
"self",
".",
"mainaccount",
"try",
":",
"h",
"=",
"self",
".",
"steem_instance",
"(",
")",
".",
"get... | Fetches the account history from
most recent back | [
"Fetches",
"the",
"account",
"history",
"from",
"most",
"recent",
"back"
] | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L326-L339 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.post | def post(self, title, body, permlink, tags):
''' Used for creating a main post
to an account's blog. Waits 20 seconds
after posting as that is the required
amount of time between posting.
'''
for num_of_retries in range(default.max_retry):
try:
... | python | def post(self, title, body, permlink, tags):
''' Used for creating a main post
to an account's blog. Waits 20 seconds
after posting as that is the required
amount of time between posting.
'''
for num_of_retries in range(default.max_retry):
try:
... | [
"def",
"post",
"(",
"self",
",",
"title",
",",
"body",
",",
"permlink",
",",
"tags",
")",
":",
"for",
"num_of_retries",
"in",
"range",
"(",
"default",
".",
"max_retry",
")",
":",
"try",
":",
"self",
".",
"msg",
".",
"message",
"(",
"\"Attempting to pos... | Used for creating a main post
to an account's blog. Waits 20 seconds
after posting as that is the required
amount of time between posting. | [
"Used",
"for",
"creating",
"a",
"main",
"post",
"to",
"an",
"account",
"s",
"blog",
".",
"Waits",
"20",
"seconds",
"after",
"posting",
"as",
"that",
"is",
"the",
"required",
"amount",
"of",
"time",
"between",
"posting",
"."
] | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L342-L374 |
ArtoLabs/SimpleSteem | simplesteem/simplesteem.py | SimpleSteem.reply | def reply(self, permlink, msgbody):
''' Used for creating a reply to a
post. Waits 20 seconds
after posting as that is the required
amount of time between posting.
'''
for num_of_retries in range(default.max_retry):
try:
self.steem_instance(... | python | def reply(self, permlink, msgbody):
''' Used for creating a reply to a
post. Waits 20 seconds
after posting as that is the required
amount of time between posting.
'''
for num_of_retries in range(default.max_retry):
try:
self.steem_instance(... | [
"def",
"reply",
"(",
"self",
",",
"permlink",
",",
"msgbody",
")",
":",
"for",
"num_of_retries",
"in",
"range",
"(",
"default",
".",
"max_retry",
")",
":",
"try",
":",
"self",
".",
"steem_instance",
"(",
")",
".",
"post",
"(",
"\"message\"",
",",
"msgb... | Used for creating a reply to a
post. Waits 20 seconds
after posting as that is the required
amount of time between posting. | [
"Used",
"for",
"creating",
"a",
"reply",
"to",
"a",
"post",
".",
"Waits",
"20",
"seconds",
"after",
"posting",
"as",
"that",
"is",
"the",
"required",
"amount",
"of",
"time",
"between",
"posting",
"."
] | train | https://github.com/ArtoLabs/SimpleSteem/blob/ce8be0ae81f8878b460bc156693f1957f7dd34a3/simplesteem/simplesteem.py#L377-L399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.