uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
a48c24d8b0c9eaee1976d4a9
train
class
class ImageLabel(tk.Label): """ 图像控件 """ default_img = os.path.join(get_cfd(), "python.PNG") def __init__(self, parent, img="", width=None, height=None): """ img : 可以是图片文件名,也可以是pil.Image()对象 width, height : 图片显示的宽度, 高度; 任何一个为None, 则显示原始尺寸 """ tk.Label.__init...
class ImageLabel(tk.Label):
""" 图像控件 """ default_img = os.path.join(get_cfd(), "python.PNG") def __init__(self, parent, img="", width=None, height=None): """ img : 可以是图片文件名,也可以是pil.Image()对象 width, height : 图片显示的宽度, 高度; 任何一个为None, 则显示原始尺寸 """ tk.Label.__init__(self, parent) sel...
widgets.append(current_row) for column in range(columns): self.grid_columnconfigure(column, weight=1) # 对指定行,列进行赋值处理 def set(self, row, column, value): widget = self._widgets[row][column] widget.configure(text=value) class ImageLabel(tk.Label):
69
69
230
7
62
gitgjr/hope2
framework/tk_utils.py
Python
ImageLabel
ImageLabel
583
613
583
583
dd483e38a0882edc1e365008452789f40cfc12b4
bigcode/the-stack
train
5b36ff6533c6708e46770d65
train
class
class WinBase: def __init__(self, parent=None): """ parent : tku.WinBase, 这样容易扩展功能, 而不受限于原来的 tk 对象 self.win : 为 tkinter 原来的对象,其他方法和属性是扩展处理的 """ global root self.__dummy = None self.__title = "" # 窗体标题 if parent is None: s...
class WinBase:
def __init__(self, parent=None): """ parent : tku.WinBase, 这样容易扩展功能, 而不受限于原来的 tk 对象 self.win : 为 tkinter 原来的对象,其他方法和属性是扩展处理的 """ global root self.__dummy = None self.__title = "" # 窗体标题 if parent is None: self.win = root ...
_image.config(image=tk_img) return lbl_image def font(family="微软雅黑", size=12, bold=False): """设置字体, 含缺省设置""" if bold: _bold = tkfont.BOLD else: _bold = tkfont.NORMAL ft = tkfont.Font(family=family, size=size, weight=_bold) return ft def label(frame, text, size=12, bold=False...
256
256
1,060
4
251
gitgjr/hope2
framework/tk_utils.py
Python
WinBase
WinBase
386
549
386
386
8762ea0ad18eb4cc9540f559b4f6fa1d16e7c360
bigcode/the-stack
train
2668ae289a7bfadf963fd55a
train
function
def get_cfd(): """ 获得当前python文件所在的目录 get_current_file_directory 输入: __f : 应该输入系统变量 __file__ """ return os.path.dirname(os.path.abspath(__file__))
def get_cfd():
""" 获得当前python文件所在的目录 get_current_file_directory 输入: __f : 应该输入系统变量 __file__ """ return os.path.dirname(os.path.abspath(__file__))
, "bold": False}, "default-button": {"size": 12, "bold": True, "bg": "CadetBlue", "fg": "white", "width": 12}, "bold-label": {"size": 12, "bold": True} } def get_cfd():
64
64
52
5
59
gitgjr/hope2
framework/tk_utils.py
Python
get_cfd
get_cfd
41
47
41
41
4e17d7aed5e125cc01af9cc8a09d1ef2d48325e6
bigcode/the-stack
train
ccc95a6da3cd2832fb29cd18
train
function
def process_message(message, *args): para = list(args) para.extend("".rjust(10)) # 将参数个数扩大10个,避免参数个数不够,造成下标溢出的异常 return message.format(*para)
def process_message(message, *args):
para = list(args) para.extend("".rjust(10)) # 将参数个数扩大10个,避免参数个数不够,造成下标溢出的异常 return message.format(*para)
=_["height"]) # def os_execute(command): # import win32process # win32process.CreateProcess(command, '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, # win32process.STARTUPINFO()) # def process_message(message, *args):
64
64
56
8
56
gitgjr/hope2
framework/tk_utils.py
Python
process_message
process_message
123
126
123
123
3b6c88c2643b4cda024e0896b46e8c99e0ae0f8d
bigcode/the-stack
train
a9ddafc17e0fc150d051cde5
train
function
def style_label(master, text, size=None, bold=None, family=None, width=None, height=None, bg=None, fg=None, style=None, styles=None): """ 启用样式的标签 """ style = style if style is not None else "default-label" _ = parse_style(family, size, bold, width, height, bg, fg, style, styles) return tk.Label(master, ...
def style_label(master, text, size=None, bold=None, family=None, width=None, height=None, bg=None, fg=None, style=None, styles=None):
""" 启用样式的标签 """ style = style if style is not None else "default-label" _ = parse_style(family, size, bold, width, height, bg, fg, style, styles) return tk.Label(master, text=text, font=tkfont.Font(family=_["family"], size=_["size"], weight=_["bold"]), height=_["height"], bg=_["bg"],...
"size": size, "bold": bold, "width": width, "height": height, "bg": bg, "fg": fg} def style_label(master, text, size=None, bold=None, family=None, width=None, height=None, bg=None, fg=None, style=None, styles=None):
64
64
127
34
30
gitgjr/hope2
framework/tk_utils.py
Python
style_label
style_label
78
83
78
78
28254b6fde0343dd41088406fc694627c099bce8
bigcode/the-stack
train
471843301ee207ee3ca9cc75
train
function
def set_window_icon(win, icon): win.iconbitmap(icon)
def set_window_icon(win, icon):
win.iconbitmap(icon)
most", True) def hide_window_title(win): win.overrideredirect(True) def show_window_title(win): win.overrideredirect(False) def hide_window(win): win.withdraw() def show_window(win): win.update() win.deiconify() def set_window_icon(win, icon):
64
64
14
8
56
gitgjr/hope2
framework/tk_utils.py
Python
set_window_icon
set_window_icon
293
294
293
293
7daf294637c655419dee15076e29947a293e7bbf
bigcode/the-stack
train
b3a2a14da2fa17fce998232b
train
function
def show_window(win): win.update() win.deiconify()
def show_window(win):
win.update() win.deiconify()
", True) def set_window_top_most(win): win.wm_attributes("-topmost", True) def hide_window_title(win): win.overrideredirect(True) def show_window_title(win): win.overrideredirect(False) def hide_window(win): win.withdraw() def show_window(win):
64
64
15
5
59
gitgjr/hope2
framework/tk_utils.py
Python
show_window
show_window
288
290
288
288
ea18844ae4a29c132ae6d6cc5248284880ccbbf6
bigcode/the-stack
train
23ab8395470f7e4ae8175bb0
train
function
def ask_for_filename(): return askopenfilename()
def ask_for_filename():
return askopenfilename()
.askyesno("确认", process_message(message, *args)) def show_confirm3(message="", *args): """ True : yes False: no None: cancel """ return messagebox.askyesnocancel("确认", process_message(message, *args)) def ask_for_filename():
64
64
11
5
59
gitgjr/hope2
framework/tk_utils.py
Python
ask_for_filename
ask_for_filename
162
163
162
162
f1307c4733aa39bb82765dcd6c652c2e9547520d
bigcode/the-stack
train
9e2b5aa9e777237bb30f3223
train
function
def set_window_maximize(win): """ 将窗口最大化 """ # w = win.winfo_screenwidth() # h = win.winfo_screenheight() # win.geometry("%dx%d+%d+%d" % (w, h, -10, -10)) win.state("zoomed")
def set_window_maximize(win):
""" 将窗口最大化 """ # w = win.winfo_screenwidth() # h = win.winfo_screenheight() # win.geometry("%dx%d+%d+%d" % (w, h, -10, -10)) win.state("zoomed")
)[:2] size = '%dx%d+%d+%d' % (width, height, parent_x + int((parent_width - width) / 2), parent_y + int((parent_height - height) / 2)) win.geometry(size) def set_window_maximize(win):
64
64
67
7
57
gitgjr/hope2
framework/tk_utils.py
Python
set_window_maximize
set_window_maximize
260
265
260
260
84c830965da81cdccabff60b2889f75c4f5715ed
bigcode/the-stack
train
a8c09e7814387f8dd29828ca
train
function
def set_window_center_screen(win, width=None, height=None): """ 将窗口屏幕居中 """ screenwidth = win.winfo_screenwidth() screenheight = win.winfo_screenheight() if width is None: width, height = get_window_size(win)[:2] size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight -...
def set_window_center_screen(win, width=None, height=None):
""" 将窗口屏幕居中 """ screenwidth = win.winfo_screenwidth() screenheight = win.winfo_screenheight() if width is None: width, height = get_window_size(win)[:2] size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/3) win.geometry(size)
""" if x is None: size = "%dx%d" % (width, height) else: size = '%dx%d+%d+%d' % (width, height, x, y) win.geometry(size) def set_window_center_screen(win, width=None, height=None):
64
64
101
13
51
gitgjr/hope2
framework/tk_utils.py
Python
set_window_center_screen
set_window_center_screen
237
244
237
237
dbec64bac0f20628890ba3e6f6f5881155f7dfd4
bigcode/the-stack
train
1dce94e3f4afac35c4d75ebd
train
function
def show_warning(message="", *args): messagebox.showwarning("警告", process_message(message, *args))
def show_warning(message="", *args):
messagebox.showwarning("警告", process_message(message, *args))
("提示", process_message(message, *args)) def show_info(message="", *args): messagebox.showinfo("提示", process_message(message, *args)) def show_error(message="", *args): messagebox.showerror("错误", process_message(message, *args)) def show_warning(message="", *args):
64
64
24
8
56
gitgjr/hope2
framework/tk_utils.py
Python
show_warning
show_warning
141
142
141
141
a067dcf2daeb4de25f4d7506c0b129cbb8fbb017
bigcode/the-stack
train
9c156fb88c25a2b23867ddd2
train
function
def set_window_before_parent(win, parent): win.transient(parent)
def set_window_before_parent(win, parent):
win.transient(parent)
.Style() style.theme_use(theme) def set_window_title(win, title): win.title(title) def set_window_resizeable(win, width, height): win.resizable(width, height) def set_window_fixed(win): win.resizable(False, False) def set_window_before_parent(win, parent):
64
64
15
9
55
gitgjr/hope2
framework/tk_utils.py
Python
set_window_before_parent
set_window_before_parent
224
225
224
224
9497d91210d42d6e4bc24a0346a130f12554241e
bigcode/the-stack
train
23f8758ca5b37ab3742cad8a
train
function
def join(s=" ", source=list()): """ 将列表中的元素用指定分割符连起来 """ str_source = [str(i) for i in source] return s.join(str_source)
def join(s=" ", source=list()):
""" 将列表中的元素用指定分割符连起来 """ str_source = [str(i) for i in source] return s.join(str_source)
(False) def hide_window(win): win.withdraw() def show_window(win): win.update() win.deiconify() def set_window_icon(win, icon): win.iconbitmap(icon) def set_window_bg_color(win, color): win.config(bg=color) def join(s=" ", source=list()):
63
64
42
8
55
gitgjr/hope2
framework/tk_utils.py
Python
join
join
301
304
301
301
040740da6f0e4ac881cd4a33bc30a8e632b16ee7
bigcode/the-stack
train
b207d9b2f9be392b0aff1197
train
function
def v_separator(parent, width, bg="whitesmoke"): # width 单位为像素值 """垂直分割线 , fill=tk.Y, 但如何定位不确定,直接返回对象,由容器决定 """ frame = tk.Frame(parent, width=width, bg=bg) return frame
def v_separator(parent, width, bg="whitesmoke"): # width 单位为像素值
"""垂直分割线 , fill=tk.Y, 但如何定位不确定,直接返回对象,由容器决定 """ frame = tk.Frame(parent, width=width, bg=bg) return frame
单位为像素值 """水平分割线, 水平填充 """ tk.Frame(parent, height=height, bg="whitesmoke").pack(fill=tk.X) def v_separator(parent, width, bg="whitesmoke"): # width 单位为像素值
64
64
71
24
40
gitgjr/hope2
framework/tk_utils.py
Python
v_separator
v_separator
379
383
379
380
91549445a5dd34fefddfa273d85101a9a1af2a8e
bigcode/the-stack
train
80643c7c08bcc8cda4a23d1e
train
function
def set_window_center_parent(win, parent, width=None, height=None): """ 将窗口在其父窗体居中 """ if parent is None: set_window_center_screen(win, width, height) else: parent_width, parent_height, parent_x, parent_y = get_window_size(parent, False) if width is None: width, height = ...
def set_window_center_parent(win, parent, width=None, height=None):
""" 将窗口在其父窗体居中 """ if parent is None: set_window_center_screen(win, width, height) else: parent_width, parent_height, parent_x, parent_y = get_window_size(parent, False) if width is None: width, height = get_window_size(win)[:2] size = '%dx%d+%d+%d' % (width, heig...
= get_window_size(win)[:2] size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/3) win.geometry(size) def set_window_center_parent(win, parent, width=None, height=None):
64
64
139
15
49
gitgjr/hope2
framework/tk_utils.py
Python
set_window_center_parent
set_window_center_parent
247
257
247
247
8d45c258a4aec4fcd74d81906e5d3e717a3f2ce3
bigcode/the-stack
train
2b1009e8c0ed274baf571e47
train
function
def set_window_resizeable(win, width, height): win.resizable(width, height)
def set_window_resizeable(win, width, height):
win.resizable(width, height)
clam', 'alt', 'default', 'classic', 'vista', 'xpnative') """ if theme is not None: style = ttk.Style() style.theme_use(theme) def set_window_title(win, title): win.title(title) def set_window_resizeable(win, width, height):
63
64
19
11
52
gitgjr/hope2
framework/tk_utils.py
Python
set_window_resizeable
set_window_resizeable
216
217
216
216
2111cd31fe907eebaccfd6fe91542928cb4c4e22
bigcode/the-stack
train
a6fd865f72a8ea801fbd7a4b
train
function
def ask_for_color(): return color_chooser.askcolor()
def ask_for_color():
return color_chooser.askcolor()
None: cancel """ return messagebox.askyesnocancel("确认", process_message(message, *args)) def ask_for_filename(): return askopenfilename() def ask_for_save_filename(): return asksaveasfilename() def ask_for_directory(): return askdirectory() def ask_for_color():
64
64
13
5
59
gitgjr/hope2
framework/tk_utils.py
Python
ask_for_color
ask_for_color
174
175
174
174
5f81dc5386ea3871e0c31aa4b67eee0cff7c6705
bigcode/the-stack
train
8e9dbb5bd96e28635ebeeb2f
train
function
def set_window_bg_color(win, color): win.config(bg=color)
def set_window_bg_color(win, color):
win.config(bg=color)
irect(True) def show_window_title(win): win.overrideredirect(False) def hide_window(win): win.withdraw() def show_window(win): win.update() win.deiconify() def set_window_icon(win, icon): win.iconbitmap(icon) def set_window_bg_color(win, color):
64
64
15
9
55
gitgjr/hope2
framework/tk_utils.py
Python
set_window_bg_color
set_window_bg_color
297
298
297
297
37e7b500c65e3bee869ff686469536ef3b6219da
bigcode/the-stack
train
b9e936ff6e1f31382fa8bbac
train
function
def hide_window_title(win): win.overrideredirect(True)
def hide_window_title(win):
win.overrideredirect(True)
d+%d" % (w, h, -10, -10)) win.state("zoomed") def set_window_full_screen(win): win.attributes("-fullscreen", True) def set_window_top_most(win): win.wm_attributes("-topmost", True) def hide_window_title(win):
64
64
14
6
58
gitgjr/hope2
framework/tk_utils.py
Python
hide_window_title
hide_window_title
276
277
276
276
b4dc26ff05a0363c31c2e7afc4aad6a7d0861099
bigcode/the-stack
train
07bb019e461479cd6b9afbd5
train
function
def set_window_top_most(win): win.wm_attributes("-topmost", True)
def set_window_top_most(win):
win.wm_attributes("-topmost", True)
h = win.winfo_screenheight() # win.geometry("%dx%d+%d+%d" % (w, h, -10, -10)) win.state("zoomed") def set_window_full_screen(win): win.attributes("-fullscreen", True) def set_window_top_most(win):
64
64
19
8
56
gitgjr/hope2
framework/tk_utils.py
Python
set_window_top_most
set_window_top_most
272
273
272
272
46f635807984ca1c7b7d5d01b09dc6c2d8ccccb0
bigcode/the-stack
train
6f6811275199b921ade56f3b
train
function
def tkimg_resized(img, w_box, h_box, keep_ratio=True): """对图片进行按比例缩放处理""" w, h = img.size if w_box is None or h_box is None: img1 = img else: if keep_ratio: if w > h: width = w_box height = int(h_box * (1.0 * h / w)) else: ...
def tkimg_resized(img, w_box, h_box, keep_ratio=True):
"""对图片进行按比例缩放处理""" w, h = img.size if w_box is None or h_box is None: img1 = img else: if keep_ratio: if w > h: width = w_box height = int(h_box * (1.0 * h / w)) else: height = h_box width = int(...
符连起来 """ str_source = [str(i) for i in source] return s.join(str_source) def space(n): """ 创建 n 个空格,用于定位控制 """ return ''.rjust(n) def tkimg_resized(img, w_box, h_box, keep_ratio=True):
64
64
165
17
47
gitgjr/hope2
framework/tk_utils.py
Python
tkimg_resized
tkimg_resized
312
332
312
312
0b4dee355dce111e5d4cbe826f607f6ba9461db9
bigcode/the-stack
train
7436d9472029fe5eb5852d0d
train
function
def font(family="微软雅黑", size=12, bold=False): """设置字体, 含缺省设置""" if bold: _bold = tkfont.BOLD else: _bold = tkfont.NORMAL ft = tkfont.Font(family=family, size=size, weight=_bold) return ft
def font(family="微软雅黑", size=12, bold=False):
"""设置字体, 含缺省设置""" if bold: _bold = tkfont.BOLD else: _bold = tkfont.NORMAL ft = tkfont.Font(family=family, size=size, weight=_bold) return ft
.Label(frame, width=width, height=height) tk_img = tkimg_resized(_img, width, height, keep_ratio) lbl_image.image = tk_img lbl_image.config(image=tk_img) return lbl_image def font(family="微软雅黑", size=12, bold=False):
64
64
70
14
49
gitgjr/hope2
framework/tk_utils.py
Python
font
font
358
366
358
358
7679b7b384dc20761b693d317195b431c9403488
bigcode/the-stack
train
2bbc0e8ca234529e6ae836ed
train
function
def set_window_size(win, width, height, x=None, y=None): """ 设置窗口的尺寸 """ if x is None: size = "%dx%d" % (width, height) else: size = '%dx%d+%d+%d' % (width, height, x, y) win.geometry(size)
def set_window_size(win, width, height, x=None, y=None):
""" 设置窗口的尺寸 """ if x is None: size = "%dx%d" % (width, height) else: size = '%dx%d+%d+%d' % (width, height, x, y) win.geometry(size)
def set_window_resizeable(win, width, height): win.resizable(width, height) def set_window_fixed(win): win.resizable(False, False) def set_window_before_parent(win, parent): win.transient(parent) def set_window_size(win, width, height, x=None, y=None):
64
64
73
16
48
gitgjr/hope2
framework/tk_utils.py
Python
set_window_size
set_window_size
228
234
228
228
d8675183d3e58d62f2bd73804b265d5aa172c221
bigcode/the-stack
train
44d67b16550d1b311206b4ee
train
function
def ask_for_float(minvalue=None, maxvalue=None): if minvalue is None or maxvalue is None: return askfloat("提示", "请输入浮点数") else: prompt = "请输入( {} ~ {} )之间的浮点数".format(minvalue, maxvalue) return askfloat("提示", prompt, minvalue=minvalue, maxvalue=maxvalue)
def ask_for_float(minvalue=None, maxvalue=None):
if minvalue is None or maxvalue is None: return askfloat("提示", "请输入浮点数") else: prompt = "请输入( {} ~ {} )之间的浮点数".format(minvalue, maxvalue) return askfloat("提示", prompt, minvalue=minvalue, maxvalue=maxvalue)
asfilename() def ask_for_directory(): return askdirectory() def ask_for_color(): return color_chooser.askcolor() def ask_for_integer(initial_value=0): return askinteger("提示", "请输入整数", initialvalue=initial_value) def ask_for_float(minvalue=None, maxvalue=None):
64
64
82
12
52
gitgjr/hope2
framework/tk_utils.py
Python
ask_for_float
ask_for_float
182
187
182
182
c05132d5168638e988510b60013098470f78f73c
bigcode/the-stack
train
11fd6f1203c3ff470b276074
train
function
def show_window_title(win): win.overrideredirect(False)
def show_window_title(win):
win.overrideredirect(False)
-10)) win.state("zoomed") def set_window_full_screen(win): win.attributes("-fullscreen", True) def set_window_top_most(win): win.wm_attributes("-topmost", True) def hide_window_title(win): win.overrideredirect(True) def show_window_title(win):
64
64
14
6
58
gitgjr/hope2
framework/tk_utils.py
Python
show_window_title
show_window_title
280
281
280
280
1d1570312792ef81cbc7cb9fb16e10c160ccb8c6
bigcode/the-stack
train
f716ef92f55c08cdd2a15ac4
train
function
def h_separator(parent, height=2): # height 单位为像素值 """水平分割线, 水平填充 """ tk.Frame(parent, height=height, bg="whitesmoke").pack(fill=tk.X)
def h_separator(parent, height=2): # height 单位为像素值
"""水平分割线, 水平填充 """ tk.Frame(parent, height=height, bg="whitesmoke").pack(fill=tk.X)
, text, size=12, bold=False, bg="white", fg="blue"): return tk.Label(frame, text=text, bg=bg, fg=fg, font=font(size=size, bold=bold)) def h_separator(parent, height=2): # height 单位为像素值
64
64
52
19
45
gitgjr/hope2
framework/tk_utils.py
Python
h_separator
h_separator
373
376
373
374
99111c5007c2cf7bfe0107c1d0f17bc6fb946b4a
bigcode/the-stack
train
8cc823f1b71c641afbe2c824
train
function
def exists(env): return msvc_exists()
def exists(env):
return msvc_exists()
ARFLAGS'] = SCons.Util.CLVar('/nologo') env['ARCOM'] = "${TEMPFILE('$AR $ARFLAGS /OUT:$TARGET $SOURCES')}" env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' def exists(env):
64
64
10
4
60
kerwinxu/barcodeManager
zxing/cpp/scons/scons-local-2.0.0.final.0/SCons/Tool/mslib.py
Python
exists
exists
57
58
57
57
a5e9b0e0c518420276e98887848f6c38c0de09e0
bigcode/the-stack
train
d056bf1c04f6b63bad4d767d
train
function
def generate(env): """Add Builders and construction variables for lib to an Environment.""" SCons.Tool.createStaticLibBuilder(env) # Set-up ms tools paths msvc_setup_env_once(env) env['AR'] = 'lib' env['ARFLAGS'] = SCons.Util.CLVar('/nologo') env['ARCOM'] = "${T...
def generate(env):
"""Add Builders and construction variables for lib to an Environment.""" SCons.Tool.createStaticLibBuilder(env) # Set-up ms tools paths msvc_setup_env_once(env) env['AR'] = 'lib' env['ARFLAGS'] = SCons.Util.CLVar('/nologo') env['ARCOM'] = "${TEMPFILE('$AR $ARFLAG...
2010/06/14 22:05:46 scons" import SCons.Defaults import SCons.Tool import SCons.Tool.msvs import SCons.Tool.msvc import SCons.Util from MSCommon import msvc_exists, msvc_setup_env_once def generate(env):
64
64
117
4
59
kerwinxu/barcodeManager
zxing/cpp/scons/scons-local-2.0.0.final.0/SCons/Tool/mslib.py
Python
generate
generate
44
55
44
44
a2f790bbba090430325965d80686ca8073f20041
bigcode/the-stack
train
c9ab980a487906b20735f38f
train
class
class MetadataException(PackageError): def __init__(self, pkg, attr, error, verbose=None): super().__init__(f"metadata exception: pkg {pkg}, attr {attr}: {error}") self.pkg, self.attr, self.error, self.verbose = pkg, attr, error, verbose def msg(self, verbosity=0): """Extract error mes...
class MetadataException(PackageError):
def __init__(self, pkg, attr, error, verbose=None): super().__init__(f"metadata exception: pkg {pkg}, attr {attr}: {error}") self.pkg, self.attr, self.error, self.verbose = pkg, attr, error, verbose def msg(self, verbosity=0): """Extract error message from verbose output depending on ve...
"ChksumBase", "MissingChksum", "ParseChksumError", ) from pkgcore.exceptions import PkgcoreUserException class PackageError(ValueError, PkgcoreUserException): pass class InvalidPackageName(PackageError): pass class MetadataException(PackageError):
64
64
133
7
56
mgorny/pkgcore
src/pkgcore/package/errors.py
Python
MetadataException
MetadataException
20
35
20
21
3e6fff4486a9b149b706dcd5269dcdf30d2a758c
bigcode/the-stack
train
30f5e3fd32fc47783858da9c
train
class
class ChksumBase(PkgcoreUserException): """Generic checksum failure."""
class ChksumBase(PkgcoreUserException):
"""Generic checksum failure."""
self.verbose: if verbosity > 0: s += ':\n' else: s += ': ' s += self.verbose.msg(verbosity) return s class InvalidDependency(PackageError): """Generic bad package dependency.""" class ChksumBase(PkgcoreUserException):
63
64
17
11
52
mgorny/pkgcore
src/pkgcore/package/errors.py
Python
ChksumBase
ChksumBase
42
43
42
42
5ab35e8e0b25c48a45ebe4f1a04b12768a045248
bigcode/the-stack
train
bb41103ca62014cb5d4ee084
train
class
class InvalidPackageName(PackageError): pass
class InvalidPackageName(PackageError):
pass
", "MetadataException", "InvalidDependency", "ChksumBase", "MissingChksum", "ParseChksumError", ) from pkgcore.exceptions import PkgcoreUserException class PackageError(ValueError, PkgcoreUserException): pass class InvalidPackageName(PackageError):
64
64
11
8
55
mgorny/pkgcore
src/pkgcore/package/errors.py
Python
InvalidPackageName
InvalidPackageName
16
17
16
16
2ec2588059b4ab1a057f74cdee7dc4408ecae20b
bigcode/the-stack
train
0480393f2ce453eeaaa03282
train
class
class PackageError(ValueError, PkgcoreUserException): pass
class PackageError(ValueError, PkgcoreUserException):
pass
= ( "PackageError", "InvalidPackageName", "MetadataException", "InvalidDependency", "ChksumBase", "MissingChksum", "ParseChksumError", ) from pkgcore.exceptions import PkgcoreUserException class PackageError(ValueError, PkgcoreUserException):
64
64
15
12
51
mgorny/pkgcore
src/pkgcore/package/errors.py
Python
PackageError
PackageError
12
13
12
12
56e585ff381af443e060bc99f9fcd9c9e5cf1c98
bigcode/the-stack
train
da387d8299f20e93fe6fa936
train
class
class InvalidDependency(PackageError): """Generic bad package dependency."""
class InvalidDependency(PackageError):
"""Generic bad package dependency."""
Extract error message from verbose output depending on verbosity level.""" s = self.error if self.verbose: if verbosity > 0: s += ':\n' else: s += ': ' s += self.verbose.msg(verbosity) return s class InvalidDependency(PackageErr...
64
64
14
7
56
mgorny/pkgcore
src/pkgcore/package/errors.py
Python
InvalidDependency
InvalidDependency
38
39
38
38
7bc8e3a6535b5a3da2dd5aa62d23b0cbd52590a7
bigcode/the-stack
train
c2c3daa7ed9b2416b466bbca
train
class
class ParseChksumError(ChksumBase): def __init__(self, filename, error, missing=False): if missing: super().__init__( f"failed parsing {filename!r} chksum; data isn't available: {error}") else: super().__init__( f"failed parsing {filename!r} c...
class ParseChksumError(ChksumBase):
def __init__(self, filename, error, missing=False): if missing: super().__init__( f"failed parsing {filename!r} chksum; data isn't available: {error}") else: super().__init__( f"failed parsing {filename!r} chksum due to {error}") self.f...
): def __init__(self, pkg, filename): super().__init__( f"{pkg.cpvstr}::{pkg.repo} missing chksum data for {filename!r}") self.pkg = pkg self.file = filename class ParseChksumError(ChksumBase):
64
64
101
12
51
mgorny/pkgcore
src/pkgcore/package/errors.py
Python
ParseChksumError
ParseChksumError
55
66
55
56
cbf5c1259178e54a1a8b50de0715ecb7759795c8
bigcode/the-stack
train
9280802ebcd5d82462a21738
train
class
class MissingChksum(ChksumBase): def __init__(self, pkg, filename): super().__init__( f"{pkg.cpvstr}::{pkg.repo} missing chksum data for {filename!r}") self.pkg = pkg self.file = filename
class MissingChksum(ChksumBase):
def __init__(self, pkg, filename): super().__init__( f"{pkg.cpvstr}::{pkg.repo} missing chksum data for {filename!r}") self.pkg = pkg self.file = filename
else: s += ': ' s += self.verbose.msg(verbosity) return s class InvalidDependency(PackageError): """Generic bad package dependency.""" class ChksumBase(PkgcoreUserException): """Generic checksum failure.""" class MissingChksum(ChksumBase):
63
64
62
11
52
mgorny/pkgcore
src/pkgcore/package/errors.py
Python
MissingChksum
MissingChksum
46
52
46
47
821eb645a399af1b5d09a2f0673e7ad63b1c89e0
bigcode/the-stack
train
625bd32f89103655079698cd
train
function
def train_and_evaluate(): """ The entry point of the application. The function initializes the app, configures the settings, creates the estimator, trains and evaluates the model. """ # Read the config json file config_path = os.fspath(Path(FLAGS.training_config_path).resolve()) with open(...
def train_and_evaluate():
""" The entry point of the application. The function initializes the app, configures the settings, creates the estimator, trains and evaluates the model. """ # Read the config json file config_path = os.fspath(Path(FLAGS.training_config_path).resolve()) with open(config_path) as f: ...
.image('ground_truth', labels, max_outputs=1) tf.summary.image('predictions', logits, max_outputs=1) return tf.estimator.EstimatorSpec(mode=tf.estimator.ModeKeys.TRAIN, loss=loss, train_op=optimizer.minimize( ...
205
205
685
6
199
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
train_and_evaluate
train_and_evaluate
280
351
280
280
75bcf5b8e4bcc562d7b93c2b707b7a65783e6286
bigcode/the-stack
train
8f3f63fced57dff94283ae30
train
function
def bce_dice_loss(y_true, y_pred): """ Computes custom weighted loss combining binary cross entropy and dice losses. Args: y_true: the ground truth labels y_pred: the predicted labels Returns: The loss for the given batch of predictions """ reshaped_labels = tf.reshape(y_true, shape=[c...
def bce_dice_loss(y_true, y_pred):
""" Computes custom weighted loss combining binary cross entropy and dice losses. Args: y_true: the ground truth labels y_pred: the predicted labels Returns: The loss for the given batch of predictions """ reshaped_labels = tf.reshape(y_true, shape=[config['batch_size'], -1]) resha...
be. Args: y_true: the ground truth labels y_pred: the predicted labels Returns: The dice loss for the given batch of predictions """ return 1 - dice_coefficient(y_true, y_pred) def bce_dice_loss(y_true, y_pred):
64
64
175
12
52
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
bce_dice_loss
bce_dice_loss
109
125
109
109
26e2b78e69f8ab1aa5bdc1d3e2264e17a858c52c
bigcode/the-stack
train
6ffffb328e6b6848ef00bd71
train
function
def get_generator(bridge): """ Creates a training sample generator. Args: bridge: the isaac sample accumulator node which we will acquire samples from Returns: A generator function which yields a single training example. """ def _generator(): iterations_without_samples = 0 ...
def get_generator(bridge):
""" Creates a training sample generator. Args: bridge: the isaac sample accumulator node which we will acquire samples from Returns: A generator function which yields a single training example. """ def _generator(): iterations_without_samples = 0 while True: # T...
given batch of predictions """ reshaped_labels = tf.reshape(y_true, shape=[config['batch_size'], -1]) reshaped_logits = tf.reshape(y_pred, shape=[config['batch_size'], -1]) ce_loss = K.categorical_crossentropy(reshaped_labels, reshaped_logits) ce_loss = tf.reduce_mean(ce_loss) return ce_loss de...
87
87
292
6
80
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
get_generator
get_generator
145
179
145
145
94e10630db52324406b37de39d303aff7f9f36f8
bigcode/the-stack
train
e5ce4fcb4d7022ae6f638b28
train
class
class TimeHistory(tf.train.SessionRunHook): """ A SessionHook class to record the durations of each iteration of the optimizer Attributes: times: list of time intervals in seconds, populated on each run iter_time_start: the timestamp at the start of the interation Methods: begin: initializes ...
class TimeHistory(tf.train.SessionRunHook):
""" A SessionHook class to record the durations of each iteration of the optimizer Attributes: times: list of time intervals in seconds, populated on each run iter_time_start: the timestamp at the start of the interation Methods: begin: initializes the list of time intervals before_run: r...
.FLAGS flags.DEFINE_string('training_config_path', 'packages/freespace_dnn/apps/freespace_dnn_training.config.json', 'Relative path to the config file containing training configurations') # Dictionary to store the parsed training configurations config = {} class TimeHistory(tf.tr...
63
64
161
9
54
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
TimeHistory
TimeHistory
37
56
37
37
7e82a303af6696631b7a5b97db9d9ea621144a13
bigcode/the-stack
train
8061f962a2294bf820bd6a11
train
function
def get_dataset(bridge, num_classes): """ Create a tf.data dataset which yields batches of samples for training. Args: bridge: the isaac sample accumulator node which we will acquire samples from Returns: A tf.data dataset which yields batches of training examples. """ dataset = tf.data.D...
def get_dataset(bridge, num_classes):
""" Create a tf.data dataset which yields batches of samples for training. Args: bridge: the isaac sample accumulator node which we will acquire samples from Returns: A tf.data dataset which yields batches of training examples. """ dataset = tf.data.Dataset.from_generator(generator=get_ge...
(sample) >= 1 assert len(sample[0]) == 2 num_samples = min(len(sample), config['batch_size']) for i in range(num_samples): yield sample[i][0], sample[i][1] return _generator def get_dataset(bridge, num_classes):
64
64
122
9
54
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
get_dataset
get_dataset
182
197
182
182
9ddcb18cab5df0162f012f4a2e627fddef786bdc
bigcode/the-stack
train
ffabfcef2102adeefba617d4
train
function
def dice_coefficient(y_true, y_pred): """ Computes the dice coefficient value. This is a direct indication of the coverage of positively predicted pixels. Args: y_true: the ground truth labels y_pred: the predicted labels Returns: The dice loss for the given batch of predictions """ ...
def dice_coefficient(y_true, y_pred):
""" Computes the dice coefficient value. This is a direct indication of the coverage of positively predicted pixels. Args: y_true: the ground truth labels y_pred: the predicted labels Returns: The dice loss for the given batch of predictions """ smooth = tf.keras.backend.epsilon() ...
devices in the format expected by tf.strategy """ prefix = "/device:GPU:" device_list = [] for i in range(config['num_gpus']): device = prefix + str(i) device_list.append(device) return device_list def dice_coefficient(y_true, y_pred):
64
64
132
10
53
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
dice_coefficient
dice_coefficient
76
91
76
76
353df4e4701823c6a0dc8481ebb7d82a0f3370fe
bigcode/the-stack
train
a71ad89b82b95660fc630ec1
train
function
def cross_entropy_loss(y_true, y_pred): """ Computes categorical cross entropy loss for multi-class segmentation. Args: y_true: the ground truth labels y_pred: the predicted labels Returns: The loss for the given batch of predictions """ reshaped_labels = tf.reshape(y_true, shape=[conf...
def cross_entropy_loss(y_true, y_pred):
""" Computes categorical cross entropy loss for multi-class segmentation. Args: y_true: the ground truth labels y_pred: the predicted labels Returns: The loss for the given batch of predictions """ reshaped_labels = tf.reshape(y_true, shape=[config['batch_size'], -1]) reshaped_logi...
ce_loss = tf.reduce_mean(bce_loss * config['class_weight']) dice_loss = dice_coefficient_loss(y_true, y_pred) loss = (0.7 * bce_loss) + (0.3 * dice_loss) return loss def cross_entropy_loss(y_true, y_pred):
64
64
131
10
53
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
cross_entropy_loss
cross_entropy_loss
128
142
128
128
a5aea8c366726d9d828bd5e508a7d2916dbc405e
bigcode/the-stack
train
4110c4a4656d0a12c7e69d12
train
function
def make_dir(path, load_from_checkpoint): """ Clears a directory and creates it on disk. Args: path: The path on disk where the directory should be located. """ # If we don't want to load from existing checkpoint, delete the folder first if not load_from_checkpoint: try: shu...
def make_dir(path, load_from_checkpoint):
""" Clears a directory and creates it on disk. Args: path: The path on disk where the directory should be located. """ # If we don't want to load from existing checkpoint, delete the folder first if not load_from_checkpoint: try: shutil.rmtree(path) except: ...
_generator(generator=get_generator(bridge), output_types=(tf.float32, tf.float32), output_shapes=((None, None, 3), (None, None, num_classes))) datas...
64
64
137
9
54
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
make_dir
make_dir
200
220
200
200
0bf311cb322f1472444f5b6732d82541ab26a467
bigcode/the-stack
train
42405fc69770cabd1f91f03e
train
function
def dice_coefficient_loss(y_true, y_pred): """ Computes the dice loss. This would have the inverse trend as the dice coefficient value, in the sense that the higher the intersection over union, the lesser the loss should be. Args: y_true: the ground truth labels y_pred: the predicted labels ...
def dice_coefficient_loss(y_true, y_pred):
""" Computes the dice loss. This would have the inverse trend as the dice coefficient value, in the sense that the higher the intersection over union, the lesser the loss should be. Args: y_true: the ground truth labels y_pred: the predicted labels Returns: The dice loss for the given ...
_true = K.flatten(y_true) y_pred = K.flatten(y_pred) intersection = K.sum(y_true * y_pred) return (2. * intersection + smooth) / (K.sum(y_true) + K.sum(y_pred) + smooth) def dice_coefficient_loss(y_true, y_pred):
64
64
101
11
53
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
dice_coefficient_loss
dice_coefficient_loss
94
106
94
94
cc18eb009804f7df96f4c6e8fa5ed921b64a6782
bigcode/the-stack
train
4d4612272d60bf8172eef3ab
train
function
def model_function(features, labels, mode): """ Defines the operations for different modes in which the estimator is run. The predictions and loss are obtained as a common first step. In TRAIN mode, we use the loss for backpropagation. In EVAL mode, we calculate the accuracy and IoU score of the predict...
def model_function(features, labels, mode):
""" Defines the operations for different modes in which the estimator is run. The predictions and loss are obtained as a common first step. In TRAIN mode, we use the loss for backpropagation. In EVAL mode, we calculate the accuracy and IoU score of the prediction. Args: features: the input RGB ...
output_types=(tf.float32, tf.float32), output_shapes=((None, None, 3), (None, None, num_classes))) dataset = dataset.batch(batch_size=config['batch_size']) return dataset def make_dir(pa...
193
193
645
9
183
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
model_function
model_function
223
277
223
223
772e4cabf07a3f80450339e1c88c7da12b009869
bigcode/the-stack
train
614f185e94b5e5ec7dbb2d21
train
function
def create_device_list(num_gpus): """ Creates a list of GPU devices which we can make available for training Args: num_gpus: the number of GPU's we are making available Returns: The list of GPU devices in the format expected by tf.strategy """ prefix = "/device:GPU:" device_list = [] ...
def create_device_list(num_gpus):
""" Creates a list of GPU devices which we can make available for training Args: num_gpus: the number of GPU's we are making available Returns: The list of GPU devices in the format expected by tf.strategy """ prefix = "/device:GPU:" device_list = [] for i in range(config['num_gpus...
""" def begin(self): self.times = [] def before_run(self, run_context): self.iter_time_start = time.time() def after_run(self, run_context, run_values): self.times.append(time.time() - self.iter_time_start) def create_device_list(num_gpus):
64
64
104
8
56
ddr95070/RMIsaac
sdk/packages/freespace_dnn/apps/freespace_dnn_training.py
Python
create_device_list
create_device_list
59
73
59
59
ce1b6a1fe519d7ad9eee8b17f0e26341d164d8fd
bigcode/the-stack
train
6c611faa35d4e294f1e9253c
train
class
class _sublime_linter_move_cursor(sublime_plugin.TextCommand): # We want to ensure that `on_selection_modified` handlers run and the # 'move-back' (editing history) still works. def run(self, edit, point): self.view.sel().clear() self.view.sel().add(point) self.view.show(point)
class _sublime_linter_move_cursor(sublime_plugin.TextCommand): # We want to ensure that `on_selection_modified` handlers run and the # 'move-back' (editing history) still works.
def run(self, edit, point): self.view.sel().clear() self.view.sel().add(point) self.view.show(point)
: point = jump_positions[count - 1] move_to(view, point) class _sublime_linter_move_cursor(sublime_plugin.TextCommand): # We want to ensure that `on_selection_modified` handlers run and the # 'move-back' (editing history) still works.
64
64
76
46
18
olavk/SublimeLinter
goto_commands.py
Python
_sublime_linter_move_cursor
_sublime_linter_move_cursor
76
82
76
78
c118945cf791a29c6c58ea44be9d1512907f4e0f
bigcode/the-stack
train
060119b5fc26183ef0b4b67a
train
function
def goto(view, direction, count, wrap): filename = util.get_filename(view) errors = persist.file_errors.get(filename) if not errors: flash(view, 'No problems') return cursor = view.sel()[0].begin() # Filter regions under the cursor, bc we don't want to jump to them. # Also filt...
def goto(view, direction, count, wrap):
filename = util.get_filename(view) errors = persist.file_errors.get(filename) if not errors: flash(view, 'No problems') return cursor = view.sel()[0].begin() # Filter regions under the cursor, bc we don't want to jump to them. # Also filter duplicate start positions. all_ju...
import sublime import sublime_plugin from itertools import dropwhile, takewhile from .lint import persist, util """ Implement typical Goto Next Previous Error Commands. """ class SublimeLinterGotoError(sublime_plugin.WindowCommand): def run(self, direction='next', count=1, wrap=False): active_view = s...
100
123
410
10
90
olavk/SublimeLinter
goto_commands.py
Python
goto
goto
21
73
21
21
3ce95e4809b813ade6a730f0b827faaff919c64b
bigcode/the-stack
train
f7572b72c88d4ad33ad5a422
train
class
class SublimeLinterGotoError(sublime_plugin.WindowCommand): def run(self, direction='next', count=1, wrap=False): active_view = self.window.active_view() if active_view: goto(active_view, direction, count, wrap)
class SublimeLinterGotoError(sublime_plugin.WindowCommand):
def run(self, direction='next', count=1, wrap=False): active_view = self.window.active_view() if active_view: goto(active_view, direction, count, wrap)
import sublime import sublime_plugin from itertools import dropwhile, takewhile from .lint import persist, util """ Implement typical Goto Next Previous Error Commands. """ class SublimeLinterGotoError(sublime_plugin.WindowCommand):
49
64
55
14
35
olavk/SublimeLinter
goto_commands.py
Python
SublimeLinterGotoError
SublimeLinterGotoError
14
18
14
14
1c91f8b41f3801cc8f750bdc66039841251c433c
bigcode/the-stack
train
f0a5f8ab5f05a16bb1a37930
train
function
def flash(view, msg): window = view.window() or sublime.active_window() window.status_message(msg)
def flash(view, msg):
window = view.window() or sublime.active_window() window.status_message(msg)
point': point}) else: filename = util.get_filename(view) line, col = view.rowcol(point) target = "{}:{}:{}".format(filename, line + 1, col + 1) window.open_file(target, sublime.ENCODED_POSITION) def flash(view, msg):
64
64
23
6
58
olavk/SublimeLinter
goto_commands.py
Python
flash
flash
96
98
96
96
cb08a3ff7e629420418bd06160e4b4447d935f58
bigcode/the-stack
train
1a6a0c0cb1d8cee26bd4b2b2
train
function
def move_to(view, point): window = view.window() if view == window.active_view(): view.run_command('_sublime_linter_move_cursor', {'point': point}) else: filename = util.get_filename(view) line, col = view.rowcol(point) target = "{}:{}:{}".format(filename, line + 1, col + 1) ...
def move_to(view, point):
window = view.window() if view == window.active_view(): view.run_command('_sublime_linter_move_cursor', {'point': point}) else: filename = util.get_filename(view) line, col = view.rowcol(point) target = "{}:{}:{}".format(filename, line + 1, col + 1) window.open_file(t...
want to ensure that `on_selection_modified` handlers run and the # 'move-back' (editing history) still works. def run(self, edit, point): self.view.sel().clear() self.view.sel().add(point) self.view.show(point) def move_to(view, point):
64
64
93
7
57
olavk/SublimeLinter
goto_commands.py
Python
move_to
move_to
85
93
85
85
bdc51ab01cb57e6246ad8f17d8c46eebc0b94e16
bigcode/the-stack
train
d8562a1f0d7f44f7b2d3e841
train
class
class Migration(migrations.Migration): dependencies = [ ('email_utils', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='recipient', options={'permissions': [('can_blacklist_recipient', 'Can blacklist recipients'), ('can_whitelist_recipient', 'C...
class Migration(migrations.Migration):
dependencies = [ ('email_utils', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='recipient', options={'permissions': [('can_blacklist_recipient', 'Can blacklist recipients'), ('can_whitelist_recipient', 'Can whitelist recipients')], 'verbose_nam...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-17 03:20 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):
52
64
87
7
44
E7ernal/quizwhiz
email_utils/migrations/0002_auto_20170916_2220.py
Python
Migration
Migration
8
19
8
9
1195c343a79df3a8b030df3bbbd65ab232fa8729
bigcode/the-stack
train
277e74f0c1c0aeae76c66573
train
function
def test_create_and_insert_table_multiindex(engine, schema): table_name = 'test_multiindex' namespace = f'{schema}.{table_name}' if schema is not None else table_name drop_table_if_exists(engine=engine, schema=schema, table_name=table_name) # dtype for index for MySQL... (can't have flexible text length...
def test_create_and_insert_table_multiindex(engine, schema):
table_name = 'test_multiindex' namespace = f'{schema}.{table_name}' if schema is not None else table_name drop_table_if_exists(engine=engine, schema=schema, table_name=table_name) # dtype for index for MySQL... (can't have flexible text length) dtype = {'ix2':VARCHAR(5)} if 'mysql' in engine.dialect...
('2019-01-01'), pd.Timestamp('2019-01-02')], 'foo': [1, 2]}).set_index(index_col) default_args = {'if_row_exists':'update'} # - # # Tests # ## Test MultiIndex def test_create_and_insert_table_multiindex(engine, schema):
69
69
231
12
56
ThibTrip/pangres
pangres/tests/test_index.py
Python
test_create_and_insert_table_multiindex
test_create_and_insert_table_multiindex
42
60
42
42
66932c958bc6fae436a7a2fe6fae175cdb6eda18
bigcode/the-stack
train
97ffbf690599642c2e64be1e
train
function
def test_index_with_null(engine, schema): df = pd.DataFrame({'ix':[None], 'foo': [2]}).set_index('ix') table_name='test_index_with_null' drop_table_if_exists(engine=engine, schema=schema, table_name=table_name) # don't test for mysql since only a warning is raised and the line is skipped if not 'mys...
def test_index_with_null(engine, schema):
df = pd.DataFrame({'ix':[None], 'foo': [2]}).set_index('ix') table_name='test_index_with_null' drop_table_if_exists(engine=engine, schema=schema, table_name=table_name) # don't test for mysql since only a warning is raised and the line is skipped if not 'mysql' in engine.dialect.dialect_description:...
read_from_db() # insert upsert(engine=engine, schema=schema, df=df_multiindex2, table_name=table_name, dtype=dtype, **default_args) db_db = read_from_db() # ## Test index with null value def test_index_with_null(engine, schema):
64
64
167
9
54
ThibTrip/pangres
pangres/tests/test_index.py
Python
test_index_with_null
test_index_with_null
65
75
65
65
ae334d99aacc20c217607e691f654a8f0dd686ed
bigcode/the-stack
train
caa2e97a13b1af6e6004615e
train
function
@pytest.mark.parametrize("if_row_exists", ['update', 'ignore']) def test_only_index(engine, schema, if_row_exists): # upsert df with only index df = pd.DataFrame({'ix':[1]}).set_index('ix') table_name='test_index_only' drop_table_if_exists(engine=engine, schema=schema, table_name=table_name) upsert(...
@pytest.mark.parametrize("if_row_exists", ['update', 'ignore']) def test_only_index(engine, schema, if_row_exists): # upsert df with only index
df = pd.DataFrame({'ix':[1]}).set_index('ix') table_name='test_index_only' drop_table_if_exists(engine=engine, schema=schema, table_name=table_name) upsert(engine=engine, schema=schema, df=df, table_name=table_name, if_row_exists=if_row_exists) # check data integrity namespace = f'{schema}.{tab...
print(f'upsert failed as expected with null value in index. Error was:\n\n{e}') # ## Test only index @pytest.mark.parametrize("if_row_exists", ['update', 'ignore']) def test_only_index(engine, schema, if_row_exists): # upsert df with only index
64
64
197
35
28
ThibTrip/pangres
pangres/tests/test_index.py
Python
test_only_index
test_only_index
80
94
80
82
411d2bbbf3ac30ddd78a8df1ed55f73061069430
bigcode/the-stack
train
5f34dfd2475f07d1bfdb2104
train
function
def test_n_root(): calc = Calculator() calc.add(100) assert calc.n_root(2) == 10
def test_n_root():
calc = Calculator() calc.add(100) assert calc.n_root(2) == 10
(): calc = Calculator() calc.add(10) with pytest.raises(ZeroDivisionError): calc.divide(0) def test_divide_by_zero_two_arguments(): calc = Calculator() with pytest.raises(ZeroDivisionError): calc.divide(10, 0) def test_n_root():
64
64
28
5
59
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_n_root
test_n_root
69
72
69
69
c6d1fd096f988907556f5e49868a52cf69b8ee44
bigcode/the-stack
train
0239a7e7ff0b96d04e1dce44
train
function
def test_subtract(): calc = Calculator() assert calc.subtract(10) == -10
def test_subtract():
calc = Calculator() assert calc.subtract(10) == -10
calc.reset_memory() == 0 def test_add(): calc = Calculator() assert calc.add(10) == 10 def test_add_two_arguments(): calc = Calculator() calc.add(10) assert calc.add(10, 10) == 20 def test_subtract():
64
64
21
5
58
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_subtract
test_subtract
22
24
22
22
bd0f39ea280cb1669e37b823e3d48aa5cfcdef7e
bigcode/the-stack
train
f029b3c64e73eb80586fb5a6
train
function
def test_add_two_arguments(): calc = Calculator() calc.add(10) assert calc.add(10, 10) == 20
def test_add_two_arguments():
calc = Calculator() calc.add(10) assert calc.add(10, 10) == 20
from Calculator.Calculator import Calculator import pytest def test_reset_memory(): calc = Calculator() calc.add(10) assert calc.reset_memory() == 0 def test_add(): calc = Calculator() assert calc.add(10) == 10 def test_add_two_arguments():
62
64
31
6
55
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_add_two_arguments
test_add_two_arguments
16
19
16
16
8264cada3a9c2469f2615f0781f8ade7cc0949b2
bigcode/the-stack
train
4d8fef1c198b5643a0f07d69
train
function
def test_multiply(): calc = Calculator() calc.add(10) assert calc.multiply(10) == 100
def test_multiply():
calc = Calculator() calc.add(10) assert calc.multiply(10) == 100
calc.add(10, 10) == 20 def test_subtract(): calc = Calculator() assert calc.subtract(10) == -10 def test_subtract_two_arguments(): calc = Calculator() assert calc.subtract(30, 10) == 20 def test_multiply():
64
64
27
5
58
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_multiply
test_multiply
32
35
32
32
3fc9188cafa4b450a2e40d283e332495f861c786
bigcode/the-stack
train
ffd1dea459518c1f4019c4e4
train
function
def test_add(): calc = Calculator() assert calc.add(10) == 10
def test_add():
calc = Calculator() assert calc.add(10) == 10
from Calculator.Calculator import Calculator import pytest def test_reset_memory(): calc = Calculator() calc.add(10) assert calc.reset_memory() == 0 def test_add():
40
64
20
4
35
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_add
test_add
11
13
11
11
ec4dd60a971db7d92f06bae1de6363325f9213bb
bigcode/the-stack
train
d1850b52a2b9fb6e6e446654
train
function
def test_n_root_two_arguments(): calc = Calculator() calc.add(100) assert calc.n_root(2, 16) == 4
def test_n_root_two_arguments():
calc = Calculator() calc.add(100) assert calc.n_root(2, 16) == 4
ide_by_zero_two_arguments(): calc = Calculator() with pytest.raises(ZeroDivisionError): calc.divide(10, 0) def test_n_root(): calc = Calculator() calc.add(100) assert calc.n_root(2) == 10 def test_n_root_two_arguments():
64
64
33
7
56
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_n_root_two_arguments
test_n_root_two_arguments
75
78
75
75
43d1adb68a505cd3b74aa6b6533a85aa972ccbe1
bigcode/the-stack
train
caab1564bc01c3f5bac5ec50
train
function
def test_divide_by_zero_two_arguments(): calc = Calculator() with pytest.raises(ZeroDivisionError): calc.divide(10, 0)
def test_divide_by_zero_two_arguments():
calc = Calculator() with pytest.raises(ZeroDivisionError): calc.divide(10, 0)
Calculator() calc.add(100) assert calc.divide(10, 2) == 5 def test_divide_by_zero(): calc = Calculator() calc.add(10) with pytest.raises(ZeroDivisionError): calc.divide(0) def test_divide_by_zero_two_arguments():
64
64
32
9
55
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_divide_by_zero_two_arguments
test_divide_by_zero_two_arguments
63
66
63
63
189dc920c62234b10a313b325c3468140cdf617a
bigcode/the-stack
train
cab9deddeeb9f6eebf18a4d4
train
function
def test_divide(): calc = Calculator() calc.add(100) assert calc.divide(10) == 10
def test_divide():
calc = Calculator() calc.add(100) assert calc.divide(10) == 10
def test_multiply(): calc = Calculator() calc.add(10) assert calc.multiply(10) == 100 def test_multiply_two_arguments(): calc = Calculator() calc.add(10) assert calc.multiply(10, 10) == 100 def test_divide():
64
64
27
5
58
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_divide
test_divide
44
47
44
44
5291dc85bde120c46088a8590c5e031aca113183
bigcode/the-stack
train
780f4a3b299004ef024d37b2
train
function
def test_divide_by_zero(): calc = Calculator() calc.add(10) with pytest.raises(ZeroDivisionError): calc.divide(0)
def test_divide_by_zero():
calc = Calculator() calc.add(10) with pytest.raises(ZeroDivisionError): calc.divide(0)
_divide(): calc = Calculator() calc.add(100) assert calc.divide(10) == 10 def test_divide_two_arguments(): calc = Calculator() calc.add(100) assert calc.divide(10, 2) == 5 def test_divide_by_zero():
64
64
33
7
56
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_divide_by_zero
test_divide_by_zero
56
60
56
56
55cf0ca7af440daf4d2172f39d043f570f20c317
bigcode/the-stack
train
012e3411bcbaac5ac96ad691
train
function
def test_subtract_two_arguments(): calc = Calculator() assert calc.subtract(30, 10) == 20
def test_subtract_two_arguments():
calc = Calculator() assert calc.subtract(30, 10) == 20
) == 10 def test_add_two_arguments(): calc = Calculator() calc.add(10) assert calc.add(10, 10) == 20 def test_subtract(): calc = Calculator() assert calc.subtract(10) == -10 def test_subtract_two_arguments():
64
64
26
7
56
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_subtract_two_arguments
test_subtract_two_arguments
27
29
27
27
b6e868fbb3461691ecadf745991843ec43ebda7e
bigcode/the-stack
train
c574918fa99bb7218a13c7ce
train
function
def test_reset_memory(): calc = Calculator() calc.add(10) assert calc.reset_memory() == 0
def test_reset_memory():
calc = Calculator() calc.add(10) assert calc.reset_memory() == 0
from Calculator.Calculator import Calculator import pytest def test_reset_memory():
15
64
26
5
9
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_reset_memory
test_reset_memory
5
8
5
5
b54de9433981a350c678b4c52c0bff07cec8e806
bigcode/the-stack
train
61e19e08a132dba5fee96beb
train
function
def test_n_root_by_zero_two_arguments(): calc = Calculator() calc.add(10) with pytest.raises(ZeroDivisionError): calc.n_root(0, 16)
def test_n_root_by_zero_two_arguments():
calc = Calculator() calc.add(10) with pytest.raises(ZeroDivisionError): calc.n_root(0, 16)
calc.add(100) assert calc.n_root(2, 16) == 4 def test_n_root_by_zero(): calc = Calculator() calc.add(10) with pytest.raises(ZeroDivisionError): calc.n_root(0) def test_n_root_by_zero_two_arguments():
64
64
39
9
55
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_n_root_by_zero_two_arguments
test_n_root_by_zero_two_arguments
88
92
88
88
3776fbfd88aa450c7eb71f379fce77667ecee191
bigcode/the-stack
train
c946450ec81ee4b31b018ba0
train
function
def test_n_root_by_zero(): calc = Calculator() calc.add(10) with pytest.raises(ZeroDivisionError): calc.n_root(0)
def test_n_root_by_zero():
calc = Calculator() calc.add(10) with pytest.raises(ZeroDivisionError): calc.n_root(0)
(): calc = Calculator() calc.add(100) assert calc.n_root(2) == 10 def test_n_root_two_arguments(): calc = Calculator() calc.add(100) assert calc.n_root(2, 16) == 4 def test_n_root_by_zero():
64
64
34
7
56
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_n_root_by_zero
test_n_root_by_zero
81
85
81
81
899f67648f01d2e8d5ce7b19433e42d188a83b79
bigcode/the-stack
train
84c30cf102a9af8fc02f150a
train
function
def test_divide_two_arguments(): calc = Calculator() calc.add(100) assert calc.divide(10, 2) == 5
def test_divide_two_arguments():
calc = Calculator() calc.add(100) assert calc.divide(10, 2) == 5
_multiply_two_arguments(): calc = Calculator() calc.add(10) assert calc.multiply(10, 10) == 100 def test_divide(): calc = Calculator() calc.add(100) assert calc.divide(10) == 10 def test_divide_two_arguments():
64
64
32
7
56
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_divide_two_arguments
test_divide_two_arguments
50
53
50
50
77503ef1f74d3dc9baa500b646315c8e183ec47f
bigcode/the-stack
train
91d85426e31db619ffbf717c
train
function
def test_multiply_two_arguments(): calc = Calculator() calc.add(10) assert calc.multiply(10, 10) == 100
def test_multiply_two_arguments():
calc = Calculator() calc.add(10) assert calc.multiply(10, 10) == 100
== -10 def test_subtract_two_arguments(): calc = Calculator() assert calc.subtract(30, 10) == 20 def test_multiply(): calc = Calculator() calc.add(10) assert calc.multiply(10) == 100 def test_multiply_two_arguments():
64
64
32
7
56
miglegervyte/Calculator
Tests/test_calculator.py
Python
test_multiply_two_arguments
test_multiply_two_arguments
38
41
38
38
efd64c41ab2726f125c570ebc28b68c3c0421e2b
bigcode/the-stack
train
9e1d7816729bf611c56271c8
train
class
class G_9( Pitch, ): pass
class G_9( Pitch, ):
pass
""" *G - Level 9* """ from .._pitch import Pitch __all__ = ["G_9"] class G_9( Pitch, ):
35
64
12
9
26
jedhsu/music
music/__model/integer/audio/g/g_9.py
Python
G_9
G_9
12
15
12
14
af181acb90d7f9bc973e6ef6a4cba364e0652662
bigcode/the-stack
train
76b94524ef240135847c3af6
train
function
@click.command( name="uniq", context_settings=CONTEXT_SETTINGS, help="Extract all k-mers that appear only once in the INPUT fasta file.", ) @args.input_path() @args.output_path(file_okay=True) @args.k() @args.reverse() @args.scan_mode() @args.batch_size() @args.batch_mode() @args.previous_batches() @args.th...
@click.command( name="uniq", context_settings=CONTEXT_SETTINGS, help="Extract all k-mers that appear only once in the INPUT fasta file.", ) @args.input_path() @args.output_path(file_okay=True) @args.k() @args.reverse() @args.scan_mode() @args.batch_size() @args.batch_mode() @args.previous_batches() @args.th...
"""Run kmer_uniq script. :param input_path: input FASTA file :type input_path: str :param output_path: path to output file :type output_path: str :param k: k-mer length :type k: int :param reverse: perform reverse-complement operation, defaults to False :type reverse: bool :para...
@click.command( name="uniq", context_settings=CONTEXT_SETTINGS, help="Extract all k-mers that appear only once in the INPUT fasta file.", ) @args.input_path() @args.output_path(file_okay=True) @args.k() @args.reverse() @args.scan_mode() @args.batch_size() @args.batch_mode() @args.previous_batches() @args.th...
202
179
597
202
0
ggirelli/kman
kmermaid/scripts/kmer_uniq.py
Python
run
run
19
92
19
47
6314badc07d370479fb801e93fbc1c7db239a8fd
bigcode/the-stack
train
2451442241f9e3fbe42feedc
train
function
def get_joiner(n_batches: int, threads: int = 1) -> KJoinerThreading: """Instantiate k-joiner for uniquing. :param n_batches: number of input batches. :type n_batches: int :param threads: for parallelization, defaults to 1 :type threads: int :return: updated joiner instance. :rtype: KJoiner...
def get_joiner(n_batches: int, threads: int = 1) -> KJoinerThreading:
"""Instantiate k-joiner for uniquing. :param n_batches: number of input batches. :type n_batches: int :param threads: for parallelization, defaults to 1 :type threads: int :return: updated joiner instance. :rtype: KJoinerThreading """ joiner = KJoinerThreading() joiner.threads =...
ED_MODE[batch_mode]) .collection ) get_joiner(len(batches), threads).join(batches, output_path) logging.info("That's all! :smiley:") def get_joiner(n_batches: int, threads: int = 1) -> KJoinerThreading:
63
64
134
23
41
ggirelli/kman
kmermaid/scripts/kmer_uniq.py
Python
get_joiner
get_joiner
95
108
95
95
e46eadae4f840973d7846266e6e8e5a56bca5858
bigcode/the-stack
train
37a7cf49d8537ba85cc2a2b0
train
class
@register('Jupyter.ButtonStyle') class ButtonStyle(Style, CoreWidget): """Button style widget.""" _model_name = Unicode('ButtonStyleModel').tag(sync=True) button_color = Color(None, allow_none=True, help="Color of the button").tag(sync=True) font_weight = Unicode().tag(sync=True)
@register('Jupyter.ButtonStyle') class ButtonStyle(Style, CoreWidget):
"""Button style widget.""" _model_name = Unicode('ButtonStyleModel').tag(sync=True) button_color = Color(None, allow_none=True, help="Color of the button").tag(sync=True) font_weight = Unicode().tag(sync=True)
_serialization from .widget_core import CoreWidget from .widget_style import Style from .trait_types import Color from traitlets import Unicode, Bool, CaselessStrEnum, Instance, validate, default import warnings @register('Jupyter.ButtonStyle') class ButtonStyle(Style, CoreWidget):
64
64
70
17
46
vidartf/ipywidgets
ipywidgets/widgets/widget_button.py
Python
ButtonStyle
ButtonStyle
20
25
20
21
36dfb85c44c36e8cbb069142ee5fb33458755fed
bigcode/the-stack
train
a9572b97d32500fb48fc78ec
train
class
@register('Jupyter.Button') class Button(DOMWidget, CoreWidget): """Button widget. This widget has an `on_click` method that allows you to listen for the user clicking on the button. The click event itself is stateless. Parameters ---------- description: str description displayed next ...
@register('Jupyter.Button') class Button(DOMWidget, CoreWidget):
"""Button widget. This widget has an `on_click` method that allows you to listen for the user clicking on the button. The click event itself is stateless. Parameters ---------- description: str description displayed next to the button tooltip: str tooltip caption of the togg...
a widget. Allows user to listen for click events on the button and trigger backend code when the clicks are fired. """ from .domwidget import DOMWidget from .widget import CallbackDispatcher, register, widget_serialization from .widget_core import CoreWidget from .widget_style import Style from .trait_types import C...
177
177
592
16
161
vidartf/ipywidgets
ipywidgets/widgets/widget_button.py
Python
Button
Button
28
101
28
29
c9e73598cd64091a404a9a17d9c4e68cd74a5790
bigcode/the-stack
train
7a72f2b49ace6f7b90729168
train
class
class SelectableLabel(RecycleDataViewBehavior, Label): ''' Add selection support to the Label ''' index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) def refresh_view_attrs(self, rv, index, data): ''' Catch and handle the view changes ''' self.index = i...
class SelectableLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label ''' index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) def refresh_view_attrs(self, rv, index, data): ''' Catch and handle the view changes ''' self.index = index return super(SelectableLabel, self).refres...
orientation: 'vertical' multiselect: True touch_multiselect: True ''') class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): ''' Adds selection and focus behaviour to the view. ''' class SelectableLabel(RecycleDataViewB...
65
66
220
12
53
AlexCaranha/MyLauncher
examples/recycle_view_example2.py
Python
SelectableLabel
SelectableLabel
38
63
38
38
3d2ad3305d01e1c8d82fc03e141ad99d4cd93a41
bigcode/the-stack
train
1195c406eadec05663cb5a5a
train
class
class TestApp(App): def build(self): return RV()
class TestApp(App):
def build(self): return RV()
("selection removed for {0}".format(rv.data[index])) class RV(RecycleView): def __init__(self, **kwargs): super(RV, self).__init__(**kwargs) self.data = [{'text': str(x)} for x in range(100)] class TestApp(App):
63
64
14
5
58
AlexCaranha/MyLauncher
examples/recycle_view_example2.py
Python
TestApp
TestApp
72
74
72
72
5857f968935f1f71df941fcd8a71345059027960
bigcode/the-stack
train
44063a2dc9aedbc3e317a25f
train
class
class RV(RecycleView): def __init__(self, **kwargs): super(RV, self).__init__(**kwargs) self.data = [{'text': str(x)} for x in range(100)]
class RV(RecycleView):
def __init__(self, **kwargs): super(RV, self).__init__(**kwargs) self.data = [{'text': str(x)} for x in range(100)]
): ''' Respond to the selection of items in the view. ''' self.selected = is_selected if is_selected: print("selection changed to {0}".format(rv.data[index])) else: print("selection removed for {0}".format(rv.data[index])) class RV(RecycleView):
63
64
45
6
57
AlexCaranha/MyLauncher
examples/recycle_view_example2.py
Python
RV
RV
66
69
66
66
165a323b4b6f5b389d13268f0f8bb06faebc6d76
bigcode/the-stack
train
a7129179552ed8bf77304eaa
train
class
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): ''' Adds selection and focus behaviour to the view. '''
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout):
''' Adds selection and focus behaviour to the view. '''
default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: 'vertical' multiselect: True touch_multiselect: True ''') class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout):
64
64
32
20
44
AlexCaranha/MyLauncher
examples/recycle_view_example2.py
Python
SelectableRecycleBoxLayout
SelectableRecycleBoxLayout
33
35
33
34
9bb651ab8b6e5956c65d992087a777ab2e933fe4
bigcode/the-stack
train
b357728f62c80fcf8fda7678
train
class
class PageObject(six.with_metaclass(ABCMeta, object)): """Base class for page objects Classes that inherit from this class need to define the following class variables: PAGE_TITLE the title of the page; used by the default implementation of _is_current_page PAGE_URL this sho...
class PageObject(six.with_metaclass(ABCMeta, object)):
"""Base class for page objects Classes that inherit from this class need to define the following class variables: PAGE_TITLE the title of the page; used by the default implementation of _is_current_page PAGE_URL this should be the URL of the page, minus the ...
from __future__ import absolute_import, unicode_literals import time import warnings from abc import ABCMeta from contextlib import contextmanager from SeleniumLibrary.errors import ElementNotFound import robot.api from robot.libraries.BuiltIn import BuiltIn from selenium.common.exceptions import StaleElementRefere...
113
256
922
14
98
dedie/robotframework-pageobjectlibrary
PageObjectLibrary/pageobject.py
Python
PageObject
PageObject
22
134
22
22
13ae6f3e7cb45fb87fbe3c19f2f27f04e3ebcf1f
bigcode/the-stack
train
4d936b77cbaba6c1268e1500
train
function
def product(product_id): product = Product.query.filter_by(id=product_id).first() or abort( 404, "produto nao encontrado" ) return render_template("product.html", product=product)
def product(product_id):
product = Product.query.filter_by(id=product_id).first() or abort( 404, "produto nao encontrado" ) return render_template("product.html", product=product)
from flask import abort, render_template from flask_simplelogin import login_required from flask_rest_experiments.models import Product def index(): products = Product.query.all() return render_template("index.html", products=products) def product(product_id):
53
64
45
5
48
knopperman/flask-rest-experiments
flask_rest_experiments/ext/webui/views.py
Python
product
product
12
16
12
12
53be64c4731b95fb93e98a6dc99918a38b56fc44
bigcode/the-stack
train
53ba59c1993abfda9a98070b
train
function
@login_required def secret(): return "This can be seen only if user is logged in"
@login_required def secret():
return "This can be seen only if user is logged in"
() return render_template("index.html", products=products) def product(product_id): product = Product.query.filter_by(id=product_id).first() or abort( 404, "produto nao encontrado" ) return render_template("product.html", product=product) @login_required def secret():
64
64
20
6
58
knopperman/flask-rest-experiments
flask_rest_experiments/ext/webui/views.py
Python
secret
secret
19
21
19
20
02499d3461b7d8736e3f4556abc0c7a98fe1e609
bigcode/the-stack
train
f468673599d22d581256f4ca
train
function
@login_required(username="admin") def only_admin(): return "only admin user can see this text"
@login_required(username="admin") def only_admin():
return "only admin user can see this text"
_by(id=product_id).first() or abort( 404, "produto nao encontrado" ) return render_template("product.html", product=product) @login_required def secret(): return "This can be seen only if user is logged in" @login_required(username="admin") def only_admin():
64
64
21
10
54
knopperman/flask-rest-experiments
flask_rest_experiments/ext/webui/views.py
Python
only_admin
only_admin
24
26
24
25
c9c8279ff10206cdf0ddbbeaeb0b4505fc79057f
bigcode/the-stack
train
708d90d91bc7a1a4266a508c
train
function
def index(): products = Product.query.all() return render_template("index.html", products=products)
def index():
products = Product.query.all() return render_template("index.html", products=products)
from flask import abort, render_template from flask_simplelogin import login_required from flask_rest_experiments.models import Product def index():
29
64
22
3
25
knopperman/flask-rest-experiments
flask_rest_experiments/ext/webui/views.py
Python
index
index
7
9
7
7
b19f2e1af258127a845f64d1ffa7bae451eaf555
bigcode/the-stack
train
cee3afa65d46fe4d89071fa5
train
function
def zp_list_xanes2d(e_list,mot1,x_s,x_e,x_num,mot2,y_s,y_e,y_num,accq_t): realE_list = [] scanid_list = [] ic_0 = sclr2_ch4.get() zpssx_i = zpssx.position zpssy_i = zpssy.position for i in range (len(e_list)): yield from bps.mov(e,e_list[i][0]) yield from bps.sleep(1) ...
def zp_list_xanes2d(e_list,mot1,x_s,x_e,x_num,mot2,y_s,y_e,y_num,accq_t):
realE_list = [] scanid_list = [] ic_0 = sclr2_ch4.get() zpssx_i = zpssx.position zpssy_i = zpssy.position for i in range (len(e_list)): yield from bps.mov(e,e_list[i][0]) yield from bps.sleep(1) yield from bps.mov(ugap, e_list[i][1]) yield from bps.sleep(1) ...
_e_crl= 10 low_e_crl = 8 crl_slope = (high_e_crl - low_e_crl)/(high_e-low_e) crl_list = high_e_crl + (energies - high_e)*crl_slope zpz1_ref = -34.186 energy_ref = 11.34 zpz1_slope = -5.9 zpz1_list = zpz1_ref + (energies - energy_ref)*zpz1_slope e_list = np.column_stack((energies,ugap_list,zpz1_list,crl_list)) #e_lis...
173
173
577
33
140
ahaibof/NSLS-II-HXNs
startup/XANES_Macros/Hf_L1_xanes_2d.py
Python
zp_list_xanes2d
zp_list_xanes2d
35
88
35
36
9bc04634b1cfc766370b75c44dbb28318b8fbbbe
bigcode/the-stack
train
c61a6567d7ad2ef12085c0d0
train
function
def plateau(array, threshold): """Find plateaus in an array, i.e continuous regions that exceed threshold Given an array of numbers, return a 2d array such that out[:,0] marks the indices where the array crosses threshold from below, and out[:,1] marks the next time the array crosses that same thres...
def plateau(array, threshold):
"""Find plateaus in an array, i.e continuous regions that exceed threshold Given an array of numbers, return a 2d array such that out[:,0] marks the indices where the array crosses threshold from below, and out[:,1] marks the next time the array crosses that same threshold from below. Inputs: ...
np.arange(epoch, outlierTimes[-1] + 0.5*period, period) notOutliers = [] for i in range(len(outlierTimes)): if np.any((abs(possibleTimes - outlierTimes[i]) < precision_days)): notOutliers.append(i) singleOutlierIndices = np.delete(singleOutlierIndices, notOutliers) ...
129
129
432
6
122
barentsen/dave
blsCode/outlier_detection.py
Python
plateau
plateau
99
136
99
99
96de8cf2a67a336e93cd3e6e58525b4040a9a124
bigcode/the-stack
train
9ff7e35664d52aa8ef7995c7
train
function
def medianDetrend(flux, binWidth): halfNumPoints = int(binWidth // 2) medians = np.array([]) for i in range(len(flux)): if i < halfNumPoints: medians = np.r_[medians, np.atleast_1d(np.median(flux[:i+halfNumPoints+1]))] elif i > len(flux) - halfNumPoints - 1: medians =...
def medianDetrend(flux, binWidth):
halfNumPoints = int(binWidth // 2) medians = np.array([]) for i in range(len(flux)): if i < halfNumPoints: medians = np.r_[medians, np.atleast_1d(np.median(flux[:i+halfNumPoints+1]))] elif i > len(flux) - halfNumPoints - 1: medians = np.r_[medians, np.atleast_1d(np.me...
division, print_function import numpy as np """ @TODO: We should have one, and only one, median detrend function Same for plateau function Add docstrings Should this belong to a general "lightcurve maniuplation module"? """ def medianDetrend(flux, binWidth):
63
64
164
10
53
barentsen/dave
blsCode/outlier_detection.py
Python
medianDetrend
medianDetrend
19
29
19
19
ed3f566706cac0f7eefeab08086ea73bad6007bc
bigcode/the-stack
train
55cd8d906542a9732b88e512
train
function
def outlierRemoval(time, flux, precision_days=0.0205, threshold_sigma=4): """ Remove single point outliers. Preserves consecutive outliers, and those that are evenly spaced in time. This protects short duration transits. Inputs: ------------ time, flux (1d numpy array) Input data. ...
def outlierRemoval(time, flux, precision_days=0.0205, threshold_sigma=4):
""" Remove single point outliers. Preserves consecutive outliers, and those that are evenly spaced in time. This protects short duration transits. Inputs: ------------ time, flux (1d numpy array) Input data. Flux should have mean (or median) value of zero precision_days...
to a general "lightcurve maniuplation module"? """ def medianDetrend(flux, binWidth): halfNumPoints = int(binWidth // 2) medians = np.array([]) for i in range(len(flux)): if i < halfNumPoints: medians = np.r_[medians, np.atleast_1d(np.median(flux[:i+halfNumPoints+1]))] eli...
199
199
665
21
177
barentsen/dave
blsCode/outlier_detection.py
Python
outlierRemoval
outlierRemoval
33
96
33
33
c5e4a12a4a764f52eea2433105cfd06c18e63775
bigcode/the-stack
train
d3dd9a44695c459f38c8a002
train
function
async def check_botlog_chatid(): if not BOTLOG_CHATID and LOGSPAMMER: LOGS.info( "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work." ) quit(1) elif not BOTLOG_CHATID and BOTLOG: LOGS.info...
async def check_botlog_chatid():
if not BOTLOG_CHATID and LOGSPAMMER: LOGS.info( "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work." ) quit(1) elif not BOTLOG_CHATID and BOTLOG: LOGS.info( "You must set up th...
if STRING_SESSION: # pylint: disable=invalid-name bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH) else: # pylint: disable=invalid-name bot = TelegramClient("userbot", API_KEY, API_HASH) async def check_botlog_chatid():
64
64
192
8
56
phani997/Userbot1
userbot/__init__.py
Python
check_botlog_chatid
check_botlog_chatid
160
181
160
160
a561ae0bc72bf3b34053192af4ec4bc36ea9ff3e
bigcode/the-stack
train
6490a8d86b099c4660be08b1
train
function
@app.route('/predicted', methods=['POST']) def predict(): ''' For rendering results on HTML GUI ''' int_features = [int(float(x)) for x in request.form.values()] final_features = [np.array(int_features)] prediction = model.predict(final_features) output = np.round(prediction[0], 2) ret...
@app.route('/predicted', methods=['POST']) def predict():
''' For rendering results on HTML GUI ''' int_features = [int(float(x)) for x in request.form.values()] final_features = [np.array(int_features)] prediction = model.predict(final_features) output = np.round(prediction[0], 2) return render_template('bp.html', prediction_text='Your Blood...
flask import Flask, request, render_template import pickle app = Flask(__name__,template_folder='html') model = pickle.load(open('model.pkl', 'rb')) @app.route('/') def home(): return render_template('bp.html') @app.route('/predicted', methods=['POST']) def predict():
63
64
97
13
50
FutureCoderme/week5_heroku
app.py
Python
predict
predict
17
28
17
18
ceb8a958f1c951c22c413b90ad315a2fb089ce1b
bigcode/the-stack
train
31687533086f8b064936f5a5
train
function
@app.route('/') def home(): return render_template('bp.html')
@app.route('/') def home():
return render_template('bp.html')
# -*- coding: utf-8 -*- import numpy as np from flask import Flask, request, render_template import pickle app = Flask(__name__,template_folder='html') model = pickle.load(open('model.pkl', 'rb')) @app.route('/') def home():
55
64
14
6
49
FutureCoderme/week5_heroku
app.py
Python
home
home
11
13
11
12
292a3434d8e4dec06690e433df75b20c4174690a
bigcode/the-stack
train
3a0c5e6b13a32ab6e534d9cf
train
class
class pget_bugTestCase(unittest.TestCase): """Verify that cursor.pget works properly""" db_name = 'test-cursor_pget.db' def setUp(self): self.homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') try: os.mkdir(self.homeDir) except os.error: pass ...
class pget_bugTestCase(unittest.TestCase):
"""Verify that cursor.pget works properly""" db_name = 'test-cursor_pget.db' def setUp(self): self.homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') try: os.mkdir(self.homeDir) except os.error: pass self.env = db.DBEnv() self.env...
import unittest import sys, os, glob try: # For Pythons w/distutils pybsddb from bsddb3 import db except ImportError: # For Python 2.3 from bsddb import db #---------------------------------------------------------------------- class pget_bugTestCase(unittest.TestCase):
66
127
424
10
55
jasonadu/Python-2.5
Lib/bsddb/test/test_cursor_pget_bug.py
Python
pget_bugTestCase
pget_bugTestCase
14
58
14
14
101b7aea826d3fe0a624175b3496c9b71816ad7b
bigcode/the-stack
train
a092dcbf2ca98d4990562f54
train
function
def test_suite(): return unittest.makeSuite(pget_bugTestCase)
def test_suite():
return unittest.makeSuite(pget_bugTestCase)
)) self.assertEquals(None, cursor.pget(db.DB_NEXT_DUP)) self.assertEquals(('ham', 'spam', 'ham'), cursor.pget('ham', 'spam', flags=db.DB_SET)) self.assertEquals(None, cursor.pget(db.DB_NEXT_DUP)) cursor.close() def test_suite():
64
64
15
4
60
jasonadu/Python-2.5
Lib/bsddb/test/test_cursor_pget_bug.py
Python
test_suite
test_suite
61
62
61
61
f2d8e5d9d2cef6f97e358eb445b7331465f9c925
bigcode/the-stack
train
a7d37ebeb44508039758f4f5
train
class
class AvailableDelegationsOperations: """AvailableDelegationsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operati...
class AvailableDelegationsOperations:
"""AvailableDelegationsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgm...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
211
255
852
6
205
rsdoherty/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_10_01/aio/operations/_available_delegations_operations.py
Python
AvailableDelegationsOperations
AvailableDelegationsOperations
22
112
22
22
3c0754f7e9ef33fd33ec5507fbbe1d35dba4e939
bigcode/the-stack
train
c325828b55b23b74c4cf9c8f
train
function
def make_shadows(shadow_dir, executables): """Makes shadow copies of the fpp executables The PIP sdist package must be aware of the names and paths of installed FPP executables, even though they are downloaded during the install phase (on client). Thus this function when run with touch_only creates 0-size ...
def make_shadows(shadow_dir, executables):
"""Makes shadow copies of the fpp executables The PIP sdist package must be aware of the names and paths of installed FPP executables, even though they are downloaded during the install phase (on client). Thus this function when run with touch_only creates 0-size file "shadows" of the files for the dis...
.sdist import sdist from setuptools.command.install import install from fprime_fpp.fprime_fpp_install import clean_install_fpp, clean_at_exit, WORKING_DIR SHADOW_DIR = Path("__SHADOW__") SHADOW_CACHE = None def make_shadows(shadow_dir, executables):
64
64
157
11
52
LeStarch/fpp
setup.py
Python
make_shadows
make_shadows
22
35
22
22
172b54cb766b8206b229b845c662afc02c85c323
bigcode/the-stack
train
173b5b7e25fdd4940c2f1e71
train
class
class TestDeepengineAdaptor(unittest.TestCase): def setUp(self): build_yaml() def test_adaptor(self): quantizer = Quantization('test.yaml') quantizer.model = "/home/tensorflow/inc_ut/engine/bert_mlperf_2none.pb" q_model = quantizer.fit() self.assertNotEqual(q_model, None...
class TestDeepengineAdaptor(unittest.TestCase):
def setUp(self): build_yaml() def test_adaptor(self): quantizer = Quantization('test.yaml') quantizer.model = "/home/tensorflow/inc_ut/engine/bert_mlperf_2none.pb" q_model = quantizer.fit() self.assertNotEqual(q_model, None) def test_adaptor_bf16(self): quan...
, int32, float32] tuning: exit_policy: max_trials: 1 """ with open("test_bf16.yaml", "w", encoding="utf-8") as f: f.write(fake_yaml_bf16) class TestDeepengineAdaptor(unittest.TestCase):
64
64
164
9
55
huggingface/neural-compressor
test/engine/test_adaptor_engine.py
Python
TestDeepengineAdaptor
TestDeepengineAdaptor
120
138
120
120
09a3451e068a237ed3eea85cab3b1ef72e1358e0
bigcode/the-stack
train
6d40a06957454dbe51fbb58e
train
function
def build_yaml(): fake_yaml = """ model: name: bert framework: engine quantization: calibration: sampling_size: 10 dataloader: dataset: dummy_v2: input_shape: [[324], [324], [324]] ...
def build_yaml():
fake_yaml = """ model: name: bert framework: engine quantization: calibration: sampling_size: 10 dataloader: dataset: dummy_v2: input_shape: [[324], [324], [324]] label_shape: [324...
import sys import os import unittest import numpy as np from neural_compressor.experimental import Quantization, Benchmark, common from neural_compressor.model.engine_model import EngineModel from neural_compressor.data import DATASETS def build_yaml():
51
256
855
4
46
huggingface/neural-compressor
test/engine/test_adaptor_engine.py
Python
build_yaml
build_yaml
9
117
9
9
73e465a3c7c3abe04d41da77375accda47e71b56
bigcode/the-stack
train
e4f6be8e7465cf7c408c41ba
train
class
class FusionModel(BaseModel): def name(self): return 'FusionModel' @staticmethod def modify_commandline_options(parser, is_train=True): return parser def initialize(self, opt): BaseModel.initialize(self, opt) self.model_names = ['G', 'GF'] # load/de...
class FusionModel(BaseModel):
def name(self): return 'FusionModel' @staticmethod def modify_commandline_options(parser, is_train=True): return parser def initialize(self, opt): BaseModel.initialize(self, opt) self.model_names = ['G', 'GF'] # load/define networks num_in =...
import os import torch from collections import OrderedDict from util.image_pool import ImagePool from util import util from .base_model import BaseModel from . import networks import numpy as np from skimage import io from skimage import img_as_ubyte import matplotlib.pyplot as plt import math from matp...
79
256
1,331
6
72
paepcke/InstColorization
models/fusion_model.py
Python
FusionModel
FusionModel
18
128
18
18
6443c725547cd64c2fded2ca748ef6c159092f45
bigcode/the-stack
train
e62056b0ea7ee8dc7a870fde
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,...
class Migration(migrations.Migration):
initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
# Generated by Django 3.1 on 2021-03-01 12:27 from django.db import migrations, models class Migration(migrations.Migration):
36
92
309
7
28
rohitit09/stores
store/app/core/migrations/0001_initial.py
Python
Migration
Migration
6
33
6
7
472b47e22824178e5c067693e5d70bdb7f180fe8
bigcode/the-stack
train
b35c5a24651f055dca5fc38f
train
class
class BaseEvaluator(object): def __init__(self, params_file, finetunee_script, options_str=""): with io.open(params_file, 'r', encoding='utf8') as f: self.params = yaml.safe_load(f) self.finetunee_script = finetunee_script self.model_rewards = {} self.options_str = option...
class BaseEvaluator(object):
def __init__(self, params_file, finetunee_script, options_str=""): with io.open(params_file, 'r', encoding='utf8') as f: self.params = yaml.safe_load(f) self.finetunee_script = finetunee_script self.model_rewards = {} self.options_str = options_str def get_init_param...
.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # ...
204
204
680
5
199
MRXLT/PaddleHub
paddlehub/autofinetune/evaluator.py
Python
BaseEvaluator
BaseEvaluator
38
108
38
38
683455d772adc55872d8bae63781e2630df100ed
bigcode/the-stack
train