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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7531eccc66b02ddc3edb6c33 | train | class | class TestAssetApi(unittest.TestCase):
"""AssetApi unit test stubs"""
def setUp(self):
self.api = py_insightvm_sdk.api.asset_api.AssetApi() # noqa: E501
def tearDown(self):
pass
def test_add_asset_tag(self):
"""Test case for add_asset_tag
Asset Tag # noqa: E501
... | class TestAssetApi(unittest.TestCase):
| """AssetApi unit test stubs"""
def setUp(self):
self.api = py_insightvm_sdk.api.asset_api.AssetApi() # noqa: E501
def tearDown(self):
pass
def test_add_asset_tag(self):
"""Test case for add_asset_tag
Asset Tag # noqa: E501
"""
pass
def test_crea... | \"</a> and <a target=\"_blank\" href=\"http://json-schema.org/latest/json-schema-hypermedia.html\">JSON Hyper-Schema</a> <a target=\"_blank\" href=\"http://json-schema.org/latest/json-schema-hypermedia.html#rfc.section.5.2\">\"Link Description Object\"</a> formats. For example: ```json \"links\": [{ \"rel\": \"<re... | 256 | 256 | 887 | 8 | 247 | greenpau/py_insightvm_sdk | test/test_asset_api.py | Python | TestAssetApi | TestAssetApi | 23 | 205 | 23 | 23 | 15991631099dbbcd9160acb1e9a044170d04248b | bigcode/the-stack | train |
b7a9670ff49d4d444511d60a | train | class | class PackageReleaseTests(PackagesTestCase):
"""Unit tests for rbpkg.repository.package.PackageRelease."""
def test_deserialize_with_all_info(self):
"""Testing PackageRelease.deserialize with all available info"""
bundle = PackageBundle()
channel = PackageChannel(bundle)
release... | class PackageReleaseTests(PackagesTestCase):
| """Unit tests for rbpkg.repository.package.PackageRelease."""
def test_deserialize_with_all_info(self):
"""Testing PackageRelease.deserialize with all available info"""
bundle = PackageBundle()
channel = PackageChannel(bundle)
release = PackageRelease.deserialize(
ch... | from __future__ import unicode_literals
from rbpkg.repository.package_bundle import PackageBundle
from rbpkg.repository.package_channel import PackageChannel
from rbpkg.repository.package_release import PackageRelease
from rbpkg.repository.tests.testcases import PackagesTestCase
class PackageReleaseTests(PackagesTestC... | 60 | 118 | 395 | 10 | 49 | reviewboard/rbpkg | rbpkg/repository/tests/test_package_release.py | Python | PackageReleaseTests | PackageReleaseTests | 9 | 64 | 9 | 9 | d5b333b1048256ce4a31b018c8ea7e8122a6512a | bigcode/the-stack | train |
3baa4f63c809deea330cbaff | train | function | def yandex_map(request, map_id):
map = get_object_or_404(MapAndAddress, id=map_id)
ctx = {
'longitude': map.longitude,
'latitude': map.latitude,
'zoom': 15,
'address': map.address,
}
return render(request, 'yandex_maps/map.html', ctx)
| def yandex_map(request, map_id):
| map = get_object_or_404(MapAndAddress, id=map_id)
ctx = {
'longitude': map.longitude,
'latitude': map.latitude,
'zoom': 15,
'address': map.address,
}
return render(request, 'yandex_maps/map.html', ctx)
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from yandex_maps.models import MapAndAddress
def yandex_map(request, map_id):
| 51 | 64 | 74 | 9 | 41 | gelo-zhukov/yandex-maps | yandex_maps/views.py | Python | yandex_map | yandex_map | 8 | 16 | 8 | 8 | aee69fc08aa80bb156e1f986cd9533e37b133a44 | bigcode/the-stack | train |
65adcdb27332e453253dfa5d | train | class | class Session2QuestionsAndEnd:
def __init__(self):
self.responseUtils = ResponseManager.ResponseManager()
self.calorieRestrictionAnswers = SBC.SearchBasedConversation(calorieRestrictionConversation.conversation, "Calorie Restriction Questions")
self.sugarReductionAnswers = SBC.SearchBasedCon... | class Session2QuestionsAndEnd:
| def __init__(self):
self.responseUtils = ResponseManager.ResponseManager()
self.calorieRestrictionAnswers = SBC.SearchBasedConversation(calorieRestrictionConversation.conversation, "Calorie Restriction Questions")
self.sugarReductionAnswers = SBC.SearchBasedConversation(sugarRestrictionConve... | import management_utils.response_manager as ResponseManager
import management_utils.search_based_conversation as SBC
import data_retrieval.memoryManager as shortTermData
import management_utils.diabetesConversation as diabetesConversation
from management_utils import calorieRestrictionConversation, sugarRestrictionConv... | 72 | 256 | 2,245 | 7 | 64 | asarav/MSc-Thesis-Experience-Sharing-Conversational-Agent | Client/dialogue_states/session2QuestonsAndEnd.py | Python | Session2QuestionsAndEnd | Session2QuestionsAndEnd | 9 | 254 | 9 | 9 | 80f9d82024055ea2df28171f9e2e5f7edd1aac82 | bigcode/the-stack | train |
1f1a93ae7857755d9a4c184a | train | function | def cmo(close, length=None, scalar=None, drift=None, offset=None, **kwargs):
"""Indicator: Chande Momentum Oscillator (CMO)"""
# Validate Arguments
close = verify_series(close)
length = int(length) if length and length > 0 else 14
scalar = float(scalar) if scalar else 100
drift = get_drift(drift... | def cmo(close, length=None, scalar=None, drift=None, offset=None, **kwargs):
| """Indicator: Chande Momentum Oscillator (CMO)"""
# Validate Arguments
close = verify_series(close)
length = int(length) if length and length > 0 else 14
scalar = float(scalar) if scalar else 100
drift = get_drift(drift)
offset = get_offset(offset)
# Calculate Result
negative = clos... | # -*- coding: utf-8 -*-
from ..utils import get_drift, get_offset, verify_series
def cmo(close, length=None, scalar=None, drift=None, offset=None, **kwargs):
| 42 | 98 | 327 | 20 | 21 | Ziinax/pandas-ta | pandas_ta/momentum/cmo.py | Python | cmo | cmo | 4 | 40 | 4 | 4 | 124a105dd63ae2b0645482169ffd25617d03366a | bigcode/the-stack | train |
4e6195c2328c554e16758871 | train | function | def autocomplete(choice, options):
possibilities = [pos for pos in options if choice == pos[0:len(choice)]]
return possibilities
| def autocomplete(choice, options):
| possibilities = [pos for pos in options if choice == pos[0:len(choice)]]
return possibilities
| #!/usr/bin/env python3
def autocomplete(choice, options):
| 13 | 64 | 30 | 6 | 6 | iatenine/Coders-Workshop | Contributors/GabrielConlon/autocomplete/autocomplete.py | Python | autocomplete | autocomplete | 3 | 6 | 3 | 3 | 584165992bb27c07ba688d2e417d9cd1dd99a27e | bigcode/the-stack | train |
7e887931d72c9fdcaefa109a | train | function | def main():
print(autocomplete("ed", ["educate", "edify", "opted"]))
| def main():
| print(autocomplete("ed", ["educate", "edify", "opted"]))
| #!/usr/bin/env python3
def autocomplete(choice, options):
possibilities = [pos for pos in options if choice == pos[0:len(choice)]]
return possibilities
def main():
| 40 | 64 | 22 | 3 | 36 | iatenine/Coders-Workshop | Contributors/GabrielConlon/autocomplete/autocomplete.py | Python | main | main | 8 | 9 | 8 | 8 | c7110d6cf1b186e2fa8cf9bddb8d8a712ed69e1b | bigcode/the-stack | train |
e81f5693d4a99f6443e76f00 | train | function | def _write_to_serial(text_input, log_lines):
log = lambda s: log_lines([s])
if not _serial:
log('No serial port open.')
return
_serial.write(text_input.get().encode('utf8')+b'\r\n')
text_input.delete(0, 'end')
| def _write_to_serial(text_input, log_lines):
| log = lambda s: log_lines([s])
if not _serial:
log('No serial port open.')
return
_serial.write(text_input.get().encode('utf8')+b'\r\n')
text_input.delete(0, 'end')
| ))
load_button.pack(side='left', padx=(10, 0))
save_button = tkinter.Button(frame, text='Save', padx=10, command=lambda: _save_file(log_lines))
save_button.pack(side='left')
return frame
def _write_to_serial(text_input, log_lines):
| 64 | 64 | 68 | 11 | 52 | tmontes/puppy | src/puppy/__main__.py | Python | _write_to_serial | _write_to_serial | 101 | 110 | 101 | 102 | b35c3e0e49be047f1f6119526ccca3732daee728 | bigcode/the-stack | train |
2fc53ec1ef2485b52f614cc8 | train | function | def _populate_serial_ports(window, serial_select, log_lines):
serial_devices = [
port.device
for port in serial.tools.list_ports.comports()
]
serial_select['values'] = serial_devices
log_lines([
'Serial devices:',
*map(lambda s: f' {s!r}', serial_devices),
'',... | def _populate_serial_ports(window, serial_select, log_lines):
| serial_devices = [
port.device
for port in serial.tools.list_ports.comports()
]
serial_select['values'] = serial_devices
log_lines([
'Serial devices:',
*map(lambda s: f' {s!r}', serial_devices),
'',
])
serial_select.bind(
'<<ComboboxSelected>>'... | _lines([s])
if not _serial:
log('No serial port open.')
return
_serial.write(text_input.get().encode('utf8')+b'\r\n')
text_input.delete(0, 'end')
def _populate_serial_ports(window, serial_select, log_lines):
| 63 | 64 | 106 | 13 | 50 | tmontes/puppy | src/puppy/__main__.py | Python | _populate_serial_ports | _populate_serial_ports | 114 | 130 | 114 | 115 | 4a3c6a681c9d759066766c892eb79b8e3f5663a5 | bigcode/the-stack | train |
8d4c17134e92b004aed285ef | train | function | def _top_frame_widget(window):
frame = tkinter.Frame()
file_path = ilr.files(__package__) / 'logo.png'
# Must keep reference to PhotoImage, otherwise it doesn't become visible
_top_frame_widget.img = tkinter.PhotoImage(file=file_path)
tkinter.Label(
frame,
image=_top_frame_widget.... | def _top_frame_widget(window):
| frame = tkinter.Frame()
file_path = ilr.files(__package__) / 'logo.png'
# Must keep reference to PhotoImage, otherwise it doesn't become visible
_top_frame_widget.img = tkinter.PhotoImage(file=file_path)
tkinter.Label(
frame,
image=_top_frame_widget.img,
).pack(
side='l... | w}x{h}+{x}+{y}')
window.minsize(w, h)
meta = ilm.metadata(__package__)
name = meta['name']
version = meta['version']
window.title(f'{name} {version}')
return window
def _top_frame_widget(window):
| 64 | 64 | 125 | 7 | 56 | tmontes/puppy | src/puppy/__main__.py | Python | _top_frame_widget | _top_frame_widget | 47 | 71 | 47 | 48 | 5f462e687d9dda54f284fd2e71f9221d5d3ee996 | bigcode/the-stack | train |
ac543cd053da7f4415da6a97 | train | function | def _create_window():
window = tkinter.Tk()
screen_w = window.winfo_screenwidth()
screen_h = window.winfo_screenheight()
w = (screen_w // 2) - 16
h = (screen_h // 2) - 16
x = (screen_w - w) // 2
y = (screen_h - h) // 2
window.geometry(f'{w}x{h}+{x}+{y}')
window.minsize(w, h)
... | def _create_window():
| window = tkinter.Tk()
screen_w = window.winfo_screenwidth()
screen_h = window.winfo_screenheight()
w = (screen_w // 2) - 16
h = (screen_h // 2) - 16
x = (screen_w - w) // 2
y = (screen_h - h) // 2
window.geometry(f'{w}x{h}+{x}+{y}')
window.minsize(w, h)
meta = ilm.metadata(__p... | pprint
import sys
import tkinter
import tkinter.ttk
import tkinter.filedialog
import importlib_metadata as ilm
import importlib_resources as ilr
import serial
import serial.tools.list_ports
# The serial.Serial object we're connected to, if any.
_serial = None
def _create_window():
| 64 | 64 | 148 | 5 | 58 | tmontes/puppy | src/puppy/__main__.py | Python | _create_window | _create_window | 24 | 43 | 24 | 25 | 0484b8a464b0c4c512e2500dbb39dddd4f2e2051 | bigcode/the-stack | train |
6412ff849f49189bcf68ddca | train | function | def _add_widgets(window):
_top_frame_widget(window).pack(
side='top',
fill='x',
padx=16,
pady=16,
)
log_widget = tkinter.Text(
window,
highlightthickness=1,
highlightcolor='lightgray',
state=tkinter.DISABLED,
wrap='none',
heig... | def _add_widgets(window):
| _top_frame_widget(window).pack(
side='top',
fill='x',
padx=16,
pady=16,
)
log_widget = tkinter.Text(
window,
highlightthickness=1,
highlightcolor='lightgray',
state=tkinter.DISABLED,
wrap='none',
height=1,
padx=8,
... | , 'wb') as f:
log(f'Writing payload...')
f.write(payload)
except OSError as e:
log(f'Failed: {e}.')
else:
log(f'Wrote {payload!r}.')
finally:
log('')
def _add_widgets(window):
| 63 | 64 | 211 | 6 | 58 | tmontes/puppy | src/puppy/__main__.py | Python | _add_widgets | _add_widgets | 205 | 242 | 205 | 206 | 8f42ea2497a85114eb1a0b2252e797461fc08f03 | bigcode/the-stack | train |
545613c9cc17e4916b7406e1 | train | function | def _bottom_frame_widget(window, log_lines):
frame = tkinter.Frame()
text_input = tkinter.Entry(frame)
text_input.pack(side='left', fill='x', expand=True)
text_input.bind('<Return>', lambda _: _write_to_serial(text_input, log_lines))
text_input.focus()
serial_select = tkinter.ttk.Combobox(
... | def _bottom_frame_widget(window, log_lines):
| frame = tkinter.Frame()
text_input = tkinter.Entry(frame)
text_input.pack(side='left', fill='x', expand=True)
text_input.bind('<Return>', lambda _: _write_to_serial(text_input, log_lines))
text_input.focus()
serial_select = tkinter.ttk.Combobox(
frame,
state='readonly',
)
... | ,
).pack(
side='left',
)
tkinter.Label(
frame,
text='Minimal GUI app to test pup.',
justify='left',
).pack(
side='left',
padx=16,
)
return frame
def _bottom_frame_widget(window, log_lines):
| 64 | 64 | 206 | 10 | 53 | tmontes/puppy | src/puppy/__main__.py | Python | _bottom_frame_widget | _bottom_frame_widget | 75 | 98 | 75 | 76 | 55e436dab97782c109d17cb4852ac2df0e1682db | bigcode/the-stack | train |
0acb51d97b61230faa850f27 | train | function | def main():
window = _create_window()
log_lines = _add_widgets(window)
log_lines([
'os.getcwd():',
f' {os.getcwd()!r}',
'',
'sys.path:',
*map(lambda s: f' {s!r}', sys.path),
'',
])
tkinter.mainloop()
| def main():
| window = _create_window()
log_lines = _add_widgets(window)
log_lines([
'os.getcwd():',
f' {os.getcwd()!r}',
'',
'sys.path:',
*map(lambda s: f' {s!r}', sys.path),
'',
])
tkinter.mainloop()
| log_widget.yview('end')
log_widget.configure(state=tkinter.DISABLED)
window.update()
_bottom_frame_widget(window, log_lines).pack(
side='top',
fill='x',
padx=16,
pady=16,
)
return log_lines
def main():
| 64 | 64 | 72 | 3 | 60 | tmontes/puppy | src/puppy/__main__.py | Python | main | main | 245 | 259 | 245 | 246 | 5349fb9d59f23093eeb4612acdc38c97315cbff0 | bigcode/the-stack | train |
244ec4cc9007fab97887eee5 | train | function | def _select_serial_port(window, serial_device, log_lines):
global _serial
log = lambda s: log_lines([s])
if _serial:
log(f'Closing {_serial.name!r}.')
_serial.close()
log(f'Opening {serial_device!r}.')
try:
_serial = serial.Serial(serial_device, 115200, timeout=0.05)
e... | def _select_serial_port(window, serial_device, log_lines):
| global _serial
log = lambda s: log_lines([s])
if _serial:
log(f'Closing {_serial.name!r}.')
_serial.close()
log(f'Opening {serial_device!r}.')
try:
_serial = serial.Serial(serial_device, 115200, timeout=0.05)
except Exception as exc:
log(f'Failed: {exc}.')
... | map(lambda s: f' {s!r}', serial_devices),
'',
])
serial_select.bind(
'<<ComboboxSelected>>',
lambda _: _select_serial_port(window, serial_select.get(), log_lines),
)
def _select_serial_port(window, serial_device, log_lines):
| 63 | 64 | 150 | 13 | 50 | tmontes/puppy | src/puppy/__main__.py | Python | _select_serial_port | _select_serial_port | 134 | 154 | 134 | 135 | cb4cf52b47c13932d0a38af6295cc188e5d639f2 | bigcode/the-stack | train |
81f4d375e4ebdd0ee9a3ce52 | train | function | def _save_file(log_lines):
log = lambda s: log_lines([s])
filename = tkinter.filedialog.asksaveasfilename()
log(f'Opening {filename!r} in write mode...')
payload = b'puppy wrote this file!\n'
try:
with open(filename, 'wb') as f:
log(f'Writing payload...')
f.write(pa... | def _save_file(log_lines):
| log = lambda s: log_lines([s])
filename = tkinter.filedialog.asksaveasfilename()
log(f'Opening {filename!r} in write mode...')
payload = b'puppy wrote this file!\n'
try:
with open(filename, 'wb') as f:
log(f'Writing payload...')
f.write(payload)
except OSError as... | f:
log(f'Reading 128 bytes...')
payload = f.read(128)
except OSError as e:
log(f'Failed: {e}.')
else:
log(f'Read {payload!r}.')
finally:
log('')
def _save_file(log_lines):
| 63 | 64 | 122 | 7 | 57 | tmontes/puppy | src/puppy/__main__.py | Python | _save_file | _save_file | 186 | 202 | 186 | 187 | bc6cf52c8920176f41ab56769b366a4958d77e80 | bigcode/the-stack | train |
c918e4d8f5a121850c6b3e9d | train | function | def _load_file(log_lines):
log = lambda s: log_lines([s])
filename = tkinter.filedialog.askopenfilename()
log(f'Opening {filename!r} in read mode...')
try:
with open(filename, 'rb') as f:
log(f'Reading 128 bytes...')
payload = f.read(128)
except OSError as e:
... | def _load_file(log_lines):
| log = lambda s: log_lines([s])
filename = tkinter.filedialog.askopenfilename()
log(f'Opening {filename!r} in read mode...')
try:
with open(filename, 'rb') as f:
log(f'Reading 128 bytes...')
payload = f.read(128)
except OSError as e:
log(f'Failed: {e}.')
e... | :
line = _serial.readline()
if line:
text_line = line.decode('utf8', errors='replace').rstrip('\r\n')
log(f'| {text_line}')
window.after(100, lambda: _read_serial_port(window, log))
def _load_file(log_lines):
| 63 | 64 | 111 | 7 | 56 | tmontes/puppy | src/puppy/__main__.py | Python | _load_file | _load_file | 168 | 183 | 168 | 169 | ab7b8fe1a0fff3aa64f9b4ebb272060c8f2fed11 | bigcode/the-stack | train |
5ae50a5f33320bb3e6346be6 | train | function | def _read_serial_port(window, log):
if _serial:
line = _serial.readline()
if line:
text_line = line.decode('utf8', errors='replace').rstrip('\r\n')
log(f'| {text_line}')
window.after(100, lambda: _read_serial_port(window, log))
| def _read_serial_port(window, log):
| if _serial:
line = _serial.readline()
if line:
text_line = line.decode('utf8', errors='replace').rstrip('\r\n')
log(f'| {text_line}')
window.after(100, lambda: _read_serial_port(window, log))
| Failed: {exc}.')
_serial = None
return
log(f'Opened {_serial.name!r}:')
log('')
_serial.write(b'\x02')
window.after(100, lambda: _read_serial_port(window, log))
def _read_serial_port(window, log):
| 64 | 64 | 69 | 9 | 55 | tmontes/puppy | src/puppy/__main__.py | Python | _read_serial_port | _read_serial_port | 157 | 164 | 157 | 158 | b40a08c89447167ffe0f7aca413a6219d7d20a26 | bigcode/the-stack | train |
ae6e4ed6ce8991a5986e0157 | train | function | def test_bazeldeps_interface_buildfiles():
conanfile = ConanFile(Mock(), None)
cpp_info = CppInfo("mypkg", "dummy_root_folder2")
conanfile_dep = ConanFile(Mock(), None)
conanfile_dep.cpp_info = cpp_info
conanfile_dep._conan_node = Mock()
conanfile_dep._conan_node.ref = ConanFileReference.loads... | def test_bazeldeps_interface_buildfiles():
| conanfile = ConanFile(Mock(), None)
cpp_info = CppInfo("mypkg", "dummy_root_folder2")
conanfile_dep = ConanFile(Mock(), None)
conanfile_dep.cpp_info = cpp_info
conanfile_dep._conan_node = Mock()
conanfile_dep._conan_node.ref = ConanFileReference.loads("OriginalDepName/2.0")
with mock.patc... | = "OriginalDepName",' in dependency_content
assert 'defines = ["DUMMY_DEFINE=\'string/value\'"],' in dependency_content
assert 'linkopts = ["-lsystem_lib1"],' in dependency_content
assert 'deps = [\n \n ":lib1_precompiled",' in dependency_content
def test_bazeldeps_interface_b... | 79 | 79 | 266 | 10 | 68 | mohammadzainabbas/conan | conans/test/unittests/tools/google/test_bazeldeps.py | Python | test_bazeldeps_interface_buildfiles | test_bazeldeps_interface_buildfiles | 41 | 59 | 41 | 41 | afe54726969c305c48af7e1fcfbd82a530b71c35 | bigcode/the-stack | train |
ede2828383e453ea5ef9eafc | train | function | def test_bazeldeps_dependency_buildfiles():
conanfile = ConanFile(Mock(), None)
cpp_info = CppInfo("mypkg", "dummy_root_folder1")
cpp_info.defines = ["DUMMY_DEFINE=\"string/value\""]
cpp_info.system_libs = ["system_lib1"]
cpp_info.libs = ["lib1"]
conanfile_dep = ConanFile(Mock(), None)
con... | def test_bazeldeps_dependency_buildfiles():
| conanfile = ConanFile(Mock(), None)
cpp_info = CppInfo("mypkg", "dummy_root_folder1")
cpp_info.defines = ["DUMMY_DEFINE=\"string/value\""]
cpp_info.system_libs = ["system_lib1"]
cpp_info.libs = ["lib1"]
conanfile_dep = ConanFile(Mock(), None)
conanfile_dep.cpp_info = cpp_info
conanfile... | import mock
from mock import Mock
import re
from conan.tools.google import BazelDeps
from conans import ConanFile
from conans.model.build_info import CppInfo
from conans.model.conanfile_interface import ConanFileInterface
from conans.model.dependencies import Requirement, ConanFileDependencies
from conans.model.ref im... | 84 | 100 | 336 | 10 | 73 | mohammadzainabbas/conan | conans/test/unittests/tools/google/test_bazeldeps.py | Python | test_bazeldeps_dependency_buildfiles | test_bazeldeps_dependency_buildfiles | 13 | 38 | 13 | 13 | 66c3b1c0d6688a6e4a41b5cf4c70fdc4f0d5a342 | bigcode/the-stack | train |
0015d313d122bd7e1d216305 | train | function | def test_bazeldeps_main_buildfile():
expected_content = [
'def load_conan_dependencies():',
'native.new_local_repository(',
'name="OriginalDepName",',
'path="/path/to/folder_dep",',
'build_file="conandeps/OriginalDepName/BUILD",'
]
conanfile = ConanFile(Mock(), None)... | def test_bazeldeps_main_buildfile():
| expected_content = [
'def load_conan_dependencies():',
'native.new_local_repository(',
'name="OriginalDepName",',
'path="/path/to/folder_dep",',
'build_file="conandeps/OriginalDepName/BUILD",'
]
conanfile = ConanFile(Mock(), None)
cpp_info = CppInfo("mypkg", "du... | next(iter(bazeldeps._conanfile.dependencies.host.values()))
dependency_content = re.sub(r"\s", "", bazeldeps._get_dependency_buildfile_content(dependency))
assert(dependency_content == 'load("@rules_cc//cc:defs.bzl","cc_import","cc_library")cc_library(name="OriginalDepName",hdrs=glob(["include/**"]),in... | 99 | 100 | 334 | 10 | 90 | mohammadzainabbas/conan | conans/test/unittests/tools/google/test_bazeldeps.py | Python | test_bazeldeps_main_buildfile | test_bazeldeps_main_buildfile | 62 | 96 | 62 | 62 | 08f93a7007dc5f32a66f8260b7b8cc54c8bc4d54 | bigcode/the-stack | train |
80521a4898c6342cdcddd400 | train | function | def fcn_sherrah2016_classifier(input_shape, for_receptive_field=False):
def activation_if(for_receptive_field, x):
if for_receptive_field:
# for estimation of receptive field, we need to use linear operators
x = Activation('linear')(x)
x = BatchNormalization(axis=3)(x)
... | def fcn_sherrah2016_classifier(input_shape, for_receptive_field=False):
| def activation_if(for_receptive_field, x):
if for_receptive_field:
# for estimation of receptive field, we need to use linear operators
x = Activation('linear')(x)
x = BatchNormalization(axis=3)(x)
else:
# for regular training and inference, we use non... | = 804.2 pixel**2)
smallest_cell_area = 804
# training window length
training_window_len = 401
# remove from training cells that don't have a good enough overlap with a reference label
smallest_dice = 0.5
# segmentations with Dice >= threshold are accepted
dice_threshold = 0.9
# batch size for training
batch_size =... | 246 | 247 | 824 | 19 | 227 | rcasero/cytometer | scripts/klf14_b6ntac_exp_0088_cnn_tissue_classifier_fcn.py | Python | fcn_sherrah2016_classifier | fcn_sherrah2016_classifier | 123 | 186 | 123 | 124 | c72e033876c8c05d121a50dd919470aba9be3b44 | bigcode/the-stack | train |
4c0ae0cfbee2582ba443d0cb | train | function | def github_auth_callback_view(request):
if not settings.GITHUB_CLIENT_ID:
return HttpResponseNotFound("Sorry, GitHub Integration not configured on this server")
error = request.GET.get("error")
if error == "access_denied":
# The user clicked on "Cancel" instead of "Authorize".
# ?error=access_denied&error_de... | def github_auth_callback_view(request):
| if not settings.GITHUB_CLIENT_ID:
return HttpResponseNotFound("Sorry, GitHub Integration not configured on this server")
error = request.GET.get("error")
if error == "access_denied":
# The user clicked on "Cancel" instead of "Authorize".
# ?error=access_denied&error_description=The+user+has+denied+your+appli... | ="Login failed", data={})
auth.login(request, user)
return JsonResponse({
"user": user_plain(request.user),
})
@require_POST
@csrf_exempt
def logout_view(request):
auth.logout(request)
return JsonResponse({})
@require_GET
def profile_view(request):
user = request.user
return JsonResponse({
"user": user... | 256 | 256 | 1,118 | 7 | 249 | sharat87/prestige | backend/auth_api/views.py | Python | github_auth_callback_view | github_auth_callback_view | 216 | 353 | 216 | 216 | 040a6d57f5ba8464764c280960c0cdacb58767b1 | bigcode/the-stack | train |
a319da53bed0a9052e9f8ba5 | train | function | @require_GET
def profile_view(request):
user = request.user
return JsonResponse({
"user": user_plain(user) if user.is_authenticated else None,
})
| @require_GET
def profile_view(request):
| user = request.user
return JsonResponse({
"user": user_plain(user) if user.is_authenticated else None,
})
| .UNAUTHORIZED, reason="Login failed", data={})
auth.login(request, user)
return JsonResponse({
"user": user_plain(request.user),
})
@require_POST
@csrf_exempt
def logout_view(request):
auth.logout(request)
return JsonResponse({})
@require_GET
def profile_view(request):
| 63 | 64 | 35 | 9 | 55 | sharat87/prestige | backend/auth_api/views.py | Python | profile_view | profile_view | 184 | 189 | 184 | 185 | 9e3fb59c823dc13b4ed7a8b2d907eacaf49897c6 | bigcode/the-stack | train |
0265d13d509ad7cd21ce7c4e | train | function | @require_POST
@csrf_exempt
def signup_view(request):
email: str = request.parsed_body.get("email")
if not email:
return JsonResponse(status=HTTPStatus.BAD_REQUEST, reason="Missing email", data={
"error": {
"message": "Missing/empty email field in body.",
},
})
if not isinstance(email, str):
return J... | @require_POST
@csrf_exempt
def signup_view(request):
| email: str = request.parsed_body.get("email")
if not email:
return JsonResponse(status=HTTPStatus.BAD_REQUEST, reason="Missing email", data={
"error": {
"message": "Missing/empty email field in body.",
},
})
if not isinstance(email, str):
return JsonResponse(status=HTTPStatus.BAD_REQUEST, reason="In... | import logging
from http import HTTPStatus
import json
import secrets
import requests
from django.conf import settings
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.db import IntegrityError
from django.http import HttpResponse, JsonResponse, HttpResponseNotFound
from django... | 120 | 256 | 1,009 | 14 | 106 | sharat87/prestige | backend/auth_api/views.py | Python | signup_view | signup_view | 22 | 146 | 22 | 24 | 023205fd60ea321beadfc9fe066adafd95b19fb0 | bigcode/the-stack | train |
2e59d8a5cd144274e1c573ee | train | function | def github_auth_view(request):
if not settings.GITHUB_CLIENT_ID:
return HttpResponseNotFound("Sorry, GitHub Integration not configured on this server")
state_token = secrets.token_urlsafe(64)
request.session["github_auth_state_token"] = state_token
log.error("Ext url prefix is %r", settings.EXT_URL_PREFIX)
ret... | def github_auth_view(request):
| if not settings.GITHUB_CLIENT_ID:
return HttpResponseNotFound("Sorry, GitHub Integration not configured on this server")
state_token = secrets.token_urlsafe(64)
request.session["github_auth_state_token"] = state_token
log.error("Ext url prefix is %r", settings.EXT_URL_PREFIX)
return redirect(
f"{settings.EXT... | return JsonResponse({
"user": user_plain(user) if user.is_authenticated else None,
})
def user_plain(user):
return {
"username": user.username,
"email": user.email,
"isGitHubConnected": user.github_ids.exists(),
}
def github_auth_view(request):
| 64 | 64 | 126 | 6 | 58 | sharat87/prestige | backend/auth_api/views.py | Python | github_auth_view | github_auth_view | 200 | 213 | 200 | 200 | 7228c933917af27d976388b8f7952e9771d962d7 | bigcode/the-stack | train |
920a1a7e8ecc59330e2f69ec | train | function | def js_message_response(is_approved: bool, error: str = None) -> HttpResponse:
data = {
"type": "oauth",
"provider": "github",
"isApproved": is_approved,
"error": error,
}
return HttpResponse(content="""<!doctype html>
<title>Prestige</title>
<h1>Finished. This window should close.</h1>
<script>
// TODO... | def js_message_response(is_approved: bool, error: str = None) -> HttpResponse:
| data = {
"type": "oauth",
"provider": "github",
"isApproved": is_approved,
"error": error,
}
return HttpResponse(content="""<!doctype html>
<title>Prestige</title>
<h1>Finished. This window should close.</h1>
<script>
// TODO: Specify the incoming Origin here, instead of `*`.
// See <https://developer.... | Identity object %r %r", github_user_id, updates)
raise
else:
GitHubIdentity.objects.filter(user=user).update(**updates)
auth.login(request, user)
return js_message_response(True)
def js_message_response(is_approved: bool, error: str = None) -> HttpResponse:
| 64 | 64 | 149 | 20 | 44 | sharat87/prestige | backend/auth_api/views.py | Python | js_message_response | js_message_response | 356 | 373 | 356 | 356 | 4071769ffde4f74204bde473727460c0fe566cad | bigcode/the-stack | train |
595b25b0e942fcd96bd39ea7 | train | function | @require_POST
@csrf_exempt
def login_view(request):
email = request.parsed_body.get("email")
if not email:
return JsonResponse(status=HTTPStatus.BAD_REQUEST, reason="Missing email", data={})
if not isinstance(email, str):
return JsonResponse(status=HTTPStatus.BAD_REQUEST, reason="Invalid email", data={})
pass... | @require_POST
@csrf_exempt
def login_view(request):
| email = request.parsed_body.get("email")
if not email:
return JsonResponse(status=HTTPStatus.BAD_REQUEST, reason="Missing email", data={})
if not isinstance(email, str):
return JsonResponse(status=HTTPStatus.BAD_REQUEST, reason="Invalid email", data={})
password = request.parsed_body.get("password")
if not p... | "message": f"This {field_name} already has an account.",
},
})
raise
auth.login(request, user)
return JsonResponse(status=HTTPStatus.CREATED, data={
"user": user_plain(user),
})
@require_POST
@csrf_exempt
def login_view(request):
| 64 | 64 | 189 | 14 | 50 | sharat87/prestige | backend/auth_api/views.py | Python | login_view | login_view | 149 | 174 | 149 | 151 | 93f819eda5ffc784cba974e79ef662b77124258c | bigcode/the-stack | train |
160ccb81ef3cfd9f62a4fd6c | train | function | @require_POST
@csrf_exempt
def logout_view(request):
auth.logout(request)
return JsonResponse({})
| @require_POST
@csrf_exempt
def logout_view(request):
| auth.logout(request)
return JsonResponse({})
| =email, password=password)
if user is None:
return JsonResponse(status=HTTPStatus.UNAUTHORIZED, reason="Login failed", data={})
auth.login(request, user)
return JsonResponse({
"user": user_plain(request.user),
})
@require_POST
@csrf_exempt
def logout_view(request):
| 64 | 64 | 22 | 14 | 50 | sharat87/prestige | backend/auth_api/views.py | Python | logout_view | logout_view | 177 | 181 | 177 | 179 | 7182dd42fe0325b221d0d3ee9cc8ecb2f9aac32a | bigcode/the-stack | train |
e6d10a3b7583a026da62f7fd | train | function | def user_plain(user):
return {
"username": user.username,
"email": user.email,
"isGitHubConnected": user.github_ids.exists(),
}
| def user_plain(user):
| return {
"username": user.username,
"email": user.email,
"isGitHubConnected": user.github_ids.exists(),
}
| })
@require_POST
@csrf_exempt
def logout_view(request):
auth.logout(request)
return JsonResponse({})
@require_GET
def profile_view(request):
user = request.user
return JsonResponse({
"user": user_plain(user) if user.is_authenticated else None,
})
def user_plain(user):
| 64 | 64 | 37 | 5 | 59 | sharat87/prestige | backend/auth_api/views.py | Python | user_plain | user_plain | 192 | 197 | 192 | 192 | 6c2b8320b399b6d1e8fa25402df477fd7af69f30 | bigcode/the-stack | train |
fbaa89114c807178e2f4e90b | train | class | class MsLogFactroy(object):
"""The log factory for creating new loggers using the logger providers."""
# the default logger create locker
__dft_lgr_locker = threading.Lock()
# the initial locker
__locker = threading.Lock()
__initialed: bool = False
# all logger providers on using
prov... | class MsLogFactroy(object):
| """The log factory for creating new loggers using the logger providers."""
# the default logger create locker
__dft_lgr_locker = threading.Lock()
# the initial locker
__locker = threading.Lock()
__initialed: bool = False
# all logger providers on using
providers: list = []
__dft_... | """The log factory for creating new loggers using the logger providers."""
# -*- coding:utf-8 -*-
import threading
from .mslogconfig import MsLogConfig
from .mslogger import MsLogger
from .msloglevel import MsLogLevel, MsLogLevels
from .mslogprovider import MsLogProvider
class MsLogFactroy(object):
| 73 | 201 | 673 | 7 | 65 | Octoberr/swm0920 | savecode/pythonpackages/commonbaby/mslog/mslogfactory.py | Python | MsLogFactroy | MsLogFactroy | 13 | 94 | 13 | 13 | 1f1e2e7d88f41179338ca9c5bdf09d7b36a80fe4 | bigcode/the-stack | train |
71f51ba0eaa8a7d7c20d0d6e | train | function | def find_models() -> Iterable[str]:
for name in os.listdir("api/allennlp_demo"):
if name.startswith("."):
continue
path = os.path.join("api/allennlp_demo/", name)
if not os.path.isdir(path):
continue
config_path = os.path.join(path, "model.json")
if no... | def find_models() -> Iterable[str]:
| for name in os.listdir("api/allennlp_demo"):
if name.startswith("."):
continue
path = os.path.join("api/allennlp_demo/", name)
if not os.path.isdir(path):
continue
config_path = os.path.join(path, "model.json")
if not os.path.isfile(config_path):
... | """
Script to verify that all demo models are covered by CI in our GitHub Actions workflow.
"""
import yaml
import os
from typing import Iterable
WORKFLOW_FILE_PATH = ".github/workflows/ci.yml"
def find_models() -> Iterable[str]:
| 52 | 64 | 85 | 8 | 44 | jvstokes/allennlp-demo | dev/check_models_ci.py | Python | find_models | find_models | 13 | 23 | 13 | 13 | 93b930d4a601f404a2a81649c515166f78295c88 | bigcode/the-stack | train |
047d9d6e5c8e952969f491b7 | train | function | def main():
with open(WORKFLOW_FILE_PATH) as workflow_file:
workflow = yaml.load(workflow_file, Loader=yaml.FullLoader)
tested_models = set(
workflow["jobs"]["endpoint_test"]["strategy"]["matrix"]["model"]
)
all_models = set(find_models())
for model in all_models:
assert mode... | def main():
| with open(WORKFLOW_FILE_PATH) as workflow_file:
workflow = yaml.load(workflow_file, Loader=yaml.FullLoader)
tested_models = set(
workflow["jobs"]["endpoint_test"]["strategy"]["matrix"]["model"]
)
all_models = set(find_models())
for model in all_models:
assert model in tested_... | .startswith("."):
continue
path = os.path.join("api/allennlp_demo/", name)
if not os.path.isdir(path):
continue
config_path = os.path.join(path, "model.json")
if not os.path.isfile(config_path):
continue
yield name
def main():
| 64 | 64 | 196 | 3 | 60 | jvstokes/allennlp-demo | dev/check_models_ci.py | Python | main | main | 26 | 43 | 26 | 26 | 794bc5711884d84c6aab26e1f5be29cf6b5ebe9e | bigcode/the-stack | train |
88db8330f0dc3f57cf27e599 | train | class | class ProfilesApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
... | class ProfilesApi(object):
| """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = ap... | # coding: utf-8
"""
蓝鲸用户管理 API
蓝鲸用户管理后台服务 API # noqa: E501
OpenAPI spec version: v2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from bkuser_sdk.api_cl... | 101 | 256 | 14,085 | 5 | 95 | Canway-shiisa/bk-user | src/sdk/bkuser_sdk/api/profiles_api.py | Python | ProfilesApi | ProfilesApi | 23 | 1,441 | 23 | 23 | a5c2759196f05a30419f113ac31216ab2013c9be | bigcode/the-stack | train |
95c138409b3fb4db123ba0bd | train | class | class spectralNet():
def __init__(self, X, k):
self.X = X
db = {}
db['add_decoder'] = False
db['learning_rate'] = 0.001
db['net_input_size'] = X.shape[1]
db['mlp_width'] = 100 #X.shape[1]
db['net_depth'] = 3
db['k'] = k
db['n'] = X.shape[0]
db['cuda'] = False
db['batch_size'] = 40
if(db['cuda... | class spectralNet():
| def __init__(self, X, k):
self.X = X
db = {}
db['add_decoder'] = False
db['learning_rate'] = 0.001
db['net_input_size'] = X.shape[1]
db['mlp_width'] = 100 #X.shape[1]
db['net_depth'] = 3
db['k'] = k
db['n'] = X.shape[0]
db['cuda'] = False
db['batch_size'] = 40
if(db['cuda']): db['dataType'] =... |
import sys
sys.path.append('./src')
sys.path.append('./src/models')
sys.path.append('./src/data_loader')
sys.path.append('./src/optimizer')
sys.path.append('./src/helper')
from sklearn.cluster import KMeans
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import normalize # version : 0.17
f... | 147 | 256 | 1,022 | 4 | 143 | endsley/spectralNet | src/spectralNet.py | Python | spectralNet | spectralNet | 26 | 142 | 26 | 26 | 6a67ab6106fa3a4dc771e6d2a9eb6fba4ab76d63 | bigcode/the-stack | train |
e098dcd786dc319dbc1b28ab | train | function | def test_cant_delete_property(mock_init, monkeypatch):
# A property should not be deleted: we don't know whether it was initially
# set to a default, loaded from a config file, env var, etc. Therefore, if a property
# is removed from the config file, it will not be modified or deleted.
# edits to confi... | def test_cant_delete_property(mock_init, monkeypatch):
# A property should not be deleted: we don't know whether it was initially
# set to a default, loaded from a config file, env var, etc. Therefore, if a property
# is removed from the config file, it will not be modified or deleted.
# edits to confi... | monkeypatch.setattr(config, 'read_properties_from_file', lambda _: {R1: 1, N1: 3})
appconfig = GalaxyAppConfiguration()
assert getattr(appconfig, R1) == 1
assert getattr(appconfig, R2) == 2
assert getattr(appconfig, N1) == 3
assert getattr(appconfig, N2) == 4
reload_config_options(appconf... | def test_cant_delete_property(mock_init, monkeypatch):
# A property should not be deleted: we don't know whether it was initially
# set to a default, loaded from a config file, env var, etc. Therefore, if a property
# is removed from the config file, it will not be modified or deleted.
# edits to confi... | 84 | 77 | 257 | 84 | 0 | lawrence14701/galaxy | test/unit/config/test_reload_config.py | Python | test_cant_delete_property | test_cant_delete_property | 78 | 98 | 78 | 83 | 19b8b3eb2fb5335dce4ee35101930e8bd26aa7ba | bigcode/the-stack | train |
265e654bbcd928b46f746f15 | train | function | def test_update_property(mock_init, monkeypatch):
# This also covers adding a property. When a config file does not set a property,
# that property is set to its default value. Thus, if we add a reloadable property
# to the config file, it's the same as modifying that property's value.
# edits to confi... | def test_update_property(mock_init, monkeypatch):
# This also covers adding a property. When a config file does not set a property,
# that property is set to its default value. Thus, if we add a reloadable property
# to the config file, it's the same as modifying that property's value.
# edits to confi... | monkeypatch.setattr(config, 'read_properties_from_file', lambda _: {R1: 1, R2: 42, N1: 99})
appconfig = GalaxyAppConfiguration()
assert getattr(appconfig, R1) == 1
assert getattr(appconfig, R2) == 2
assert getattr(appconfig, N1) == 3
reload_config_options(appconfig)
assert getattr(appcon... | def test_update_property(mock_init, monkeypatch):
# This also covers adding a property. When a config file does not set a property,
# that property is set to its default value. Thus, if we add a reloadable property
# to the config file, it's the same as modifying that property's value.
# edits to confi... | 80 | 69 | 231 | 80 | 0 | lawrence14701/galaxy | test/unit/config/test_reload_config.py | Python | test_update_property | test_update_property | 31 | 49 | 31 | 36 | 1555ef643b3d5c02576984f98810ad846167e75c | bigcode/the-stack | train |
40a488039bba349d0563c360 | train | function | @pytest.fixture
def mock_init(monkeypatch):
monkeypatch.setattr(AppSchema, '_read_schema', lambda a, b: get_schema(MOCK_SCHEMA))
monkeypatch.setattr(GalaxyAppConfiguration, '_process_config', lambda a, b: None)
monkeypatch.setattr(GalaxyAppConfiguration, '_override_tempdir', lambda a, b: None)
| @pytest.fixture
def mock_init(monkeypatch):
| monkeypatch.setattr(AppSchema, '_read_schema', lambda a, b: get_schema(MOCK_SCHEMA))
monkeypatch.setattr(GalaxyAppConfiguration, '_process_config', lambda a, b: None)
monkeypatch.setattr(GalaxyAppConfiguration, '_override_tempdir', lambda a, b: None)
| reloadable': True, 'default': 2},
N1: {'default': 3},
N2: {'default': 4},
}
def get_schema(app_mapping):
return {'mapping': {'galaxy': {'mapping': app_mapping}}}
@pytest.fixture
def mock_init(monkeypatch):
| 64 | 64 | 78 | 10 | 54 | lawrence14701/galaxy | test/unit/config/test_reload_config.py | Python | mock_init | mock_init | 23 | 28 | 23 | 25 | 65a74e446426f11c0bf69ecf5e7943fe192bee78 | bigcode/the-stack | train |
d4f350a1c951d9508302bd6e | train | function | def get_schema(app_mapping):
return {'mapping': {'galaxy': {'mapping': app_mapping}}}
| def get_schema(app_mapping):
| return {'mapping': {'galaxy': {'mapping': app_mapping}}}
| MOCK_SCHEMA = {
R1: {'reloadable': True, 'default': 1},
R2: {'reloadable': True, 'default': 2},
N1: {'default': 3},
N2: {'default': 4},
}
def get_schema(app_mapping):
| 64 | 64 | 22 | 6 | 58 | lawrence14701/galaxy | test/unit/config/test_reload_config.py | Python | get_schema | get_schema | 19 | 20 | 19 | 19 | 5f62902dca94c3019973db947d20e71125aeac92 | bigcode/the-stack | train |
4a6e1373399f99fb65911a0d | train | function | def test_overwrite_reloadable_attribute(mock_init, monkeypatch):
# This is similar to test_update_property, but here we overwrite the attribute before reloading.
# This can happen if a config property is modified AFTER it has been loaded from schema or kwargs.
# For example: load `foo` (from schema or kwarg... | def test_overwrite_reloadable_attribute(mock_init, monkeypatch):
# This is similar to test_update_property, but here we overwrite the attribute before reloading.
# This can happen if a config property is modified AFTER it has been loaded from schema or kwargs.
# For example: load `foo` (from schema or kwarg... | monkeypatch.setattr(config, 'read_properties_from_file', lambda _: {R1: 1, R2: 42})
appconfig = GalaxyAppConfiguration()
assert getattr(appconfig, R1) == 1
assert getattr(appconfig, R2) == 2
# overwrite R1
setattr(appconfig, R1, 99)
assert getattr(appconfig, R1) == 99
# then reload
... | def test_overwrite_reloadable_attribute(mock_init, monkeypatch):
# This is similar to test_update_property, but here we overwrite the attribute before reloading.
# This can happen if a config property is modified AFTER it has been loaded from schema or kwargs.
# For example: load `foo` (from schema or kwarg... | 188 | 100 | 334 | 188 | 0 | lawrence14701/galaxy | test/unit/config/test_reload_config.py | Python | test_overwrite_reloadable_attribute | test_overwrite_reloadable_attribute | 52 | 75 | 52 | 61 | 159e1235c0a42ea28c6534b12e06e9aeb8ddb4b2 | bigcode/the-stack | train |
dd736fc9b0be75295493323f | train | function | def make_tf_example(features, pi, value):
"""Make tf examples.
Args:
features: [N, N, FEATURE_DIM] nparray of uint8
pi: [N * N + 1] nparray of float32
value: float
Returns:
tf example.
"""
return tf.train.Example(
features=tf.train.Features(
feature={
'x': tf.t... | def make_tf_example(features, pi, value):
| """Make tf examples.
Args:
features: [N, N, FEATURE_DIM] nparray of uint8
pi: [N * N + 1] nparray of float32
value: float
Returns:
tf example.
"""
return tf.train.Example(
features=tf.train.Features(
feature={
'x': tf.train.Feature(
bytes_list... | .ZLIB)
# Constructing tf.Examples
def _one_hot(board_size, index):
onehot = np.zeros([board_size * board_size + 1], dtype=np.float32)
onehot[index] = 1
return onehot
def make_tf_example(features, pi, value):
| 64 | 64 | 151 | 10 | 53 | SimiaCryptus/models | research/minigo/preprocessing.py | Python | make_tf_example | make_tf_example | 40 | 61 | 40 | 40 | 12d97d47047d130eb42b96a8a88b3cd6f4a82225 | bigcode/the-stack | train |
a6f7e5f323fb2bb4802d91f4 | train | function | def _one_hot(board_size, index):
onehot = np.zeros([board_size * board_size + 1], dtype=np.float32)
onehot[index] = 1
return onehot
| def _one_hot(board_size, index):
| onehot = np.zeros([board_size * board_size + 1], dtype=np.float32)
onehot[index] = 1
return onehot
| numpy as np
import sgf_wrapper
import tensorflow as tf # pylint: disable=g-bad-import-order
TF_RECORD_CONFIG = tf.python_io.TFRecordOptions(
tf.python_io.TFRecordCompressionType.ZLIB)
# Constructing tf.Examples
def _one_hot(board_size, index):
| 64 | 64 | 44 | 9 | 54 | SimiaCryptus/models | research/minigo/preprocessing.py | Python | _one_hot | _one_hot | 34 | 37 | 34 | 34 | 2c9b356091bba6e1a1405d1aea84c3ab53fbda8c | bigcode/the-stack | train |
12b413a906cc686b3b349fba | train | function | def make_dataset_from_selfplay(data_extracts, params):
"""Make an iterable of tf.Examples.
Args:
data_extracts: An iterable of (position, pi, result) tuples
params: An object of hyperparameters
Returns:
An iterable of tf.Examples.
"""
board_size = params.board_size
tf_examples = (make_tf_examp... | def make_dataset_from_selfplay(data_extracts, params):
| """Make an iterable of tf.Examples.
Args:
data_extracts: An iterable of (position, pi, result) tuples
params: An object of hyperparameters
Returns:
An iterable of tf.Examples.
"""
board_size = params.board_size
tf_examples = (make_tf_example(features_lib.extract_features(
board_size, pos... | _batch_parse_tf_example(params.board_size, batch_size, dataset)
dataset = dataset.map(functools.partial(
batch_parse_tf_example, batch_size))
return dataset.make_one_shot_iterator().get_next()
# End-to-end utility functions
def make_dataset_from_selfplay(data_extracts, params):
| 64 | 64 | 111 | 12 | 51 | SimiaCryptus/models | research/minigo/preprocessing.py | Python | make_dataset_from_selfplay | make_dataset_from_selfplay | 184 | 197 | 184 | 184 | ed1142a7faf8cfc2b019cc7e2bba7e7e120f768a | bigcode/the-stack | train |
81216edbfc8aa69422070b1f | train | function | def write_tf_examples(filename, tf_examples, serialize=True):
"""Write tf.Example to files.
Args:
filename: Where to write tf.records
tf_examples: An iterable of tf.Example
serialize: whether to serialize the examples.
"""
with tf.python_io.TFRecordWriter(
filename, options=TF_RECORD_CONFIG) ... | def write_tf_examples(filename, tf_examples, serialize=True):
| """Write tf.Example to files.
Args:
filename: Where to write tf.records
tf_examples: An iterable of tf.Example
serialize: whether to serialize the examples.
"""
with tf.python_io.TFRecordWriter(
filename, options=TF_RECORD_CONFIG) as writer:
for ex in tf_examples:
if serialize:
... | (value=[features.tostring()])),
'pi': tf.train.Feature(
bytes_list=tf.train.BytesList(value=[pi.tostring()])),
'outcome': tf.train.Feature(
float_list=tf.train.FloatList(value=[value]))
}))
def write_tf_examples(filename, tf_examples, serialize=T... | 63 | 64 | 104 | 12 | 51 | SimiaCryptus/models | research/minigo/preprocessing.py | Python | write_tf_examples | write_tf_examples | 64 | 78 | 64 | 64 | 3b9156bf86700111ba826fe58a212c1164e3b037 | bigcode/the-stack | train |
42683743548c620b5510d193 | train | function | def make_dataset_from_sgf(board_size, sgf_filename, tf_record):
pwcs = sgf_wrapper.replay_sgf_file(board_size, sgf_filename)
def make_tf_example_from_pwc(pwcs):
return _make_tf_example_from_pwc(board_size, pwcs)
tf_examples = map(make_tf_example_from_pwc, pwcs)
write_tf_examples(tf_record, tf_examples)
| def make_dataset_from_sgf(board_size, sgf_filename, tf_record):
| pwcs = sgf_wrapper.replay_sgf_file(board_size, sgf_filename)
def make_tf_example_from_pwc(pwcs):
return _make_tf_example_from_pwc(board_size, pwcs)
tf_examples = map(make_tf_example_from_pwc, pwcs)
write_tf_examples(tf_record, tf_examples)
| """
board_size = params.board_size
tf_examples = (make_tf_example(features_lib.extract_features(
board_size, pos), pi, result) for pos, pi, result in data_extracts)
return tf_examples
def make_dataset_from_sgf(board_size, sgf_filename, tf_record):
| 64 | 64 | 87 | 16 | 47 | SimiaCryptus/models | research/minigo/preprocessing.py | Python | make_dataset_from_sgf | make_dataset_from_sgf | 200 | 205 | 200 | 200 | 08e914944a84b06dac92c266aa1aa6e326f040da | bigcode/the-stack | train |
8816473439be3483d611d0a9 | train | function | def _make_tf_example_from_pwc(board_size, position_w_context):
features = features_lib.extract_features(
board_size, position_w_context.position)
pi = _one_hot(board_size, coords.to_flat(
board_size, position_w_context.next_move))
value = position_w_context.result
return make_tf_example(features, pi... | def _make_tf_example_from_pwc(board_size, position_w_context):
| features = features_lib.extract_features(
board_size, position_w_context.position)
pi = _one_hot(board_size, coords.to_flat(
board_size, position_w_context.next_move))
value = position_w_context.result
return make_tf_example(features, pi, value)
| _tf_example_from_pwc(pwcs):
return _make_tf_example_from_pwc(board_size, pwcs)
tf_examples = map(make_tf_example_from_pwc, pwcs)
write_tf_examples(tf_record, tf_examples)
def _make_tf_example_from_pwc(board_size, position_w_context):
| 64 | 64 | 74 | 15 | 49 | SimiaCryptus/models | research/minigo/preprocessing.py | Python | _make_tf_example_from_pwc | _make_tf_example_from_pwc | 208 | 214 | 208 | 208 | 340d22dc731c09b17bfe14c85e43b876dc108fab | bigcode/the-stack | train |
43047a7928d1c16b092a9f39 | train | function | def get_input_tensors(params, batch_size, tf_records, num_repeats=None,
shuffle_records=True, shuffle_examples=True,
filter_amount=0.05):
"""Read tf.Records and prepare them for ingestion by dualnet.
Args:
params: An object of hyperparameters
batch_size: batch si... | def get_input_tensors(params, batch_size, tf_records, num_repeats=None,
shuffle_records=True, shuffle_examples=True,
filter_amount=0.05):
| """Read tf.Records and prepare them for ingestion by dualnet.
Args:
params: An object of hyperparameters
batch_size: batch size to return
tf_records: a list of tf_record filenames
num_repeats: how many times the data should be read (default: infinite)
shuffle_records: whether to shuffle the ord... | not None:
dataset = dataset.repeat(num_repeats)
else:
dataset = dataset.repeat()
if shuffle_examples:
dataset = dataset.shuffle(buffer_size=shuffle_buffer_size)
dataset = dataset.batch(batch_size)
return dataset
def get_input_tensors(params, batch_size, tf_records, num_repeats=None,
... | 87 | 87 | 292 | 36 | 50 | SimiaCryptus/models | research/minigo/preprocessing.py | Python | get_input_tensors | get_input_tensors | 153 | 180 | 153 | 155 | 62ce2e05562f67981c530b560168605f3e6d0a9b | bigcode/the-stack | train |
af11322f77cc0116617aa584 | train | function | def shuffle_tf_examples(shuffle_buffer_size, gather_size, records_to_shuffle):
"""Read through tf.Record and yield shuffled, but unparsed tf.Examples.
Args:
shuffle_buffer_size: the size for shuffle buffer
gather_size: The number of tf.Examples to be gathered together
records_to_shuffle: A list of file... | def shuffle_tf_examples(shuffle_buffer_size, gather_size, records_to_shuffle):
| """Read through tf.Record and yield shuffled, but unparsed tf.Examples.
Args:
shuffle_buffer_size: the size for shuffle buffer
gather_size: The number of tf.Examples to be gathered together
records_to_shuffle: A list of filenames
Yields:
An iterator yielding lists of bytes, which are serialized ... | , position_w_context.position)
pi = _one_hot(board_size, coords.to_flat(
board_size, position_w_context.next_move))
value = position_w_context.result
return make_tf_example(features, pi, value)
def shuffle_tf_examples(shuffle_buffer_size, gather_size, records_to_shuffle):
| 64 | 64 | 169 | 16 | 48 | SimiaCryptus/models | research/minigo/preprocessing.py | Python | shuffle_tf_examples | shuffle_tf_examples | 217 | 237 | 217 | 217 | 70c0a159e20f99bf2c9957620468d352713b73c9 | bigcode/the-stack | train |
e566141dd017afbf28008327 | train | function | def _batch_parse_tf_example(board_size, batch_size, example_batch):
"""Parse tf examples.
Args:
board_size: the go board size
batch_size: the batch size
example_batch: a batch of tf.Example
Returns:
A tuple (feature_tensor, dict of output tensors)
"""
features = {
'x': tf.FixedLenFeatu... | def _batch_parse_tf_example(board_size, batch_size, example_batch):
| """Parse tf examples.
Args:
board_size: the go board size
batch_size: the batch size
example_batch: a batch of tf.Example
Returns:
A tuple (feature_tensor, dict of output tensors)
"""
features = {
'x': tf.FixedLenFeature([], tf.string),
'pi': tf.FixedLenFeature([], tf.string),
... | with tf.python_io.TFRecordWriter(
filename, options=TF_RECORD_CONFIG) as writer:
for ex in tf_examples:
if serialize:
writer.write(ex.SerializeToString())
else:
writer.write(ex)
# Read tf.Example from files
def _batch_parse_tf_example(board_size, batch_size, example_batch):
| 72 | 72 | 242 | 15 | 56 | SimiaCryptus/models | research/minigo/preprocessing.py | Python | _batch_parse_tf_example | _batch_parse_tf_example | 82 | 107 | 82 | 82 | c676aeb5cf88ef10061b32649534414b0c43502c | bigcode/the-stack | train |
143c131daa93aa6a530fad68 | train | function | def read_tf_records(
shuffle_buffer_size, batch_size, tf_records, num_repeats=None,
shuffle_records=True, shuffle_examples=True, filter_amount=1.0):
"""Read tf records.
Args:
shuffle_buffer_size: how big of a buffer to fill before shuffling
batch_size: batch size to return
tf_records: a list of... | def read_tf_records(
shuffle_buffer_size, batch_size, tf_records, num_repeats=None,
shuffle_records=True, shuffle_examples=True, filter_amount=1.0):
| """Read tf records.
Args:
shuffle_buffer_size: how big of a buffer to fill before shuffling
batch_size: batch size to return
tf_records: a list of tf_record filenames
num_repeats: how many times the data should be read (default: infinite)
shuffle_records: whether to shuffle the order of files r... | _size,
features_lib.NEW_FEATURES_PLANES])
pi = tf.decode_raw(parsed['pi'], tf.float32)
pi = tf.reshape(pi, [batch_size, board_size * board_size + 1])
outcome = parsed['outcome']
outcome.set_shape([batch_size])
return (x, {'pi_tensor': pi, 'value_tensor': outcome})
def read_tf_records(
... | 116 | 116 | 388 | 38 | 78 | SimiaCryptus/models | research/minigo/preprocessing.py | Python | read_tf_records | read_tf_records | 110 | 150 | 110 | 112 | 9b63ac97ffe57ee6afe547dd468c6be5c0f1fdcf | bigcode/the-stack | train |
9569a563f7579149c052f1fb | train | class | class PyWord2number(PythonPackage):
"""This is a Python module to convert number words (eg.
twenty one) to numeric digits (21). It works for positive
numbers upto the range of 999,999,999,999 (i.e.
billions)."""
homepage = "https://w2n.readthedocs.io"
pypi = "word2number/word2number-1.1.zip... | class PyWord2number(PythonPackage):
| """This is a Python module to convert number words (eg.
twenty one) to numeric digits (21). It works for positive
numbers upto the range of 999,999,999,999 (i.e.
billions)."""
homepage = "https://w2n.readthedocs.io"
pypi = "word2number/word2number-1.1.zip"
version('1.1', sha256='70e27a... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyWord2number(PythonPackage):
| 63 | 64 | 157 | 9 | 54 | LiamBindle/spack | var/spack/repos/builtin/packages/py-word2number/package.py | Python | PyWord2number | PyWord2number | 9 | 20 | 9 | 9 | 25593b8544b567b18c08db6cfa9df9ddfb5dc600 | bigcode/the-stack | train |
2f61a138f20f9eca977c2f64 | train | class | class CloudPoolCreateParams(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_m... | class CloudPoolCreateParams(object):
| """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
... | # coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 3
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_8_0.models.cloud_poo... | 110 | 256 | 1,887 | 7 | 102 | mohitjain97/isilon_sdk_python | isi_sdk_8_0/isi_sdk_8_0/models/cloud_pool_create_params.py | Python | CloudPoolCreateParams | CloudPoolCreateParams | 22 | 265 | 22 | 22 | 222ff7ef72e3acb701c85416bb771dd2613101af | bigcode/the-stack | train |
239160c378a74424e9e5d9e6 | train | function | def ad_fuller_test(series):
"""
Prints results of adfuller test for a given time series.
"""
result = adfuller(series, autolag='AIC')
print(f'ADF Statistic: {result[0]}')
print(f'p-value: {result[1]}')
print(f'n_lags: {result[2]}')
print(f'num_obs: {result[3]}')
for key, value in res... | def ad_fuller_test(series):
| """
Prints results of adfuller test for a given time series.
"""
result = adfuller(series, autolag='AIC')
print(f'ADF Statistic: {result[0]}')
print(f'p-value: {result[1]}')
print(f'n_lags: {result[2]}')
print(f'num_obs: {result[3]}')
for key, value in result[4].items():
prin... | num_features.remove(target)
skewed_features = df[num_features].apply(lambda x: skew(x))
high_skew = skewed_features[abs(skewed_features) > s]
df[high_skew] = np.log1p(df[high_skew])
def ad_fuller_test(series):
| 64 | 64 | 121 | 7 | 57 | meren26/playground | notebooks/utils/preprocess_utils.py | Python | ad_fuller_test | ad_fuller_test | 36 | 47 | 36 | 36 | c04e3c43f5c0b3354ec4018f2c6f392e8b56eab5 | bigcode/the-stack | train |
9e59a7762dbb68ec6ec2c9fa | train | function | def boxcox_on_skewed_features(df, target, s: float):
"""
Get a df, target and s (skewness), returns boxcox on df.
"""
num_features = list(df.select_dtypes(include=np.number).columns)
num_features.remove(target)
skewed_features = df[num_features].apply(lambda x: skew(x))
high_skew = skewed_... | def boxcox_on_skewed_features(df, target, s: float):
| """
Get a df, target and s (skewness), returns boxcox on df.
"""
num_features = list(df.select_dtypes(include=np.number).columns)
num_features.remove(target)
skewed_features = df[num_features].apply(lambda x: skew(x))
high_skew = skewed_features[abs(skewed_features) > s]
for feat in h... | import numpy as np
from scipy.stats import skew
from scipy.special import boxcox1p
from scipy.stats import boxcox_normmax
from statsmodels.tsa.stattools import adfuller
def boxcox_on_skewed_features(df, target, s: float):
| 57 | 64 | 129 | 16 | 40 | meren26/playground | notebooks/utils/preprocess_utils.py | Python | boxcox_on_skewed_features | boxcox_on_skewed_features | 7 | 19 | 7 | 7 | c5347efeaed0ca28ec6fac34d93c758f1822f25e | bigcode/the-stack | train |
d267abbdfaa562baa8df2f70 | train | function | def logtransform_on_skewed_features(df, target, s: float):
"""
Get a df, target and s (skewness), returns log1p on df.
"""
num_features = list(df.select_dtypes(include=np.number).columns)
num_features.remove(target)
skewed_features = df[num_features].apply(lambda x: skew(x))
high_skew = sk... | def logtransform_on_skewed_features(df, target, s: float):
| """
Get a df, target and s (skewness), returns log1p on df.
"""
num_features = list(df.select_dtypes(include=np.number).columns)
num_features.remove(target)
skewed_features = df[num_features].apply(lambda x: skew(x))
high_skew = skewed_features[abs(skewed_features) > s]
df[high_skew] ... | skewed_features[abs(skewed_features) > s]
for feat in high_skew.index:
df[feat] = boxcox1p(df[feat], boxcox_normmax(df[feat] + 1))
def logtransform_on_skewed_features(df, target, s: float):
| 64 | 64 | 113 | 16 | 48 | meren26/playground | notebooks/utils/preprocess_utils.py | Python | logtransform_on_skewed_features | logtransform_on_skewed_features | 22 | 33 | 22 | 22 | f3dec0da1a787b71d764d6a2cd50270c8a08a683 | bigcode/the-stack | train |
87f595af6f7343284c3895ec | train | class | class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('user_profil', '0008_alter_sportprofil_user'),
]
operations = [
migrations.AlterField(
model_name='sportprofil',
name='user',
fiel... | class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('user_profil', '0008_alter_sportprofil_user'),
]
operations = [
migrations.AlterField(
model_name='sportprofil',
name='user',
field=models.OneToOneField(default=None, on_... | # Generated by Django 3.2.3 on 2021-06-11 11:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 51 | 64 | 90 | 7 | 43 | MaewenPell/trailing-planner | user_profil/migrations/0009_alter_sportprofil_user.py | Python | Migration | Migration | 8 | 21 | 8 | 9 | 96cb1963fca19e7e00a61bb89fbcb2b8f31e62bc | bigcode/the-stack | train |
eee79e1b4774a8e03430271a | train | class | class ImageClassificator:
batch_size = 32
img_height = 180
img_width = 180
class_names = ''
model = None
def create_model(self, flag):
dataset_url = "C:\\Users\\matti\\OneDrive\\Desktop\\logos"
data_dir = pathlib.Path(dataset_url)
image_count = len(list(data_dir.glob('... | class ImageClassificator:
| batch_size = 32
img_height = 180
img_width = 180
class_names = ''
model = None
def create_model(self, flag):
dataset_url = "C:\\Users\\matti\\OneDrive\\Desktop\\logos"
data_dir = pathlib.Path(dataset_url)
image_count = len(list(data_dir.glob('*/*.png')))
print(... | import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
import pathlib
class ImageClassificator:
| 49 | 256 | 1,003 | 6 | 42 | Lube-Project/ProgettoLube | ProgettoLube/WebInspector/ImageClassificator.py | Python | ImageClassificator | ImageClassificator | 14 | 144 | 14 | 14 | 764201077b8820362e73b7094449234804609c9d | bigcode/the-stack | train |
dbc0d7c99ab006cf0091a272 | train | class | class Dataset(ABC):
MODE_TRAIN = 1
MODE_TEST = 2
path_h5 = {
MODE_TRAIN: '',
MODE_TEST: ''
}
sz_a = (-1, -1)
sz_s = (-1, -1) # Spatial dimensions will be resized to this size when necessary, e.g. testing when training.
def __init__(self, config):
self.config = ... | class Dataset(ABC):
| MODE_TRAIN = 1
MODE_TEST = 2
path_h5 = {
MODE_TRAIN: '',
MODE_TEST: ''
}
sz_a = (-1, -1)
sz_s = (-1, -1) # Spatial dimensions will be resized to this size when necessary, e.g. testing when training.
def __init__(self, config):
self.config = config
def get_... | from abc import ABC, abstractmethod
from os import path
class Dataset(ABC):
| 18 | 64 | 188 | 5 | 12 | huzexi/SADenseNet | components/datasets/Dataset.py | Python | Dataset | Dataset | 5 | 34 | 5 | 5 | 7c0f69a753e5d0ea4a49598652258a5bd7c81b5c | bigcode/the-stack | train |
0fba8552bb28d4c99684f984 | train | class | class LimitsTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('limits', selector='limits')
rates = xmlutil.SubTemplateElement(root, 'rates')
rate = xmlutil.SubTemplateElement(rates, 'rate', selector='rate')
rate.set('uri', 'uri')
rate.set... | class LimitsTemplate(xmlutil.TemplateBuilder):
| def construct(self):
root = xmlutil.TemplateElement('limits', selector='limits')
rates = xmlutil.SubTemplateElement(root, 'rates')
rate = xmlutil.SubTemplateElement(rates, 'rate', selector='rate')
rate.set('uri', 'uri')
rate.set('regex', 'regex')
limit = xmlutil.SubT... | 1
PER_MINUTE = 60
PER_HOUR = 60 * 60
PER_DAY = 60 * 60 * 24
limits_nsmap = {None: xmlutil.XMLNS_COMMON_V10, 'atom': xmlutil.XMLNS_ATOM}
class LimitsTemplate(xmlutil.TemplateBuilder):
| 65 | 65 | 218 | 8 | 57 | Thingee/cinder | cinder/api/v1/limits.py | Python | LimitsTemplate | LimitsTemplate | 53 | 75 | 53 | 53 | c6f582b570a37892c9f6db2d975d0ae60b65afca | bigcode/the-stack | train |
7ef15cb26d71fceae74ebf95 | train | function | def create_resource():
return wsgi.Resource(LimitsController())
| def create_resource():
| return wsgi.Resource(LimitsController())
| ']) for k, v in quotas.items())
rate_limits = req.environ.get("cinder.limits", [])
builder = self._get_view_builder(req)
return builder.build(rate_limits, abs_limits)
def _get_view_builder(self, req):
return limits_views.ViewBuilder()
def create_resource():
| 64 | 64 | 13 | 4 | 60 | Thingee/cinder | cinder/api/v1/limits.py | Python | create_resource | create_resource | 97 | 98 | 97 | 97 | 1ffb6c8617fec90ee0ebe964f9bf4146785f6e8e | bigcode/the-stack | train |
e4fa632b03218c1adeb16ff5 | train | class | class Limit(object):
"""Stores information about a limit for HTTP requests."""
UNITS = {
1: "SECOND",
60: "MINUTE",
60 * 60: "HOUR",
60 * 60 * 24: "DAY",
}
UNIT_MAP = dict([(v, k) for k, v in UNITS.items()])
def __init__(self, verb, uri, regex, value, unit):
... | class Limit(object):
| """Stores information about a limit for HTTP requests."""
UNITS = {
1: "SECOND",
60: "MINUTE",
60 * 60: "HOUR",
60 * 60 * 24: "DAY",
}
UNIT_MAP = dict([(v, k) for k, v in UNITS.items()])
def __init__(self, verb, uri, regex, value, unit):
"""Initialize a new... | )
limit.set('name', 0)
limit.set('value', 1)
return xmlutil.MasterTemplate(root, 1, nsmap=limits_nsmap)
class LimitsController(wsgi.Controller):
"""Controller for accessing limits in the OpenStack API."""
@wsgi.serializers(xml=LimitsTemplate)
def index(self, req):
"""Retu... | 203 | 203 | 677 | 4 | 199 | Thingee/cinder | cinder/api/v1/limits.py | Python | Limit | Limit | 101 | 197 | 101 | 101 | 8a6d3b4c263c26008e6f57c33b50cd5b2f5b6eae | bigcode/the-stack | train |
8a2e5a17c94317c8d1542731 | train | class | class WsgiLimiterProxy(object):
"""Rate-limit requests based on answers from a remote source."""
def __init__(self, limiter_address):
"""Initialize the new `WsgiLimiterProxy`.
@param limiter_address: IP/port combination of where to request limit
"""
self.limiter_address = limit... | class WsgiLimiterProxy(object):
| """Rate-limit requests based on answers from a remote source."""
def __init__(self, limiter_address):
"""Initialize the new `WsgiLimiterProxy`.
@param limiter_address: IP/port combination of where to request limit
"""
self.limiter_address = limiter_address
def check_for_de... | _info_pop()
verb = info.get("verb")
path = info.get("path")
delay, error = self._limiter.check_for_delay(verb, path, username)
if delay:
headers = {"X-Wait-Seconds": "%.2f" % delay}
return webob.exc.HTTPForbidden(headers=headers, explanation=error)
else:... | 92 | 92 | 309 | 7 | 85 | Thingee/cinder | cinder/api/v1/limits.py | Python | WsgiLimiterProxy | WsgiLimiterProxy | 426 | 466 | 426 | 426 | 3967db6a0a36d5a50e56994ec13a66e56a73ed75 | bigcode/the-stack | train |
10f3626925c46f615acbd728 | train | class | class WsgiLimiter(object):
"""Rate-limit checking from a WSGI application.
Uses an in-memory `Limiter`.
To use, POST ``/<username>`` with JSON data such as::
{
"verb" : GET,
"path" : "/servers"
}
and receive a 204 No Content, or a 403 Forbidden with an X-Wait-... | class WsgiLimiter(object):
| """Rate-limit checking from a WSGI application.
Uses an in-memory `Limiter`.
To use, POST ``/<username>`` with JSON data such as::
{
"verb" : GET,
"path" : "/servers"
}
and receive a 204 No Content, or a 403 Forbidden with an X-Wait-Seconds
header containi... | args
# Upper-case the verb
verb = verb.upper()
# Convert value--raises ValueError if it's not integer
value = int(value)
# Convert unit
unit = unit.upper()
if unit not in Limit.UNIT_MAP:
raise ValueError("Invalid uni... | 106 | 106 | 356 | 6 | 99 | Thingee/cinder | cinder/api/v1/limits.py | Python | WsgiLimiter | WsgiLimiter | 373 | 423 | 373 | 373 | 30f2410bcf31bbd857f3ad3fbe922759575188b9 | bigcode/the-stack | train |
7236a36460ed2aba513c7848 | train | class | class LimitsController(wsgi.Controller):
"""Controller for accessing limits in the OpenStack API."""
@wsgi.serializers(xml=LimitsTemplate)
def index(self, req):
"""Return all global and rate limit information."""
context = req.environ['cinder.context']
quotas = QUOTAS.get_project_qu... | class LimitsController(wsgi.Controller):
| """Controller for accessing limits in the OpenStack API."""
@wsgi.serializers(xml=LimitsTemplate)
def index(self, req):
"""Return all global and rate limit information."""
context = req.environ['cinder.context']
quotas = QUOTAS.get_project_quotas(context, context.project_id,
... | limit = xmlutil.SubTemplateElement(absolute, 'limit',
selector=xmlutil.get_items)
limit.set('name', 0)
limit.set('value', 1)
return xmlutil.MasterTemplate(root, 1, nsmap=limits_nsmap)
class LimitsController(wsgi.Controller):
| 64 | 64 | 149 | 7 | 57 | Thingee/cinder | cinder/api/v1/limits.py | Python | LimitsController | LimitsController | 78 | 94 | 78 | 78 | 8e0d7fc0537d9f7917f66205296730ae8fdcb0e5 | bigcode/the-stack | train |
fd1c01eb2e0575767fe4b6f9 | train | class | class Limiter(object):
"""Rate-limit checking class which handles limits in memory."""
def __init__(self, limits, **kwargs):
"""Initialize the new `Limiter`.
@param limits: List of `Limit` objects
"""
self.limits = copy.deepcopy(limits)
self.levels = collections.default... | class Limiter(object):
| """Rate-limit checking class which handles limits in memory."""
def __init__(self, limits, **kwargs):
"""Initialize the new `Limiter`.
@param limits: List of `Limit` objects
"""
self.limits = copy.deepcopy(limits)
self.levels = collections.defaultdict(lambda: copy.deepc... | @webob.dec.wsgify(RequestClass=wsgi.Request)
def __call__(self, req):
"""Represent a single call through this middleware.
We should record the request if we have a limit relevant to it.
If no limit is relevant to the request, ignore it.
If the request should be rate limited, retur... | 217 | 217 | 724 | 5 | 211 | Thingee/cinder | cinder/api/v1/limits.py | Python | Limiter | Limiter | 273 | 370 | 273 | 273 | 9c9d73cee8fc57dc1e4b700463b467a1b1dc1707 | bigcode/the-stack | train |
a7bc42600454e4d78516e0e7 | train | class | class RateLimitingMiddleware(base_wsgi.Middleware):
"""Rate-limits requests passing through this middleware.
All limit information is stored in memory for this implementation.
"""
def __init__(self, application, limits=None, limiter=None, **kwargs):
"""Initialize new `RateLimitingMiddleware`
... | class RateLimitingMiddleware(base_wsgi.Middleware):
| """Rate-limits requests passing through this middleware.
All limit information is stored in memory for this implementation.
"""
def __init__(self, application, limits=None, limiter=None, **kwargs):
"""Initialize new `RateLimitingMiddleware`
This wraps the given WSGI application and s... | # a regular-expression to match, value and unit of measure (PER_DAY, etc.)
DEFAULT_LIMITS = [
Limit("POST", "*", ".*", 10, PER_MINUTE),
Limit("POST", "*/servers", "^/servers", 50, PER_DAY),
Limit("PUT", "*", ".*", 10, PER_MINUTE),
Limit("GET", "*changes-since*", ".*changes-since.*", 3, PER_MINUTE),
... | 128 | 128 | 428 | 10 | 118 | Thingee/cinder | cinder/api/v1/limits.py | Python | RateLimitingMiddleware | RateLimitingMiddleware | 211 | 270 | 211 | 211 | e717050b8e13a00ec0700f2939b254ec969754d4 | bigcode/the-stack | train |
405d0ce47ce3a62c5156bc67 | train | class | class Parser(BaseParser):
"""Extract text from pipe separated values files (.psv).
"""
delimiter = '|' | class Parser(BaseParser):
| """Extract text from pipe separated values files (.psv).
"""
delimiter = '|' | import csv
from convertextract.parsers.csv_parser import Parser as BaseParser
class Parser(BaseParser):
| 21 | 64 | 25 | 5 | 15 | roedoejet/convertextract | convertextract/parsers/psv_parser.py | Python | Parser | Parser | 5 | 9 | 5 | 5 | 162f9715fd35ed2bed248a55173d0aea8b5b8438 | bigcode/the-stack | train |
199f423d2c973608525eda1c | train | function | def main():
args = parse_args()
model_settings = ModelSettings(
model_architecture=args.model_architecture,
embedding_dim=args.embedding_dim,
lfw_batch_size=args.lfw_batch_size,
)
data_settings = DataSettings(
checkpoint_path=args.checkpoint_path,
lfw_dir=args.lf... | def main():
| args = parse_args()
model_settings = ModelSettings(
model_architecture=args.model_architecture,
embedding_dim=args.embedding_dim,
lfw_batch_size=args.lfw_batch_size,
)
data_settings = DataSettings(
checkpoint_path=args.checkpoint_path,
lfw_dir=args.lfw_dir,
... | "inception_resnet_v1_casia",
"inceptionresnetv2",
],
default=ModelSettings.model_architecture,
)
parser.add_argument(
"--embedding_dim", type=int, default=ModelSettings.embedding_dim
)
return parser.parse_args()
def main():
| 64 | 64 | 87 | 3 | 61 | dawidkski/federated-faceid | src/facenet/evaluate_model.py | Python | main | main | 81 | 95 | 81 | 81 | b066e4d6a251ad1c1a58407de33f147392e9cdf0 | bigcode/the-stack | train |
f7bf63b8c629590f331cefc1 | train | function | def parse_args():
parser = argparse.ArgumentParser(description="Evaluate model on LFW dataset")
parser.add_argument(
"--output_dir",
type=lambda p: Path(p) if p else None,
default=DataSettings.output_dir,
)
parser.add_argument(
"--checkpoint_path", type=lambda p: Path(p) ... | def parse_args():
| parser = argparse.ArgumentParser(description="Evaluate model on LFW dataset")
parser.add_argument(
"--output_dir",
type=lambda p: Path(p) if p else None,
default=DataSettings.output_dir,
)
parser.add_argument(
"--checkpoint_path", type=lambda p: Path(p) if p else None, re... | checkpoint.epoch
model.eval()
figure_name = f"roc_eval_{epoch_last}.png"
figure_path: Path = settings_data.output_dir.joinpath(figure_name)
metrics: EvaluationMetrics = evaluate(
model, distance_l2, data_loader_validate, figure_path
)
pprint(dataclasses.asdict(metrics))
def parse_arg... | 74 | 74 | 249 | 4 | 70 | dawidkski/federated-faceid | src/facenet/evaluate_model.py | Python | parse_args | parse_args | 44 | 78 | 44 | 44 | b4bd936817845e766bac97542453e3fbc2744081 | bigcode/the-stack | train |
5e1b67e6a75c0b04bd6edcc4 | train | function | def evaluate_model(settings_model: ModelSettings, settings_data: DataSettings):
data_loader_validate: DataLoader = get_validation_data_loader(
settings_model, settings_data
)
distance_l2: Module = PairwiseDistance(2).cuda()
model: Module = ModelBuilder.build(
settings_model.model_archit... | def evaluate_model(settings_model: ModelSettings, settings_data: DataSettings):
| data_loader_validate: DataLoader = get_validation_data_loader(
settings_model, settings_data
)
distance_l2: Module = PairwiseDistance(2).cuda()
model: Module = ModelBuilder.build(
settings_model.model_architecture,
settings_model.embedding_dim,
imagenet_pretrained=False,... | wiseDistance
from torch.utils.data import DataLoader
from facenet.commons import ModelBuilder, get_validation_data_loader, load_checkpoint
from facenet.evaluation import EvaluationMetrics, evaluate
from facenet.settings import DataSettings, ModelSettings
def evaluate_model(settings_model: ModelSettings, settings_data:... | 64 | 64 | 189 | 15 | 48 | dawidkski/federated-faceid | src/facenet/evaluate_model.py | Python | evaluate_model | evaluate_model | 14 | 41 | 14 | 14 | f7b19bfac33491d85ba09ef8d8faeabab6052feb | bigcode/the-stack | train |
553e8cafcaf57ef68d4b356a | train | function | def test_config_keys() -> None:
"""Tests the config key parser with both string and full email formats."""
with pytest.raises(ConfigFileError):
f = StringIO("""
configs:
has.periods:
urls:
- json://localhost
""")
load_config(_lo... | def test_config_keys() -> None:
| """Tests the config key parser with both string and full email formats."""
with pytest.raises(ConfigFileError):
f = StringIO("""
configs:
has.periods:
urls:
- json://localhost
""")
load_config(_logger, f)
with pytest.raises(... | == NotifyFormat.TEXT
with pytest.raises(ConfigFileError):
f = StringIO("""
configs:
test:
urls:
- json://localhost
mailrise:
body_format: "BAD"
""")
load_config(_logger, f)
def test_config_keys() ... | 64 | 64 | 178 | 8 | 56 | YoRyan/mailrise | tests/test_config.py | Python | test_config_keys | test_config_keys | 107 | 134 | 107 | 107 | 75bfeb5a5b1c776ee0ca276ffda89db43fa4b806 | bigcode/the-stack | train |
34a446fa179fe9d481926bce | train | function | def test_multi_load() -> None:
"""Tests a sucessful load with :fun:`load_config` with multiple configs."""
f = StringIO("""
configs:
test1:
urls:
- json://localhost
test2:
urls:
- json://localhost
""")
mrise = load_config(_l... | def test_multi_load() -> None:
| """Tests a sucessful load with :fun:`load_config` with multiple configs."""
f = StringIO("""
configs:
test1:
urls:
- json://localhost
test2:
urls:
- json://localhost
""")
mrise = load_config(_logger, f)
assert len(mrise.... | 1
key = Key(user='test')
assert key in mrise.senders
sender = mrise.senders[key]
assert len(sender.apprise) == 1
assert sender.apprise[0].url().startswith('json://localhost/')
def test_multi_load() -> None:
| 63 | 64 | 151 | 8 | 55 | YoRyan/mailrise | tests/test_config.py | Python | test_multi_load | test_multi_load | 51 | 71 | 51 | 51 | ff713760ee0d74c244068e3e7bd638e248b8140a | bigcode/the-stack | train |
cb2363ab42ff3265ba160194 | train | function | def test_errors() -> None:
"""Tests for :fun:`load_config`'s failure conditions."""
with pytest.raises(ConfigFileError):
f = StringIO("""
24
""")
load_config(_logger, f)
with pytest.raises(ConfigFileError):
f = StringIO("""
configs: 24
""")
... | def test_errors() -> None:
| """Tests for :fun:`load_config`'s failure conditions."""
with pytest.raises(ConfigFileError):
f = StringIO("""
24
""")
load_config(_logger, f)
with pytest.raises(ConfigFileError):
f = StringIO("""
configs: 24
""")
load_config(_logger, f... | import logging
from io import StringIO
from mailrise.config import ConfigFileError, Key, load_config
import pytest
from apprise import NotifyFormat
_logger = logging.getLogger(__name__)
def test_errors() -> None:
| 48 | 64 | 116 | 7 | 41 | YoRyan/mailrise | tests/test_config.py | Python | test_errors | test_errors | 13 | 30 | 13 | 13 | ced3abc82d94f15b86d5ce2d363139f1f686a59d | bigcode/the-stack | train |
88c11a6bf3db596afb2861b8 | train | function | def test_load() -> None:
"""Tests a successful load with :fun:`load_config`."""
f = StringIO("""
configs:
test:
urls:
- json://localhost
""")
mrise = load_config(_logger, f)
assert len(mrise.senders) == 1
key = Key(user='test')
assert key in mrise.... | def test_load() -> None:
| """Tests a successful load with :fun:`load_config`."""
f = StringIO("""
configs:
test:
urls:
- json://localhost
""")
mrise = load_config(_logger, f)
assert len(mrise.senders) == 1
key = Key(user='test')
assert key in mrise.senders
sender = mri... | f = StringIO("""
configs: 24
""")
load_config(_logger, f)
with pytest.raises(ConfigFileError):
f = StringIO("""
configs:
test: 24
""")
load_config(_logger, f)
def test_load() -> None:
| 64 | 64 | 121 | 7 | 57 | YoRyan/mailrise | tests/test_config.py | Python | test_load | test_load | 33 | 48 | 33 | 33 | 160019e24058b7e4bd576c51f13038dfb6e55fea | bigcode/the-stack | train |
817507a6bb97b8d8eb0970b5 | train | function | def test_mailrise_options() -> None:
"""Tests a successful load with :fun:`load_config` with Mailrise-specific
options."""
f = StringIO("""
configs:
test:
urls:
- json://localhost
mailrise:
title_template: ""
body_format: "t... | def test_mailrise_options() -> None:
| """Tests a successful load with :fun:`load_config` with Mailrise-specific
options."""
f = StringIO("""
configs:
test:
urls:
- json://localhost
mailrise:
title_template: ""
body_format: "text"
""")
mrise = load_config... | 2'):
key = Key(user=user)
assert key in mrise.senders
sender = mrise.senders[key]
assert len(sender.apprise) == 1
assert sender.apprise[0].url().startswith('json://localhost/')
def test_mailrise_options() -> None:
| 63 | 64 | 188 | 9 | 54 | YoRyan/mailrise | tests/test_config.py | Python | test_mailrise_options | test_mailrise_options | 74 | 104 | 74 | 74 | a1b294ab0bb36acd9d9e224dc3f39069c48463d1 | bigcode/the-stack | train |
cd5c94b8604ca8262feecf85 | train | class | class ExceededMaxAttempts(Exception):
pass
| class ExceededMaxAttempts(Exception):
| pass
| import client as kube_client
from kubernetes import config as kube_config
from kubernetes.client.exceptions import ApiException
from kubernetes.client.models.v1_pod import V1Pod
logger = logging.getLogger(__name__)
DEFAULT_ATTEMPTS = 2
class ExceededMaxAttempts(Exception):
| 64 | 64 | 10 | 7 | 56 | Yelp/task_processing | task_processing/plugins/kubernetes/kube_client.py | Python | ExceededMaxAttempts | ExceededMaxAttempts | 16 | 17 | 16 | 16 | 184ca0a0875068464a7d73bca1312f5d9994be71 | bigcode/the-stack | train |
cef16628f4c95f3c7ec38412 | train | class | class KubeClient:
def __init__(self, kubeconfig_path: Optional[str] = None) -> None:
kubeconfig_path = kubeconfig_path or os.environ.get("KUBECONFIG")
if kubeconfig_path is None:
raise ValueError(
"No kubeconfig specified: set a KUBECONFIG environment variable "
... | class KubeClient:
| def __init__(self, kubeconfig_path: Optional[str] = None) -> None:
kubeconfig_path = kubeconfig_path or os.environ.get("KUBECONFIG")
if kubeconfig_path is None:
raise ValueError(
"No kubeconfig specified: set a KUBECONFIG environment variable "
"or pass a ... | import logging
import os
from http import HTTPStatus
from typing import Optional
from kubernetes import client as kube_client
from kubernetes import config as kube_config
from kubernetes.client.exceptions import ApiException
from kubernetes.client.models.v1_pod import V1Pod
logger = logging.getLogger(__name__)
DEFAU... | 93 | 256 | 1,442 | 5 | 87 | Yelp/task_processing | task_processing/plugins/kubernetes/kube_client.py | Python | KubeClient | KubeClient | 20 | 191 | 20 | 20 | f9794d34f6af1c0b4b32965470686bec4a438046 | bigcode/the-stack | train |
318cd40fda1c1f51163aba39 | train | function | def align(file1, file2, file2_aligned, file_subtracted):
def get_diff(a, b):
corr = np.correlate(a, b, "full")
diff = corr.argmax() - (b.shape[0] - 1)
return diff
def get_diff_val(a, b):
d = np.abs(a - b)
return np.mean(d) / max(min(np.max(d), 0.1), 1e-6)
print("Processing: {} ... | def align(file1, file2, file2_aligned, file_subtracted):
| def get_diff(a, b):
corr = np.correlate(a, b, "full")
diff = corr.argmax() - (b.shape[0] - 1)
return diff
def get_diff_val(a, b):
d = np.abs(a - b)
return np.mean(d) / max(min(np.max(d), 0.1), 1e-6)
print("Processing: {} / {}".format(file1, file2))
# read tracks
if os.... | import os
import sys
import random
import glob
import soundfile as sf
import librosa
import numpy as np
def align(file1, file2, file2_aligned, file_subtracted):
| 44 | 256 | 933 | 17 | 26 | lucassantilli/UVR-Colab-GUI | lib/align_tracks.py | Python | align | align | 9 | 79 | 9 | 9 | b6768e548489620a4e67e99b668735a04324a034 | bigcode/the-stack | train |
f9b9e0feac50813fe8068342 | train | function | def align_files(pat1, pat2):
files1 = glob.glob(pat1)
files2 = glob.glob(pat2)
files1.sort()
files2.sort()
for file1, file2 in zip(files1, files2):
base_name = os.path.basename(os.path.splitext(file2)[0])
aligned_file = base_name + '_aligned.wav'
subtracted_file = base_name + '_inverted... | def align_files(pat1, pat2):
| files1 = glob.glob(pat1)
files2 = glob.glob(pat2)
files1.sort()
files2.sort()
for file1, file2 in zip(files1, files2):
base_name = os.path.basename(os.path.splitext(file2)[0])
aligned_file = base_name + '_aligned.wav'
subtracted_file = base_name + '_inverted.wav'
align(file1, file2,... | _len]
wav_sub = np.clip(wav_sub, -1, +1)
sf.write(file_subtracted, wav_sub, sr2, subtype='PCM_24')
print("Already aligned! - Saving difference as {}".format(file_subtracted))
def align_files(pat1, pat2):
| 63 | 64 | 110 | 10 | 53 | lucassantilli/UVR-Colab-GUI | lib/align_tracks.py | Python | align_files | align_files | 81 | 90 | 81 | 81 | a2188f9926c874de5164786b73cec641783da479 | bigcode/the-stack | train |
69439de84b8c654025cc672d | train | class | class ModuleImplCPC(ModuleImplBase):
def __init__(self, **kwargs):
self._opened = None
self._prevPins = None
self._winid = None
self._machineType = 'atom'
super(ModuleImplCPC,self).__init__(**kwargs)
self._moduleType = ModuleType.ATOMIC
def __del__(self):
... | class ModuleImplCPC(ModuleImplBase):
| def __init__(self, **kwargs):
self._opened = None
self._prevPins = None
self._winid = None
self._machineType = 'atom'
super(ModuleImplCPC,self).__init__(**kwargs)
self._moduleType = ModuleType.ATOMIC
def __del__(self):
log.warn("Hello from del/CPC")
... |
from ..Log import Log
log = Log(__name__)
from ..ModuleFactory import *
import q3c
class ModuleImplCPC(ModuleImplBase):
| 33 | 256 | 988 | 9 | 23 | virtimus/makaronLab | q3/q3/Q3Chips/ModuleImplCPC.py | Python | ModuleImplCPC | ModuleImplCPC | 9 | 134 | 9 | 9 | b0f41b0d7f5fc50e758076470ab65478fc6faec3 | bigcode/the-stack | train |
6472550520df54409bca3ae5 | train | class | class AdmissionregistrationApi(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_clien... | class AdmissionregistrationApi(object):
| """NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_api_group(se... | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.19.15
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re #... | 145 | 256 | 923 | 6 | 139 | lsst-sqre/kubernetes_asyncio | kubernetes_asyncio/client/api/admissionregistration_api.py | Python | AdmissionregistrationApi | AdmissionregistrationApi | 27 | 142 | 27 | 27 | 536d944b6dd0a9f96703f40864cb917a731557a5 | bigcode/the-stack | train |
ddf9450794c9f45537c7d3bb | train | class | class TimeParser:
def __init__(self, argument):
compiled = re.compile(r"(?:(?P<hours>[0-9]{1,5})h)?(?:(?P<minutes>[0-9]{1,5})m)?(?:(?P<seconds>[0-9]{1,5})s)?$")
self.original = argument
try:
self.seconds = int(argument)
except ValueError as e:
match = compiled... | class TimeParser:
| def __init__(self, argument):
compiled = re.compile(r"(?:(?P<hours>[0-9]{1,5})h)?(?:(?P<minutes>[0-9]{1,5})m)?(?:(?P<seconds>[0-9]{1,5})s)?$")
self.original = argument
try:
self.seconds = int(argument)
except ValueError as e:
match = compiled.match(argument)
... | from discord.ext import commands
from .utils import checks, formats
import discord
from collections import OrderedDict, deque, Counter
import os, datetime
import re, asyncio
import copy
import unicodedata
import inspect
class TimeParser:
| 52 | 78 | 261 | 4 | 47 | Brentxz/idkio | cogs/meta.py | Python | TimeParser | TimeParser | 11 | 37 | 11 | 11 | 9c511fe5a1e1c583c538e294d830d6e14c049584 | bigcode/the-stack | train |
c535afc83a7be82f6e889710 | train | class | class Meta:
"""Commands for utilities related to Discord or the Bot itself."""
def __init__(self, bot):
self.bot = bot
@commands.command(hidden=True)
async def hello(self):
"""Displays my intro message."""
await self.bot.say('Hello! I\'m a robot! Danny#0007 made me.')
@com... | class Meta:
| """Commands for utilities related to Discord or the Bot itself."""
def __init__(self, bot):
self.bot = bot
@commands.command(hidden=True)
async def hello(self):
"""Displays my intro message."""
await self.bot.say('Hello! I\'m a robot! Danny#0007 made me.')
@commands.comman... | __(self, argument):
compiled = re.compile(r"(?:(?P<hours>[0-9]{1,5})h)?(?:(?P<minutes>[0-9]{1,5})m)?(?:(?P<seconds>[0-9]{1,5})s)?$")
self.original = argument
try:
self.seconds = int(argument)
except ValueError as e:
match = compiled.match(argument)
if ... | 256 | 256 | 2,244 | 3 | 253 | Brentxz/idkio | cogs/meta.py | Python | Meta | Meta | 39 | 288 | 39 | 39 | 2d9f3d2fff2ca687b2d99cbb24dc9ab1b9c04bc2 | bigcode/the-stack | train |
80293b8a3b0757413463ddd8 | train | function | def setup(bot):
bot.add_cog(Meta(bot))
| def setup(bot):
| bot.add_cog(Meta(bot))
| ):
await self.bot.say(content)
@commands.command(hidden=True)
async def cud(self):
"""pls no spam"""
for i in range(3):
await self.bot.say(3 - i)
await asyncio.sleep(1)
await self.bot.say('go')
def setup(bot):
| 64 | 64 | 13 | 4 | 60 | Brentxz/idkio | cogs/meta.py | Python | setup | setup | 290 | 291 | 290 | 290 | ca64a51b787644a264c4ef1330775e5a211399fc | bigcode/the-stack | train |
efaa0dbc3da1192fe731199b | train | class | class GetCookiePolicyTests(TestCase):
def tearDown(self):
from zope.testing.cleanup import cleanUp
# clear the component registry
cleanUp()
def test_defaults(self):
self.assertIs(getCookieParamPolicy(), defaultCookieParamPolicy)
self.assertIs(getCookieValuePolicy(), def... | class GetCookiePolicyTests(TestCase):
| def tearDown(self):
from zope.testing.cleanup import cleanUp
# clear the component registry
cleanUp()
def test_defaults(self):
self.assertIs(getCookieParamPolicy(), defaultCookieParamPolicy)
self.assertIs(getCookieValuePolicy(), defaultCookieValuePolicy)
def test_c... | n, v = convertCookieParameter("comment", "comment")
self.assertEqual(n, "Comment")
self.assertEqual(v, "comment")
def test_unknown_parameter(self):
with self.assertRaises(KeyError):
convertCookieParameter("xyz", "abc")
class GetCookiePolicyTests(TestCase):
| 64 | 64 | 134 | 8 | 56 | arnaud-fontaine/Zope | src/ZPublisher/tests/test_cookie.py | Python | GetCookiePolicyTests | GetCookiePolicyTests | 203 | 221 | 203 | 203 | c48a73b687806e2a1074b1dcee9b9f7848fbf40a | bigcode/the-stack | train |
17f0abafb059db5fb32c4186 | train | class | class CookieParameterRegistryTests(TestCase):
def test_basics(self):
reg = CookieParameterRegistry()
register = reg.register
def converter(value):
return "pref" + value
register("Max-Age", converter)
for n in "Max-Age max-age Max_Age max_age".split():
... | class CookieParameterRegistryTests(TestCase):
| def test_basics(self):
reg = CookieParameterRegistry()
register = reg.register
def converter(value):
return "pref" + value
register("Max-Age", converter)
for n in "Max-Age max-age Max_Age max_age".split():
self.assertIs(reg._normalize[n], "Max-Age")
... | 1"}))
assertRfc1123(self, np["Expires"])
# with ``Max-Age>0``, with ``Expires``
op = {"Max-Age": "1", "Expires": "exp"}
self.assertEqual(op, dict(parameters("n", op)))
def test_check_consistency(self):
# it does nothing -- thus, just check the correct signature
defau... | 256 | 256 | 1,162 | 8 | 247 | arnaud-fontaine/Zope | src/ZPublisher/tests/test_cookie.py | Python | CookieParameterRegistryTests | CookieParameterRegistryTests | 82 | 200 | 82 | 82 | 5ef54df03dcf145af9cfa8835e6846c18a2ed376 | bigcode/the-stack | train |
83f6be5440c4e7a0274d2388 | train | function | def assertRfc1123(self, s):
"""check *s* is an RFC1123 date."""
m = match(r"(.{3}), \d{2} (.{3}) \d{4} \d{2}:\d{2}:\d{2} GMT$", s)
self.assertIsNotNone(m)
self.assertIn(m.group(1), tuple(wdmap.values()))
self.assertIn(m.group(2), tuple(mmap.values()))
| def assertRfc1123(self, s):
| """check *s* is an RFC1123 date."""
m = match(r"(.{3}), \d{2} (.{3}) \d{4} \d{2}:\d{2}:\d{2} GMT$", s)
self.assertIsNotNone(m)
self.assertIn(m.group(1), tuple(wdmap.values()))
self.assertIn(m.group(2), tuple(mmap.values()))
| defaultCookieParamPolicy
from ..cookie import defaultCookieValuePolicy
from ..cookie import getCookieParamPolicy
from ..cookie import getCookieValuePolicy
from ..cookie import mmap
from ..cookie import normalizeCookieParameterName
from ..cookie import wdmap
def assertRfc1123(self, s):
| 64 | 64 | 103 | 10 | 53 | arnaud-fontaine/Zope | src/ZPublisher/tests/test_cookie.py | Python | assertRfc1123 | assertRfc1123 | 31 | 36 | 31 | 31 | 779a9f0939a3b75a817714a0d0af2be13dbc2ed1 | bigcode/the-stack | train |
42216af23b25810729a5ef6d | train | class | class DefaultPolicyTests(TestCase):
def test_parameters(self):
parameters = defaultCookieParamPolicy.parameters
# normal
self.assertEqual(
tuple(parameters("n", dict(value="v", param="p"))),
(("param", "p"),))
# with ``Max-Age=-1`` without ``Expires``
... | class DefaultPolicyTests(TestCase):
| def test_parameters(self):
parameters = defaultCookieParamPolicy.parameters
# normal
self.assertEqual(
tuple(parameters("n", dict(value="v", param="p"))),
(("param", "p"),))
# with ``Max-Age=-1`` without ``Expires``
np = dict(parameters("n", {"Max-Age"... | def assertRfc1123(self, s):
"""check *s* is an RFC1123 date."""
m = match(r"(.{3}), \d{2} (.{3}) \d{4} \d{2}:\d{2}:\d{2} GMT$", s)
self.assertIsNotNone(m)
self.assertIn(m.group(1), tuple(wdmap.values()))
self.assertIn(m.group(2), tuple(mmap.values()))
class DefaultPolicyTests(TestCase):
| 110 | 111 | 372 | 7 | 103 | arnaud-fontaine/Zope | src/ZPublisher/tests/test_cookie.py | Python | DefaultPolicyTests | DefaultPolicyTests | 39 | 75 | 39 | 39 | 7cd07d582c3543773456f38c8e9a839c317a9a21 | bigcode/the-stack | train |
58a0d77a327903a9cffbeca7 | train | function | def main() :
'''Run phasomeit using command line arguments'''
# Create the parser
parser = argparse.ArgumentParser(prog='PhasomeIt', description='Identify the phasome of multiple genomes')
# Target path
parser.add_argument(
'-t', '--target',
metavar='target-folder',
... | def main() :
| '''Run phasomeit using command line arguments'''
# Create the parser
parser = argparse.ArgumentParser(prog='PhasomeIt', description='Identify the phasome of multiple genomes')
# Target path
parser.add_argument(
'-t', '--target',
metavar='target-folder',
help='Folde... | # Command line parsing main entry file
import argparse
import logging
import os
import sys
import time
import loghandler
import settings
import findpvinstrains
from speciesannotator import SpeciesAnnotator
__version__ = '1.1.3'
def main() :
| 61 | 256 | 1,249 | 4 | 57 | JackAidley/PhasomeIt | phasomeit.py | Python | main | main | 16 | 167 | 16 | 16 | 024d52427c3aaecb24190056cbf53502b4a988a7 | bigcode/the-stack | train |
d5f16e417ab50ca48c68a13d | train | class | class Migration(migrations.Migration):
dependencies = [
('micro_admin', '0007_auto_20160730_1009'),
]
operations = [
migrations.CreateModel(
name='Menu',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_n... | class Migration(migrations.Migration):
| dependencies = [
('micro_admin', '0007_auto_20160730_1009'),
]
operations = [
migrations.CreateModel(
name='Menu',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', mo... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-03 11:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 61 | 69 | 230 | 7 | 53 | lance0145/micro-finance | micro_admin/migrations/0008_auto_20160803_1130.py | Python | Migration | Migration | 9 | 33 | 9 | 10 | 21dc81b00a21530618c9a11e37c532a040bb4f71 | bigcode/the-stack | train |
54d3925ace6ccf9b37390c89 | train | function | def boolean_fn1(a, b, c):
""" Return the truth value of (a ∨ b) → (-a ∧ -b) """
return not (a or b) or not a and not b
| def boolean_fn1(a, b, c):
| """ Return the truth value of (a ∨ b) → (-a ∧ -b) """
return not (a or b) or not a and not b
| of functions which implement Boolean
expressions.
It also defines a function to generate and print truth tables
using these functions.
It should be implemented for Exercise 2 of Assignment 0.
See the assignment notes for a descript... | 64 | 64 | 47 | 10 | 54 | ybhan/Artificial-Intelligence-Projects | assignment-0/truth_tables.py | Python | boolean_fn1 | boolean_fn1 | 16 | 18 | 16 | 16 | e891cc003df5e0186deff7e223b0285029a5811a | bigcode/the-stack | train |
9180fb7a8c620e96a27030b9 | train | function | def boolean_fn2(a, b, c):
""" Return the truth value of (a ∧ b) ∨ (-a ∧ -b) """
return a and b or not a and not b
| def boolean_fn2(a, b, c):
| """ Return the truth value of (a ∧ b) ∨ (-a ∧ -b) """
return a and b or not a and not b
| a description of its contents.
"""
def boolean_fn1(a, b, c):
""" Return the truth value of (a ∨ b) → (-a ∧ -b) """
return not (a or b) or not a and not b
def boolean_fn2(a, b, c):
| 64 | 64 | 45 | 10 | 53 | ybhan/Artificial-Intelligence-Projects | assignment-0/truth_tables.py | Python | boolean_fn2 | boolean_fn2 | 21 | 23 | 21 | 21 | 06842a1d1d414af911c80647b0c44ff732c31e78 | bigcode/the-stack | train |
8dc9474a3c6db98ebf1add0d | train | function | def draw_truth_table(boolean_fn):
""" This function prints a truth table for the given boolean function.
It is assumed that the supplied function has three arguments.
((bool, bool, bool) -> bool) -> None
If your function is working correctly, your console output should look
like th... | def draw_truth_table(boolean_fn):
| """ This function prints a truth table for the given boolean function.
It is assumed that the supplied function has three arguments.
((bool, bool, bool) -> bool) -> None
If your function is working correctly, your console output should look
like this:
>>> from truth_tables... | (-a ∧ -b) """
return a and b or not a and not b
def boolean_fn3(a, b, c):
""" Return the truth value of ((c → a) ∧ (a ∧ -b)) ∨ (-a ∧ b) """
return (not c or a) and a and not b or not a and b
def draw_truth_table(boolean_fn):
| 86 | 86 | 288 | 7 | 78 | ybhan/Artificial-Intelligence-Projects | assignment-0/truth_tables.py | Python | draw_truth_table | draw_truth_table | 31 | 67 | 31 | 31 | 0b0a8d8666a366ff3d595484e2ab42b6d727e631 | bigcode/the-stack | train |
5e803dc7503091416f9643f2 | train | function | def boolean_fn3(a, b, c):
""" Return the truth value of ((c → a) ∧ (a ∧ -b)) ∨ (-a ∧ b) """
return (not c or a) and a and not b or not a and b
| def boolean_fn3(a, b, c):
| """ Return the truth value of ((c → a) ∧ (a ∧ -b)) ∨ (-a ∧ b) """
return (not c or a) and a and not b or not a and b
| b) or not a and not b
def boolean_fn2(a, b, c):
""" Return the truth value of (a ∧ b) ∨ (-a ∧ -b) """
return a and b or not a and not b
def boolean_fn3(a, b, c):
| 64 | 64 | 59 | 10 | 53 | ybhan/Artificial-Intelligence-Projects | assignment-0/truth_tables.py | Python | boolean_fn3 | boolean_fn3 | 26 | 28 | 26 | 26 | a90c6eda21b9c1c6badd6d52afe5b665ee86af5c | bigcode/the-stack | train |
19c317c219840f5211e6947b | train | function | def main():
with open("analysis.csv", "w") as f_out:
f_out.write("task-nrun,opentuner,hpbandster,gptune,TLA2(worst),TLA2(best),TLA3(worst),TLA3(best),TLA4(worst),TLA4(best),TLA5\n")
########
for nrun in [10,20,30,40,50]:
for task in [0.6,0.8,1.0,1.2,1.4]:
f_out... | def main():
| with open("analysis.csv", "w") as f_out:
f_out.write("task-nrun,opentuner,hpbandster,gptune,TLA2(worst),TLA2(best),TLA3(worst),TLA3(best),TLA4(worst),TLA4(best),TLA5\n")
########
for nrun in [10,20,30,40,50]:
for task in [0.6,0.8,1.0,1.2,1.4]:
f_out.write(str(ta... | #! /usr/bin/env python
import sys
import os
import json
import re
number_re = "+([0-9]+\.[01-9]+|[0-9]+)"
def main():
| 43 | 256 | 2,171 | 3 | 40 | gptune/GPTune | examples/GPTune-Demo/analysis_TLA.py | Python | main | main | 10 | 161 | 10 | 11 | 29425b2857c5f4890d622fe2d8c10935afaed734 | bigcode/the-stack | train |
ad7ce597d8bf91ef478350d4 | train | function | @command_matching_group()
def main():
"""Template bash command by Laz, ᒪᗩᘔ, ㄥ卂乙, ןɐz, lคz, ℓДՀ, լᕱᏃ, Նคઽ, レム乙"""
| @command_matching_group()
def main():
| """Template bash command by Laz, ᒪᗩᘔ, ㄥ卂乙, ןɐz, lคz, ℓДՀ, լᕱᏃ, Նคઽ, レム乙"""
| import zlick
from lztools.zlick import command_matching_group
@command_matching_group()
def main():
| 23 | 64 | 68 | 8 | 14 | Zanzes/lztools | lztools/third/main.py | Python | main | main | 4 | 6 | 4 | 5 | a68aed88d4eca735e758a61890ac59dd7aabcfef | bigcode/the-stack | train |
55d57b5208558a1386415078 | train | class | class PowerBlock(BlockWithOneExtension):
def __init__(self, address: int=None, measurement_period: float=1):
"""
@param address:block address
@param mesurement_period: sampling frequency in sec
"""
super().__init__(BlockTypes.power, address)
self.is_usb_connected = ActiveVariable(False, measu... | class PowerBlock(BlockWithOneExtension):
| def __init__(self, address: int=None, measurement_period: float=1):
"""
@param address:block address
@param mesurement_period: sampling frequency in sec
"""
super().__init__(BlockTypes.power, address)
self.is_usb_connected = ActiveVariable(False, measurement_period, self._get_usb_state)
se... | const(0x00)
_ina219_shunt_voltage_command = const(0x01)
_ina219_busvoltag_command = const(0x02)
#reset bit is 0
_config = const(_ina219_mode_shunt_bus_continuous | (_ina219_sadc_8sam_4260 << 3) | (_ina219_badc_res_12bit << 7) | (_ina219_pg_gd4_160mv << 11) | (_ina219_brng_16v << 13))
#_ina219_power_command = const(0... | 169 | 169 | 565 | 8 | 160 | jakub-vesely/micropython | ports/esp32/boards/HUGO/modules/power_block.py | Python | PowerBlock | PowerBlock | 30 | 80 | 30 | 31 | b6020ddeccd478b0586131d7a802e0d68a5aa479 | bigcode/the-stack | train |
4fa728eba49c8b9ace0d7cb0 | train | class | class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, nullable=False)
content = Column(String, nullable=False)
published = Column(Boolean, server_default="TRUE", nullable=False)
created_at = Column(TIMESTAMP(timezone=True), nullable=False, ... | class Post(Base):
| __tablename__ = 'posts'
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, nullable=False)
content = Column(String, nullable=False)
published = Column(Boolean, server_default="TRUE", nullable=False)
created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text... | from datetime import timezone
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.orm import relationship
from sqlalchemy.sql.expression import text
from sqlalchemy.sql.schema import ForeignKey
from sqlalchemy.sql.sqltypes import TIMESTAMP
from .database import Base
class Post(Base):
| 56 | 64 | 108 | 4 | 51 | shriekdj/fastapi-1 | app/models.py | Python | Post | Post | 9 | 19 | 9 | 9 | 44cfbe2ea159c6e9449a20480dcfbc4c5089e740 | bigcode/the-stack | train |
242439f14b55f686136015ed | train | class | class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, nullable=False)
email = Column(String, nullable=False, unique=True)
password = Column(String, nullable=False)
created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()'))
| class User(Base):
| __tablename__ = "users"
id = Column(Integer, primary_key=True, nullable=False)
email = Column(String, nullable=False, unique=True)
password = Column(String, nullable=False)
created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()'))
| ="TRUE", nullable=False)
created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()'))
owner_id = Column(Integer, ForeignKey(
'users.id', ondelete="CASCADE"), nullable=False)
owner = relationship("User")
class User(Base):
| 64 | 64 | 65 | 4 | 60 | shriekdj/fastapi-1 | app/models.py | Python | User | User | 21 | 26 | 21 | 21 | c751ae9a2017a8b49d828bcda8f93d60b42aec17 | bigcode/the-stack | train |
1df128e09e3e157c62df2fdb | train | function | @pytest.mark.parametrize(
"shape, out_chans, chans, center_fractions, accelerations",
[
([1, 3, 32, 16, 2], 2, 1, [0.08], [4]),
([5, 5, 15, 12, 2], 2, 32, [0.04], [8]),
([3, 8, 13, 18, 2], 2, 16, [0.08], [4]),
([1, 2, 17, 19, 2], 2, 8, [0.08], [4]),
],
)
def test_varnet(shape... | @pytest.mark.parametrize(
"shape, out_chans, chans, center_fractions, accelerations",
[
([1, 3, 32, 16, 2], 2, 1, [0.08], [4]),
([5, 5, 15, 12, 2], 2, 32, [0.04], [8]),
([3, 8, 13, 18, 2], 2, 16, [0.08], [4]),
([1, 2, 17, 19, 2], 2, 8, [0.08], [4]),
],
)
def test_varnet(shape... | mask_func = RandomMaskFunc(center_fractions, accelerations)
x = create_input(shape)
output, mask = transforms.apply_mask(x, mask_func, seed=123)
varnet = VarNet(num_cascades=2, sens_chans=4, sens_pools=2, chans=4, pools=2)
y = varnet(output, mask.byte())
assert y.shape[1:] == x.shape[2:4]
| @pytest.mark.parametrize(
"shape, out_chans, chans, center_fractions, accelerations",
[
([1, 3, 32, 16, 2], 2, 1, [0.08], [4]),
([5, 5, 15, 12, 2], 2, 32, [0.04], [8]),
([3, 8, 13, 18, 2], 2, 16, [0.08], [4]),
([1, 2, 17, 19, 2], 2, 8, [0.08], [4]),
],
)
def test_varnet(shape... | 165 | 78 | 261 | 165 | 0 | josmfred/fastMRI | tests/test_models.py | Python | test_varnet | test_varnet | 39 | 57 | 39 | 48 | 17fe2524dbf19a31b12ffa46850841c3caffd860 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.