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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a376b2276bc5a9456ea1fc8b | train | function | def compile_copyright_regex(copyright_style, year_style, name):
return re.compile('%s %s %s' % (copyright_style, year_style, name))
| def compile_copyright_regex(copyright_style, year_style, name):
| return re.compile('%s %s %s' % (copyright_style, year_style, name))
| (YEAR_RANGE, YEAR_LIST)
ANY_COPYRIGHT_STYLE_OR_YEAR_STYLE = ("%s %s" % (ANY_COPYRIGHT_STYLE,
ANY_YEAR_STYLE))
ANY_COPYRIGHT_COMPILED = re.compile(ANY_COPYRIGHT_STYLE_OR_YEAR_STYLE)
def compile_copyright_regex(copyright_style, year_style, name):
| 64 | 64 | 35 | 14 | 50 | adnetcoin/adnetcoin | contrib/devtools/copyright_header.py | Python | compile_copyright_regex | compile_copyright_regex | 81 | 82 | 81 | 81 | 5411bb081a899acde3acef295b0a3ab1dd8ac85c | bigcode/the-stack | train |
3e73503c43da71ce30799d88 | train | function | def insert_cpp_header(filename, file_lines, start_year, end_year):
header_lines = get_cpp_header_lines_to_insert(start_year, end_year)
for line in header_lines:
file_lines.insert(0, line)
write_file_lines(filename, file_lines)
| def insert_cpp_header(filename, file_lines, start_year, end_year):
| header_lines = get_cpp_header_lines_to_insert(start_year, end_year)
for line in header_lines:
file_lines.insert(0, line)
write_file_lines(filename, file_lines)
| :
insert_idx = 0
header_lines = get_python_header_lines_to_insert(start_year, end_year)
for line in header_lines:
file_lines.insert(insert_idx, line)
write_file_lines(filename, file_lines)
def insert_cpp_header(filename, file_lines, start_year, end_year):
| 64 | 64 | 56 | 15 | 49 | adnetcoin/adnetcoin | contrib/devtools/copyright_header.py | Python | insert_cpp_header | insert_cpp_header | 515 | 519 | 515 | 515 | b4116632c7cfb822aa8d7143964dfcb5bc194f23 | bigcode/the-stack | train |
02501b98cf831ff3252ccc1a | train | function | def file_has_year_list_style_copyright_for_holder(contents, holder_name):
match = YEAR_LIST_STYLE_COMPILED[holder_name].search(contents)
return match is not None
| def file_has_year_list_style_copyright_for_holder(contents, holder_name):
| match = YEAR_LIST_STYLE_COMPILED[holder_name].search(contents)
return match is not None
| ANY_COPYRIGHT_COMPILED.findall(contents))
def file_has_dominant_style_copyright_for_holder(contents, holder_name):
match = DOMINANT_STYLE_COMPILED[holder_name].search(contents)
return match is not None
def file_has_year_list_style_copyright_for_holder(contents, holder_name):
| 64 | 64 | 38 | 15 | 48 | adnetcoin/adnetcoin | contrib/devtools/copyright_header.py | Python | file_has_year_list_style_copyright_for_holder | file_has_year_list_style_copyright_for_holder | 134 | 136 | 134 | 134 | 7eb78cb34faab3f414b628bb73957c2a26ccadce | bigcode/the-stack | train |
31549b980b8e4c634187a3e9 | train | function | def get_count_of_copyrights_of_any_style_any_holder(contents):
return len(ANY_COPYRIGHT_COMPILED.findall(contents))
| def get_count_of_copyrights_of_any_style_any_holder(contents):
| return len(ANY_COPYRIGHT_COMPILED.findall(contents))
| _name))
WITHOUT_C_STYLE_COMPILED[holder_name] = (
compile_copyright_regex(COPYRIGHT_WITHOUT_C, ANY_YEAR_STYLE,
holder_name))
################################################################################
# search file contents for copyright message of particular category
#... | 64 | 64 | 27 | 14 | 49 | adnetcoin/adnetcoin | contrib/devtools/copyright_header.py | Python | get_count_of_copyrights_of_any_style_any_holder | get_count_of_copyrights_of_any_style_any_holder | 127 | 128 | 127 | 127 | 400ba2ce041f0da894cdab78867e92792675aa6a | bigcode/the-stack | train |
2e53422d23c405a8e0ad94b7 | train | function | def get_header_lines(header, start_year, end_year):
lines = header.split('\n')[1:-1]
lines[0] = lines[0] % year_range_to_str(start_year, end_year)
return [line + '\n' for line in lines]
| def get_header_lines(header, start_year, end_year):
| lines = header.split('\n')[1:-1]
lines[0] = lines[0] % year_range_to_str(start_year, end_year)
return [line + '\n' for line in lines]
| )
base_directory = argv[2]
if not os.path.exists(base_directory):
sys.exit("*** bad base_directory: %s" % base_directory)
exec_update_header_year(base_directory)
################################################################################
# inserted copyright header format
################... | 64 | 64 | 58 | 12 | 51 | adnetcoin/adnetcoin | contrib/devtools/copyright_header.py | Python | get_header_lines | get_header_lines | 455 | 458 | 455 | 455 | 63ba3663d9cfde7973e51a77f50f88f06473174a | bigcode/the-stack | train |
880d11df4864140b316da616 | train | function | def year_range_to_str(start_year, end_year):
if start_year == end_year:
return start_year
return "%s-%s" % (start_year, end_year)
| def year_range_to_str(start_year, end_year):
| if start_year == end_year:
return start_year
return "%s-%s" % (start_year, end_year)
| def parse_year_range(year_range):
year_split = year_range.split('-')
start_year = year_split[0]
if len(year_split) == 1:
return start_year, start_year
return start_year, year_split[1]
def year_range_to_str(start_year, end_year):
| 64 | 64 | 39 | 11 | 53 | adnetcoin/adnetcoin | contrib/devtools/copyright_header.py | Python | year_range_to_str | year_range_to_str | 361 | 364 | 361 | 361 | aee12221735e46f41bcd0110600c3288964cfee7 | bigcode/the-stack | train |
4ba630aaef469e19f1cab0c1 | train | function | def get_python_header_lines_to_insert(start_year, end_year):
return reversed(get_header_lines(PYTHON_HEADER, start_year, end_year))
| def get_python_header_lines_to_insert(start_year, end_year):
| return reversed(get_header_lines(PYTHON_HEADER, start_year, end_year))
| start_year, end_year))
PYTHON_HEADER = '''
# Copyright (c) %s The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
def get_python_header_lines_to_insert(start_year, end_year):
| 64 | 64 | 30 | 13 | 51 | adnetcoin/adnetcoin | contrib/devtools/copyright_header.py | Python | get_python_header_lines_to_insert | get_python_header_lines_to_insert | 475 | 476 | 475 | 475 | 46041f410bb3648285612ca8f927d1ecdf13bfcc | bigcode/the-stack | train |
82c453bcb8562ec197054e14 | train | function | def get_git_change_year_range(filename):
years = get_git_change_years(filename)
return min(years), max(years)
| def get_git_change_year_range(filename):
| years = get_git_change_years(filename)
return min(years), max(years)
| or http://www.opensource.org/licenses/mit-license.php.
'''
def get_python_header_lines_to_insert(start_year, end_year):
return reversed(get_header_lines(PYTHON_HEADER, start_year, end_year))
################################################################################
# query git for year of last change
#####... | 64 | 64 | 28 | 8 | 55 | adnetcoin/adnetcoin | contrib/devtools/copyright_header.py | Python | get_git_change_year_range | get_git_change_year_range | 482 | 484 | 482 | 482 | 24c74925fe822f868a271175de3cac86f5b06992 | bigcode/the-stack | train |
304c4009111f8ad4ef32b480 | train | function | def movies_list(response):
"""Lists all movies"""
movies = Movie.objects.all().order_by('director__first_name')
return render(response, 'list.html', {'movies': movies})
| def movies_list(response):
| """Lists all movies"""
movies = Movie.objects.all().order_by('director__first_name')
return render(response, 'list.html', {'movies': movies})
| """Movies app views"""
from django.shortcuts import render, get_object_or_404
from .models import Movie
def movies_list(response):
| 28 | 64 | 40 | 5 | 22 | bernest/modulo-django-desarrollo-web-cdmx-20-05pt | sesion_02/movies/views.py | Python | movies_list | movies_list | 8 | 11 | 8 | 8 | 62ed113bbadff6566f711c64a717a50f17654db7 | bigcode/the-stack | train |
21c62bd7790c4d0689cd413c | train | function | def movies_detail(response, pk):
"""Gets movie detail"""
movie = get_object_or_404(Movie, pk=pk)
return render(response, 'detail.html', {'movie': movie})
| def movies_detail(response, pk):
| """Gets movie detail"""
movie = get_object_or_404(Movie, pk=pk)
return render(response, 'detail.html', {'movie': movie})
| django.shortcuts import render, get_object_or_404
from .models import Movie
def movies_list(response):
"""Lists all movies"""
movies = Movie.objects.all().order_by('director__first_name')
return render(response, 'list.html', {'movies': movies})
def movies_detail(response, pk):
| 64 | 64 | 41 | 7 | 57 | bernest/modulo-django-desarrollo-web-cdmx-20-05pt | sesion_02/movies/views.py | Python | movies_detail | movies_detail | 14 | 17 | 14 | 14 | e04e8765e751986e6f5379ddbdf08a19e9d1d2f0 | bigcode/the-stack | train |
3f7f6caee08906a469ea7964 | train | class | class MDBottomNavigationHeader(BaseFlatButton, BasePressedButton):
panel_color = ListProperty([1, 1, 1, 0])
width = BoundedNumericProperty(
dp(0),
min=dp(80),
max=dp(168),
errorhandler=lambda x: small_error_warn(x),
)
tab = ObjectProperty()
panel = ObjectProperty()
... | class MDBottomNavigationHeader(BaseFlatButton, BasePressedButton):
| panel_color = ListProperty([1, 1, 1, 0])
width = BoundedNumericProperty(
dp(0),
min=dp(80),
max=dp(168),
errorhandler=lambda x: small_error_warn(x),
)
tab = ObjectProperty()
panel = ObjectProperty()
active = BooleanProperty(False)
text = StringProperty()
... | than the minimum size "
# f"of 80dp for a MDBottomNavigationItem. "
# f"We must now expand to 168dp."
# )
# Did you come here to find out what the bug is?
# The bug is that on startup, this function returning dp(80)
# breaks the way it displ... | 116 | 116 | 387 | 13 | 103 | gottadiveintopython/KivyMD | kivymd/uix/bottomnavigation.py | Python | MDBottomNavigationHeader | MDBottomNavigationHeader | 247 | 295 | 247 | 247 | f73c7c3dcb24dfb90bc60799a6bf929fe39be487 | bigcode/the-stack | train |
fc9ce9400220ab343682cdf7 | train | function | def small_error_warn(x):
if dp(x) <= dp(80):
if MDBottomNavigationErrorCache.last_size_warning != x:
MDBottomNavigationErrorCache.last_size_warning = x
# Logger.warning(
# f"MDBottomNavigation: {x}dp is less than the minimum size "
# f"of 80dp for a MDBo... | def small_error_warn(x):
| if dp(x) <= dp(80):
if MDBottomNavigationErrorCache.last_size_warning != x:
MDBottomNavigationErrorCache.last_size_warning = x
# Logger.warning(
# f"MDBottomNavigation: {x}dp is less than the minimum size "
# f"of 80dp for a MDBottomNavigationItem. "
... | _normal
Rectangle:
size: root.size
"""
)
class MDBottomNavigationBar(
ThemableBehavior,
BackgroundColorBehavior,
FloatLayout,
RectangularElevationBehavior,
):
pass
class MDBottomNavigationErrorCache:
last_size_warning = 0
def small_error_warn(x):
| 64 | 64 | 164 | 6 | 57 | gottadiveintopython/KivyMD | kivymd/uix/bottomnavigation.py | Python | small_error_warn | small_error_warn | 231 | 244 | 231 | 231 | 6f747441698c54bdaad194f8578bd6e0f9b91921 | bigcode/the-stack | train |
adb137439545d462c727493c | train | class | class TabbedPanelBase(
ThemableBehavior, SpecificBackgroundColorBehavior, BoxLayout
):
"""
A class that contains all variables a TabPannel must have
It is here so I (zingballyhoo) don't get mad about
the TabbedPannels not being DRY.
"""
tabs = ListProperty()
# Current tab name
cur... | class TabbedPanelBase(
ThemableBehavior, SpecificBackgroundColorBehavior, BoxLayout
):
| """
A class that contains all variables a TabPannel must have
It is here so I (zingballyhoo) don't get mad about
the TabbedPannels not being DRY.
"""
tabs = ListProperty()
# Current tab name
current = StringProperty(None)
previous_tab = ObjectProperty()
panel_color = ListPro... | ,
).start(par.previous_tab.header)
par.previous_tab.header.active = False
self.header.active = True
par.previous_tab = self
def on_leave(self, *args):
pass
class TabbedPanelBase(
ThemableBehavior, SpecificBackgroundColorBehavior, BoxLayout
):
| 64 | 64 | 99 | 20 | 43 | gottadiveintopython/KivyMD | kivymd/uix/bottomnavigation.py | Python | TabbedPanelBase | TabbedPanelBase | 381 | 398 | 381 | 383 | 67f03fbd83585050bf2ff25d7d7d3ed25d311d91 | bigcode/the-stack | train |
e6ddea95955c296b833b28ef | train | class | class MDBottomNavigationItem(MDTab):
header = ObjectProperty()
def on_tab_press(self, *args):
par = self.parent_widget
par.ids.tab_manager.current = self.name
if par.previous_tab is not self:
Animation(_label_font_size=sp(12), d=0.1).start(
par.previous_tab.h... | class MDBottomNavigationItem(MDTab):
| header = ObjectProperty()
def on_tab_press(self, *args):
par = self.parent_widget
par.ids.tab_manager.current = self.name
if par.previous_tab is not self:
Animation(_label_font_size=sp(12), d=0.1).start(
par.previous_tab.header
)
Anima... | par.ids.tab_manager.current = self.name
par.previous_tab = self
def on_tab_release(self, *args):
pass
def __repr__(self):
return f"<MDTab name='{self.name}', text='{self.text}'>"
class MDBottomNavigationItem(MDTab):
| 64 | 64 | 147 | 9 | 54 | gottadiveintopython/KivyMD | kivymd/uix/bottomnavigation.py | Python | MDBottomNavigationItem | MDBottomNavigationItem | 359 | 378 | 359 | 359 | e676738d6f96b009c5dfedd00414ac2994e357b8 | bigcode/the-stack | train |
d5d7a669467136027e131e9b | train | class | class MDBottomNavigationBar(
ThemableBehavior,
BackgroundColorBehavior,
FloatLayout,
RectangularElevationBehavior,
):
pass
| class MDBottomNavigationBar(
ThemableBehavior,
BackgroundColorBehavior,
FloatLayout,
RectangularElevationBehavior,
):
| pass
| 'center_y': .6}
<MDTab>
canvas:
Color:
rgba: root.theme_cls.bg_normal
Rectangle:
size: root.size
"""
)
class MDBottomNavigationBar(
ThemableBehavior,
BackgroundColorBehavior,
FloatLayout,
RectangularElevationBehavior,
):
| 64 | 64 | 30 | 27 | 37 | gottadiveintopython/KivyMD | kivymd/uix/bottomnavigation.py | Python | MDBottomNavigationBar | MDBottomNavigationBar | 218 | 224 | 218 | 223 | 3b44adfa7c6f9b90d2248a64f02c3f4a8bff81bd | bigcode/the-stack | train |
086e102c915c450254dd308b | train | class | class MDBottomNavigationErrorCache:
last_size_warning = 0
| class MDBottomNavigationErrorCache:
| last_size_warning = 0
| >
canvas:
Color:
rgba: root.theme_cls.bg_normal
Rectangle:
size: root.size
"""
)
class MDBottomNavigationBar(
ThemableBehavior,
BackgroundColorBehavior,
FloatLayout,
RectangularElevationBehavior,
):
pass
class MDBottomNavigationErrorCache:
| 64 | 64 | 15 | 7 | 56 | gottadiveintopython/KivyMD | kivymd/uix/bottomnavigation.py | Python | MDBottomNavigationErrorCache | MDBottomNavigationErrorCache | 227 | 228 | 227 | 227 | fb014048c03013522de112488dcfdea11bb085fc | bigcode/the-stack | train |
e36e36e536848dd360b2a987 | train | class | class MDTab(Screen, ThemableBehavior):
""" A tab is simply a screen with meta information
that defines the content that goes in the tab header.
"""
__events__ = (
"on_tab_touch_down",
"on_tab_touch_move",
"on_tab_touch_up",
"on_tab_press",
"on_tab_release",
... | class MDTab(Screen, ThemableBehavior):
| """ A tab is simply a screen with meta information
that defines the content that goes in the tab header.
"""
__events__ = (
"on_tab_touch_down",
"on_tab_touch_move",
"on_tab_touch_up",
"on_tab_press",
"on_tab_release",
)
# Tab header text
text = ... | (self):
Animation(_label_font_size=sp(14), d=0.1).start(self)
Animation(_current_color=self.theme_cls.primary_color, d=0.1).start(
self
)
def _update_theme_color(self, instance, color):
if self.active:
self._current_color = self.theme_cls.primary_color
d... | 116 | 116 | 388 | 9 | 106 | gottadiveintopython/KivyMD | kivymd/uix/bottomnavigation.py | Python | MDTab | MDTab | 298 | 356 | 298 | 298 | 99164c719c031ab1bc112b9b1f7fe3dc26e01aaf | bigcode/the-stack | train |
a3d95ab93f7f9d6c5fb57218 | train | class | class MDBottomNavigation(TabbedPanelBase):
""" A bottom navigation that is implemented by delegating
all items to a ScreenManager."""
first_widget = ObjectProperty()
tab_header = None
def on_panel_color(self, instance, value):
self.tab_header.panel_color = value
def __init__(self, **... | class MDBottomNavigation(TabbedPanelBase):
| """ A bottom navigation that is implemented by delegating
all items to a ScreenManager."""
first_widget = ObjectProperty()
tab_header = None
def on_panel_color(self, instance, value):
self.tab_header.panel_color = value
def __init__(self, **kwargs):
super().__init__(**kwargs)... | 1).start(
par.previous_tab.header
)
Animation(
_current_color=par.previous_tab.header.theme_cls.disabled_hint_text_color,
d=0.1,
).start(par.previous_tab.header)
par.previous_tab.header.active = False
self.header... | 189 | 189 | 631 | 9 | 180 | gottadiveintopython/KivyMD | kivymd/uix/bottomnavigation.py | Python | MDBottomNavigation | MDBottomNavigation | 401 | 489 | 401 | 401 | 771345348d35d24088b982f85374812e04b9f74d | bigcode/the-stack | train |
835b9825be187b1c6e3aa458 | train | class | class UserFavSerializer(serializers.ModelSerializer):
"""用户收藏的序列化函数"""
user = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
class Meta:
model = UserFav
validators = [
UniqueTogetherValidator(
queryset=UserFav.objects.all(),
... | class UserFavSerializer(serializers.ModelSerializer):
| """用户收藏的序列化函数"""
user = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
class Meta:
model = UserFav
validators = [
UniqueTogetherValidator(
queryset=UserFav.objects.all(),
fields=('user', 'article'),
... | from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from .models import UserFav
from apps.users.serializers import UserSerializer
class UserFavSerializer(serializers.ModelSerializer):
| 39 | 64 | 93 | 8 | 30 | Niracler/display-back-end | apps/user_operation/serializers.py | Python | UserFavSerializer | UserFavSerializer | 8 | 26 | 8 | 8 | 71b6c525970dcecf3807f6453d6f08d820c4aba4 | bigcode/the-stack | train |
b4603737649f4d123867b50e | train | function | def parse(opt_path, is_train=True):
# ----------------------------------------
# remove comments starting with '//'
# ----------------------------------------
json_str = ''
with open(opt_path, 'r') as f:
for line in f:
line = line.split('//')[0] + '\n'
json_str += li... | def parse(opt_path, is_train=True):
# ----------------------------------------
# remove comments starting with '//'
# ----------------------------------------
| json_str = ''
with open(opt_path, 'r') as f:
for line in f:
line = line.split('//')[0] + '\n'
json_str += line
# ----------------------------------------
# initialize opt
# ----------------------------------------
opt = json.loads(json_str, object_pairs_hook=Orde... | import os
from collections import OrderedDict
from datetime import datetime
import json
import re
import glob
'''
# --------------------------------------------
# Kai Zhang (github: https://github.com/cszn)
# 03/Mar/2019
# --------------------------------------------
# https://github.com/xinntao/BasicSR
# -----------... | 117 | 256 | 1,262 | 25 | 92 | hduba/KAIR | utils/utils_option.py | Python | parse | parse | 23 | 159 | 23 | 27 | 2f1886f1d2d31a8cda2eef16881cf76dbcf7a1cc | bigcode/the-stack | train |
efb6d4f544f1f46f98155c30 | train | function | def find_last_checkpoint(save_dir, opt, net_type='G'):
"""
Args:
save_dir: model folder
net_type: 'G' or 'D' or 'optimizerG' or 'optimizerD'
Return:
init_iter: iteration number
init_path: model path
"""
file_list = glob.glob(os.path.join(save_dir, '*_{}.pth'.format(... | def find_last_checkpoint(save_dir, opt, net_type='G'):
| """
Args:
save_dir: model folder
net_type: 'G' or 'D' or 'optimizerG' or 'optimizerD'
Return:
init_iter: iteration number
init_path: model path
"""
file_list = glob.glob(os.path.join(save_dir, '*_{}.pth'.format(net_type)))
if file_list:
iter_exist = []
... | in opt['netD']:
opt['netD']['n_layers'] = 3
if 'norm_type' not in opt['netD']:
opt['netD']['norm_type'] = 'spectral'
return opt
def find_last_checkpoint(save_dir, opt, net_type='G'):
| 64 | 64 | 191 | 14 | 49 | hduba/KAIR | utils/utils_option.py | Python | find_last_checkpoint | find_last_checkpoint | 162 | 183 | 162 | 162 | 7f5b93f45820c639c6284f580ea7fabf27462f81 | bigcode/the-stack | train |
0b800bc008926476c7b4767e | train | class | class NoneDict(dict):
def __missing__(self, key):
return None
| class NoneDict(dict):
| def __missing__(self, key):
return None
| sub_opt in opt.items():
new_opt[key] = dict_to_nonedict(sub_opt)
return NoneDict(**new_opt)
elif isinstance(opt, list):
return [dict_to_nonedict(sub_opt) for sub_opt in opt]
else:
return opt
class NoneDict(dict):
| 64 | 64 | 18 | 5 | 58 | hduba/KAIR | utils/utils_option.py | Python | NoneDict | NoneDict | 242 | 244 | 242 | 242 | 133465ec64f462af05f8638613c7276a32dd3358 | bigcode/the-stack | train |
8cf6ffc013e70648db2cfa99 | train | function | def get_timestamp():
return datetime.now().strftime('_%y%m%d_%H%M%S')
| def get_timestamp():
| return datetime.now().strftime('_%y%m%d_%H%M%S')
| datetime import datetime
import json
import re
import glob
'''
# --------------------------------------------
# Kai Zhang (github: https://github.com/cszn)
# 03/Mar/2019
# --------------------------------------------
# https://github.com/xinntao/BasicSR
# --------------------------------------------
'''
def get_time... | 63 | 64 | 22 | 4 | 59 | hduba/KAIR | utils/utils_option.py | Python | get_timestamp | get_timestamp | 19 | 20 | 19 | 19 | edd2fcb25a7ccc7019459608a1117cffe86ac316 | bigcode/the-stack | train |
2ec81d9988c4e86558c0e442 | train | function | def save(opt):
opt_path = opt['opt_path']
opt_path_copy = opt['path']['options']
dirname, filename_ext = os.path.split(opt_path)
filename, ext = os.path.splitext(filename_ext)
dump_path = os.path.join(opt_path_copy, filename+get_timestamp()+ext)
with open(dump_path, 'w') as dump_file:
js... | def save(opt):
| opt_path = opt['opt_path']
opt_path_copy = opt['path']['options']
dirname, filename_ext = os.path.split(opt_path)
filename, ext = os.path.splitext(filename_ext)
dump_path = os.path.join(opt_path_copy, filename+get_timestamp()+ext)
with open(dump_path, 'w') as dump_file:
json.dump(opt, du... | = os.path.join(save_dir, '{}_{}.pth'.format(init_iter, net_type))
else:
init_iter = 0
init_path = None
return init_iter, init_path
'''
# --------------------------------------------
# convert the opt into json file
# --------------------------------------------
'''
def save(opt):
| 63 | 64 | 91 | 4 | 59 | hduba/KAIR | utils/utils_option.py | Python | save | save | 193 | 200 | 193 | 193 | 15e50546afa142fda6b3a2d11b7c865fd0367190 | bigcode/the-stack | train |
de2254f0c04cdd8d64452cc6 | train | function | def dict2str(opt, indent_l=1):
msg = ''
for k, v in opt.items():
if isinstance(v, dict):
msg += ' ' * (indent_l * 2) + k + ':[\n'
msg += dict2str(v, indent_l + 1)
msg += ' ' * (indent_l * 2) + ']\n'
else:
msg += ' ' * (indent_l * 2) + k + ': ' + st... | def dict2str(opt, indent_l=1):
| msg = ''
for k, v in opt.items():
if isinstance(v, dict):
msg += ' ' * (indent_l * 2) + k + ':[\n'
msg += dict2str(v, indent_l + 1)
msg += ' ' * (indent_l * 2) + ']\n'
else:
msg += ' ' * (indent_l * 2) + k + ': ' + str(v) + '\n'
return msg
| (opt_path_copy, filename+get_timestamp()+ext)
with open(dump_path, 'w') as dump_file:
json.dump(opt, dump_file, indent=2)
'''
# --------------------------------------------
# dict to string for logger
# --------------------------------------------
'''
def dict2str(opt, indent_l=1):
| 63 | 64 | 117 | 11 | 52 | hduba/KAIR | utils/utils_option.py | Python | dict2str | dict2str | 210 | 219 | 210 | 210 | e612fc025a81bad04c6b51f251c70462f2190a6c | bigcode/the-stack | train |
f6356ff17df673c976ae9776 | train | function | def dict_to_nonedict(opt):
if isinstance(opt, dict):
new_opt = dict()
for key, sub_opt in opt.items():
new_opt[key] = dict_to_nonedict(sub_opt)
return NoneDict(**new_opt)
elif isinstance(opt, list):
return [dict_to_nonedict(sub_opt) for sub_opt in opt]
else:
... | def dict_to_nonedict(opt):
| if isinstance(opt, dict):
new_opt = dict()
for key, sub_opt in opt.items():
new_opt[key] = dict_to_nonedict(sub_opt)
return NoneDict(**new_opt)
elif isinstance(opt, list):
return [dict_to_nonedict(sub_opt) for sub_opt in opt]
else:
return opt
| else:
msg += ' ' * (indent_l * 2) + k + ': ' + str(v) + '\n'
return msg
'''
# --------------------------------------------
# convert OrderedDict to NoneDict,
# return None for missing key
# --------------------------------------------
'''
def dict_to_nonedict(opt):
| 63 | 64 | 84 | 8 | 55 | hduba/KAIR | utils/utils_option.py | Python | dict_to_nonedict | dict_to_nonedict | 230 | 239 | 230 | 230 | 02a5b99ba5b627533e12a561360ead07cce72506 | bigcode/the-stack | train |
1ee0c0f964333a9088dc155c | train | function | def simulation(fn):
newpath = fn
# path=utils.wd()+'/results/'+fn+'/'
params = utils.load_config(utils.wd() + '/utils/input.data')
# os.makedirs(path,exist_ok=True)
# copyfile(utils.wd()+'/utils/input.data',path+'_input.data')
rates = params['rates']
proteins = params['proteins']
sim_par... | def simulation(fn):
| newpath = fn
# path=utils.wd()+'/results/'+fn+'/'
params = utils.load_config(utils.wd() + '/utils/input.data')
# os.makedirs(path,exist_ok=True)
# copyfile(utils.wd()+'/utils/input.data',path+'_input.data')
rates = params['rates']
proteins = params['proteins']
sim_params = params['simula... | import importlib as port
import statevector as sv
import utils.utes as utils
k = port.import_module('kernels')
import KMC
def simulation(fn):
| 36 | 208 | 694 | 4 | 31 | jbrid867/SIMPLE | simple/simulations.py | Python | simulation | simulation | 10 | 87 | 10 | 10 | 01d62c5fdd8a031485e888c22cf862bea196dc1b | bigcode/the-stack | train |
d84b428fab428e408627a906 | train | class | class Attribute(ProvenanceObject):
"""
This class defines a dataflow attribute.
Attributes:
- name (str): Attribute name.
- type (:obj:`AttributeType`): Attribute Type.
"""
def __init__(self, tag, type):
ProvenanceObject.__init__(self, "")
self.name = tag
se... | class Attribute(ProvenanceObject):
| """
This class defines a dataflow attribute.
Attributes:
- name (str): Attribute name.
- type (:obj:`AttributeType`): Attribute Type.
"""
def __init__(self, tag, type):
ProvenanceObject.__init__(self, "")
self.name = tag
self.type = type
@property
d... | from dfa_lib_python.ProvenanceObject import ProvenanceObject
from dfa_lib_python.attribute_type import AttributeType
class Attribute(ProvenanceObject):
| 32 | 70 | 236 | 7 | 24 | vinisalazar/dfa_lib_python | dfa_lib_python/attribute.py | Python | Attribute | Attribute | 5 | 43 | 5 | 5 | 65a40c8004ba33f2422ffa7aaf03fa84a1b8662f | bigcode/the-stack | train |
fa687006bd31d80f8d7c4bff | train | function | def _scala_generate_benchmark(ctx):
# we use required providers to ensure JavaInfo exists
info = ctx.attr.src[JavaInfo]
# TODO, if we emit more than one jar, which scala_library does not,
# this might fail. We could possibly extend the BenchmarkGenerator
# to accept more than one jar to scan, and t... | def _scala_generate_benchmark(ctx):
# we use required providers to ensure JavaInfo exists
| info = ctx.attr.src[JavaInfo]
# TODO, if we emit more than one jar, which scala_library does not,
# this might fail. We could possibly extend the BenchmarkGenerator
# to accept more than one jar to scan, and then allow multiple labels
# in ctx.attr.src
outs = info.outputs.jars
if len(outs) ... | _servers,
)
native.bind(
name =
"io_bazel_rules_scala/dependency/jmh/org_apache_commons_commons_math3",
actual = "@io_bazel_rules_scala_org_apache_commons_commons_math3//jar",
)
def _scala_generate_benchmark(ctx):
# we use required providers to ensure JavaInfo exists
| 77 | 77 | 258 | 20 | 57 | wisechengyi/rules_scala | jmh/jmh.bzl | Python | _scala_generate_benchmark | _scala_generate_benchmark | 82 | 107 | 82 | 83 | 91f7866128c4f17933cb3460ed6ccdab2d1fd59d | bigcode/the-stack | train |
7884217b04fd8806c20ee4ef | train | function | def scala_benchmark_jmh(**kw):
name = kw["name"]
deps = kw.get("deps", [])
srcs = kw["srcs"]
data = kw.get("data", [])
generator_type = kw.get("generator_type", "reflection")
lib = "%s_generator" % name
scalacopts = kw.get("scalacopts", [])
main_class = kw.get("main_class", "org.openjdk.... | def scala_benchmark_jmh(**kw):
| name = kw["name"]
deps = kw.get("deps", [])
srcs = kw["srcs"]
data = kw.get("data", [])
generator_type = kw.get("generator_type", "reflection")
lib = "%s_generator" % name
scalacopts = kw.get("scalacopts", [])
main_class = kw.get("main_class", "org.openjdk.jmh.Main")
scala_library(
... | atory = True, providers = [[JavaInfo]]),
"generator_type": attr.string(
default = "reflection",
mandatory = False,
),
"_generator": attr.label(
executable = True,
cfg = "host",
default = Label(
"//src/scala/io/bazel/rule... | 122 | 122 | 409 | 9 | 113 | wisechengyi/rules_scala | jmh/jmh.bzl | Python | scala_benchmark_jmh | scala_benchmark_jmh | 131 | 181 | 131 | 131 | 60f964940832a0eca6d813ee0d48167ee28e4038 | bigcode/the-stack | train |
a112a38ab6d3c694ae2b64c4 | train | function | def jmh_repositories(maven_servers = _default_maven_server_urls()):
_scala_maven_import_external(
name = "io_bazel_rules_scala_org_openjdk_jmh_jmh_core",
artifact = "org.openjdk.jmh:jmh-core:1.20",
artifact_sha256 = "1688db5110ea6413bf63662113ed38084106ab1149e020c58c5ac22b91b842ca",
... | def jmh_repositories(maven_servers = _default_maven_server_urls()):
| _scala_maven_import_external(
name = "io_bazel_rules_scala_org_openjdk_jmh_jmh_core",
artifact = "org.openjdk.jmh:jmh-core:1.20",
artifact_sha256 = "1688db5110ea6413bf63662113ed38084106ab1149e020c58c5ac22b91b842ca",
licenses = ["notice"],
server_urls = maven_servers,
)
... | load("//scala:scala.bzl", "scala_binary", "scala_library")
load(
"//scala:scala_cross_version.bzl",
_default_maven_server_urls = "default_maven_server_urls",
)
load(
"@io_bazel_rules_scala//scala:scala_maven_import_external.bzl",
_scala_maven_import_external = "scala_maven_import_external",
)
def jmh_re... | 97 | 256 | 942 | 16 | 81 | wisechengyi/rules_scala | jmh/jmh.bzl | Python | jmh_repositories | jmh_repositories | 11 | 80 | 11 | 11 | 78072f8bb0c2c50b456aff2c5ddc097b39fb18ad | bigcode/the-stack | train |
a46bc9a0106973ac19d89619 | train | class | class ManualQA(BaseCase):
def setUp(self):
self.check_count = 0
self.auto_close_results_page = False
super(ManualQA, self).setUp(masterqa_mode=True)
self.LATEST_REPORT_DIR = settings.LATEST_REPORT_DIR
self.ARCHIVE_DIR = settings.REPORT_ARCHIVE_DIR
self.RESULTS_PAGE =... | class ManualQA(BaseCase):
| def setUp(self):
self.check_count = 0
self.auto_close_results_page = False
super(ManualQA, self).setUp(masterqa_mode=True)
self.LATEST_REPORT_DIR = settings.LATEST_REPORT_DIR
self.ARCHIVE_DIR = settings.REPORT_ARCHIVE_DIR
self.RESULTS_PAGE = settings.HTML_REPORT
... | import os
import shutil
import sys
import time
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.remote.errorhandler import NoAlertPresentException
from automation import BaseCase
from automation.core.style_sheet import style
from automation.config import settings
from automation.fixture... | 81 | 256 | 3,721 | 6 | 74 | zahed3795/Super-Automation | automation/manual_qa/manual_qa.py | Python | ManualQA | ManualQA | 15 | 431 | 15 | 16 | 302f5d7519fad03f636945e98a8134238ecd5ad6 | bigcode/the-stack | train |
009c9caf98e69b246c8b0f3b | train | class | class Int2StrServicer(grpc_bt_grpc.Int2StrServicer):
def __init__(self):
self.argument = 0
self.result = 0
# Just for debugging purpose.
log.debug("Int2StrServicer created")
# Convert int into string
def int2str(self, request, context):
self.argument = request.argume... | class Int2StrServicer(grpc_bt_grpc.Int2StrServicer):
| def __init__(self):
self.argument = 0
self.result = 0
# Just for debugging purpose.
log.debug("Int2StrServicer created")
# Convert int into string
def int2str(self, request, context):
self.argument = request.argument
self.result = Result()
# Python i... | specification checking for
services running over gRPC.
Implements an int2str method, that divides an integer by 2.
"""
# Create a class to be added to the gRPC server
# derived from the protobuf codes.
class Int2StrServicer(grpc_bt_grpc.Int2StrServicer):
| 64 | 64 | 197 | 17 | 47 | nunet-io/ai-dsl | experimental/registry/service/int2str_service.py | Python | Int2StrServicer | Int2StrServicer | 27 | 49 | 27 | 27 | fa59d13433f797daaecc948356dd0779628305b6 | bigcode/the-stack | train |
cac315d4993e432fc9cb2804 | train | function | def serve(max_workers=10, port=7777):
server = grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers))
grpc_bt_grpc.add_Int2StrServicer_to_server(Int2StrServicer(), server)
server.add_insecure_port("[::]:{}".format(port))
return server
| def serve(max_workers=10, port=7777):
| server = grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers))
grpc_bt_grpc.add_Int2StrServicer_to_server(Int2StrServicer(), server)
server.add_insecure_port("[::]:{}".format(port))
return server
| The gRPC serve function.
#
# Params:
# max_workers: pool of threads to execute calls asynchronously
# port: gRPC server port
#
# Add all your classes to the server here.
# (from generated .py files by protobuf compiler)
def serve(max_workers=10, port=7777):
| 64 | 64 | 65 | 12 | 52 | nunet-io/ai-dsl | experimental/registry/service/int2str_service.py | Python | serve | serve | 60 | 64 | 60 | 60 | 151b86db70bb72ce3bb5832e5f0697f7fe309bb8 | bigcode/the-stack | train |
297708470c0edb68cb8c567c | train | class | class motion_data(object):
'''
The motion_data class stores pitch, roll, heave, and heading data
and provides a method to interpolate the data to your ping times.
'''
CHUNK_SIZE = 500
def __init__(self):
# Create a counter to keep track of the number of datagrams.
self.n_raw =... | class motion_data(object):
| '''
The motion_data class stores pitch, roll, heave, and heading data
and provides a method to interpolate the data to your ping times.
'''
CHUNK_SIZE = 500
def __init__(self):
# Create a counter to keep track of the number of datagrams.
self.n_raw = 0
# Create arrays... | MACE)
# THIS SOFTWARE AND ITS DOCUMENTATION ARE CONSIDERED TO BE IN THE PUBLIC DOMAIN
# AND THUS ARE AVAILABLE FOR UNRESTRICTED PUBLIC USE. THEY ARE FURNISHED "AS IS."
# THE AUTHORS, THE UNITED STATES GOVERNMENT, ITS INSTRUMENTALITIES, OFFICERS,
# EMPLOYEES, AND AGENTS MAKE NO WARRANTY, EXPRESS OR IMPLIED, AS TO T... | 256 | 256 | 1,527 | 5 | 250 | iambaim/pyEcholab | echolab2/instruments/util/motion_data.py | Python | motion_data | motion_data | 31 | 224 | 31 | 31 | 47ebb147d53c6900f00a75b5974a16d309e8e260 | bigcode/the-stack | train |
698bc27d7699ee4b3c1a8143 | train | function | def find_greeting(s):
""" Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string
>>> find_greeting('Hi Mr. Turing!')
'Hi'
>>> find_greeting('Hello, Rosa.')
'Hello'
>>> find_greeting("Yo, what's up?")
'Yo'
>>> find_greeting("Hello")
'Hello'
>>> ... | def find_greeting(s):
| """ Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string
>>> find_greeting('Hi Mr. Turing!')
'Hi'
>>> find_greeting('Hello, Rosa.')
'Hello'
>>> find_greeting("Yo, what's up?")
'Yo'
>>> find_greeting("Hello")
'Hello'
>>> print(find_greeting("h... | """ A naive way to build a Finit State Machine to extract piece of information """
def find_greeting(s):
| 23 | 68 | 227 | 6 | 17 | byukan/nlpia | src/nlpia/book/examples/ch11_greetings.py | Python | find_greeting | find_greeting | 4 | 28 | 4 | 4 | 1b76d849832da50c04b44da886d5392b5917425d | bigcode/the-stack | train |
c594b348ed7222a3ebd62549 | train | function | @contextlib.contextmanager
def stream(path, *args, **kwargs):
if path == '-':
yield sys.stdout
else:
with open(path, *args, **kwargs) as fp:
yield fp
| @contextlib.contextmanager
def stream(path, *args, **kwargs):
| if path == '-':
yield sys.stdout
else:
with open(path, *args, **kwargs) as fp:
yield fp
| either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
from pxr import Ar, Sdf, Usd, UsdUtils
import argparse, contextlib, sys
@contextlib.contextmanager
def stream(path, *args, **kwargs):
| 64 | 64 | 48 | 16 | 47 | WD-stefaang/USD | pxr/usd/lib/usdUtils/testenv/testUsdUtilsCreateNewUsdzPackage.py | Python | stream | stream | 29 | 35 | 29 | 30 | b489913504a1ed5921d796b73ef8c67a416e0c55 | bigcode/the-stack | train |
cf797bf6d52a7c00f3601c23 | train | class | class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('applications', '0015_merge_20190218_1144'),
]
operations = [
migrations.AddField(
model_name='application',
name='assigned',
fiel... | class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('applications', '0015_merge_20190218_1144'),
]
operations = [
migrations.AddField(
model_name='application',
name='assigned',
field=models.ForeignKey(blank=True, null=Tru... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2019-06-11 17:11
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 67 | 75 | 250 | 7 | 59 | HackAssistant/backend | applications/migrations/0016_auto_20190611_1011.py | Python | Migration | Migration | 10 | 38 | 10 | 11 | baff9c6fa093a051536916433a2ade40345d20b1 | bigcode/the-stack | train |
f2421bd9172cca622f86115a | train | class | class TestSchedulingV1alpha1Api(unittest.TestCase):
"""SchedulingV1alpha1Api unit test stubs"""
def setUp(self):
self.api = kubernetes_asyncio.client.api.scheduling_v1alpha1_api.SchedulingV1alpha1Api() # noqa: E501
def tearDown(self):
pass
def test_create_priority_class(self):
... | class TestSchedulingV1alpha1Api(unittest.TestCase):
| """SchedulingV1alpha1Api unit test stubs"""
def setUp(self):
self.api = kubernetes_asyncio.client.api.scheduling_v1alpha1_api.SchedulingV1alpha1Api() # noqa: E501
def tearDown(self):
pass
def test_create_priority_class(self):
"""Test case for create_priority_class
""... | .git
"""
from __future__ import absolute_import
import unittest
import kubernetes_asyncio.client
from kubernetes_asyncio.client.api.scheduling_v1alpha1_api import SchedulingV1alpha1Api # noqa: E501
from kubernetes_asyncio.client.rest import ApiException
class TestSchedulingV1alpha1Api(unittest.TestCase):
| 75 | 75 | 251 | 12 | 62 | olitheolix/kubernetes_asyncio | kubernetes_asyncio/test/test_scheduling_v1alpha1_api.py | Python | TestSchedulingV1alpha1Api | TestSchedulingV1alpha1Api | 23 | 78 | 23 | 23 | b4b1c5dedf666fbb7dcb4800f7fb4166208e21a8 | bigcode/the-stack | train |
9e7e270f0a8e98d57dc91982 | train | function | def test_assert_refund(w3, get_contract_with_gas_estimation, assert_tx_failed):
code = """
@external
def foo():
assert 1 == 2
"""
c = get_contract_with_gas_estimation(code)
a0 = w3.eth.accounts[0]
gas_sent = 10 ** 6
tx_hash = c.foo(transact={"from": a0, "gas": gas_sent, "gasPrice": 10})
... | def test_assert_refund(w3, get_contract_with_gas_estimation, assert_tx_failed):
| code = """
@external
def foo():
assert 1 == 2
"""
c = get_contract_with_gas_estimation(code)
a0 = w3.eth.accounts[0]
gas_sent = 10 ** 6
tx_hash = c.foo(transact={"from": a0, "gas": gas_sent, "gasPrice": 10})
# More info on receipt status:
# https://github.com/ethereum/EIPs/blob/maste... | decode_single
from eth_tester.exceptions import TransactionFailed
# web3 returns f"execution reverted: {err_str}"
def _fixup_err_str(s):
return s.replace("execution reverted: ", "")
def test_assert_refund(w3, get_contract_with_gas_estimation, assert_tx_failed):
| 63 | 64 | 179 | 20 | 43 | SWDOp/vyper | tests/parser/features/test_assert.py | Python | test_assert_refund | test_assert_refund | 11 | 26 | 11 | 11 | 4192d45e75572bd850f968b4ba370f1e71a490c1 | bigcode/the-stack | train |
0fe8888221609e8ecf156c11 | train | function | @pytest.mark.parametrize("code", invalid_code)
def test_invalid_assertions(get_contract, assert_compile_failed, code):
assert_compile_failed(lambda: get_contract(code))
| @pytest.mark.parametrize("code", invalid_code)
def test_invalid_assertions(get_contract, assert_compile_failed, code):
| assert_compile_failed(lambda: get_contract(code))
| """
@external
def test(a: int128) -> int128:
raise ""
""",
"""
@external
def test():
assert create_forwarder_to(self)
""",
]
@pytest.mark.parametrize("code", invalid_code)
def test_invalid_assertions(get_contract, assert_compile_failed, code):
| 64 | 64 | 33 | 23 | 41 | SWDOp/vyper | tests/parser/features/test_assert.py | Python | test_invalid_assertions | test_invalid_assertions | 90 | 92 | 90 | 91 | 77d58e1cffd181a4e82efe903a28b434dedfaed9 | bigcode/the-stack | train |
d36fd089f3a42256a60c8e77 | train | function | def test_assert_staticcall(get_contract, assert_tx_failed, memory_mocker):
foreign_code = """
state: uint256
@external
def not_really_constant() -> uint256:
self.state += 1
return self.state
"""
code = """
interface ForeignContract:
def not_really_constant() -> uint256: view
@external
def test(... | def test_assert_staticcall(get_contract, assert_tx_failed, memory_mocker):
| foreign_code = """
state: uint256
@external
def not_really_constant() -> uint256:
self.state += 1
return self.state
"""
code = """
interface ForeignContract:
def not_really_constant() -> uint256: view
@external
def test():
assert ForeignContract(msg.sender).not_really_constant() == 1
""... | ",
"""
@external
def test():
assert create_forwarder_to(self) == self
""",
]
@pytest.mark.parametrize("code", valid_code)
def test_valid_assertions(get_contract, code):
get_contract(code)
def test_assert_staticcall(get_contract, assert_tx_failed, memory_mocker):
| 64 | 64 | 141 | 16 | 48 | SWDOp/vyper | tests/parser/features/test_assert.py | Python | test_assert_staticcall | test_assert_staticcall | 135 | 154 | 135 | 135 | 0ec83bd4a7202bc151af114becbdd1eed0832484 | bigcode/the-stack | train |
97fb9904a6fee4559349098b | train | function | def test_assert_reason_revert_length(w3, get_contract, memory_mocker):
code = """
@external
def test() -> int128:
assert 1 == 2, "oops"
return 1
"""
c = get_contract(code)
w3.manager.provider.ethereum_tester.backend.is_eip838_error = lambda err: False
with pytest.raises(TransactionFailed) as e_i... | def test_assert_reason_revert_length(w3, get_contract, memory_mocker):
| code = """
@external
def test() -> int128:
assert 1 == 2, "oops"
return 1
"""
c = get_contract(code)
w3.manager.provider.ethereum_tester.backend.is_eip838_error = lambda err: False
with pytest.raises(TransactionFailed) as e_info:
c.test()
error_bytes = eval(_fixup_err_str(e_info.valu... | : c.test([5, 1, 3]))
assert_tx_failed(lambda: c.test([1, 5, 3]))
assert_tx_failed(lambda: c.test([1, 3, 5]))
def test_assert_reason_revert_length(w3, get_contract, memory_mocker):
| 63 | 64 | 137 | 17 | 46 | SWDOp/vyper | tests/parser/features/test_assert.py | Python | test_assert_reason_revert_length | test_assert_reason_revert_length | 191 | 205 | 191 | 191 | 3017814411289f9f43463816b51794f7248dcb9b | bigcode/the-stack | train |
daca4d7412e2ea1bf5e40030 | train | function | @pytest.mark.parametrize("code", valid_code)
def test_valid_assertions(get_contract, code):
get_contract(code)
| @pytest.mark.parametrize("code", valid_code)
def test_valid_assertions(get_contract, code):
| get_contract(code)
| size=1, gas=10, value=1000*1000) == b''
""",
"""
@external
def test():
assert create_forwarder_to(self) == self
""",
]
@pytest.mark.parametrize("code", valid_code)
def test_valid_assertions(get_contract, code):
| 64 | 64 | 24 | 19 | 45 | SWDOp/vyper | tests/parser/features/test_assert.py | Python | test_valid_assertions | test_valid_assertions | 130 | 132 | 130 | 131 | 70ec3ce3ab19637e7197ccf62d2dc195609c908b | bigcode/the-stack | train |
ecb94b1483ecb068e756319f | train | function | def _fixup_err_str(s):
return s.replace("execution reverted: ", "")
| def _fixup_err_str(s):
| return s.replace("execution reverted: ", "")
| import pytest
from eth_abi import decode_single
from eth_tester.exceptions import TransactionFailed
# web3 returns f"execution reverted: {err_str}"
def _fixup_err_str(s):
| 41 | 64 | 18 | 8 | 33 | SWDOp/vyper | tests/parser/features/test_assert.py | Python | _fixup_err_str | _fixup_err_str | 7 | 8 | 7 | 7 | 28730bf714bb421d18b8f92f2c5e0bd98b1dbafb | bigcode/the-stack | train |
fec33a6c54f11e96cf4f7f9a | train | function | def test_assert_with_reason_in_for_loop(get_contract, assert_tx_failed, memory_mocker):
code = """
@external
def test(x: uint256[3]) -> bool:
for i in range(3):
assert x[i] < 5, "because reasons"
return True
"""
c = get_contract(code)
c.test([1, 2, 3])
assert_tx_failed(lambda: c.te... | def test_assert_with_reason_in_for_loop(get_contract, assert_tx_failed, memory_mocker):
| code = """
@external
def test(x: uint256[3]) -> bool:
for i in range(3):
assert x[i] < 5, "because reasons"
return True
"""
c = get_contract(code)
c.test([1, 2, 3])
assert_tx_failed(lambda: c.test([5, 1, 3]))
assert_tx_failed(lambda: c.test([1, 5, 3]))
assert_tx_failed(lamb... | .test([5, 1, 3]))
assert_tx_failed(lambda: c.test([1, 5, 3]))
assert_tx_failed(lambda: c.test([1, 3, 5]))
def test_assert_with_reason_in_for_loop(get_contract, assert_tx_failed, memory_mocker):
| 63 | 64 | 135 | 19 | 44 | SWDOp/vyper | tests/parser/features/test_assert.py | Python | test_assert_with_reason_in_for_loop | test_assert_with_reason_in_for_loop | 174 | 188 | 174 | 174 | 5fecc5ff264b300413e77cbe64f4b415b560b628 | bigcode/the-stack | train |
63cdad010a4b557d5690aca3 | train | function | def test_assert_in_for_loop(get_contract, assert_tx_failed, memory_mocker):
code = """
@external
def test(x: uint256[3]) -> bool:
for i in range(3):
assert x[i] < 5
return True
"""
c = get_contract(code)
c.test([1, 2, 3])
assert_tx_failed(lambda: c.test([5, 1, 3]))
assert_tx_fa... | def test_assert_in_for_loop(get_contract, assert_tx_failed, memory_mocker):
| code = """
@external
def test(x: uint256[3]) -> bool:
for i in range(3):
assert x[i] < 5
return True
"""
c = get_contract(code)
c.test([1, 2, 3])
assert_tx_failed(lambda: c.test([5, 1, 3]))
assert_tx_failed(lambda: c.test([1, 5, 3]))
assert_tx_failed(lambda: c.test([1, 3, 5... | 1
"""
c1 = get_contract(foreign_code)
c2 = get_contract(code, *[c1.address])
# static call prohibits state change
assert_tx_failed(lambda: c2.test())
def test_assert_in_for_loop(get_contract, assert_tx_failed, memory_mocker):
| 64 | 64 | 129 | 17 | 47 | SWDOp/vyper | tests/parser/features/test_assert.py | Python | test_assert_in_for_loop | test_assert_in_for_loop | 157 | 171 | 157 | 157 | 503639f6a9715b734c86872db5e25eab89934c79 | bigcode/the-stack | train |
780202c2f3ceca4e88e54fd3 | train | function | def test_assert_reason(w3, get_contract_with_gas_estimation, assert_tx_failed, memory_mocker):
code = """
@external
def test(a: int128) -> int128:
assert a > 1, "larger than one please"
return 1 + a
@external
def test2(a: int128, b: int128, extra_reason: String[32]) -> int128:
c: int128 = 11
assert... | def test_assert_reason(w3, get_contract_with_gas_estimation, assert_tx_failed, memory_mocker):
| code = """
@external
def test(a: int128) -> int128:
assert a > 1, "larger than one please"
return 1 + a
@external
def test2(a: int128, b: int128, extra_reason: String[32]) -> int128:
c: int128 = 11
assert a > 1, "a is not large enough"
assert b == 1, concat("b may only be 1", extra_reason)
... | ={"from": a0, "gas": gas_sent, "gasPrice": 10})
# More info on receipt status:
# https://github.com/ethereum/EIPs/blob/master/EIPS/eip-658.md#specification.
tx_receipt = w3.eth.getTransactionReceipt(tx_hash)
assert tx_receipt["status"] == 0
# Checks for gas refund from revert
assert tx_receipt["... | 121 | 121 | 406 | 23 | 97 | SWDOp/vyper | tests/parser/features/test_assert.py | Python | test_assert_reason | test_assert_reason | 29 | 67 | 29 | 29 | 42ce5797f04fe0f1b7709b00a6e007ee0f755b7d | bigcode/the-stack | train |
dc8a75745ff629bca96d473c | train | function | @register.inclusion_tag('spirit/topic_favorite/_form.html')
def render_favorite_form(topic, user, next=None):
try:
favorite = TopicFavorite.objects.get(user=user, topic=topic)
except TopicFavorite.DoesNotExist:
favorite = None
form = FavoriteForm()
return {'form': form, 'topic_id': topi... | @register.inclusion_tag('spirit/topic_favorite/_form.html')
def render_favorite_form(topic, user, next=None):
| try:
favorite = TopicFavorite.objects.get(user=user, topic=topic)
except TopicFavorite.DoesNotExist:
favorite = None
form = FavoriteForm()
return {'form': form, 'topic_id': topic.pk, 'favorite': favorite, 'next': next}
| utf-8 -*-
from __future__ import unicode_literals
from . import register
from spirit.models.topic_favorite import TopicFavorite
from spirit.forms.topic_favorite import FavoriteForm
@register.inclusion_tag('spirit/topic_favorite/_form.html')
def render_favorite_form(topic, user, next=None):
| 64 | 64 | 87 | 27 | 36 | rterehov/Spirit | spirit/templatetags/tags/topic_favorite.py | Python | render_favorite_form | render_favorite_form | 10 | 18 | 10 | 11 | 15e6ec70bafbb5fcb95887430ef40c0b9c105d55 | bigcode/the-stack | train |
499412a67bdc285f74c99409 | train | class | class AboutLists(Koan):
def test_creating_lists(self):
empty_list = list()
self.assertEqual(list, type(empty_list))
self.assertEqual(0, len(empty_list))
def test_list_literals(self):
nums = list()
self.assertEqual([], nums)
nums[0:] = [1]
self.assertEqua... | class AboutLists(Koan):
| def test_creating_lists(self):
empty_list = list()
self.assertEqual(list, type(empty_list))
self.assertEqual(0, len(empty_list))
def test_list_literals(self):
nums = list()
self.assertEqual([], nums)
nums[0:] = [1]
self.assertEqual([1], nums)
nu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrays in the Ruby Koans
#
from runner.koan import *
class AboutLists(Koan):
| 40 | 256 | 897 | 6 | 34 | coder36/python_koans | python2/koans/about_lists.py | Python | AboutLists | AboutLists | 11 | 107 | 11 | 11 | 7497a31009ce8fbdd86c4d1bca81b0d9e0f79f89 | bigcode/the-stack | train |
c0504b6dd24027378af7cc8c | train | class | class ThreadManager(models.Manager):
def get_query_set(self):
return super(ThreadManager, self).get_query_set().annotate(
post_count=Count('post'),
last_post_date=Max('post__pub_date')
).order_by('-is_sticky', '-last_post_date')
| class ThreadManager(models.Manager):
| def get_query_set(self):
return super(ThreadManager, self).get_query_set().annotate(
post_count=Count('post'),
last_post_date=Max('post__pub_date')
).order_by('-is_sticky', '-last_post_date')
| meta.db_table,
'position': self.model._meta.get_field('position').column,
'increment': increment,
'addition': addition,
'where': where
}
cursor = connection.cursor()
cursor.execute(query)
transaction.commit_unless_managed()
class ThreadMana... | 64 | 64 | 62 | 6 | 58 | kylef-archive/lithium | lithium/forum/managers.py | Python | ThreadManager | ThreadManager | 40 | 45 | 40 | 40 | e4673466054aa55cda185bc50061a3aa442aa6ec | bigcode/the-stack | train |
e62c1766aa4919b658fe310b | train | class | class ForumManager(models.Manager):
def get_query_set(self):
return super(ForumManager, self).get_query_set().annotate(
thread_count=Count('thread'))
def update_position(self, position, addition=1, increment=True):
if isinstance(position, (list, tuple)):
if posit... | class ForumManager(models.Manager):
| def get_query_set(self):
return super(ForumManager, self).get_query_set().annotate(
thread_count=Count('thread'))
def update_position(self, position, addition=1, increment=True):
if isinstance(position, (list, tuple)):
if position[0] == position[-1]:
... | from django.db import connection, models, transaction
from django.db.models import Count, Max
# from lithium.forum.models import Thread, Post
class ForumManager(models.Manager):
| 36 | 90 | 301 | 6 | 29 | kylef-archive/lithium | lithium/forum/managers.py | Python | ForumManager | ForumManager | 6 | 38 | 6 | 6 | c65d9cc468535c40243b64c836b63e3d3f0af970 | bigcode/the-stack | train |
1f02abe69e68339f35c6253c | train | function | def char_frequency(string):
dict = { }
for i in string:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict [n] = 1
return dict
| def char_frequency(string):
| dict = { }
for i in string:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict [n] = 1
return dict
| string = input(" please enter a string: ")
def char_frequency(string):
| 15 | 64 | 53 | 5 | 10 | sreeja808/area | charfreq.py | Python | char_frequency | char_frequency | 2 | 10 | 2 | 2 | b28bab9a2495f1fda8fa1f4d1d7dd872af10962a | bigcode/the-stack | train |
e7af464966b9e89c88fb2aa9 | train | class | class Solution:
def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
result = []
left, right = 0, len(matrix[0])
top, bottom = 0, len(matrix)
while left < right and top < bottom:
# get elements in the top row
for i in range(left, right):
... | class Solution:
| def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
result = []
left, right = 0, len(matrix[0])
top, bottom = 0, len(matrix)
while left < right and top < bottom:
# get elements in the top row
for i in range(left, right):
result.append... | class Solution:
| 3 | 68 | 229 | 3 | 0 | luckyrabbit85/Python | Leetcode/0054. Spiral Matrix.py | Python | Solution | Solution | 1 | 31 | 1 | 1 | 02509a17065ca81fabab32563de6cde3900fd891 | bigcode/the-stack | train |
712242285e73db968360e88f | train | class | class ConnectionSchema(komand.Input):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"license_key": {
"$ref": "#/definitions/credential_secret_key",
"title": "License Key",
"description": "License key",
"order": 2
},
"user": {
"ty... | class ConnectionSchema(komand.Input):
| schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"license_key": {
"$ref": "#/definitions/credential_secret_key",
"title": "License Key",
"description": "License key",
"order": 2
},
"user": {
"type": "integer",
"title": "User",... | # GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Input:
LICENSE_KEY = "license_key"
USER = "user"
class ConnectionSchema(komand.Input):
| 42 | 82 | 276 | 8 | 34 | lukaszlaszuk/insightconnect-plugins | plugins/geoip2precision/komand_geoip2precision/connection/schema.py | Python | ConnectionSchema | ConnectionSchema | 11 | 58 | 11 | 11 | bf6b6dc11852c3dc9a60b32498b05b2058fbe6d9 | bigcode/the-stack | train |
dd36dacddbda8fb316eac41f | train | class | class Input:
LICENSE_KEY = "license_key"
USER = "user"
| class Input:
| LICENSE_KEY = "license_key"
USER = "user"
| # GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Input:
| 20 | 64 | 17 | 3 | 16 | lukaszlaszuk/insightconnect-plugins | plugins/geoip2precision/komand_geoip2precision/connection/schema.py | Python | Input | Input | 6 | 8 | 6 | 6 | 39c78d343e1cfed525fa96cf7ae8898035c75587 | bigcode/the-stack | train |
dda4d1aab7a76b50a73ae47b | train | function | @_add_docstring_header(num_lines=NUM_LINES, num_classes=2)
@_create_dataset_directory(dataset_name=DATASET_NAME)
@_wrap_split_argument(("train", "test"))
def AmazonReviewPolarity(root: str, split: Union[Tuple[str], str]):
# TODO Remove this after removing conditional dependency
if not is_module_available("torch... | @_add_docstring_header(num_lines=NUM_LINES, num_classes=2)
@_create_dataset_directory(dataset_name=DATASET_NAME)
@_wrap_split_argument(("train", "test"))
def AmazonReviewPolarity(root: str, split: Union[Tuple[str], str]):
# TODO Remove this after removing conditional dependency
| if not is_module_available("torchdata"):
raise ModuleNotFoundError("Package `torchdata` not found. Please install following instructions at `https://github.com/pytorch/data`")
url_dp = IterableWrapper([URL])
cache_dp = url_dp.on_disk_cache(
filepath_fn=lambda x: os.path.join(root, _PATH), h... | DATASET_NAME = "AmazonReviewPolarity"
@_add_docstring_header(num_lines=NUM_LINES, num_classes=2)
@_create_dataset_directory(dataset_name=DATASET_NAME)
@_wrap_split_argument(("train", "test"))
def AmazonReviewPolarity(root: str, split: Union[Tuple[str], str]):
# TODO Remove this after removing conditional dependency... | 78 | 78 | 262 | 68 | 10 | kevinchn/text | torchtext/datasets/amazonreviewpolarity.py | Python | AmazonReviewPolarity | AmazonReviewPolarity | 34 | 50 | 34 | 38 | 1c9350f8f95c9ea4f826483f5f7b23e4185676c0 | bigcode/the-stack | train |
15686ba021b604537f8894c2 | train | function | def vgg(cfg, i, batch_norm=False):
layers = []
in_channels = i
for v in cfg:
if v == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
elif v == 'C':
layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]
else:
conv2d = nn.Conv2d(in... | def vgg(cfg, i, batch_norm=False):
| layers = []
in_channels = i
for v in cfg:
if v == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
elif v == 'C':
layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]
else:
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, paddin... | base_file, map_location=lambda storage, loc: storage))
print('Finished!')
else:
print('Sorry only .pth and .pkl files supported.')
# This function is derived from torchvision VGG make_layers()
# https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py
def vgg(cfg, i, ba... | 77 | 77 | 257 | 11 | 65 | sashuIya/ssd.pytorch | ssd.py | Python | vgg | vgg | 127 | 147 | 127 | 127 | 74f2c7b7588f90453860201b83947a18a3233463 | bigcode/the-stack | train |
fccf111de054d1360ac876b4 | train | function | def build_ssd(phase, size=300, num_classes=21, top_k=200):
if phase != "test" and phase != "train":
raise ValueError("Error: Phase '{}' not recognized".format(phase))
size_key = str(size)
if size_key not in base:
raise ValueError("Error: Sorry only sizes {} are supported currently!"
... | def build_ssd(phase, size=300, num_classes=21, top_k=200):
| if phase != "test" and phase != "train":
raise ValueError("Error: Phase '{}' not recognized".format(phase))
size_key = str(size)
if size_key not in base:
raise ValueError("Error: Sorry only sizes {} are supported currently!"
.format(', '.join(sorted(base))))
ret... | 4, 6, 6, 6, 4, 4],
'512': [4, 6, 6, 6, 6, 4, 4],
}
def build_ssd(phase, size=300, num_classes=21, top_k=200):
| 64 | 64 | 148 | 21 | 43 | sashuIya/ssd.pytorch | ssd.py | Python | build_ssd | build_ssd | 201 | 215 | 201 | 201 | 5b7fa3eb06c52546ce99b6f031e95377a2836535 | bigcode/the-stack | train |
b2748c28f4256eed7ce87f67 | train | class | class SSD(nn.Module):
"""Single Shot Multibox Architecture
The network is composed of a base VGG network followed by the
added multibox conv layers. Each multibox layer branches into
1) conv2d for class conf scores
2) conv2d for localization predictions
3) associated priorbox layer ... | class SSD(nn.Module):
| """Single Shot Multibox Architecture
The network is composed of a base VGG network followed by the
added multibox conv layers. Each multibox layer branches into
1) conv2d for class conf scores
2) conv2d for localization predictions
3) associated priorbox layer to produce default bou... | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from layers import PriorBox, L2Norm, Detect
from data import v2
class SSD(nn.Module):
| 49 | 256 | 1,019 | 5 | 43 | sashuIya/ssd.pytorch | ssd.py | Python | SSD | SSD | 12 | 122 | 12 | 12 | 75f95c26a5a7e1ef8370fcaf211d08b1a2356a48 | bigcode/the-stack | train |
0c83faf634e8e79e8b022d90 | train | function | def add_extras(cfg, i, batch_norm=False):
# Extra layers added to VGG for feature scaling
layers = []
in_channels = i
flag = False
for k, v in enumerate(cfg):
if in_channels != 'S':
if v == 'S':
layers += [nn.Conv2d(in_channels, cfg[k + 1],
... | def add_extras(cfg, i, batch_norm=False):
# Extra layers added to VGG for feature scaling
| layers = []
in_channels = i
flag = False
for k, v in enumerate(cfg):
if in_channels != 'S':
if v == 'S':
layers += [nn.Conv2d(in_channels, cfg[k + 1],
kernel_size=(1, 3)[flag], stride=2, padding=1)]
else:
layers +... | , 1024, kernel_size=1)
layers += [pool5, conv6,
nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)]
return layers
def add_extras(cfg, i, batch_norm=False):
# Extra layers added to VGG for feature scaling
| 64 | 64 | 141 | 24 | 39 | sashuIya/ssd.pytorch | ssd.py | Python | add_extras | add_extras | 150 | 164 | 150 | 151 | 391d2744d8bf19083c11ad4e54f3493ec20b2a78 | bigcode/the-stack | train |
1de7c4e57bd25696a2c1d6a0 | train | function | def multibox(vgg, extra_layers, cfg, num_classes):
loc_layers = []
conf_layers = []
vgg_source = [24, -2]
for k, v in enumerate(vgg_source):
loc_layers += [nn.Conv2d(
vgg[v].out_channels, cfg[k] * 4, kernel_size=3, padding=1)]
conf_layers += [nn.Conv2d(
vgg[v].out... | def multibox(vgg, extra_layers, cfg, num_classes):
| loc_layers = []
conf_layers = []
vgg_source = [24, -2]
for k, v in enumerate(vgg_source):
loc_layers += [nn.Conv2d(
vgg[v].out_channels, cfg[k] * 4, kernel_size=3, padding=1)]
conf_layers += [nn.Conv2d(
vgg[v].out_channels, cfg[k] * num_classes,
kernel... | stride=2, padding=1)]
else:
layers += [nn.Conv2d(in_channels, v, kernel_size=(1, 3)[flag])]
flag = not flag
in_channels = v
return layers
def multibox(vgg, extra_layers, cfg, num_classes):
| 64 | 64 | 209 | 14 | 49 | sashuIya/ssd.pytorch | ssd.py | Python | multibox | multibox | 167 | 182 | 167 | 167 | ae38b1b0dd7aec7d55fbee5ff3e35c8fed72c387 | bigcode/the-stack | train |
68b5f7fbd6e17935fe09e35d | train | class | class Migration(migrations.Migration):
dependencies = [
('searchengine', '0010_stemscore'),
]
operations = [
migrations.RemoveField(
model_name='stemscore',
name='id',
),
migrations.AlterField(
model_name='stemscore',
name='st... | class Migration(migrations.Migration):
| dependencies = [
('searchengine', '0010_stemscore'),
]
operations = [
migrations.RemoveField(
model_name='stemscore',
name='id',
),
migrations.AlterField(
model_name='stemscore',
name='stem',
field=models.CharField(... | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-05 08:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 52 | 64 | 86 | 7 | 44 | edwinyoung/recipe-webscraper | searchengine/migrations/0011_auto_20170505_0831.py | Python | Migration | Migration | 8 | 24 | 8 | 9 | 1e31a0ff692aa5c1a083c8f74255de7613217905 | bigcode/the-stack | train |
441f88b63e8438896ee03319 | train | class | class WindowsHardwareManager:
"""
Instance, implementing `DeviceManager`, for extracting system information
from Windows systems using the `WMI` infrastructure.
https://docs.microsoft.com/en-us/windows/win32/wmisdk/wmi-start-page
"""
def __init__(self, parent):
self.info = par... | class WindowsHardwareManager:
| """
Instance, implementing `DeviceManager`, for extracting system information
from Windows systems using the `WMI` infrastructure.
https://docs.microsoft.com/en-us/windows/win32/wmisdk/wmi-start-page
"""
def __init__(self, parent):
self.info = parent.info
self.pci = pa... | import re
from util.codename_manager import CodenameManager
import wmi
from .cpuid import CPUID
from util.codename import gpu as _gpu
from util.pci_root import pci_from_acpi_win
from error.cpu_err import cpu_err
from operator import itemgetter
from .win_enum import BUS_TYPE, MEDIA_TYPE, POINT_DEV_INTERFACE
clas... | 81 | 256 | 3,048 | 5 | 75 | flagersgit/OCSysInfo | src/dumps/Windows/win.py | Python | WindowsHardwareManager | WindowsHardwareManager | 12 | 443 | 12 | 12 | e303b99e153d6a862fc83380dffcbae7e5a9361b | bigcode/the-stack | train |
bb588a3cdd01847755789140 | train | class | @attr.s(slots=True, frozen=True)
class RoomVersion:
"""An object which describes the unique attributes of a room version."""
identifier = attr.ib(type=str) # the identifier for this version
disposition = attr.ib(type=str) # one of the RoomDispositions
event_format = attr.ib(type=int) # one of the Ev... | @attr.s(slots=True, frozen=True)
class RoomVersion:
| """An object which describes the unique attributes of a room version."""
identifier = attr.ib(type=str) # the identifier for this version
disposition = attr.ib(type=str) # one of the RoomDispositions
event_format = attr.ib(type=int) # one of the EventFormatVersions
state_res = attr.ib(type=int) ... | }
class StateResolutionVersions:
"""Enum to identify the state resolution algorithms"""
V1 = 1 # room v1 state res
V2 = 2 # MSC1442 state res: room v2 and later
class RoomDisposition:
STABLE = "stable"
UNSTABLE = "unstable"
@attr.s(slots=True, frozen=True)
class RoomVersion:
| 84 | 84 | 283 | 14 | 70 | chris-ruecker/synapse | synapse/api/room_versions.py | Python | RoomVersion | RoomVersion | 50 | 71 | 50 | 51 | 46e257da781333b24c47471e514aab04b94a1a86 | bigcode/the-stack | train |
bef58a5da61d3142ed73477b | train | class | class RoomDisposition:
STABLE = "stable"
UNSTABLE = "unstable"
| class RoomDisposition:
| STABLE = "stable"
UNSTABLE = "unstable"
| .V2,
EventFormatVersions.V3,
}
class StateResolutionVersions:
"""Enum to identify the state resolution algorithms"""
V1 = 1 # room v1 state res
V2 = 2 # MSC1442 state res: room v2 and later
class RoomDisposition:
| 64 | 64 | 20 | 4 | 59 | chris-ruecker/synapse | synapse/api/room_versions.py | Python | RoomDisposition | RoomDisposition | 45 | 47 | 45 | 45 | 58d017d3fc968203805fce7c156f559cb949d9ff | bigcode/the-stack | train |
70e9ebaa210c517aa4dff85b | train | class | class RoomVersions:
V1 = RoomVersion(
"1",
RoomDisposition.STABLE,
EventFormatVersions.V1,
StateResolutionVersions.V1,
enforce_key_validity=False,
special_case_aliases_auth=True,
strict_canonicaljson=False,
limit_notifications_power_levels=False,
... | class RoomVersions:
| V1 = RoomVersion(
"1",
RoomDisposition.STABLE,
EventFormatVersions.V1,
StateResolutionVersions.V1,
enforce_key_validity=False,
special_case_aliases_auth=True,
strict_canonicaljson=False,
limit_notifications_power_levels=False,
msc2176_redaction... | rules
special_case_aliases_auth = attr.ib(type=bool)
# Strictly enforce canonicaljson, do not allow:
# * Integers outside the range of [-2 ^ 53 + 1, 2 ^ 53 - 1]
# * Floats
# * NaN, Infinity, -Infinity
strict_canonicaljson = attr.ib(type=bool)
# MSC2209: Check 'notifications' key while verif... | 154 | 154 | 515 | 4 | 150 | chris-ruecker/synapse | synapse/api/room_versions.py | Python | RoomVersions | RoomVersions | 74 | 151 | 74 | 74 | ccba1ff431210baa5e8623280d17d203441d0977 | bigcode/the-stack | train |
dbcd3693298ab4d00e6c6a7a | train | class | class EventFormatVersions:
"""This is an internal enum for tracking the version of the event format,
independently from the room version.
"""
V1 = 1 # $id:server event id format
V2 = 2 # MSC1659-style $hash event id format: introduced for room v3
V3 = 3 # MSC1884-style $hash format: introduc... | class EventFormatVersions:
| """This is an internal enum for tracking the version of the event format,
independently from the room version.
"""
V1 = 1 # $id:server event id format
V2 = 2 # MSC1659-style $hash event id format: introduced for room v3
V3 = 3 # MSC1884-style $hash format: introduced for room v4
| writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Dict
import attr
class EventFormat... | 64 | 64 | 92 | 5 | 58 | chris-ruecker/synapse | synapse/api/room_versions.py | Python | EventFormatVersions | EventFormatVersions | 21 | 28 | 21 | 21 | b5aecdd50fcffba98b74b8fc227e05d9172a05ec | bigcode/the-stack | train |
18b026d74044998c62b021a4 | train | class | class StateResolutionVersions:
"""Enum to identify the state resolution algorithms"""
V1 = 1 # room v1 state res
V2 = 2 # MSC1442 state res: room v2 and later
| class StateResolutionVersions:
| """Enum to identify the state resolution algorithms"""
V1 = 1 # room v1 state res
V2 = 2 # MSC1442 state res: room v2 and later
| : introduced for room v3
V3 = 3 # MSC1884-style $hash format: introduced for room v4
KNOWN_EVENT_FORMAT_VERSIONS = {
EventFormatVersions.V1,
EventFormatVersions.V2,
EventFormatVersions.V3,
}
class StateResolutionVersions:
| 64 | 64 | 49 | 5 | 59 | chris-ruecker/synapse | synapse/api/room_versions.py | Python | StateResolutionVersions | StateResolutionVersions | 38 | 42 | 38 | 38 | b027a60161849b4dd314e9e0e9a4e34f094df597 | bigcode/the-stack | train |
65f18f04498b30d94d998635 | train | function | @pytest.mark.parametrize("patience", [3])
def test_pytorch_early_stop_metrics_logged(pytorch_model_with_callback):
_, run = pytorch_model_with_callback
data = run.data
assert "stopped_epoch" in data.metrics
assert "wait_count" in data.metrics
assert "restored_epoch" in data.metrics
| @pytest.mark.parametrize("patience", [3])
def test_pytorch_early_stop_metrics_logged(pytorch_model_with_callback):
| _, run = pytorch_model_with_callback
data = run.data
assert "stopped_epoch" in data.metrics
assert "wait_count" in data.metrics
assert "restored_epoch" in data.metrics
| ience" in data.params
assert float(data.params["patience"]) == patience
assert "min_delta" in data.params
assert "stopped_epoch" in data.params
@pytest.mark.parametrize("patience", [3])
def test_pytorch_early_stop_metrics_logged(pytorch_model_with_callback):
| 64 | 64 | 73 | 25 | 38 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_early_stop_metrics_logged | test_pytorch_early_stop_metrics_logged | 186 | 192 | 186 | 187 | 49ee647376911188a9b9a5b392d6d1f8a7e24349 | bigcode/the-stack | train |
84c6dfaef377a1243a1c72b8 | train | function | @pytest.mark.large
@pytest.mark.parametrize("log_models", [True, False])
def test_pytorch_autolog_log_models_configuration(log_models):
mlflow.pytorch.autolog(log_models=log_models)
model = IrisClassification()
trainer = pl.Trainer(max_epochs=NUM_EPOCHS)
trainer.fit(model)
client = mlflow.tracking.M... | @pytest.mark.large
@pytest.mark.parametrize("log_models", [True, False])
def test_pytorch_autolog_log_models_configuration(log_models):
| mlflow.pytorch.autolog(log_models=log_models)
model = IrisClassification()
trainer = pl.Trainer(max_epochs=NUM_EPOCHS)
trainer.fit(model)
client = mlflow.tracking.MlflowClient()
run = client.get_run(client.list_run_infos(experiment_id="0")[0].run_id)
run_id = run.info.run_id
client = mlf... | mlflow.tracking.MlflowClient()
run = client.get_run(client.list_run_infos(experiment_id="0")[0].run_id)
return trainer, run
@pytest.mark.large
@pytest.mark.parametrize("log_models", [True, False])
def test_pytorch_autolog_log_models_configuration(log_models):
| 64 | 64 | 148 | 28 | 35 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_autolog_log_models_configuration | test_pytorch_autolog_log_models_configuration | 25 | 37 | 25 | 27 | 6da15b4a576cb50779b1f3c53999a8d8c920af79 | bigcode/the-stack | train |
5f830546ad9ed166b3b10d6c | train | function | @pytest.fixture
def pytorch_model():
mlflow.pytorch.autolog()
model = IrisClassification()
trainer = pl.Trainer(max_epochs=NUM_EPOCHS)
trainer.fit(model)
client = mlflow.tracking.MlflowClient()
run = client.get_run(client.list_run_infos(experiment_id="0")[0].run_id)
return trainer, run
| @pytest.fixture
def pytorch_model():
| mlflow.pytorch.autolog()
model = IrisClassification()
trainer = pl.Trainer(max_epochs=NUM_EPOCHS)
trainer.fit(model)
client = mlflow.tracking.MlflowClient()
run = client.get_run(client.list_run_infos(experiment_id="0")[0].run_id)
return trainer, run
| import IrisClassification
import mlflow
import mlflow.pytorch
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from pytorch_lightning.callbacks import ModelCheckpoint
from mlflow.utils.file_utils import TempDir
NUM_EPOCHS = 20
@pytest.fixture
def pytorch_model():
| 64 | 64 | 80 | 8 | 55 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | pytorch_model | pytorch_model | 14 | 22 | 14 | 15 | ae515b3da498bf866124603a04623bfc47e34f14 | bigcode/the-stack | train |
be632b8e593996a6ee6e4e2b | train | function | def test_pytorch_autolog_ends_auto_created_run(pytorch_model):
assert mlflow.active_run() is None
| def test_pytorch_autolog_ends_auto_created_run(pytorch_model):
| assert mlflow.active_run() is None
| Classification()
trainer = pl.Trainer(max_epochs=NUM_EPOCHS)
trainer.fit(model)
assert mlflow.active_run() is not None
assert mlflow.active_run().info.run_id == manual_run.info.run_id
def test_pytorch_autolog_ends_auto_created_run(pytorch_model):
| 64 | 64 | 25 | 15 | 48 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_autolog_ends_auto_created_run | test_pytorch_autolog_ends_auto_created_run | 80 | 81 | 80 | 80 | 89ccef114bb68f734680d6a9711479de6141c482 | bigcode/the-stack | train |
1d712bac074f2180506a1e29 | train | function | def test_pytorch_autolog_logs_default_params(pytorch_model):
_, run = pytorch_model
data = run.data
assert "lr" in data.params
assert "eps" in data.params
assert "optimizer_name" in data.params
assert "weight_decay" in data.params
assert "betas" in data.params
| def test_pytorch_autolog_logs_default_params(pytorch_model):
| _, run = pytorch_model
data = run.data
assert "lr" in data.params
assert "eps" in data.params
assert "optimizer_name" in data.params
assert "weight_decay" in data.params
assert "betas" in data.params
| _id)
run_id = run.info.run_id
client = mlflow.tracking.MlflowClient()
artifacts = [f.path for f in client.list_artifacts(run_id)]
assert ("model" in artifacts) == log_models
def test_pytorch_autolog_logs_default_params(pytorch_model):
| 64 | 64 | 75 | 13 | 50 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_autolog_logs_default_params | test_pytorch_autolog_logs_default_params | 40 | 47 | 40 | 40 | be03394a5d1aa9d1fd9a2bd0d51f23a4df55e7e8 | bigcode/the-stack | train |
8c544db29022e4f7dde7fb9d | train | function | def test_pytorch_autolog_persists_manually_created_run():
with mlflow.start_run() as manual_run:
mlflow.pytorch.autolog()
model = IrisClassification()
trainer = pl.Trainer(max_epochs=NUM_EPOCHS)
trainer.fit(model)
assert mlflow.active_run() is not None
assert mlflow.a... | def test_pytorch_autolog_persists_manually_created_run():
| with mlflow.start_run() as manual_run:
mlflow.pytorch.autolog()
model = IrisClassification()
trainer = pl.Trainer(max_epochs=NUM_EPOCHS)
trainer.fit(model)
assert mlflow.active_run() is not None
assert mlflow.active_run().info.run_id == manual_run.info.run_id
| .tracking.MlflowClient()
artifacts = client.list_artifacts(run.info.run_id)
artifacts = map(lambda x: x.path, artifacts)
assert "model_summary.txt" in artifacts
# pylint: disable=unused-argument
def test_pytorch_autolog_persists_manually_created_run():
| 64 | 64 | 86 | 14 | 49 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_autolog_persists_manually_created_run | test_pytorch_autolog_persists_manually_created_run | 70 | 77 | 70 | 70 | 40b6589d86f02b111da745ec6556052263e315c4 | bigcode/the-stack | train |
45f24c93457e54b91a2a216a | train | function | def test_pytorch_test_metrics_logged(pytorch_model_tests):
_, run = pytorch_model_tests
data = run.data
assert "test_loss" in data.metrics
assert "test_acc" in data.metrics
| def test_pytorch_test_metrics_logged(pytorch_model_tests):
| _, run = pytorch_model_tests
data = run.data
assert "test_loss" in data.metrics
assert "test_acc" in data.metrics
| _EPOCHS)
trainer.fit(model)
trainer.test()
client = mlflow.tracking.MlflowClient()
run = client.get_run(client.list_run_infos(experiment_id="0")[0].run_id)
return trainer, run
def test_pytorch_test_metrics_logged(pytorch_model_tests):
| 64 | 64 | 47 | 12 | 51 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_test_metrics_logged | test_pytorch_test_metrics_logged | 215 | 219 | 215 | 215 | d9601f915f54f856dfb447c66456cd711782f0ce | bigcode/the-stack | train |
f02ade8333326679d4f00952 | train | function | def test_pytorch_autolog_non_early_stop_callback_does_not_log(pytorch_model):
trainer, run = pytorch_model
client = mlflow.tracking.MlflowClient()
metric_history = client.get_metric_history(run.info.run_id, "loss")
assert trainer.max_epochs == NUM_EPOCHS
assert len(metric_history) == NUM_EPOCHS
| def test_pytorch_autolog_non_early_stop_callback_does_not_log(pytorch_model):
| trainer, run = pytorch_model
client = mlflow.tracking.MlflowClient()
metric_history = client.get_metric_history(run.info.run_id, "loss")
assert trainer.max_epochs == NUM_EPOCHS
assert len(metric_history) == NUM_EPOCHS
| = pytorch_model_with_callback
data = run.data
assert "stopped_epoch" in data.metrics
assert "wait_count" in data.metrics
assert "restored_epoch" in data.metrics
def test_pytorch_autolog_non_early_stop_callback_does_not_log(pytorch_model):
| 64 | 64 | 79 | 19 | 44 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_autolog_non_early_stop_callback_does_not_log | test_pytorch_autolog_non_early_stop_callback_does_not_log | 195 | 200 | 195 | 195 | 7c063aecb748fb6ec123987ace5f294e108b5113 | bigcode/the-stack | train |
b8270534b50d6dd0d373050e | train | function | @pytest.mark.large
@pytest.mark.parametrize("log_models", [True, False])
@pytest.mark.parametrize("patience", [3])
def test_pytorch_with_early_stopping_autolog_log_models_configuration_with(log_models, patience):
mlflow.pytorch.autolog(log_models=log_models)
model = IrisClassification()
early_stopping = Ear... | @pytest.mark.large
@pytest.mark.parametrize("log_models", [True, False])
@pytest.mark.parametrize("patience", [3])
def test_pytorch_with_early_stopping_autolog_log_models_configuration_with(log_models, patience):
| mlflow.pytorch.autolog(log_models=log_models)
model = IrisClassification()
early_stopping = EarlyStopping(monitor="val_loss", mode="min", patience=patience, verbose=True)
with TempDir() as tmp:
checkpoint_callback = ModelCheckpoint(
filepath=tmp.path(),
save_top_k=1,
... | model(torch.Tensor([1.5, 2, 2.5, 3.5]).unsqueeze(0))
assert result is not None
@pytest.mark.large
@pytest.mark.parametrize("log_models", [True, False])
@pytest.mark.parametrize("patience", [3])
def test_pytorch_with_early_stopping_autolog_log_models_configuration_with(log_models, patience):
| 79 | 79 | 264 | 46 | 32 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_with_early_stopping_autolog_log_models_configuration_with | test_pytorch_with_early_stopping_autolog_log_models_configuration_with | 141 | 171 | 141 | 144 | 3512308f0a1d0191313e81433448f7db2907b538 | bigcode/the-stack | train |
b223dbf3b3edc00ffb5d9ad5 | train | function | @pytest.fixture
def pytorch_model_tests():
model = IrisClassification()
trainer = pl.Trainer(max_epochs=NUM_EPOCHS)
trainer.fit(model)
trainer.test()
client = mlflow.tracking.MlflowClient()
run = client.get_run(client.list_run_infos(experiment_id="0")[0].run_id)
return trainer, run
| @pytest.fixture
def pytorch_model_tests():
| model = IrisClassification()
trainer = pl.Trainer(max_epochs=NUM_EPOCHS)
trainer.fit(model)
trainer.test()
client = mlflow.tracking.MlflowClient()
run = client.get_run(client.list_run_infos(experiment_id="0")[0].run_id)
return trainer, run
| pytorch_model
client = mlflow.tracking.MlflowClient()
metric_history = client.get_metric_history(run.info.run_id, "loss")
assert trainer.max_epochs == NUM_EPOCHS
assert len(metric_history) == NUM_EPOCHS
@pytest.fixture
def pytorch_model_tests():
| 64 | 64 | 77 | 9 | 54 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | pytorch_model_tests | pytorch_model_tests | 203 | 212 | 203 | 204 | 9d14a20281f89836e67afbae55683ae1b4421141 | bigcode/the-stack | train |
1ffbab104d6c47695add8223 | train | function | @pytest.mark.parametrize("patience", [0, 1, 5])
def test_pytorch_early_stop_params_logged(pytorch_model_with_callback, patience):
_, run = pytorch_model_with_callback
data = run.data
assert "monitor" in data.params
assert "mode" in data.params
assert "patience" in data.params
assert float(data.p... | @pytest.mark.parametrize("patience", [0, 1, 5])
def test_pytorch_early_stop_params_logged(pytorch_model_with_callback, patience):
| _, run = pytorch_model_with_callback
data = run.data
assert "monitor" in data.params
assert "mode" in data.params
assert "patience" in data.params
assert float(data.params["patience"]) == patience
assert "min_delta" in data.params
assert "stopped_epoch" in data.params
| artifacts = [f.path for f in client.list_artifacts(run_id)]
assert ("restored_model_checkpoint" in artifacts) == log_models
@pytest.mark.parametrize("patience", [0, 1, 5])
def test_pytorch_early_stop_params_logged(pytorch_model_with_callback, patience):
| 64 | 64 | 110 | 33 | 30 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_early_stop_params_logged | test_pytorch_early_stop_params_logged | 174 | 183 | 174 | 175 | 427d74ca16df4a42d4cc8d279dfc8e3f729b585a | bigcode/the-stack | train |
9bb698a89f9087afd1581a66 | train | function | @pytest.fixture
def pytorch_model_with_callback(patience):
mlflow.pytorch.autolog()
model = IrisClassification()
early_stopping = EarlyStopping(
monitor="val_loss",
mode="min",
min_delta=99999999, # forces early stopping
patience=patience,
verbose=True,
)
wi... | @pytest.fixture
def pytorch_model_with_callback(patience):
| mlflow.pytorch.autolog()
model = IrisClassification()
early_stopping = EarlyStopping(
monitor="val_loss",
mode="min",
min_delta=99999999, # forces early stopping
patience=patience,
verbose=True,
)
with TempDir() as tmp:
checkpoint_callback = ModelChe... | mlflow.active_run() is not None
assert mlflow.active_run().info.run_id == manual_run.info.run_id
def test_pytorch_autolog_ends_auto_created_run(pytorch_model):
assert mlflow.active_run() is None
@pytest.fixture
def pytorch_model_with_callback(patience):
| 64 | 64 | 200 | 13 | 50 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | pytorch_model_with_callback | pytorch_model_with_callback | 84 | 116 | 84 | 85 | 5ad3e8dbdd3cf210226f66419377ce7b7f0e355d | bigcode/the-stack | train |
a243fff099d2fb19762d3ac7 | train | function | @pytest.mark.parametrize("patience", [3])
def test_pytorch_autolog_model_can_load_from_artifact(pytorch_model_with_callback):
_, run = pytorch_model_with_callback
run_id = run.info.run_id
client = mlflow.tracking.MlflowClient()
artifacts = client.list_artifacts(run_id)
artifacts = map(lambda x: x.pa... | @pytest.mark.parametrize("patience", [3])
def test_pytorch_autolog_model_can_load_from_artifact(pytorch_model_with_callback):
| _, run = pytorch_model_with_callback
run_id = run.info.run_id
client = mlflow.tracking.MlflowClient()
artifacts = client.list_artifacts(run_id)
artifacts = map(lambda x: x.path, artifacts)
assert "model" in artifacts
model = mlflow.pytorch.load_model("runs:/" + run_id + "/model")
result ... | ()
artifacts = client.list_artifacts(run.info.run_id)
artifacts = map(lambda x: x.path, artifacts)
assert "restored_model_checkpoint" in artifacts
@pytest.mark.parametrize("patience", [3])
def test_pytorch_autolog_model_can_load_from_artifact(pytorch_model_with_callback):
| 64 | 64 | 145 | 28 | 35 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_autolog_model_can_load_from_artifact | test_pytorch_autolog_model_can_load_from_artifact | 128 | 138 | 128 | 129 | c6c4accbb72bd1c9f87cbbbb17d430d5785ab010 | bigcode/the-stack | train |
554ac5ca9444b4a0ab694336 | train | function | def test_pytorch_autolog_logs_expected_data(pytorch_model):
_, run = pytorch_model
data = run.data
# Checking if metrics are logged
assert "loss" in data.metrics
assert "val_loss" in data.metrics
# Testing optimizer parameters are logged
assert "optimizer_name" in data.params
assert da... | def test_pytorch_autolog_logs_expected_data(pytorch_model):
| _, run = pytorch_model
data = run.data
# Checking if metrics are logged
assert "loss" in data.metrics
assert "val_loss" in data.metrics
# Testing optimizer parameters are logged
assert "optimizer_name" in data.params
assert data.params["optimizer_name"] == "Adam"
# Testing model_s... | run.data
assert "lr" in data.params
assert "eps" in data.params
assert "optimizer_name" in data.params
assert "weight_decay" in data.params
assert "betas" in data.params
def test_pytorch_autolog_logs_expected_data(pytorch_model):
| 64 | 64 | 139 | 13 | 50 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_autolog_logs_expected_data | test_pytorch_autolog_logs_expected_data | 50 | 66 | 50 | 50 | 9db7bd7be46b0d6050a2c7c5c1055d86e439c586 | bigcode/the-stack | train |
c0d66d36a3f26eecdc1ef246 | train | function | @pytest.mark.parametrize("patience", [3])
def test_pytorch_early_stop_artifacts_logged(pytorch_model_with_callback):
_, run = pytorch_model_with_callback
client = mlflow.tracking.MlflowClient()
artifacts = client.list_artifacts(run.info.run_id)
artifacts = map(lambda x: x.path, artifacts)
assert "re... | @pytest.mark.parametrize("patience", [3])
def test_pytorch_early_stop_artifacts_logged(pytorch_model_with_callback):
| _, run = pytorch_model_with_callback
client = mlflow.tracking.MlflowClient()
artifacts = client.list_artifacts(run.info.run_id)
artifacts = map(lambda x: x.path, artifacts)
assert "restored_model_checkpoint" in artifacts
| client = mlflow.tracking.MlflowClient()
run = client.get_run(client.list_run_infos(experiment_id="0")[0].run_id)
return trainer, run
@pytest.mark.parametrize("patience", [3])
def test_pytorch_early_stop_artifacts_logged(pytorch_model_with_callback):
| 64 | 64 | 83 | 26 | 37 | ConsultingMD/mlflow | tests/pytorch/test_pytorch_autolog.py | Python | test_pytorch_early_stop_artifacts_logged | test_pytorch_early_stop_artifacts_logged | 119 | 125 | 119 | 120 | d6a17d087fb8d97e2ee121a56fde28f2d42f87d5 | bigcode/the-stack | train |
d84def3d44b85f1618280087 | train | function | def avg_mol_wt(x):
gases = np.array(['o2','na','h2','he','k','co2','n2','so2','ar','h2o','co','ch4','nh3'])
fraction = np.array(dat.planet_atm(x))
wt = np.array([])
for i in gases:
wt1 = dat.atomic_wt(i)
wt = np.hstack((wt,wt1))
avg_wt = np.sum(fraction*wt)
return avg_wt*u.kg
| def avg_mol_wt(x):
| gases = np.array(['o2','na','h2','he','k','co2','n2','so2','ar','h2o','co','ch4','nh3'])
fraction = np.array(dat.planet_atm(x))
wt = np.array([])
for i in gases:
wt1 = dat.atomic_wt(i)
wt = np.hstack((wt,wt1))
avg_wt = np.sum(fraction*wt)
return avg_wt*u.kg
| i in gases:
cp1 = dat.c_p(i)
cp = np.hstack((cp,cp1))
t_cv = np.sum(fraction*cv)
t_cp = np.sum(fraction*cp)
gamma = t_cp/t_cv
return gamma
def avg_mol_wt(x):
| 64 | 64 | 116 | 8 | 55 | Jayshil/Planetory_atmosphere | atm_details.py | Python | avg_mol_wt | avg_mol_wt | 26 | 34 | 26 | 26 | 7e2e301a47954a54d2e3bd3b8bd84fd8e69a83a4 | bigcode/the-stack | train |
6cad3d8e0e752193d92190ba | train | function | def gamma(x):
gases = np.array(['o2','na','h2','he','k','co2','n2','so2','ar','h2o','co','ch4','nh3'])
fraction = np.array(dat.planet_atm(x))
cv = np.array([])
for i in gases:
cv1 = dat.c_v(i)
cv = np.hstack((cv,cv1))
cp = np.array([])
for i in gases:
cp1 = dat.c_p(i)
cp = np.hstack((cp,cp1))
t_cv = np.s... | def gamma(x):
| gases = np.array(['o2','na','h2','he','k','co2','n2','so2','ar','h2o','co','ch4','nh3'])
fraction = np.array(dat.planet_atm(x))
cv = np.array([])
for i in gases:
cv1 = dat.c_v(i)
cv = np.hstack((cv,cv1))
cp = np.array([])
for i in gases:
cp1 = dat.c_p(i)
cp = np.hstack((cp,cp1))
t_cv = np.sum(fraction*cv... | #Jayshil Patel
#This program calculates the adiabatic ratio for any atmosphere
#And average molecular weight for any atmosphere
import numpy as np
import astropy.constants as con
import astropy.units as u
import data as dat
def gamma(x):
| 56 | 64 | 150 | 4 | 51 | Jayshil/Planetory_atmosphere | atm_details.py | Python | gamma | gamma | 10 | 24 | 10 | 10 | a8aaa3ba387a4e8306cca23e06dd7b9a2c425757 | bigcode/the-stack | train |
ed19494f3203e10c3bc59500 | train | function | def updateDisplay(count, inbound):
drawCount(count, inbound)
| def updateDisplay(count, inbound):
| drawCount(count, inbound)
| .
draw = ImageDraw.Draw(image)
drawBitmap(draw, signs[number])
display.set_image(image)
display.write_display()
def clearDisplay():
image = Image.new('1', (8, 8))
display.set_image(image)
display.write_display()
def updateDisplay(count, inbound):
| 64 | 64 | 14 | 7 | 57 | mp911de/my-little-keller | cli/cli.py | Python | updateDisplay | updateDisplay | 92 | 93 | 92 | 92 | 286a1edd198a8a6b7a56c55ec78c9878a464ba01 | bigcode/the-stack | train |
37759a9d3f5e3540bf3b15a7 | train | function | def drawBitmap(draw, bitmap):
for x in range(0, 8):
row = (bitmap >> x * 8) & 0xFF
for y in range(0, 8):
if ((row & (1 << y)) != 0):
draw.point((7 - x, y), fill=255)
| def drawBitmap(draw, bitmap):
| for x in range(0, 8):
row = (bitmap >> x * 8) & 0xFF
for y in range(0, 8):
if ((row & (1 << y)) != 0):
draw.point((7 - x, y), fill=255)
| 3030303030303, # in
0x0705070000000000, # out
0x00040a1120408000, # check
0x6666006666666600 # exclamation
]
def drawBitmap(draw, bitmap):
| 64 | 64 | 74 | 7 | 57 | mp911de/my-little-keller | cli/cli.py | Python | drawBitmap | drawBitmap | 50 | 55 | 50 | 50 | 93e10f5a88a71ab6f0287b0c60139ac419ce371e | bigcode/the-stack | train |
aad2c3f28a88deecaa281045 | train | function | def clearDisplay():
image = Image.new('1', (8, 8))
display.set_image(image)
display.write_display()
| def clearDisplay():
| image = Image.new('1', (8, 8))
display.set_image(image)
display.write_display()
| an 8x8 1 bit color image.
image = Image.new('1', (8, 8))
# Then create a draw instance.
draw = ImageDraw.Draw(image)
drawBitmap(draw, signs[number])
display.set_image(image)
display.write_display()
def clearDisplay():
| 64 | 64 | 29 | 4 | 60 | mp911de/my-little-keller | cli/cli.py | Python | clearDisplay | clearDisplay | 86 | 89 | 86 | 86 | d1a03ebc4fb68c58ffbccb12098648789f05f9f8 | bigcode/the-stack | train |
a77114965772fe0e0059ce62 | train | function | def drawIcon(number):
# First create an 8x8 1 bit color image.
image = Image.new('1', (8, 8))
# Then create a draw instance.
draw = ImageDraw.Draw(image)
drawBitmap(draw, signs[number])
display.set_image(image)
display.write_display()
| def drawIcon(number):
# First create an 8x8 1 bit color image.
| image = Image.new('1', (8, 8))
# Then create a draw instance.
draw = ImageDraw.Draw(image)
drawBitmap(draw, signs[number])
display.set_image(image)
display.write_display()
| (inbound):
drawBitmap(draw, signs[0])
# Draw the image on the display buffer.
display.set_image(image)
# Draw the buffer to the display hardware.
display.write_display()
def drawIcon(number):
# First create an 8x8 1 bit color image.
| 64 | 64 | 69 | 20 | 44 | mp911de/my-little-keller | cli/cli.py | Python | drawIcon | drawIcon | 75 | 83 | 75 | 76 | 36b17ad1c1cd87967135f0411f56bb06de642497 | bigcode/the-stack | train |
6ea79d6683d182e5055407a8 | train | function | def drawCount(number, inbound):
# First create an 8x8 1 bit color image.
image = Image.new('1', (8, 8))
# Then create a draw instance.
draw = ImageDraw.Draw(image)
drawBitmap(draw, numbers[number - 1])
if (inbound):
drawBitmap(draw, signs[0])
# Draw the image on the display buffer.... | def drawCount(number, inbound):
# First create an 8x8 1 bit color image.
| image = Image.new('1', (8, 8))
# Then create a draw instance.
draw = ImageDraw.Draw(image)
drawBitmap(draw, numbers[number - 1])
if (inbound):
drawBitmap(draw, signs[0])
# Draw the image on the display buffer.
display.set_image(image)
# Draw the buffer to the display hardware.... | xFF
for y in range(0, 8):
if ((row & (1 << y)) != 0):
draw.point((7 - x, y), fill=255)
def drawCount(number, inbound):
# First create an 8x8 1 bit color image.
| 64 | 64 | 109 | 22 | 42 | mp911de/my-little-keller | cli/cli.py | Python | drawCount | drawCount | 58 | 72 | 58 | 59 | 5f2db7ee9adf14b516703b4da200731e5db6d567 | bigcode/the-stack | train |
80aa894770ea2085eb16520b | train | function | def test_dataset_get_indices_as_dataframe_duplicates():
ds = DatasetMetadata(
"some_uuid",
indices={
"l_external_code": ExplicitSecondaryIndex(
"l_external_code", {"1": ["part1", "part2"], "2": ["part1", "part2"]}
),
"p_external_code": ExplicitSeco... | def test_dataset_get_indices_as_dataframe_duplicates():
| ds = DatasetMetadata(
"some_uuid",
indices={
"l_external_code": ExplicitSecondaryIndex(
"l_external_code", {"1": ["part1", "part2"], "2": ["part1", "part2"]}
),
"p_external_code": ExplicitSecondaryIndex(
"p_external_code", {"1": ["p... | P=2/cluster_2"], name="partition"),
)
ds = dataset_with_index.load_partition_indices()
ds = ds.load_index("L", store_session)
result = ds.get_indices_as_dataframe()
pdt.assert_frame_equal(result, expected)
def test_dataset_get_indices_as_dataframe_duplicates():
| 64 | 64 | 197 | 9 | 55 | detritus3872/kartothek | tests/io_components/test_dataset.py | Python | test_dataset_get_indices_as_dataframe_duplicates | test_dataset_get_indices_as_dataframe_duplicates | 47 | 69 | 47 | 47 | 894cbf094bb71c5c7f1e19e9ba3784fb1d4c4f87 | bigcode/the-stack | train |
bd97b8cfaa572ddc702e4aea | train | function | def test_dataset_get_indices_as_dataframe(dataset_with_index, store_session):
expected = pd.DataFrame(
OrderedDict([("L", [1, 2]), ("P", [1, 2])]),
index=pd.Index(["P=1/cluster_1", "P=2/cluster_2"], name="partition"),
)
ds = dataset_with_index.load_partition_indices()
ds = ds.load_index(... | def test_dataset_get_indices_as_dataframe(dataset_with_index, store_session):
| expected = pd.DataFrame(
OrderedDict([("L", [1, 2]), ("P", [1, 2])]),
index=pd.Index(["P=1/cluster_1", "P=2/cluster_2"], name="partition"),
)
ds = dataset_with_index.load_partition_indices()
ds = ds.load_index("L", store_session)
result = ds.get_indices_as_dataframe()
pdt.assert... | P=2/cluster_2"], name="partition"),
)
ds = dataset_with_index.load_partition_indices()
result = ds.get_indices_as_dataframe(columns=dataset_with_index.partition_keys)
pdt.assert_frame_equal(result, expected)
def test_dataset_get_indices_as_dataframe(dataset_with_index, store_session):
| 64 | 64 | 113 | 14 | 50 | detritus3872/kartothek | tests/io_components/test_dataset.py | Python | test_dataset_get_indices_as_dataframe | test_dataset_get_indices_as_dataframe | 35 | 44 | 35 | 35 | d4dca138c825434a358283ecf797b0f4bdcac72c | bigcode/the-stack | train |
326a799934c329c020ed0cf9 | train | function | def test_dataset_get_indices_as_dataframe_raise_index_not_loaded(dataset_with_index):
with pytest.raises(RuntimeError):
dataset_with_index.get_indices_as_dataframe(
columns=dataset_with_index.partition_keys
)
| def test_dataset_get_indices_as_dataframe_raise_index_not_loaded(dataset_with_index):
| with pytest.raises(RuntimeError):
dataset_with_index.get_indices_as_dataframe(
columns=dataset_with_index.partition_keys
)
| require entire datasets, indices, etc
"""
from collections import OrderedDict
import pandas as pd
import pandas.testing as pdt
import pytest
from kartothek.core.dataset import DatasetMetadata
from kartothek.core.index import ExplicitSecondaryIndex
def test_dataset_get_indices_as_dataframe_raise_index_not_loaded(dat... | 64 | 64 | 42 | 15 | 48 | detritus3872/kartothek | tests/io_components/test_dataset.py | Python | test_dataset_get_indices_as_dataframe_raise_index_not_loaded | test_dataset_get_indices_as_dataframe_raise_index_not_loaded | 16 | 20 | 16 | 16 | 6d8ab14bc6bfd9ba5ade50c7368d36154cf28631 | bigcode/the-stack | train |
f6880544e547d6fdf1b93bb8 | train | function | def test_dataset_get_indices_as_dataframe_partition_keys_only(
dataset_with_index, store_session
):
expected = pd.DataFrame(
OrderedDict([("P", [1, 2])]),
index=pd.Index(["P=1/cluster_1", "P=2/cluster_2"], name="partition"),
)
ds = dataset_with_index.load_partition_indices()
result =... | def test_dataset_get_indices_as_dataframe_partition_keys_only(
dataset_with_index, store_session
):
| expected = pd.DataFrame(
OrderedDict([("P", [1, 2])]),
index=pd.Index(["P=1/cluster_1", "P=2/cluster_2"], name="partition"),
)
ds = dataset_with_index.load_partition_indices()
result = ds.get_indices_as_dataframe(columns=dataset_with_index.partition_keys)
pdt.assert_frame_equal(resul... | Index
def test_dataset_get_indices_as_dataframe_raise_index_not_loaded(dataset_with_index):
with pytest.raises(RuntimeError):
dataset_with_index.get_indices_as_dataframe(
columns=dataset_with_index.partition_keys
)
def test_dataset_get_indices_as_dataframe_partition_keys_only(
data... | 64 | 64 | 105 | 20 | 44 | detritus3872/kartothek | tests/io_components/test_dataset.py | Python | test_dataset_get_indices_as_dataframe_partition_keys_only | test_dataset_get_indices_as_dataframe_partition_keys_only | 23 | 32 | 23 | 25 | 4ef0954a89a8e4f82217c18f9dabbf66d03801d5 | bigcode/the-stack | train |
470fabad3b772c137204093b | train | function | def preprocess_image(img, img_width, img_height):
img = imresize(img, (img_height, img_width), interp='bicubic').astype('float32')
img = models.img_to_vgg(img)
img = np.expand_dims(img, axis=0)
return img
| def preprocess_image(img, img_width, img_height):
| img = imresize(img, (img_height, img_width), interp='bicubic').astype('float32')
img = models.img_to_vgg(img)
img = np.expand_dims(img, axis=0)
return img
| resize and format pictures into appropriate tensors
def load_image(image_path):
return imread(image_path, mode='RGB') # NOTE: this mode kwarg requires v0.17
# util function to open, resize and format pictures into appropriate tensors
def preprocess_image(img, img_width, img_height):
| 64 | 64 | 61 | 11 | 52 | awentzonline/keras-vgg-buddy | keras_vgg_buddy/img_utils.py | Python | preprocess_image | preprocess_image | 13 | 17 | 13 | 13 | 462fc88d4eb98da8bc3dedcac2c415a26faa7f09 | bigcode/the-stack | train |
360adbd5554cf5f16350e589 | train | function | def resize_image(img, img_width, img_height):
img = models.img_from_vgg(img)
img = imresize(img, (img_height, img_width), interp='bicubic').astype('float32')
img = models.img_to_vgg(img)
return img
| def resize_image(img, img_width, img_height):
| img = models.img_from_vgg(img)
img = imresize(img, (img_height, img_width), interp='bicubic').astype('float32')
img = models.img_to_vgg(img)
return img
| width:
n_rows = int(float(width) / n_cols * n_rows)
n_cols = width
if square:
n_rows = n_cols
img = preprocess_image(img, n_cols, n_rows)[0]
return img
def resize_image(img, img_width, img_height):
| 64 | 64 | 59 | 11 | 52 | awentzonline/keras-vgg-buddy | keras_vgg_buddy/img_utils.py | Python | resize_image | resize_image | 32 | 36 | 32 | 32 | 25a2a129aee61c1bc64cdb9d6086c2590c658cbc | bigcode/the-stack | train |
72d69bd69379548a4d7d6209 | train | function | def load_and_preprocess_image(path, width=None, square=False):
img = load_image(path)
n_channels, n_cols, n_rows = img.shape[::-1]
if width:
n_rows = int(float(width) / n_cols * n_rows)
n_cols = width
if square:
n_rows = n_cols
img = preprocess_image(img, n_cols, n_rows)[0]
... | def load_and_preprocess_image(path, width=None, square=False):
| img = load_image(path)
n_channels, n_cols, n_rows = img.shape[::-1]
if width:
n_rows = int(float(width) / n_cols * n_rows)
n_cols = width
if square:
n_rows = n_cols
img = preprocess_image(img, n_cols, n_rows)[0]
return img
| img = imresize(img, (img_height, img_width), interp='bicubic').astype('float32')
img = models.img_to_vgg(img)
img = np.expand_dims(img, axis=0)
return img
def load_and_preprocess_image(path, width=None, square=False):
| 64 | 64 | 91 | 14 | 49 | awentzonline/keras-vgg-buddy | keras_vgg_buddy/img_utils.py | Python | load_and_preprocess_image | load_and_preprocess_image | 20 | 29 | 20 | 20 | e82af5492c11739b004ad71a1c46534aea9cd6fe | bigcode/the-stack | train |
a78fd6b23273012c2bef36a9 | train | function | def deprocess_image(x, contrast_percent=0.0, resize=None):
x = models.img_from_vgg(x)
if contrast_percent:
min_x, max_x = np.percentile(x, (contrast_percent, 100 - contrast_percent))
x = (x - min_x) * 255.0 / (max_x - min_x)
x = np.clip(x, 0, 255)
if resize:
x = imresize(x, resiz... | def deprocess_image(x, contrast_percent=0.0, resize=None):
| x = models.img_from_vgg(x)
if contrast_percent:
min_x, max_x = np.percentile(x, (contrast_percent, 100 - contrast_percent))
x = (x - min_x) * 255.0 / (max_x - min_x)
x = np.clip(x, 0, 255)
if resize:
x = imresize(x, resize, interp='bicubic')
return x.astype('uint8')
| = imresize(img, (img_height, img_width), interp='bicubic').astype('float32')
img = models.img_to_vgg(img)
return img
# util function to convert a tensor into a valid image
def deprocess_image(x, contrast_percent=0.0, resize=None):
| 64 | 64 | 114 | 16 | 47 | awentzonline/keras-vgg-buddy | keras_vgg_buddy/img_utils.py | Python | deprocess_image | deprocess_image | 39 | 47 | 39 | 39 | efab52c553baea83a29fea3f77c30e357287f73b | bigcode/the-stack | train |
f84e52f7033443b0a791243b | train | function | def load_image(image_path):
return imread(image_path, mode='RGB') # NOTE: this mode kwarg requires v0.17
| def load_image(image_path):
| return imread(image_path, mode='RGB') # NOTE: this mode kwarg requires v0.17
| import numpy as np
from scipy.misc import imread, imresize
from . import models
# util function to open, resize and format pictures into appropriate tensors
def load_image(image_path):
| 40 | 64 | 31 | 6 | 33 | awentzonline/keras-vgg-buddy | keras_vgg_buddy/img_utils.py | Python | load_image | load_image | 8 | 9 | 8 | 8 | 9f48618b7b78e5604b8fde9a45397d4a85a0e2d5 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.