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
c70e05ba58e496304a771fc8
train
function
@client.event async def on_message(message): if message.content.startswith("|help"): await message.channel.send(helpcom()) if message.content.startswith("|gbcomparesingle"): try: await message.channel.send(CompareCPU(singlecoreGB5, message.content.split()[1].capitalize(), ...
@client.event async def on_message(message):
if message.content.startswith("|help"): await message.channel.send(helpcom()) if message.content.startswith("|gbcomparesingle"): try: await message.channel.send(CompareCPU(singlecoreGB5, message.content.split()[1].capitalize(), ...
def Geekbenchmulticore(CPU): return f'```The {CPU} scores on average {multicoreGB5.get(CPU)} points in Geekbench 5 multicore```' def Geekbenchsinglecore(CPU): return f'```The {CPU} scores on average {singlecoreGB5.get(CPU)} points in Geekbench 5 singlecore```' @client.event async def on_message(message)...
91
92
309
10
81
monabuntur/BenchBot
BenchBot.py
Python
on_message
on_message
82
122
82
83
795e7e542af1d51a6d639a9f14c8f99c0fbe747b
bigcode/the-stack
train
888c76c2159ddd7d7d4d90ae
train
function
@client.event async def on_ready(): print("BenchBot 1.3") asyncio.create_task(gb5scraper.main())
@client.event async def on_ready():
print("BenchBot 1.3") asyncio.create_task(gb5scraper.main())
await message.channel.send("```Please try again with a valid CPU```") if message.content.startswith("|bpecs"): await message.channel.send(BotSpecs()) if message.content.startswith("|botinfo"): await message.channel.send(BotInfo()) @client.event async def on_ready():
63
64
30
9
54
monabuntur/BenchBot
BenchBot.py
Python
on_ready
on_ready
125
128
125
126
e796db53ac456de12d455716493e7034914ad3d4
bigcode/the-stack
train
09940c29da05ac8f31bf5e96
train
function
def Faster(dictionary, CPU1, CPU2): if int(dictionary.get(CPU1)) > int(dictionary.get(CPU2)): return f'The {CPU1} is ~{round(100 - (int(dictionary.get(CPU2)) / int(dictionary.get(CPU1))) * 100, 2)}% faster' elif int(dictionary.get(CPU2)) > int(dictionary.get(CPU1)): return f'The {CPU2} is ~{...
def Faster(dictionary, CPU1, CPU2):
if int(dictionary.get(CPU1)) > int(dictionary.get(CPU2)): return f'The {CPU1} is ~{round(100 - (int(dictionary.get(CPU2)) / int(dictionary.get(CPU1))) * 100, 2)}% faster' elif int(dictionary.get(CPU2)) > int(dictionary.get(CPU1)): return f'The {CPU2} is ~{round(100 - (int(dictionary.get(CPU1)...
Darwin": return "```Too cool for macOS```" else: return "```Unsupported action, this likely means that the bot is running on an OS that is neither Windows nor " \ "Linux``` " # Compares two CPUs def Faster(dictionary, CPU1, CPU2):
64
64
128
10
53
monabuntur/BenchBot
BenchBot.py
Python
Faster
Faster
44
48
44
44
7f785bb231c50fb42169816bb4974aa6eb7edb53
bigcode/the-stack
train
9b357f28c94a540a8fa4e9b8
train
function
def helpcom(): return "```" \ "Commands\n" \ "|help = this thing here\n" \ "|gbsingle *CPU* = single core Geekbench 5\n" \ "|gbmulti *CPU* = multi core Geekbench 5\n" \ "|gbcomparesingle *CPU1* *CPU2* = compares two CPUs in single core Geekbench 5\n" \ ...
def helpcom():
return "```" \ "Commands\n" \ "|help = this thing here\n" \ "|gbsingle *CPU* = single core Geekbench 5\n" \ "|gbmulti *CPU* = multi core Geekbench 5\n" \ "|gbcomparesingle *CPU1* *CPU2* = compares two CPUs in single core Geekbench 5\n" \ "|gbco...
} --> {dictionary.get(CPU1)} points\n' \ f'{CPU2} --> {dictionary.get(CPU2)} points\n' \ f'---------------------------------\n' \ f'{Faster(dictionary, CPU1, CPU2)}```' # Help command def helpcom():
64
64
149
4
59
monabuntur/BenchBot
BenchBot.py
Python
helpcom
helpcom
61
71
61
61
33e6880d360ca6cb8aa86a7065e6c23d0107aeeb
bigcode/the-stack
train
adb4e765aa6e11bfe5e96849
train
function
def BotSpecs(): if OS == 'Linux': return f'```OS: {OS} {platform.release()}\n' \ 'CPU: %s' \ f'Total RAM installed: {subprocess.check_output("echo $(($(getconf _PHYS_PAGES) * $(getconf PAGE_SIZE) / (1073741824)))", shell=True).strip().decode()}' % (str(subprocess.check_outp...
def BotSpecs():
if OS == 'Linux': return f'```OS: {OS} {platform.release()}\n' \ 'CPU: %s' \ f'Total RAM installed: {subprocess.check_output("echo $(($(getconf _PHYS_PAGES) * $(getconf PAGE_SIZE) / (1073741824)))", shell=True).strip().decode()}' % (str(subprocess.check_output("cat /proc/cpu...
file containing the token and reads the first line TOKEN = open("TOKEN.txt", "r").readline() client = discord.Client() OS = platform.system() def BotInfo(): return "```BenchBot 1.2, developed by Monabuntur, April 2021\n" \ "Github: https://github.com/monabuntur/BenchBot```" def BotSpecs():
82
83
277
4
78
monabuntur/BenchBot
BenchBot.py
Python
BotSpecs
BotSpecs
22
38
22
22
c79922d50cf88d90b902807e2ab53324f1cb1099
bigcode/the-stack
train
c1984c5f56451abb90da53cb
train
function
def CompareCPU(dictionary, CPU1, CPU2): return f'```{CPU1} --> {dictionary.get(CPU1)} points\n' \ f'{CPU2} --> {dictionary.get(CPU2)} points\n' \ f'---------------------------------\n' \ f'{Faster(dictionary, CPU1, CPU2)}```'
def CompareCPU(dictionary, CPU1, CPU2):
return f'```{CPU1} --> {dictionary.get(CPU1)} points\n' \ f'{CPU2} --> {dictionary.get(CPU2)} points\n' \ f'---------------------------------\n' \ f'{Faster(dictionary, CPU1, CPU2)}```'
2)) > int(dictionary.get(CPU1)): return f'The {CPU2} is ~{round(100 - (int(dictionary.get(CPU1)) / int(dictionary.get(CPU2))) * 100, 2)}% faster' def CompareCPU(dictionary, CPU1, CPU2):
63
64
74
11
52
monabuntur/BenchBot
BenchBot.py
Python
CompareCPU
CompareCPU
51
55
51
51
631d778ba45cc7465ca16ffb06414aaae7e9dc32
bigcode/the-stack
train
6a42f515c33e732087789d14
train
function
def Geekbenchsinglecore(CPU): return f'```The {CPU} scores on average {singlecoreGB5.get(CPU)} points in Geekbench 5 singlecore```'
def Geekbenchsinglecore(CPU):
return f'```The {CPU} scores on average {singlecoreGB5.get(CPU)} points in Geekbench 5 singlecore```'
"|botinfo = pretty self explanatory" \ "```" def Geekbenchmulticore(CPU): return f'```The {CPU} scores on average {multicoreGB5.get(CPU)} points in Geekbench 5 multicore```' def Geekbenchsinglecore(CPU):
63
64
39
8
55
monabuntur/BenchBot
BenchBot.py
Python
Geekbenchsinglecore
Geekbenchsinglecore
78
79
78
78
15d8089699e8aaa1682f22c4168d07dca269acbe
bigcode/the-stack
train
9273e83ab1ace0828cf97cc7
train
class
class Biopieces(Package): """The Biopieces are a collection of bioinformatics tools that can be pieced together in a very easy and flexible manner to perform both simple and complex tasks.""" homepage = "https://maasha.github.io/biopieces/" git = "https://github.com/maasha/biopieces.git"...
class Biopieces(Package):
"""The Biopieces are a collection of bioinformatics tools that can be pieced together in a very easy and flexible manner to perform both simple and complex tasks.""" homepage = "https://maasha.github.io/biopieces/" git = "https://github.com/maasha/biopieces.git" version('2016-04-12'...
# Copyright 2013-2022 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 Biopieces(Package):
61
201
670
7
54
player1537-forks/spack
var/spack/repos/builtin/packages/biopieces/package.py
Python
Biopieces
Biopieces
9
70
9
9
0f1d4dadf98aa842bf9cefb7ec6638572e2be813
bigcode/the-stack
train
3671e49bea08d06e35d12a8c
train
class
class TestPart1(unittest.TestCase): @classmethod def setUpClass(cls): cls.sample_input = """[1518-11-01 00:00] Guard #10 begins shift [1518-11-01 00:05] falls asleep [1518-11-01 00:25] wakes up [1518-11-01 00:30] falls asleep [1518-11-01 00:55] wakes up [1518-11-01 23:58] Guard #99 begins shift [1518-11...
class TestPart1(unittest.TestCase): @classmethod
def setUpClass(cls): cls.sample_input = """[1518-11-01 00:00] Guard #10 begins shift [1518-11-01 00:05] falls asleep [1518-11-01 00:25] wakes up [1518-11-01 00:30] falls asleep [1518-11-01 00:55] wakes up [1518-11-01 23:58] Guard #99 begins shift [1518-11-02 00:40] falls asleep [1518-11-02 00:50] wakes up [...
import unittest from datetime import datetime from day4.common import process_events, nap_intervals_per_guard from day4.events import EventType, ScheduleEvent from day4.part_1 import calc_highest_total_sleep_id, calc_sleepiest_minute from day4.part_2 import calc_guard_with_sleepiest_minute class TestPart1(unittest.Tes...
80
256
1,224
12
67
NekohimeMusou/advent-of-code
day4/tests.py
Python
TestPart1
TestPart1
10
83
10
11
c378cc6650c64acb802b9c352f653dbfbc4bcb5f
bigcode/the-stack
train
0e52d14488b5a5859a638f9a
train
class
class SimplePreprocessor: def __init__(self, width, height, inter=cv2.INTER_AREA): # store the target image width, height, and interpolation # method used when resizing self.width = width self.height = height self.inter = inter def preprocess(self, image): # resize the image to a fixed size, ignoring the...
class SimplePreprocessor:
def __init__(self, width, height, inter=cv2.INTER_AREA): # store the target image width, height, and interpolation # method used when resizing self.width = width self.height = height self.inter = inter def preprocess(self, image): # resize the image to a fixed size, ignoring the aspect # ratio return...
#!/home/knielbo/virtenvs/cv/bin/python """ """ # import the necessary packages import cv2 class SimplePreprocessor:
32
64
108
5
26
knielbo/kartina
preprocessing/simplepreprocessor.py
Python
SimplePreprocessor
SimplePreprocessor
7
19
7
7
0c23c4dba9c0e372f6f238af3c5c64d576242568
bigcode/the-stack
train
d2980c0d523316afbd8902f8
train
class
class TestKeyValueDataSet (unittest.TestCase): MEM_STORE: MemoryKeyValueStore @classmethod def setUpClass(cls) -> None: cls.MEM_STORE = MemoryKeyValueStore() cls.MEM_STORE.add_many({ 0: 'a', 1: 'b', 'key': 'value' }) def test_is_usable(self) ...
class TestKeyValueDataSet (unittest.TestCase):
MEM_STORE: MemoryKeyValueStore @classmethod def setUpClass(cls) -> None: cls.MEM_STORE = MemoryKeyValueStore() cls.MEM_STORE.add_many({ 0: 'a', 1: 'b', 'key': 'value' }) def test_is_usable(self) -> None: # Should always be true ...
import unittest from smqtk_core.configuration import configuration_test_helper from smqtk_dataprovider.impls.data_element.memory import DataMemoryElement from smqtk_dataprovider.impls.data_set.kvstore_backed import KVSDataSet, DFLT_KVSTORE from smqtk_dataprovider.impls.key_value_store.memory import MemoryKeyValueStore...
90
248
829
12
77
joshanderson-kw/SMQTK-Dataprovider
tests/representation/DataSet/test_kvstore_backed.py
Python
TestKeyValueDataSet
TestKeyValueDataSet
9
98
9
9
b83e1128cd75df9a1e5c48e6288766669076fcca
bigcode/the-stack
train
f973e59c06c790ad18b9ae87
train
function
def main(argv): # True means extract x, y coordinates # False means fix z coordinates enableModeExtract = True usageMsg = "z-fixer.py [--extract|--fix]" try: opts, args = getopt.getopt(argv, "h?e:f:", ["help", "extract", "fix"]) except getopt.GetoptError: print("ERROR: Unknown ...
def main(argv): # True means extract x, y coordinates # False means fix z coordinates
enableModeExtract = True usageMsg = "z-fixer.py [--extract|--fix]" try: opts, args = getopt.getopt(argv, "h?e:f:", ["help", "extract", "fix"]) except getopt.GetoptError: print("ERROR: Unknown argument. Please see below for usage.") print(usageMsg) sys.exit(2) if le...
03_c_graff": Tree(1, 0, -1.9), "prop_palm_fan_03_d": Tree(0.8, 0, -1.7), "prop_palm_fan_03_d_graff": Tree(0.8, 0, -1.7), "prop_palm_fan_04_c": Tree(1.25, -0.22, -1.1), "prop_palm_fan_04_d": Tree(1.5, -0.15, -1.1), "prop_palm_huge_01a": Tree(0.95, 0.37, -0.25), "prop_palm_huge_01b": Tree(0.95, -0...
200
200
667
22
178
Larcius/gta5-modder-utils
z_fixer/z-fixer.py
Python
main
main
118
183
118
120
3b75c50efc7baa6f86ee7f2f28321983ebc7a26e
bigcode/the-stack
train
a60ec14a4ec1f2a98e0e6960
train
class
@dataclass class Tree: trunkRadius: float offsetZ: float = 0 maxOffsetZ: Optional[float] = None def getRandomOffsetZ(self) -> float: maxOffsetZ = self.offsetZ if (DISABLE_INCREASE_OF_Z or self.maxOffsetZ is None or self.maxOffsetZ > self.offsetZ) else self.maxOffsetZ return random.unifo...
@dataclass class Tree:
trunkRadius: float offsetZ: float = 0 maxOffsetZ: Optional[float] = None def getRandomOffsetZ(self) -> float: maxOffsetZ = self.offsetZ if (DISABLE_INCREASE_OF_Z or self.maxOffsetZ is None or self.maxOffsetZ > self.offsetZ) else self.maxOffsetZ return random.uniform(maxOffsetZ, self.off...
actoring needed import math import os import getopt import random import re import shutil import struct import sys from typing import Optional import numpy as np import transforms3d from dataclasses import dataclass from natsort import natsorted @dataclass class Tree:
64
64
95
6
57
Larcius/gta5-modder-utils
z_fixer/z-fixer.py
Python
Tree
Tree
18
26
18
19
1e0feec2b9e7b2d28ae4b47d54db63b9bbe9b734
bigcode/the-stack
train
26cb0de043028f179b54a72a
train
function
def floatToStr(val): return "{:.8f}".format(val)
def floatToStr(val):
return "{:.8f}".format(val)
if len(parts) < 8: print("ERROR: invalid line in heightmap entry:") print(heightmapEntry) quit() return float(parts[3]), [float(parts[4]), float(parts[5]), float(parts[6])], float(parts[7]) def floatToStr(val):
64
64
16
6
58
Larcius/gta5-modder-utils
z_fixer/z-fixer.py
Python
floatToStr
floatToStr
202
203
202
202
499e1368ae2fc4a0fec48fa7c29dbc2bf3bac48e
bigcode/the-stack
train
bb600762a774534b190a2305
train
function
def calculateAngle(vertexMiddle: list[float], vertex1: list[float], vertex2: list[float]) -> float: unitVector1 = normalize(np.subtract(vertex1, vertexMiddle)) unitVector2 = normalize(np.subtract(vertex2, vertexMiddle)) return np.arccos(np.dot(unitVector1, unitVector2))
def calculateAngle(vertexMiddle: list[float], vertex1: list[float], vertex2: list[float]) -> float:
unitVector1 = normalize(np.subtract(vertex1, vertexMiddle)) unitVector2 = normalize(np.subtract(vertex2, vertexMiddle)) return np.arccos(np.dot(unitVector1, unitVector2))
, "because it is placed on a steep spot") return "" return matchobj.group(1) + floatToStr(calcZCoord) + matchobj.group(6) def calculateAngle(vertexMiddle: list[float], vertex1: list[float], vertex2: list[float]) -> float:
64
64
71
27
37
Larcius/gta5-modder-utils
z_fixer/z-fixer.py
Python
calculateAngle
calculateAngle
266
270
266
266
8e13b30461427c915c4d95a6d3f5ae0d74ae9512
bigcode/the-stack
train
08d9fb90c1789e916ad80d24
train
function
def normalize(vector: list[float]) -> list[float]: norm = np.linalg.norm(vector) if abs(norm) < 1e-8: return vector else: return vector / norm
def normalize(vector: list[float]) -> list[float]:
norm = np.linalg.norm(vector) if abs(norm) < 1e-8: return vector else: return vector / norm
list[float]) -> float: unitVector1 = normalize(np.subtract(vertex1, vertexMiddle)) unitVector2 = normalize(np.subtract(vertex2, vertexMiddle)) return np.arccos(np.dot(unitVector1, unitVector2)) def normalize(vector: list[float]) -> list[float]:
64
64
46
13
51
Larcius/gta5-modder-utils
z_fixer/z-fixer.py
Python
normalize
normalize
273
278
273
273
3d9e4eceba37552ac229e99908211224559a5b43
bigcode/the-stack
train
db77d6bb179ff5d1506bd860
train
function
def hashFloat(val: float) -> int: return hash(struct.pack("f", val))
def hashFloat(val: float) -> int:
return hash(struct.pack("f", val))
print(heightmapEntry) quit() return float(parts[3]), [float(parts[4]), float(parts[5]), float(parts[6])], float(parts[7]) def floatToStr(val): return "{:.8f}".format(val) def hashFloat(val: float) -> int:
64
64
20
10
54
Larcius/gta5-modder-utils
z_fixer/z-fixer.py
Python
hashFloat
hashFloat
206
207
206
206
151dd84e037892b3135914e398d60cd31dd242f3
bigcode/the-stack
train
5744f93a9cddbcc71d19e807
train
function
def repl(matchobj, outCoords, heightmap): global trees prop = matchobj.group(2).lower() if prop not in trees or (IGNORE_BUSHES and prop.startswith("prop_bush_")): return matchobj.group(0) tree = trees[prop] coords = [float(matchobj.group(3)), float(matchobj.group(4)), float(matchobj.grou...
def repl(matchobj, outCoords, heightmap):
global trees prop = matchobj.group(2).lower() if prop not in trees or (IGNORE_BUSHES and prop.startswith("prop_bush_")): return matchobj.group(0) tree = trees[prop] coords = [float(matchobj.group(3)), float(matchobj.group(4)), float(matchobj.group(5))] scaleXY = float(matchobj.group(...
_new) f.close() if heightmap is not None: heightmap.close() def getMinHeight(heightmap) -> [float, [float, float, float], float]: heightmapEntry = heightmap.readline().rstrip("\n") if not heightmapEntry: print("ERROR: cannot get entry in heightmap") quit() parts =...
189
189
633
11
178
Larcius/gta5-modder-utils
z_fixer/z-fixer.py
Python
repl
repl
210
263
210
210
4a352c369a639708429852d2484411039f2bfeb8
bigcode/the-stack
train
d244129c9b5e4a081b03c73b
train
function
def getMinHeight(heightmap) -> [float, [float, float, float], float]: heightmapEntry = heightmap.readline().rstrip("\n") if not heightmapEntry: print("ERROR: cannot get entry in heightmap") quit() parts = heightmapEntry.split(",") if len(parts) < 8: print("ERROR: invalid line i...
def getMinHeight(heightmap) -> [float, [float, float, float], float]:
heightmapEntry = heightmap.readline().rstrip("\n") if not heightmapEntry: print("ERROR: cannot get entry in heightmap") quit() parts = heightmapEntry.split(",") if len(parts) < 8: print("ERROR: invalid line in heightmap entry:") print(heightmapEntry) quit() ...
f = open(os.path.join(os.path.dirname(__file__), "generated", filename), 'w') f.write(content_new) f.close() if heightmap is not None: heightmap.close() def getMinHeight(heightmap) -> [float, [float, float, float], float]:
64
64
123
20
44
Larcius/gta5-modder-utils
z_fixer/z-fixer.py
Python
getMinHeight
getMinHeight
186
199
186
186
d512ce8bd772ee7bfce5ed9872e3d3823447d069
bigcode/the-stack
train
97522c63e257ff5d1bda0c21
train
class
@dataclass class Member: id: int name: str @classmethod def from_dict(cls, data: dict): return cls( id=data['id'], name=data['name'], ) def to_dict(self) -> dict: return { 'id': self.id, 'name': self.name, }
@dataclass class Member:
id: int name: str @classmethod def from_dict(cls, data: dict): return cls( id=data['id'], name=data['name'], ) def to_dict(self) -> dict: return { 'id': self.id, 'name': self.name, }
4511, 4582, 4722, 4723, 4789, 5551, 7011, 7033, 7991, 7992, ]: return cls.TRAVEL else: return cls.OTHER @dataclass class Member:
64
64
76
6
57
vladtsap/your-financier
models/core.py
Python
Member
Member
146
162
146
147
b19713e0de5475251dbaebb93b04d30bc0668862
bigcode/the-stack
train
a0d0e461138abc76ba77d975
train
class
class BudgetType(ExtendedEnum): WEEKLY = ('weekly', texts.WEEKLY) MONTHLY = ('monthly', texts.MONTHLY) YEARLY = ('yearly', texts.YEARLY) ONE_TIME = ('one-time', texts.ONE_TIME)
class BudgetType(ExtendedEnum):
WEEKLY = ('weekly', texts.WEEKLY) MONTHLY = ('monthly', texts.MONTHLY) YEARLY = ('yearly', texts.YEARLY) ONE_TIME = ('one-time', texts.ONE_TIME)
verbose_name(self): return super().value[1] @classmethod def _missing_(cls, key): for item in cls: if item.value == key or item.verbose_name == key: return item return super()._missing_(key) class BudgetType(ExtendedEnum):
64
64
54
7
57
vladtsap/your-financier
models/core.py
Python
BudgetType
BudgetType
28
32
28
28
0b99784ec84ae105ce54cb86c121c4dd3dd4a5ba
bigcode/the-stack
train
8dd0dc250adfc5f0d60edb43
train
class
class Categories(ExtendedEnum): AUTO = ('auto', texts.AUTO_CATEGORY) BOOKS = ('books', texts.BOOKS_CATEGORY) CLOTHES = ('clothes', texts.CLOTHES_CATEGORY) ENTERTAINMENT = ('entertainment', texts.ENTERTAINMENT_CATEGORY) FEES = ('fees', texts.FEES_CATEGORY) FOOD = ('food', texts.FOOD_CATEGORY) ...
class Categories(ExtendedEnum):
AUTO = ('auto', texts.AUTO_CATEGORY) BOOKS = ('books', texts.BOOKS_CATEGORY) CLOTHES = ('clothes', texts.CLOTHES_CATEGORY) ENTERTAINMENT = ('entertainment', texts.ENTERTAINMENT_CATEGORY) FEES = ('fees', texts.FEES_CATEGORY) FOOD = ('food', texts.FOOD_CATEGORY) GIFTS = ('gifts', texts.GIFTS_C...
from dataclasses import dataclass, field from datetime import datetime, timedelta from enum import Enum from typing import List, Optional from pytz import timezone from utils import texts class ExtendedEnum(Enum): @property def value(self): return super().value[0] @property def verbose_name...
184
256
1,603
6
178
vladtsap/your-financier
models/core.py
Python
Categories
Categories
35
143
35
35
42a541657fc949abb97513b1dfef29d0f42ffb41
bigcode/the-stack
train
0a54b0a21c5065edb326033e
train
class
@dataclass class Transaction: budget_id: str member_id: int date: datetime category: Categories outcome: Optional[float] = field(default=0.) income: Optional[float] = field(default=0.) note: Optional[str] = field(default=None) id: Optional[str] = field(default=None) @classmethod ...
@dataclass class Transaction:
budget_id: str member_id: int date: datetime category: Categories outcome: Optional[float] = field(default=0.) income: Optional[float] = field(default=0.) note: Optional[str] = field(default=None) id: Optional[str] = field(default=None) @classmethod def from_dict(cls, data: dict...
:</b> {self.left:,.2f}₴\n' if self.type != BudgetType.ONE_TIME: result += f'<b>{texts.MSG_BUDGET_LEFT_TODAY}:</b> {self.left_for_today:,.2f}₴\n' result += f'<b>{texts.MSG_BUDGET_ROLLOUT}:</b> {"✅" if self.rollover else "❎"}\n' \ f'<b>{texts.MSG_BUDGET_GROUP}:</b> {MongoGr...
137
137
459
6
130
vladtsap/your-financier
models/core.py
Python
Transaction
Transaction
286
344
286
287
44c24cb888546ce59084b12317660341f3b47af5
bigcode/the-stack
train
b84365e858ffad428da8d364
train
class
@dataclass class Group: name: str members: List[int] id: Optional[str] = field(default=None) @classmethod def from_dict(cls, data: dict): return cls( name=data['name'], members=data['members'], id=str(data.get('_id')), ) def to_dict(self) -> ...
@dataclass class Group:
name: str members: List[int] id: Optional[str] = field(default=None) @classmethod def from_dict(cls, data: dict): return cls( name=data['name'], members=data['members'], id=str(data.get('_id')), ) def to_dict(self) -> dict: result = {...
classmethod def from_dict(cls, data: dict): return cls( id=data['id'], name=data['name'], ) def to_dict(self) -> dict: return { 'id': self.id, 'name': self.name, } @dataclass class Group:
64
64
202
6
58
vladtsap/your-financier
models/core.py
Python
Group
Group
165
197
165
166
7632098468438ee9160e70a9d65bf8ce297a9230
bigcode/the-stack
train
8fa00372634cda839b0c4a2c
train
class
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: instance = super().__call__(*args, **kwargs) cls._instances[cls] = instance return cls._instances[cls]
class Singleton(type):
_instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: instance = super().__call__(*args, **kwargs) cls._instances[cls] = instance return cls._instances[cls]
f'💰 {budget.name}\n' \ f'👤 {MongoMember().get_by_id(self.member_id).name}\n' \ f'🏷 {self.category.verbose_name}\n' if self.note: result += self.note return result class Singleton(type):
64
64
61
4
59
vladtsap/your-financier
models/core.py
Python
Singleton
Singleton
347
354
347
347
ad5f8963c4750c0bfe0127f117581c1b87e45f66
bigcode/the-stack
train
bceddac7b1958d3737374b67
train
class
class ExtendedEnum(Enum): @property def value(self): return super().value[0] @property def verbose_name(self): return super().value[1] @classmethod def _missing_(cls, key): for item in cls: if item.value == key or item.verbose_name == key: re...
class ExtendedEnum(Enum): @property
def value(self): return super().value[0] @property def verbose_name(self): return super().value[1] @classmethod def _missing_(cls, key): for item in cls: if item.value == key or item.verbose_name == key: return item return super()._missin...
from dataclasses import dataclass, field from datetime import datetime, timedelta from enum import Enum from typing import List, Optional from pytz import timezone from utils import texts class ExtendedEnum(Enum): @property
48
64
85
9
38
vladtsap/your-financier
models/core.py
Python
ExtendedEnum
ExtendedEnum
11
25
11
12
db85c6675e212a6a9e43d69b182690d6fd201d97
bigcode/the-stack
train
ed33dc6e4475aaf85acc719a
train
class
@dataclass class Budget: name: str type: BudgetType amount: float left: float rollover: bool group_id: str id: Optional[str] = field(default=None) @classmethod def from_dict(cls, data: dict): return cls( name=data['name'], type=BudgetType(data['type']...
@dataclass class Budget:
name: str type: BudgetType amount: float left: float rollover: bool group_id: str id: Optional[str] = field(default=None) @classmethod def from_dict(cls, data: dict): return cls( name=data['name'], type=BudgetType(data['type']), amount=dat...
class Group: name: str members: List[int] id: Optional[str] = field(default=None) @classmethod def from_dict(cls, data: dict): return cls( name=data['name'], members=data['members'], id=str(data.get('_id')), ) def to_dict(self) -> dict: ...
206
206
688
6
199
vladtsap/your-financier
models/core.py
Python
Budget
Budget
200
283
200
201
baa32d0489bd1cde45710f3a72e3067c87cb3c00
bigcode/the-stack
train
b8c859d4322d53a4a8f94780
train
class
class NetworkProposalStatus: VOTING = 0 APPROVED = 1 DISAPPROVED = 2 CANCELED = 3 MIN = VOTING MAX = CANCELED
class NetworkProposalStatus:
VOTING = 0 APPROVED = 1 DISAPPROVED = 2 CANCELED = 3 MIN = VOTING MAX = CANCELED
iconservice import * class NetworkProposalType: TEXT = 0 REVISION = 1 MALICIOUS_SCORE = 2 PREP_DISQUALIFICATION = 3 STEP_PRICE = 4 MIN = TEXT MAX = STEP_PRICE class NetworkProposalStatus:
64
64
51
5
58
bayeshack2016/icon-service
tests/integrate_test/samples/sample_builtin_for_tests/1_1_0_change_the_value_of_invs_on_migrations/governance/network_proposal.py
Python
NetworkProposalStatus
NetworkProposalStatus
14
20
14
14
3a7176e3cee4c28cdfce8dc72cb83992fc52de3f
bigcode/the-stack
train
0be535f3626691538f146a89
train
class
class ProposalInfo: """ ProposalInfo Class including proposal information""" def __init__(self, id: bytes, proposer: 'Address', proposer_name: str, title: str, description: str, type: int, value: dict, start_block_height: int, end_block_height: int, status: int, vote: dict, to...
class ProposalInfo:
""" ProposalInfo Class including proposal information""" def __init__(self, id: bytes, proposer: 'Address', proposer_name: str, title: str, description: str, type: int, value: dict, start_block_height: int, end_block_height: int, status: int, vote: dict, total_voter: int = 0, ...
the voter to vote for the proposal :param timestamp: timestamp :param prep: 'Prep' having attributes of prep information like address, name, delegated and etc. :return: voter information in dict; one of the items in dict for voter list. A data type is either integer or string i...
141
141
470
4
136
bayeshack2016/icon-service
tests/integrate_test/samples/sample_builtin_for_tests/1_1_0_change_the_value_of_invs_on_migrations/governance/network_proposal.py
Python
ProposalInfo
ProposalInfo
427
471
427
427
854d0b8917b5a474a98ac4663295b66bc9fe1db2
bigcode/the-stack
train
ee14c119ed568e09f79a6536
train
class
class MaliciousScoreType: FREEZE = 0 UNFREEZE = 1 MIN = FREEZE MAX = UNFREEZE
class MaliciousScoreType:
FREEZE = 0 UNFREEZE = 1 MIN = FREEZE MAX = UNFREEZE
ProposalVote: DISAGREE = 0 AGREE = 1 MIN = DISAGREE MAX = AGREE class ApproveCondition: APPROVE_RATE = 0.66 DISAPPROVE_RATE = 0.33 class MaliciousScoreType:
64
64
34
6
57
bayeshack2016/icon-service
tests/integrate_test/samples/sample_builtin_for_tests/1_1_0_change_the_value_of_invs_on_migrations/governance/network_proposal.py
Python
MaliciousScoreType
MaliciousScoreType
35
39
35
35
9b7919472e80faf89c8c279d3430fcc3d162c457
bigcode/the-stack
train
310b64e84b661a30f5779d86
train
class
class NetworkProposal: """ Network Proposal which implements related method, controls DB and make result formatted """ _PROPOSAL_LIST = 'proposal_list' _PROPOSAL_LIST_KEYS = 'proposal_list_keys' def __init__(self, db: IconScoreDatabase) -> None: self._proposal_list = DictDB(self._PROPOSAL_LIST,...
class NetworkProposal:
""" Network Proposal which implements related method, controls DB and make result formatted """ _PROPOSAL_LIST = 'proposal_list' _PROPOSAL_LIST_KEYS = 'proposal_list_keys' def __init__(self, db: IconScoreDatabase) -> None: self._proposal_list = DictDB(self._PROPOSAL_LIST, db, value_type=bytes) ...
from iconservice import * class NetworkProposalType: TEXT = 0 REVISION = 1 MALICIOUS_SCORE = 2 PREP_DISQUALIFICATION = 3 STEP_PRICE = 4 MIN = TEXT MAX = STEP_PRICE class NetworkProposalStatus: VOTING = 0 APPROVED = 1 DISAPPROVED = 2 CANCELED = 3 MIN = VOTING MAX =...
209
256
3,613
4
204
bayeshack2016/icon-service
tests/integrate_test/samples/sample_builtin_for_tests/1_1_0_change_the_value_of_invs_on_migrations/governance/network_proposal.py
Python
NetworkProposal
NetworkProposal
42
424
42
42
625e4d5a177a99662f394943619185a1b433ca23
bigcode/the-stack
train
c090e5e3af3357b74af92ebe
train
class
class ApproveCondition: APPROVE_RATE = 0.66 DISAPPROVE_RATE = 0.33
class ApproveCondition:
APPROVE_RATE = 0.66 DISAPPROVE_RATE = 0.33
= 2 CANCELED = 3 MIN = VOTING MAX = CANCELED class NetworkProposalVote: DISAGREE = 0 AGREE = 1 MIN = DISAGREE MAX = AGREE class ApproveCondition:
64
64
27
5
58
bayeshack2016/icon-service
tests/integrate_test/samples/sample_builtin_for_tests/1_1_0_change_the_value_of_invs_on_migrations/governance/network_proposal.py
Python
ApproveCondition
ApproveCondition
30
32
30
30
ff2f6672fc558a928825e2bfeec68f2fbe495c13
bigcode/the-stack
train
6d43ace7d9d96087b862bcf7
train
class
class NetworkProposalVote: DISAGREE = 0 AGREE = 1 MIN = DISAGREE MAX = AGREE
class NetworkProposalVote:
DISAGREE = 0 AGREE = 1 MIN = DISAGREE MAX = AGREE
TEXT MAX = STEP_PRICE class NetworkProposalStatus: VOTING = 0 APPROVED = 1 DISAPPROVED = 2 CANCELED = 3 MIN = VOTING MAX = CANCELED class NetworkProposalVote:
64
64
33
5
58
bayeshack2016/icon-service
tests/integrate_test/samples/sample_builtin_for_tests/1_1_0_change_the_value_of_invs_on_migrations/governance/network_proposal.py
Python
NetworkProposalVote
NetworkProposalVote
23
27
23
23
90bc3b3e6eea1d0ba1f9391cd43a1157bbbf7155
bigcode/the-stack
train
6c926fc4a9863895000e7649
train
class
class NetworkProposalType: TEXT = 0 REVISION = 1 MALICIOUS_SCORE = 2 PREP_DISQUALIFICATION = 3 STEP_PRICE = 4 MIN = TEXT MAX = STEP_PRICE
class NetworkProposalType:
TEXT = 0 REVISION = 1 MALICIOUS_SCORE = 2 PREP_DISQUALIFICATION = 3 STEP_PRICE = 4 MIN = TEXT MAX = STEP_PRICE
from iconservice import * class NetworkProposalType:
10
64
55
5
5
bayeshack2016/icon-service
tests/integrate_test/samples/sample_builtin_for_tests/1_1_0_change_the_value_of_invs_on_migrations/governance/network_proposal.py
Python
NetworkProposalType
NetworkProposalType
4
11
4
4
4f457ac396fefe2ab340e44544515882cb6fbcb5
bigcode/the-stack
train
6b31653bcfefec359358438f
train
class
@pytest.mark.selenium class Test_Div: def test_displays_div_as_html(self, bokeh_model_page) -> None: div = Div(text=text, css_classes=["foo"]) page = bokeh_model_page(div) el = page.driver.find_element_by_css_selector('.foo div') assert el.get_attribute("innerHTML") == text ...
@pytest.mark.selenium class Test_Div:
def test_displays_div_as_html(self, bokeh_model_page) -> None: div = Div(text=text, css_classes=["foo"]) page = bokeh_model_page(div) el = page.driver.find_element_by_css_selector('.foo div') assert el.get_attribute("innerHTML") == text assert page.has_no_console_errors() ...
</a>-supported text is initialized with the <b>text</b> argument. The remaining div arguments are <b>width</b> and <b>height</b>. For this example, those values are <i>200</i> and <i>100</i> respectively.""" @pytest.mark.selenium class Test_Div:
74
75
250
9
65
samwill/bokeh
tests/integration/widgets/test_div.py
Python
Test_Div
Test_Div
38
68
38
39
e7e41f179ed597a0969532cdc39199c55124be26
bigcode/the-stack
train
fb6153e2dfa03c841db6d23d
train
function
def count_measures(midi, max_time): bpm_st, bpm_value = midi.get_tempo_changes() bpm_st = np.append(bpm_st, max_time) n_measures = 0 for i in range(len(bpm_value)): bar_st = bpm_st[i] bpm = bpm_value[i] TIME_PER_BAR = 60/bpm TIME_PER_MEASURE = TIME_PER_BAR*4 # 4/4 measures while bar_st < bpm_st[i...
def count_measures(midi, max_time):
bpm_st, bpm_value = midi.get_tempo_changes() bpm_st = np.append(bpm_st, max_time) n_measures = 0 for i in range(len(bpm_value)): bar_st = bpm_st[i] bpm = bpm_value[i] TIME_PER_BAR = 60/bpm TIME_PER_MEASURE = TIME_PER_BAR*4 # 4/4 measures while bar_st < bpm_st[i+1]: #mientras no hayas construido com...
_length = 16).get_tensor() transform = Compose( [ TensorRepresentation(filter_instruments=None), MixMultiInstrument() ] ) data = transform(data) n_measures = len(data[0]) return n_measures def count_measures(midi, max_time):
64
64
164
11
52
maranedah/music_inpainting_benchmark
src/data/make_frames.py
Python
count_measures
count_measures
47
64
47
48
5c5228dabf5ac7ea92aa104f33fe3714b1d9227c
bigcode/the-stack
train
4e43a3469300dce9ec615285
train
function
def get_hash(file_path): md5_hash = hashlib.md5() a_file = open(file_path, "rb") content = a_file.read() md5_hash.update(content) digest = md5_hash.hexdigest() return digest
def get_hash(file_path):
md5_hash = hashlib.md5() a_file = open(file_path, "rb") content = a_file.read() md5_hash.update(content) digest = md5_hash.hexdigest() return digest
check[i] = False if n_poly > max_poly: max_poly = n_poly poly.append(n_poly>1) max_polys.append(max_poly) polys.append(sum(poly)/len(poly)) return check, max_polys, polys def get_hash(file_path):
64
64
48
6
57
maranedah/music_inpainting_benchmark
src/data/make_frames.py
Python
get_hash
get_hash
88
94
88
88
67d83e15d9cf78c5c054e65f50941d84240e98f9
bigcode/the-stack
train
2ac1679645be8b2d631c3938
train
function
def count_n_measures(path, filename): data = EncodedMidi.from_path( file = path, process = "remi", dataset_name = None, fraction = 16, min_length = 16).get_tensor() transform = Compose( [ TensorRepresentation(filter_instruments=None), ...
def count_n_measures(path, filename):
data = EncodedMidi.from_path( file = path, process = "remi", dataset_name = None, fraction = 16, min_length = 16).get_tensor() transform = Compose( [ TensorRepresentation(filter_instruments=None), MixMultiInstrument...
RAMES_DIR): os.mkdir(FRAMES_DIR) from src.features.encoded_midi import EncodedMidi from src.features.transforms.MixMultiInstrument import MixMultiInstrument from src.features.transforms.Compose import Compose from src.features.transforms.TensorRepresentation import TensorRepresentation def count_n_measures(path, file...
64
64
96
9
54
maranedah/music_inpainting_benchmark
src/data/make_frames.py
Python
count_n_measures
count_n_measures
28
45
28
28
4e32a04729edf119c9fc2b3e84d399b8e75da59a
bigcode/the-stack
train
fa8734d0dafd944197bc7da0
train
function
def poly_vals(instruments): check = [] max_polys = [] polys = [] for i, inst in enumerate(instruments): check.append(True) max_poly = 0 poly = [] for key, group in groupby(inst.notes, lambda x: x.start): note_group = [x for x in group] n_poly = len(note_group) if n_poly > 1: check[i] = False...
def poly_vals(instruments):
check = [] max_polys = [] polys = [] for i, inst in enumerate(instruments): check.append(True) max_poly = 0 poly = [] for key, group in groupby(inst.notes, lambda x: x.start): note_group = [x for x in group] n_poly = len(note_group) if n_poly > 1: check[i] = False if n_poly > max_poly: ...
bpm_st[i+1]: #mientras no hayas construido compases que lleguen al cambio de tempo o al max_time bar_et = bar_st + TIME_PER_MEASURE n_measures+=1 bar_st = bar_et return n_measures def poly_vals(instruments):
64
64
150
6
57
maranedah/music_inpainting_benchmark
src/data/make_frames.py
Python
poly_vals
poly_vals
66
86
66
66
a05c29ad0f7cb37ee89d8f31711bac804bd3884f
bigcode/the-stack
train
ca22cc90ae9a6a6a3394e718
train
function
def make_frames(): folders = [x for x in os.listdir(RAW_DIR) if os.path.isdir(join(RAW_DIR, x))] for folder in folders: raw_folder = join(RAW_DIR, folder) column_names = ["filename", "n_instruments", "instrument_names", "n_notes", "is_monophony", "max_poly", "polys_percent", "tempo_changes", "tsc_length", "fir...
def make_frames():
folders = [x for x in os.listdir(RAW_DIR) if os.path.isdir(join(RAW_DIR, x))] for folder in folders: raw_folder = join(RAW_DIR, folder) column_names = ["filename", "n_instruments", "instrument_names", "n_notes", "is_monophony", "max_poly", "polys_percent", "tempo_changes", "tsc_length", "first_tsc", "tsc", "du...
que lleguen al cambio de tempo o al max_time bar_et = bar_st + TIME_PER_MEASURE n_measures+=1 bar_st = bar_et return n_measures def poly_vals(instruments): check = [] max_polys = [] polys = [] for i, inst in enumerate(instruments): check.append(True) max_poly = 0 poly = [] for key, group in ...
246
246
823
4
241
maranedah/music_inpainting_benchmark
src/data/make_frames.py
Python
make_frames
make_frames
96
166
96
96
3e5d9bcfcab3becd9a9ed1c2777ea519deebbc98
bigcode/the-stack
train
638e60688aff37710b0d17c8
train
class
class Marker(): """ Defines portions of the graph for events """ def __init__(self, sEventType, iEventId, sName, sStartMbt, sEndMbt, iStartMeasure, ppqn): self.sEventType = sEventType self.iEventId = iEventId self.sName = sName self.StartMbt = ConvertStrTimeToTuple(sStartMbt) ...
class Marker():
""" Defines portions of the graph for events """ def __init__(self, sEventType, iEventId, sName, sStartMbt, sEndMbt, iStartMeasure, ppqn): self.sEventType = sEventType self.iEventId = iEventId self.sName = sName self.StartMbt = ConvertStrTimeToTuple(sStartMbt) self.EndMbt...
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import wx import logging from JetUtils import * from JetDefs import * GRAPH_COLORS = [ '#C0E272', '#85CF89', ...
140
141
471
3
137
folkengine/JetCreator
JetSegGraph.py
Python
Marker
Marker
48
87
48
48
edc5ad348c6dafd25de3958f7697cc281be73db6
bigcode/the-stack
train
c08f925f863fd48d0cf92396
train
class
class SegmentGraph(wx.Panel): """ Draws the player graph bar """ def __init__(self, parent, pos=wx.DefaultPosition, size=wx.DefaultSize, ClickCallbackFct=None, showLabels=True, showClips=True, showAppEvts=True): wx.Panel.__init__(self, parent, -1, pos=pos, size=size, style=wx.BORDER_STATIC) self...
class SegmentGraph(wx.Panel):
""" Draws the player graph bar """ def __init__(self, parent, pos=wx.DefaultPosition, size=wx.DefaultSize, ClickCallbackFct=None, showLabels=True, showClips=True, showAppEvts=True): wx.Panel.__init__(self, parent, -1, pos=pos, size=size, style=wx.BORDER_STATIC) self.iLocationInMs = 0 sel...
measures iStartM = self.StartMbt[0] - self.iStartMeasure iEndM = self.EndMbt[0] - self.iStartMeasure self.iStart = step * iStartM self.iEnd = step * iEndM #beats self.iStart = self.iStart + ((step / 4.0) * (self.StartMbt[1]-1)) self.iEnd = self.iEnd + ((step / 4.0...
256
256
3,017
6
249
folkengine/JetCreator
JetSegGraph.py
Python
SegmentGraph
SegmentGraph
89
361
89
89
a2ff4c67b1a49904c78f669007ef5b7f21df8caf
bigcode/the-stack
train
1a996f8b1428df760908912d
train
function
def calc(): return 0.2 * bac.getNota() + 0.8 * (mate.getNota() + info.getNota())
def calc():
return 0.2 * bac.getNota() + 0.8 * (mate.getNota() + info.getNota())
def setNota(self): self.nota = float(input("Nota " + self.nume + ": ")) def getNota(self): if self.nume == "Bacalaureat": return self.nota return 0.5 * self.nota def calc():
64
64
30
3
60
flawreen/admission-average
main.py
Python
calc
calc
15
16
15
15
c42952ba090a1c1244eb237c018ea293ccc40649
bigcode/the-stack
train
6a3549148cd44933d5d80604
train
class
class Materie: def __init__(self, nume): self.nota = None self.nume = nume def setNota(self): self.nota = float(input("Nota " + self.nume + ": ")) def getNota(self): if self.nume == "Bacalaureat": return self.nota return 0.5 * self.nota
class Materie:
def __init__(self, nume): self.nota = None self.nume = nume def setNota(self): self.nota = float(input("Nota " + self.nume + ": ")) def getNota(self): if self.nume == "Bacalaureat": return self.nota return 0.5 * self.nota
class Materie:
4
64
89
4
0
flawreen/admission-average
main.py
Python
Materie
Materie
1
12
1
1
e7af34296345578bb7e4644fd5f3ef0edcba80ec
bigcode/the-stack
train
0c590131fdfbe55c1a7dd513
train
class
class TestPPO(unittest.TestCase): @classmethod def setUpClass(cls): ray.init() @classmethod def tearDownClass(cls): ray.shutdown() def test_ppo_compilation_and_schedule_mixins(self): """Test whether a PPOTrainer can be built with all frameworks.""" # Build a PPOCon...
class TestPPO(unittest.TestCase): @classmethod
def setUpClass(cls): ray.init() @classmethod def tearDownClass(cls): ray.shutdown() def test_ppo_compilation_and_schedule_mixins(self): """Test whether a PPOTrainer can be built with all frameworks.""" # Build a PPOConfig object. config = ( ppo.PPOC...
!" @staticmethod def _check_lr_tf(policy, policy_id): lr = policy.cur_lr sess = policy.get_session() if sess: lr = sess.run(lr) optim_lr = sess.run(policy._optimizer._lr) else: lr = lr.numpy() optim_lr = policy._optimizer.lr.numpy(...
256
256
3,018
12
244
mgelbart/ray
rllib/agents/ppo/tests/test_ppo.py
Python
TestPPO
TestPPO
84
464
84
85
901d5e1db023befb4bdfecb2fca6e3df888f95ff
bigcode/the-stack
train
67f08a7b3b858f43decf337b
train
class
class MyCallbacks(DefaultCallbacks): @staticmethod def _check_lr_torch(policy, policy_id): for j, opt in enumerate(policy._optimizers): for p in opt.param_groups: assert p["lr"] == policy.cur_lr, "LR scheduling error!" @staticmethod def _check_lr_tf(policy, policy_id...
class MyCallbacks(DefaultCallbacks): @staticmethod
def _check_lr_torch(policy, policy_id): for j, opt in enumerate(policy._optimizers): for p in opt.param_groups: assert p["lr"] == policy.cur_lr, "LR scheduling error!" @staticmethod def _check_lr_tf(policy, policy_id): lr = policy.cur_lr sess = policy.get...
2.5]], dtype=np.float32 ), SampleBatch.ACTION_LOGP: np.array([-0.5, -0.1, -0.2], dtype=np.float32), SampleBatch.EPS_ID: np.array([0, 0, 0]), SampleBatch.AGENT_INDEX: np.array([0, 0, 0]), } ) class MyCallbacks(DefaultCallbacks): @staticmethod
90
90
301
10
80
mgelbart/ray
rllib/agents/ppo/tests/test_ppo.py
Python
MyCallbacks
MyCallbacks
51
81
51
52
a93c32217f99dce34f7a6a0c46878cca80883186
bigcode/the-stack
train
09964d035bc02214074d58be
train
class
class BaseModel(models.Model): created = models.DateTimeField( _("created"), auto_now_add=True, editable=False, db_index=True ) modified = models.DateTimeField(auto_now=True, editable=False) deleted = models.DateTimeField(editable=False, null=True) # ability to hide stuff publicly conce...
class BaseModel(models.Model):
created = models.DateTimeField( _("created"), auto_now_add=True, editable=False, db_index=True ) modified = models.DateTimeField(auto_now=True, editable=False) deleted = models.DateTimeField(editable=False, null=True) # ability to hide stuff publicly concealed = models.BooleanField(defa...
*args, **kwargs): if "pk" in kwargs or "id" in kwargs: return self.get_full_queryset().filter(*args, **kwargs) return self.get_queryset().filter(*args, **kwargs) def deleted(self): return self.get_full_queryset().filter(deleted__isnull=False) def visible(self): ret...
97
97
326
6
91
kakulukia/django-undeletable
django_undeletable/models.py
Python
BaseModel
BaseModel
86
125
86
86
754cce8041fb41a0716abfa56d922ac787a74a17
bigcode/the-stack
train
78d8fd37db72d563f668ace7
train
class
class AbstractUser(AbstractBaseUser, PermissionsMixin, BaseModel): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. Username, email and password are required. Other fields are optional. """ username_validator = UnicodeUsernameValidator() ...
class AbstractUser(AbstractBaseUser, PermissionsMixin, BaseModel):
""" An abstract base class implementing a fully featured User model with admin-compliant permissions. Username, email and password are required. Other fields are optional. """ username_validator = UnicodeUsernameValidator() username = models.CharField( _("username"), max_...
lete(self): # the model cannot just be saved since its not visible to Django # and thus it will come to the conclusion that new data has to be inserted self._meta.model.data.deleted().filter(id=self.id).update(deleted=None) def pprint(self): pprint(self.__dict__) class NamedModel(...
170
170
569
13
156
kakulukia/django-undeletable
django_undeletable/models.py
Python
AbstractUser
AbstractUser
146
225
146
146
447131d3cdcf92a56a1bee9260babba686ffb4c1
bigcode/the-stack
train
04d29341fd269b6abc3c897f
train
class
class UserDataManager(UserManager, DataManager): pass
class UserDataManager(UserManager, DataManager):
pass
class NamedModel(BaseModel): name = models.CharField(_("Name"), max_length=150, db_index=True) class Meta(BaseModel.Meta): ordering = ["name"] abstract = True def __str__(self): return self.name class UserDataManager(UserManager, DataManager):
64
64
13
10
53
kakulukia/django-undeletable
django_undeletable/models.py
Python
UserDataManager
UserDataManager
139
140
139
139
6c5da28fb53af77b716d744b4b858324a0cfe14e
bigcode/the-stack
train
e3440a7f6511369cff8c9634
train
class
class NamedModel(BaseModel): name = models.CharField(_("Name"), max_length=150, db_index=True) class Meta(BaseModel.Meta): ordering = ["name"] abstract = True def __str__(self): return self.name
class NamedModel(BaseModel):
name = models.CharField(_("Name"), max_length=150, db_index=True) class Meta(BaseModel.Meta): ordering = ["name"] abstract = True def __str__(self): return self.name
cannot just be saved since its not visible to Django # and thus it will come to the conclusion that new data has to be inserted self._meta.model.data.deleted().filter(id=self.id).update(deleted=None) def pprint(self): pprint(self.__dict__) class NamedModel(BaseModel):
64
64
54
6
58
kakulukia/django-undeletable
django_undeletable/models.py
Python
NamedModel
NamedModel
128
136
128
128
1cc74860341c0b3625c18ad333268856e50eb68f
bigcode/the-stack
train
486d1dccc199e8e810fca8a3
train
class
class DataQuerySet(QuerySet): def delete(self, force=False): if force: return super(DataQuerySet, self).delete() else: # otherwise this list will be different in the next loop :) to_be_notified = list(self) for obj in to_be_notified: pr...
class DataQuerySet(QuerySet):
def delete(self, force=False): if force: return super(DataQuerySet, self).delete() else: # otherwise this list will be different in the next loop :) to_be_notified = list(self) for obj in to_be_notified: pre_delete.send(sender=self.mode...
import models from django.db.models.query import QuerySet from django.db.models.signals import pre_delete, post_delete from django.utils import timezone from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ # basic model managers ########################################## class...
64
64
194
7
57
kakulukia/django-undeletable
django_undeletable/models.py
Python
DataQuerySet
DataQuerySet
20
48
20
20
a4afb1b299a50277b508ea433c3e8a8af77f6b25
bigcode/the-stack
train
dea692290c1d35b7253ecffa
train
class
class DataManager(models.Manager): # use_for_related_fields = True def get_queryset(self): qs = self.get_full_queryset() return qs.filter(deleted__isnull=True) def get_full_queryset(self): qs = super().get_queryset() if not isinstance(qs, DataQuerySet): qs = Dat...
class DataManager(models.Manager): # use_for_related_fields = True
def get_queryset(self): qs = self.get_full_queryset() return qs.filter(deleted__isnull=True) def get_full_queryset(self): qs = super().get_queryset() if not isinstance(qs, DataQuerySet): qs = DataQuerySet(self.model, using=self._db) return qs def get(sel...
=None) def conceal(self): """ Some times you just want to be able to hide stuff from the public eye. Use the visible manager method for your views instead to filter the data. """ self.update(concealed=True) def reveal(self): self.update(concealed=False) class Da...
79
79
265
15
64
kakulukia/django-undeletable
django_undeletable/models.py
Python
DataManager
DataManager
51
81
51
53
bd3ad726d7cf87d5f4fd29001f7eaef696411dd9
bigcode/the-stack
train
bd784ffa66ae9a9b2805f37f
train
function
@register_algo_factory_func("iris") def algo_config_to_class(algo_config): """ Maps algo config to the IRIS algo class to instantiate, along with additional algo kwargs. Args: algo_config (Config instance): algo config Returns: algo_class: subclass of Algo algo_kwargs (dict): d...
@register_algo_factory_func("iris") def algo_config_to_class(algo_config):
""" Maps algo config to the IRIS algo class to instantiate, along with additional algo kwargs. Args: algo_config (Config instance): algo config Returns: algo_class: subclass of Algo algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm """ pol_cls, _ ...
_utils as ObsUtils from robomimic.config.config import Config from robomimic.algo import register_algo_factory_func, algo_name_to_factory_func, HBC, ValuePlanner, ValueAlgo, GL_VAE @register_algo_factory_func("iris") def algo_config_to_class(algo_config):
64
64
167
17
46
akolobov/robomimic
robomimic/algo/iris.py
Python
algo_config_to_class
algo_config_to_class
16
31
16
17
39bd211e237aa6e9465a601801529febc2bca240
bigcode/the-stack
train
e54815d01c0a7aa3b95062e5
train
class
class IRIS(HBC, ValueAlgo): """ Implementation of IRIS (https://arxiv.org/abs/1911.05321). """ def __init__( self, planner_algo_class, value_algo_class, policy_algo_class, algo_config, obs_config, global_config, obs_key_shapes, ac_d...
class IRIS(HBC, ValueAlgo):
""" Implementation of IRIS (https://arxiv.org/abs/1911.05321). """ def __init__( self, planner_algo_class, value_algo_class, policy_algo_class, algo_config, obs_config, global_config, obs_key_shapes, ac_dim, device, ): ...
from collections import OrderedDict from copy import deepcopy import torch import robomimic.utils.tensor_utils as TensorUtils import robomimic.utils.obs_utils as ObsUtils from robomimic.config.config import Config from robomimic.algo import register_algo_factory_func, algo_name_to_factory_func, HBC, ValuePlanner, Val...
256
256
1,168
9
247
akolobov/robomimic
robomimic/algo/iris.py
Python
IRIS
IRIS
34
181
34
34
9bfeec56e745ab9f1baaa36924f04c01815269cc
bigcode/the-stack
train
ca4fbd9fc54d2547329feb6c
train
class
@dataclass class MinimumValue: """The gml:minimumValue and gml:maximumValue properties allow the specification of minimum and maximum value normally allowed for this axis, in the unit of measure for the axis. For a continuous angular axis such as longitude, the values wrap- around at this value. Al...
@dataclass class MinimumValue:
"""The gml:minimumValue and gml:maximumValue properties allow the specification of minimum and maximum value normally allowed for this axis, in the unit of measure for the axis. For a continuous angular axis such as longitude, the values wrap- around at this value. Also, values beyond this minimum/...
from dataclasses import dataclass, field from typing import Optional __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class MinimumValue:
36
64
194
7
29
NIVANorge/s-enda-playground
catalog/bindings/gmd/minimum_value.py
Python
MinimumValue
MinimumValue
7
30
7
8
d8502f0e6cde239fd4937a82c88e03c2fc262098
bigcode/the-stack
train
406cc528c419ef0c65963894
train
class
class KeeperLookupTest(unittest.TestCase): def setUp(self): # Add in addition Python libs. This includes the base # module for Keeper Ansible and the Keeper SDK. self.base_dir = os.path.dirname(os.path.realpath(__file__)) self.ansible_base_dir = os.path.join(self.base_dir, "ansible...
class KeeperLookupTest(unittest.TestCase):
def setUp(self): # Add in addition Python libs. This includes the base # module for Keeper Ansible and the Keeper SDK. self.base_dir = os.path.dirname(os.path.realpath(__file__)) self.ansible_base_dir = os.path.join(self.base_dir, "ansible_example") def _common(self): w...
", files=[ {"name": "nailing it.mp4", "type": "video/mp4", "url": "http://localhost/abc", "data": "ABC123"}, {"name": "video_file.mp4", "type": "video/mp4", "url": "http://localhost/xzy", "data": "XYZ123"}, ] ) } def get_secrets(*args): if len(args) > 0: uid = ...
140
140
467
8
131
Keeper-Security/secrets-manager
integration/keeper_secrets_manager_ansible/tests/keeper_lookup_test.py
Python
KeeperLookupTest
KeeperLookupTest
43
86
43
44
1f2305dc0548fd0e6e4da1135887616d2cfb564a
bigcode/the-stack
train
7c6a4c1f342b87d2bce5ebc5
train
function
def get_secrets(*args): if len(args) > 0: uid = args[0][0] ret = [records[uid]] else: ret = [records[x] for x in records] return ret
def get_secrets(*args):
if len(args) > 0: uid = args[0][0] ret = [records[uid]] else: ret = [records[x] for x in records] return ret
"url": "http://localhost/abc", "data": "ABC123"}, {"name": "video_file.mp4", "type": "video/mp4", "url": "http://localhost/xzy", "data": "XYZ123"}, ] ) } def get_secrets(*args):
64
64
52
7
57
Keeper-Security/secrets-manager
integration/keeper_secrets_manager_ansible/tests/keeper_lookup_test.py
Python
get_secrets
get_secrets
33
40
33
34
05e11301202c3737dc6f93b51fcb1cbb7f1862fc
bigcode/the-stack
train
1015000bc6e3b93288ac104b
train
function
def test_2(): inputs = keras.Input(shape=(28, 28, 1)) x = keras.layers.ZeroPadding2D(2)( inputs ) # padding to increase dimenstions to 32x32 x = keras.layers.Conv2D(3, (1, 1), padding="same")( x ) # increasing the number of channels to 3 x = convnets.VGG16(use_dense=False)(x) ...
def test_2():
inputs = keras.Input(shape=(28, 28, 1)) x = keras.layers.ZeroPadding2D(2)( inputs ) # padding to increase dimenstions to 32x32 x = keras.layers.Conv2D(3, (1, 1), padding="same")( x ) # increasing the number of channels to 3 x = convnets.VGG16(use_dense=False)(x) x = keras.l...
")( x ) # increasing the number of channels to 3 x = convnets.VGG16()(x) outputs = keras.layers.Dense(10, activation="softmax")(x) model = keras.models.Model(inputs=inputs, outputs=outputs) def test_2():
64
64
147
5
59
p4vv37/pyradox
tests/test_vgg_16.py
Python
test_2
test_2
24
36
24
24
16a2e313a2505f343fce952de308a535c8d00c67
bigcode/the-stack
train
b64487a10d20d70b38f28a4e
train
function
def test_1(): inputs = keras.Input(shape=(28, 28, 1)) x = keras.layers.ZeroPadding2D(2)( inputs ) # padding to increase dimenstions to 32x32 x = keras.layers.Conv2D(3, (1, 1), padding="same")( x ) # increasing the number of channels to 3 x = convnets.VGG16()(x) outputs = ke...
def test_1():
inputs = keras.Input(shape=(28, 28, 1)) x = keras.layers.ZeroPadding2D(2)( inputs ) # padding to increase dimenstions to 32x32 x = keras.layers.Conv2D(3, (1, 1), padding="same")( x ) # increasing the number of channels to 3 x = convnets.VGG16()(x) outputs = keras.layers.Den...
import sys, os sys.path.append(os.path.dirname(os.getcwd())) from tensorflow import keras import numpy as np from pyradox import convnets def test_1():
36
64
131
5
30
p4vv37/pyradox
tests/test_vgg_16.py
Python
test_1
test_1
10
21
10
10
21ab77e09f0de1f153a59044f70e4023b0e95dab
bigcode/the-stack
train
d80f8913febbb45925da80b7
train
class
class MultinomialOp(Op): ''' Samples from an unnormalized multinomial distribution. First input is matrix of dimension [batch_size, num_classes], and sampling occurs along num_classes dimension. Second input is the number of samples to draw for each batch element. ''' def __init__(se...
class MultinomialOp(Op):
''' Samples from an unnormalized multinomial distribution. First input is matrix of dimension [batch_size, num_classes], and sampling occurs along num_classes dimension. Second input is the number of samples to draw for each batch element. ''' def __init__(self, name): super(...
from .base_op import Op from catamount.api import utils class MultinomialOp(Op):
21
155
517
7
13
jthestness/catamount
catamount/ops/random_ops.py
Python
MultinomialOp
MultinomialOp
5
56
5
5
f1310fa93e779fa16ad52fb0fefc6af0970afdb7
bigcode/the-stack
train
1c23ee8794b83abc5418a146
train
class
class CandidateSamplerOp(Op): def __init__(self, name): super(CandidateSamplerOp, self).__init__(name) # TODO (Joel): Read these from compute graph op attributes self.setNumTrue(1) self.setNumSampled(None) # TODO: Depending on the generator, there should be some small number ...
class CandidateSamplerOp(Op):
def __init__(self, name): super(CandidateSamplerOp, self).__init__(name) # TODO (Joel): Read these from compute graph op attributes self.setNumTrue(1) self.setNumSampled(None) # TODO: Depending on the generator, there should be some small number # of Flops per sampled...
self._num_samples_symbol in_0_shape = self._inputs[0].shape full_shape_elts = in_0_shape.numElements() * num_samples total_flops = full_shape_elts # 2) Calculate scores = logits - log(-log(noises)) with broadcasting total_flops += 3 * full_shape_elts # 3) Minimum reducti...
147
147
491
6
141
jthestness/catamount
catamount/ops/random_ops.py
Python
CandidateSamplerOp
CandidateSamplerOp
59
109
59
59
7ff4b792e022e8d80c1917c20db9962e9bc95931
bigcode/the-stack
train
4caddc097d290a16e399588b
train
function
def test_resource_import(): from terrascript.resource.Ouest_France.harbor import harbor_project
def test_resource_import():
from terrascript.resource.Ouest_France.harbor import harbor_project
# tests/test_provider_Ouest-France_harbor.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:17:58 UTC) def test_provider_import(): import terrascript.provider.Ouest_France.harbor def test_resource_import():
58
64
20
5
52
mjuenema/python-terrascript
tests/test_provider_Ouest_France_harbor.py
Python
test_resource_import
test_resource_import
9
10
9
9
9da52700e7c08f23577b0239438653cb2af9307b
bigcode/the-stack
train
1f6e729a6ac61fc1ff12729e
train
function
def test_provider_import(): import terrascript.provider.Ouest_France.harbor
def test_provider_import():
import terrascript.provider.Ouest_France.harbor
# tests/test_provider_Ouest-France_harbor.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:17:58 UTC) def test_provider_import():
41
64
17
5
36
mjuenema/python-terrascript
tests/test_provider_Ouest_France_harbor.py
Python
test_provider_import
test_provider_import
5
6
5
5
f8afb69d5eefe97808d8749716efb233764008aa
bigcode/the-stack
train
df8fb14fc0d37970c7097d68
train
function
@asyncio.coroutine def echo_multiple_args(request): args = { 'first': fields.Str(), 'last': fields.Str(), } parsed = yield from parser.parse(args, request) return json_response(parsed)
@asyncio.coroutine def echo_multiple_args(request):
args = { 'first': fields.Str(), 'last': fields.Str(), } parsed = yield from parser.parse(args, request) return json_response(parsed)
.coroutine def echo_nested(request): args = { 'name': fields.Nested({'first': fields.Str(), 'last': fields.Str()}) } parsed = yield from parser.parse(args, request) return json_response(parsed) @asyncio.coroutine def echo_multiple_args(request):
64
64
49
12
52
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_multiple_args
echo_multiple_args
115
122
115
116
64adb19412c1f7ccf2dbe0108b184a399feb9030
bigcode/the-stack
train
7100cff3f0ffe3c83a0022ae
train
function
@asyncio.coroutine def echo_multi(request): parsed = yield from parser.parse(hello_multiple, request) return json_response(parsed)
@asyncio.coroutine def echo_multi(request):
parsed = yield from parser.parse(hello_multiple, request) return json_response(parsed)
): return json_response({'name': name}) @asyncio.coroutine @use_args({'value': fields.Int()}, validate=lambda args: args['value'] > 42) def echo_use_args_validated(request, args): return json_response(args) @asyncio.coroutine def echo_multi(request):
64
64
30
11
53
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_multi
echo_multi
52
55
52
53
fa62df720877df6934d0ae2802079468cd83696f
bigcode/the-stack
train
87230c0afa3060119cee4627
train
function
@asyncio.coroutine def echo_many_schema(request): parsed = yield from parser.parse(hello_many_schema, request, locations=('json', )) return json_response(parsed)
@asyncio.coroutine def echo_many_schema(request):
parsed = yield from parser.parse(hello_many_schema, request, locations=('json', )) return json_response(parsed)
value'] > 42) def echo_use_args_validated(request, args): return json_response(args) @asyncio.coroutine def echo_multi(request): parsed = yield from parser.parse(hello_multiple, request) return json_response(parsed) @asyncio.coroutine def echo_many_schema(request):
64
64
37
12
52
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_many_schema
echo_many_schema
57
60
57
58
496c506408535f7cf1be9d204a479a35dcd44d4d
bigcode/the-stack
train
e7486eab6e30cd6ecc3c9107
train
class
class EchoHandler: @asyncio.coroutine @use_args(hello_args) def get(self, request, args): return json_response(args)
class EchoHandler: @asyncio.coroutine @use_args(hello_args)
def get(self, request, args): return json_response(args)
return json_response(parsed) @asyncio.coroutine def echo_match_info(request): parsed = yield from parser.parse({'mymatch': fields.Int(location='match_info')}, request) return json_response(parsed) class EchoHandler: @asyncio.coroutine @use_args(hello_args)
64
64
34
19
45
Reskov/webargs
tests/apps/aiohttp_app.py
Python
EchoHandler
EchoHandler
148
153
148
151
54eb87a4bfce216d144bd4ea8800b5ea4178e22f
bigcode/the-stack
train
70eb8f6523c399b2137ae3dc
train
function
@asyncio.coroutine def echo_nested(request): args = { 'name': fields.Nested({'first': fields.Str(), 'last': fields.Str()}) } parsed = yield from parser.parse(args, request) return json_response(parsed)
@asyncio.coroutine def echo_nested(request):
args = { 'name': fields.Nested({'first': fields.Str(), 'last': fields.Str()}) } parsed = yield from parser.parse(args, request) return json_response(parsed)
.parse(hello_args, request, locations=('headers', )) return json_response(parsed) @asyncio.coroutine def echo_cookie(request): parsed = yield from parser.parse(hello_args, request, locations=('cookies', )) return json_response(parsed) @asyncio.coroutine def echo_nested(request):
64
64
55
11
53
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_nested
echo_nested
106
113
106
107
574592edb9ad5777666c219d37182bc01cc1e420
bigcode/the-stack
train
ad26b58d690b19b7c83179ba
train
function
@asyncio.coroutine def echo_cookie(request): parsed = yield from parser.parse(hello_args, request, locations=('cookies', )) return json_response(parsed)
@asyncio.coroutine def echo_cookie(request):
parsed = yield from parser.parse(hello_args, request, locations=('cookies', )) return json_response(parsed)
)} parsed = yield from parser.parse(args, request) return json_response(parsed) @asyncio.coroutine def echo_headers(request): parsed = yield from parser.parse(hello_args, request, locations=('headers', )) return json_response(parsed) @asyncio.coroutine def echo_cookie(request):
64
64
35
11
53
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_cookie
echo_cookie
101
104
101
102
07515373ef2b65782336cd5555a33fcb003d7900
bigcode/the-stack
train
f7e070f8f5aab8930d074272
train
function
def add_route(app, methods, route, handler): for method in methods: app.router.add_route(method, route, handler)
def add_route(app, methods, route, handler):
for method in methods: app.router.add_route(method, route, handler)
def get(self, args): return json_response(args) @asyncio.coroutine @use_args(HelloSchema, as_kwargs=True) def echo_use_schema_as_kwargs(request, name): return json_response({'name': name}) ##### App factory ##### def add_route(app, methods, route, handler):
64
64
28
11
52
Reskov/webargs
tests/apps/aiohttp_app.py
Python
add_route
add_route
169
171
169
169
50cf3c4add1689f53ce8d5a9a981e1b813977e18
bigcode/the-stack
train
f69b4506f947e2384151dce6
train
function
@asyncio.coroutine def error_invalid(request): def always_fail(value): raise ValidationError('something went wrong', status_code=12345) args = {'text': fields.Str(validate=always_fail)} parsed = yield from parser.parse(args, request) return json_response(parsed)
@asyncio.coroutine def error_invalid(request):
def always_fail(value): raise ValidationError('something went wrong', status_code=12345) args = {'text': fields.Str(validate=always_fail)} parsed = yield from parser.parse(args, request) return json_response(parsed)
400(request): def always_fail(value): raise ValidationError('something went wrong', status_code=400) args = {'text': fields.Str(validate=always_fail)} parsed = yield from parser.parse(args, request) return json_response(parsed) @asyncio.coroutine def error_invalid(request):
64
64
62
11
53
Reskov/webargs
tests/apps/aiohttp_app.py
Python
error_invalid
error_invalid
88
94
88
89
74fc996b902a51649888a200d042a92a182582fb
bigcode/the-stack
train
5814cb0878b2d35311d76509
train
function
@asyncio.coroutine @use_args(hello_args) def echo_use_args(request, args): return json_response(args)
@asyncio.coroutine @use_args(hello_args) def echo_use_args(request, args):
return json_response(args)
request) return json_response(parsed) @asyncio.coroutine def echo_query(request): parsed = yield from parser.parse(hello_args, request, locations=('query', )) return json_response(parsed) @asyncio.coroutine @use_args(hello_args) def echo_use_args(request, args):
64
64
27
21
43
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_use_args
echo_use_args
37
40
37
39
1c89da38df81dbee8edbb772598679b46c759cda
bigcode/the-stack
train
c7e99015c839921fb5c92108
train
function
@asyncio.coroutine def echo_nested_many(request): args = { 'users': fields.Nested({'id': fields.Int(), 'name': fields.Str()}, many=True) } parsed = yield from parser.parse(args, request) return json_response(parsed)
@asyncio.coroutine def echo_nested_many(request):
args = { 'users': fields.Nested({'id': fields.Int(), 'name': fields.Str()}, many=True) } parsed = yield from parser.parse(args, request) return json_response(parsed)
_response(parsed) @asyncio.coroutine def echo_multiple_args(request): args = { 'first': fields.Str(), 'last': fields.Str(), } parsed = yield from parser.parse(args, request) return json_response(parsed) @asyncio.coroutine def echo_nested_many(request):
64
64
57
12
52
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_nested_many
echo_nested_many
125
131
125
126
7ed62cd84ec72b1b153bd73c8394c0655272f42b
bigcode/the-stack
train
f96c6eb843322af4806bc2f6
train
function
@asyncio.coroutine @use_kwargs({'value': fields.Int()}) def echo_use_kwargs_with_path_param(request, value): return json_response({'value': value})
@asyncio.coroutine @use_kwargs({'value': fields.Int()}) def echo_use_kwargs_with_path_param(request, value):
return json_response({'value': value})
json_response(parsed) @asyncio.coroutine @use_args({'value': fields.Int()}) def echo_use_args_with_path_param(request, args): return json_response(args) @asyncio.coroutine @use_kwargs({'value': fields.Int()}) def echo_use_kwargs_with_path_param(request, value):
64
64
36
27
37
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_use_kwargs_with_path_param
echo_use_kwargs_with_path_param
67
70
67
69
e5e15050c9838423394bf06edbfe7fed70196a64
bigcode/the-stack
train
d52b6a11c5b239e942849521
train
function
@asyncio.coroutine @use_args(HelloSchema, as_kwargs=True) def echo_use_schema_as_kwargs(request, name): return json_response({'name': name})
@asyncio.coroutine @use_args(HelloSchema, as_kwargs=True) def echo_use_schema_as_kwargs(request, name):
return json_response({'name': name})
(args) class EchoHandlerView(web.View): @asyncio.coroutine @use_args(hello_args) def get(self, args): return json_response(args) @asyncio.coroutine @use_args(HelloSchema, as_kwargs=True) def echo_use_schema_as_kwargs(request, name):
64
64
36
27
37
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_use_schema_as_kwargs
echo_use_schema_as_kwargs
162
165
162
164
dd88d4740e6f27daf9f88f80dcf64b8d85137929
bigcode/the-stack
train
501ef5b03eeb97acfb81c502
train
function
@asyncio.coroutine def echo_match_info(request): parsed = yield from parser.parse({'mymatch': fields.Int(location='match_info')}, request) return json_response(parsed)
@asyncio.coroutine def echo_match_info(request):
parsed = yield from parser.parse({'mymatch': fields.Int(location='match_info')}, request) return json_response(parsed)
': 'X-Field'} args = { 'x_field': fields.Nested({'id': fields.Int()}, many=True, **data_key_kwarg) } parsed = yield from parser.parse(args, request) return json_response(parsed) @asyncio.coroutine def echo_match_info(request):
64
64
40
12
52
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_match_info
echo_match_info
143
146
143
144
edfc1d99f16259580cbf134e413562a8bbb7c7fc
bigcode/the-stack
train
b5b1bdaaeeb0b8deb944a1c5
train
function
@asyncio.coroutine def error400(request): def always_fail(value): raise ValidationError('something went wrong', status_code=400) args = {'text': fields.Str(validate=always_fail)} parsed = yield from parser.parse(args, request) return json_response(parsed)
@asyncio.coroutine def error400(request):
def always_fail(value): raise ValidationError('something went wrong', status_code=400) args = {'text': fields.Str(validate=always_fail)} parsed = yield from parser.parse(args, request) return json_response(parsed)
.coroutine def always_error(request): def always_fail(value): raise ValidationError('something went wrong') args = {'text': fields.Str(validate=always_fail)} parsed = yield from parser.parse(args, request) return json_response(parsed) @asyncio.coroutine def error400(request):
64
64
61
11
53
Reskov/webargs
tests/apps/aiohttp_app.py
Python
error400
error400
80
86
80
81
4dd7a3647da43b5285fc860de1fabb8d8c7eee6b
bigcode/the-stack
train
7b3ce4280efd618c205736c8
train
function
@asyncio.coroutine @use_kwargs(hello_args) def echo_use_kwargs(request, name): return json_response({'name': name})
@asyncio.coroutine @use_kwargs(hello_args) def echo_use_kwargs(request, name):
return json_response({'name': name})
hello_args, request, locations=('query', )) return json_response(parsed) @asyncio.coroutine @use_args(hello_args) def echo_use_args(request, args): return json_response(args) @asyncio.coroutine @use_kwargs(hello_args) def echo_use_kwargs(request, name):
64
64
30
21
43
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_use_kwargs
echo_use_kwargs
42
45
42
44
788ea127f3a9ded51e3ded7f5a50d4bfe4c916cd
bigcode/the-stack
train
d3ed347188e1c602f1574271
train
function
@asyncio.coroutine def echo_query(request): parsed = yield from parser.parse(hello_args, request, locations=('query', )) return json_response(parsed)
@asyncio.coroutine def echo_query(request):
parsed = yield from parser.parse(hello_args, request, locations=('query', )) return json_response(parsed)
< 3 else {} hello_many_schema = HelloSchema(many=True, **strict_kwargs) ##### Handlers ##### @asyncio.coroutine def echo(request): parsed = yield from parser.parse(hello_args, request) return json_response(parsed) @asyncio.coroutine def echo_query(request):
64
64
35
11
53
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_query
echo_query
32
35
32
33
826e24856d4b0ed1cd282add411a60fb5271492b
bigcode/the-stack
train
42a2bea29da191b673964fd0
train
class
class HelloSchema(ma.Schema): name = fields.Str(missing='World', validate=lambda n: len(n) >= 3)
class HelloSchema(ma.Schema):
name = fields.Str(missing='World', validate=lambda n: len(n) >= 3)
_args, use_kwargs from webargs.core import MARSHMALLOW_VERSION_INFO hello_args = { 'name': fields.Str(missing='World', validate=lambda n: len(n) >= 3), } hello_multiple = { 'name': fields.List(fields.Str()) } class HelloSchema(ma.Schema):
64
64
27
6
58
Reskov/webargs
tests/apps/aiohttp_app.py
Python
HelloSchema
HelloSchema
19
20
19
19
3c95d8114d3b0c4f4fe974ba49b7a9392f8668a5
bigcode/the-stack
train
16355c3342a3a81b30a2dc80
train
function
@asyncio.coroutine def echo_headers(request): parsed = yield from parser.parse(hello_args, request, locations=('headers', )) return json_response(parsed)
@asyncio.coroutine def echo_headers(request):
parsed = yield from parser.parse(hello_args, request, locations=('headers', )) return json_response(parsed)
(request): def always_fail(value): raise ValidationError('something went wrong', status_code=12345) args = {'text': fields.Str(validate=always_fail)} parsed = yield from parser.parse(args, request) return json_response(parsed) @asyncio.coroutine def echo_headers(request):
64
64
35
11
53
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_headers
echo_headers
96
99
96
97
79b3e994e95e8991890868d3f12787a25ac541e0
bigcode/the-stack
train
eedb5b5b595045603c864b69
train
function
@asyncio.coroutine def always_error(request): def always_fail(value): raise ValidationError('something went wrong') args = {'text': fields.Str(validate=always_fail)} parsed = yield from parser.parse(args, request) return json_response(parsed)
@asyncio.coroutine def always_error(request):
def always_fail(value): raise ValidationError('something went wrong') args = {'text': fields.Str(validate=always_fail)} parsed = yield from parser.parse(args, request) return json_response(parsed)
def echo_use_args_with_path_param(request, args): return json_response(args) @asyncio.coroutine @use_kwargs({'value': fields.Int()}) def echo_use_kwargs_with_path_param(request, value): return json_response({'value': value}) @asyncio.coroutine def always_error(request):
64
64
56
11
53
Reskov/webargs
tests/apps/aiohttp_app.py
Python
always_error
always_error
72
78
72
73
9cda3399e5f0e854045fe99860df7aff9bb1a37c
bigcode/the-stack
train
4029274287ab0a19ca96edcb
train
function
@asyncio.coroutine def echo_nested_many_data_key(request): data_key_kwarg = { 'load_from' if (MARSHMALLOW_VERSION_INFO[0] < 3) else 'data_key': 'X-Field'} args = { 'x_field': fields.Nested({'id': fields.Int()}, many=True, **data_key_kwarg) } parsed = yield from parser.parse(args, request...
@asyncio.coroutine def echo_nested_many_data_key(request):
data_key_kwarg = { 'load_from' if (MARSHMALLOW_VERSION_INFO[0] < 3) else 'data_key': 'X-Field'} args = { 'x_field': fields.Nested({'id': fields.Int()}, many=True, **data_key_kwarg) } parsed = yield from parser.parse(args, request) return json_response(parsed)
echo_nested_many(request): args = { 'users': fields.Nested({'id': fields.Int(), 'name': fields.Str()}, many=True) } parsed = yield from parser.parse(args, request) return json_response(parsed) @asyncio.coroutine def echo_nested_many_data_key(request):
64
64
97
14
50
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_nested_many_data_key
echo_nested_many_data_key
133
141
133
134
65045078ba42142d576fbc5384c4f0115f4adee7
bigcode/the-stack
train
dd6b51ca3e4ae3db5685ebcd
train
function
@asyncio.coroutine @use_args({'value': fields.Int()}) def echo_use_args_with_path_param(request, args): return json_response(args)
@asyncio.coroutine @use_args({'value': fields.Int()}) def echo_use_args_with_path_param(request, args):
return json_response(args)
@asyncio.coroutine def echo_many_schema(request): parsed = yield from parser.parse(hello_many_schema, request, locations=('json', )) return json_response(parsed) @asyncio.coroutine @use_args({'value': fields.Int()}) def echo_use_args_with_path_param(request, args):
64
64
33
27
37
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_use_args_with_path_param
echo_use_args_with_path_param
62
65
62
64
fa5f603b3c51a44e0383a22d656fd04ad5570369
bigcode/the-stack
train
7d0a3513ccc32374947e1e67
train
function
def create_app(): app = aiohttp.web.Application() add_route(app, ['GET', 'POST'], '/echo', echo) add_route(app, ['GET'], '/echo_query', echo_query) add_route(app, ['GET', 'POST'], '/echo_use_args', echo_use_args) add_route(app, ['GET', 'POST'], '/echo_use_kwargs', echo_use_kwargs) add_route(app...
def create_app():
app = aiohttp.web.Application() add_route(app, ['GET', 'POST'], '/echo', echo) add_route(app, ['GET'], '/echo_query', echo_query) add_route(app, ['GET', 'POST'], '/echo_use_args', echo_use_args) add_route(app, ['GET', 'POST'], '/echo_use_kwargs', echo_use_kwargs) add_route(app, ['GET', 'POST'],...
use_args(hello_args) def get(self, request, args): return json_response(args) class EchoHandlerView(web.View): @asyncio.coroutine @use_args(hello_args) def get(self, args): return json_response(args) @asyncio.coroutine @use_args(HelloSchema, as_kwargs=True) def echo_use_schema_as_kwar...
129
129
433
4
125
Reskov/webargs
tests/apps/aiohttp_app.py
Python
create_app
create_app
173
200
173
173
59cf04251c1b39c7e872ba47ec40d3c5d225af82
bigcode/the-stack
train
903b7220c1ae6e31d6bab1b6
train
function
@asyncio.coroutine @use_args({'value': fields.Int()}, validate=lambda args: args['value'] > 42) def echo_use_args_validated(request, args): return json_response(args)
@asyncio.coroutine @use_args({'value': fields.Int()}, validate=lambda args: args['value'] > 42) def echo_use_args_validated(request, args):
return json_response(args)
.coroutine @use_kwargs(hello_args) def echo_use_kwargs(request, name): return json_response({'name': name}) @asyncio.coroutine @use_args({'value': fields.Int()}, validate=lambda args: args['value'] > 42) def echo_use_args_validated(request, args):
64
64
43
37
27
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo_use_args_validated
echo_use_args_validated
47
50
47
49
dd8b3141f9ef2b4d55fd47d7e97c7844d956cb68
bigcode/the-stack
train
1f01dd5ee0a3d8ea1a9d74d7
train
function
@asyncio.coroutine def echo(request): parsed = yield from parser.parse(hello_args, request) return json_response(parsed)
@asyncio.coroutine def echo(request):
parsed = yield from parser.parse(hello_args, request) return json_response(parsed)
', validate=lambda n: len(n) >= 3) strict_kwargs = {'strict': True} if MARSHMALLOW_VERSION_INFO[0] < 3 else {} hello_many_schema = HelloSchema(many=True, **strict_kwargs) ##### Handlers ##### @asyncio.coroutine def echo(request):
64
64
29
10
53
Reskov/webargs
tests/apps/aiohttp_app.py
Python
echo
echo
27
30
27
28
d744ebdab935845509b01006c4eac012fedb841c
bigcode/the-stack
train
c92c2d9e5151b4ddbd1712d0
train
class
class EchoHandlerView(web.View): @asyncio.coroutine @use_args(hello_args) def get(self, args): return json_response(args)
class EchoHandlerView(web.View): @asyncio.coroutine @use_args(hello_args)
def get(self, args): return json_response(args)
request) return json_response(parsed) class EchoHandler: @asyncio.coroutine @use_args(hello_args) def get(self, request, args): return json_response(args) class EchoHandlerView(web.View): @asyncio.coroutine @use_args(hello_args)
64
64
35
22
42
Reskov/webargs
tests/apps/aiohttp_app.py
Python
EchoHandlerView
EchoHandlerView
155
160
155
158
e8373e16b3807cbcbb377741ca19698f165b1342
bigcode/the-stack
train
2c533f9f9916dac3b6f53878
train
function
@pytest.mark.cvxpy def test_same_logistic(random_xy_dataset_clf): """ Tests whether the fair classifier performs similar to logistic regression for binary classification problems when we set a high threshold in the case where we set the covariance_threshold to None """ _test_same(random_xy_datas...
@pytest.mark.cvxpy def test_same_logistic(random_xy_dataset_clf):
""" Tests whether the fair classifier performs similar to logistic regression for binary classification problems when we set a high threshold in the case where we set the covariance_threshold to None """ _test_same(random_xy_dataset_clf)
ba(X) np.testing.assert_almost_equal(normal_pred, fair_pred, decimal=3) assert np.sum(lr.predict(X_without_sens) != fair.predict(X)) / len(X) < 0.01 @pytest.mark.cvxpy def test_same_logistic(random_xy_dataset_clf):
64
64
68
17
46
quendee/scikit-lego
tests/test_estimators/test_demographic_parity.py
Python
test_same_logistic
test_same_logistic
78
85
78
79
2039c17f39e8246e78c285548b742452a6f1a82a
bigcode/the-stack
train
b895be635e31ed2627ddf5a5
train
function
@pytest.mark.cvxpy def test_regularization(sensitive_classification_dataset): """Tests whether increasing regularization decreases the norm of the coefficient vector""" X, y = sensitive_classification_dataset prev_theta_norm = np.inf for C in [1, 0.5, 0.2, 0.1]: fair = DemographicParityClassifi...
@pytest.mark.cvxpy def test_regularization(sensitive_classification_dataset):
"""Tests whether increasing regularization decreases the norm of the coefficient vector""" X, y = sensitive_classification_dataset prev_theta_norm = np.inf for C in [1, 0.5, 0.2, 0.1]: fair = DemographicParityClassifier( covariance_threshold=None, sensitive_cols=["x1"], C=C ...
whether the fair classifier performs similar to logistic regression for multiclass problems when we set a high threshold in the case where we set the covariance_threshold to None """ _test_same(random_xy_dataset_multiclf) @pytest.mark.cvxpy def test_regularization(sensitive_classification_dataset):
64
64
131
16
48
quendee/scikit-lego
tests/test_estimators/test_demographic_parity.py
Python
test_regularization
test_regularization
98
110
98
99
c79f36aa2e4a5500940786fc4fa6501aea6adef4
bigcode/the-stack
train
666ee9c854d0ebd3767cd9ca
train
function
@pytest.mark.cvxpy def test_deprecation(): with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Trigger a warning. FairClassifier( covariance_threshold=1, sensitive_cols=["x1"], ...
@pytest.mark.cvxpy def test_deprecation():
with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Trigger a warning. FairClassifier( covariance_threshold=1, sensitive_cols=["x1"], penalty="none", train_sensi...
sensitive_cols=["x1"], penalty="none", train_sensitive_cols=False, ).fit(X, y) fairness = scorer(fair, X, y) assert fairness >= prev_fairness prev_fairness = fairness @pytest.mark.cvxpy def test_deprecation():
64
64
92
11
52
quendee/scikit-lego
tests/test_estimators/test_demographic_parity.py
Python
test_deprecation
test_deprecation
132
144
132
133
cea293e3fcde835085d4358826c0c7c15205a4e3
bigcode/the-stack
train
75532960b49490f14fbcf1f0
train
function
@pytest.mark.cvxpy def test_same_logistic_multiclass(random_xy_dataset_multiclf): """ Tests whether the fair classifier performs similar to logistic regression for multiclass problems when we set a high threshold in the case where we set the covariance_threshold to None """ _test_same(random_xy_...
@pytest.mark.cvxpy def test_same_logistic_multiclass(random_xy_dataset_multiclf):
""" Tests whether the fair classifier performs similar to logistic regression for multiclass problems when we set a high threshold in the case where we set the covariance_threshold to None """ _test_same(random_xy_dataset_multiclf)
performs similar to logistic regression for binary classification problems when we set a high threshold in the case where we set the covariance_threshold to None """ _test_same(random_xy_dataset_clf) @pytest.mark.cvxpy def test_same_logistic_multiclass(random_xy_dataset_multiclf):
64
64
73
21
43
quendee/scikit-lego
tests/test_estimators/test_demographic_parity.py
Python
test_same_logistic_multiclass
test_same_logistic_multiclass
88
95
88
89
6514f13792f480f7d7e1c2020aeeea6dfd311e0e
bigcode/the-stack
train
f0a9d11d1e0d2c5ebbec68b1
train
function
@pytest.mark.cvxpy def test_fairness(sensitive_classification_dataset): """tests whether fairness (measured by p percent score) increases as we decrease the covariance threshold""" X, y = sensitive_classification_dataset scorer = p_percent_score("x1") prev_fairness = -np.inf for cov_threshold in [N...
@pytest.mark.cvxpy def test_fairness(sensitive_classification_dataset):
"""tests whether fairness (measured by p percent score) increases as we decrease the covariance threshold""" X, y = sensitive_classification_dataset scorer = p_percent_score("x1") prev_fairness = -np.inf for cov_threshold in [None, 10, 0.5, 0.1]: fair = DemographicParityClassifier( ...
sensitive_cols=["x1"], C=C ).fit(X, y) theta_norm = np.abs(np.sum(fair.coef_)) assert theta_norm < prev_theta_norm prev_theta_norm = theta_norm @pytest.mark.cvxpy def test_fairness(sensitive_classification_dataset):
64
64
157
17
46
quendee/scikit-lego
tests/test_estimators/test_demographic_parity.py
Python
test_fairness
test_fairness
113
129
113
114
dd5005eb560982e152dc5f1ecf3bc273162eee9f
bigcode/the-stack
train
df3e391c73781713c3ee7acf
train
function
def _test_same(dataset): X, y = dataset if X.shape[1] == 1: # If we only have one column (which is also the sensitive one) we can't fit return True sensitive_cols = [0] X_without_sens = np.delete(X, sensitive_cols, axis=1) lr = LogisticRegression( penalty="none", sol...
def _test_same(dataset):
X, y = dataset if X.shape[1] == 1: # If we only have one column (which is also the sensitive one) we can't fit return True sensitive_cols = [0] X_without_sens = np.delete(X, sensitive_cols, axis=1) lr = LogisticRegression( penalty="none", solver="lbfgs", mult...
exclude=[ "check_sample_weights_invariance", ] ) ) @pytest.mark.cvxpy def test_standard_checks(test_fn): trf = DemographicParityClassifier( covariance_threshold=None, C=1, penalty="none", sensitive_cols=[0], train_sensitive_cols=True, ) ...
87
87
291
6
81
quendee/scikit-lego
tests/test_estimators/test_demographic_parity.py
Python
_test_same
_test_same
38
75
38
38
03a1860ede65c53bcbc326c42b1e23eb08734299
bigcode/the-stack
train
9c6451194a886d44f85895f1
train
function
@pytest.mark.parametrize( "test_fn", select_tests( flatten([general_checks, nonmeta_checks, classifier_checks]), exclude=[ "check_sample_weights_invariance", ] ) ) @pytest.mark.cvxpy def test_standard_checks(test_fn): trf = DemographicParityClassifier( covaria...
@pytest.mark.parametrize( "test_fn", select_tests( flatten([general_checks, nonmeta_checks, classifier_checks]), exclude=[ "check_sample_weights_invariance", ] ) ) @pytest.mark.cvxpy def test_standard_checks(test_fn):
trf = DemographicParityClassifier( covariance_threshold=None, C=1, penalty="none", sensitive_cols=[0], train_sensitive_cols=True, ) test_fn(DemographicParityClassifier.__name__, trf)
_checks, select_tests, nonmeta_checks @pytest.mark.parametrize( "test_fn", select_tests( flatten([general_checks, nonmeta_checks, classifier_checks]), exclude=[ "check_sample_weights_invariance", ] ) ) @pytest.mark.cvxpy def test_standard_checks(test_fn):
64
64
107
55
8
quendee/scikit-lego
tests/test_estimators/test_demographic_parity.py
Python
test_standard_checks
test_standard_checks
17
35
17
27
b187a6f4a91b62d2002fbb40b7b63694fe50092d
bigcode/the-stack
train
5346c5eafa605736d7d86c37
train
class
class ExperimentTest(unittest.TestCase): def tearDown(self): ray.shutdown() _register_all() # re-register the evicted objects def setUp(self): def train(config, reporter): for i in range(100): reporter(timesteps_total=i) register_trainable("f1", tra...
class ExperimentTest(unittest.TestCase):
def tearDown(self): ray.shutdown() _register_all() # re-register the evicted objects def setUp(self): def train(config, reporter): for i in range(100): reporter(timesteps_total=i) register_trainable("f1", train) def testConvertExperimentFromExp...
import unittest import ray from ray.rllib import _register_all from ray.tune import register_trainable from ray.tune.experiment import Experiment, convert_to_experiment_list from ray.tune.error import TuneError class ExperimentTest(unittest.TestCase):
55
122
408
7
47
vermashresth/ray
python/ray/tune/tests/test_experiment.py
Python
ExperimentTest
ExperimentTest
10
71
10
10
a9131eca571fa92018550acce3bc6d6580b6d38d
bigcode/the-stack
train
70eb1f86aa4f25e716cbf3fd
train
class
class ReplayBuffer: """ Replay Buffer to store the experiences. """ def __init__(self, buffer_size, batch_size): """ Initialize the attributes. Args: buffer_size: The size of the buffer memory batch_size: The batch for each of the data request `get_batch...
class ReplayBuffer:
""" Replay Buffer to store the experiences. """ def __init__(self, buffer_size, batch_size): """ Initialize the attributes. Args: buffer_size: The size of the buffer memory batch_size: The batch for each of the data request `get_batch` """ ...
""" Buffer system for the RL Original author - Samuel Matthew Koesnadi """ import numpy as np from common_definitions import BUFFER_UNBALANCE_GAP import random from collections import deque class ReplayBuffer:
47
120
401
4
42
louvreaux/sphero_formation
scripts/replay_buffer.py
Python
ReplayBuffer
ReplayBuffer
13
72
13
13
37e701f577cdb49328ef0594d95ed6a6562f0632
bigcode/the-stack
train
9e99cfc78bc6ed5f060b592a
train
class
class LocationGroupTest(LocationGroupBase): def test_group_name(self): # just location name for top level self.assertEqual( 'teststate-Cases', self.test_state.sql_location.case_sharing_group_object().name ) # locations combined by forward slashes otherwise ...
class LocationGroupTest(LocationGroupBase):
def test_group_name(self): # just location name for top level self.assertEqual( 'teststate-Cases', self.test_state.sql_location.case_sharing_group_object().name ) # locations combined by forward slashes otherwise self.assertEqual( 'teststa...
track() bootstrap_location_types(cls.domain.name) cls.loc = make_loc('loc', type='outlet', domain=cls.domain.name) cls.user = CommCareUser.create( cls.domain.name, 'username', 'password', created_by=None, created_via=None, ...
223
223
744
8
215
akashkj/commcare-hq
corehq/apps/locations/tests/test_location_groups.py
Python
LocationGroupTest
LocationGroupTest
63
162
63
64
3e6cf18755047a58f7a8132605a0dc0cc935ebca
bigcode/the-stack
train
8c094bb180ab3bb66f3de865
train
class
class LocationGroupBase(TestCase): @classmethod def setUpClass(cls, set_location=True): super().setUpClass() cls.domain = create_domain('locations-test') cls.domain.convert_to_commtrack() bootstrap_location_types(cls.domain.name) cls.loc = make_loc('loc', type='outlet', ...
class LocationGroupBase(TestCase): @classmethod
def setUpClass(cls, set_location=True): super().setUpClass() cls.domain = create_domain('locations-test') cls.domain.convert_to_commtrack() bootstrap_location_types(cls.domain.name) cls.loc = make_loc('loc', type='outlet', domain=cls.domain.name) cls.user = CommCareU...
.apps.commtrack.tests.util import bootstrap_location_types from corehq.apps.domain.shortcuts import create_domain from corehq.apps.groups.exceptions import CantSaveException from corehq.apps.users.models import CommCareUser from corehq.util.test_utils import flag_enabled from ..fixtures import location_fixture_generat...
78
78
260
11
66
akashkj/commcare-hq
corehq/apps/locations/tests/test_location_groups.py
Python
LocationGroupBase
LocationGroupBase
17
60
17
19
f63c67961d3b4c9012f13fca8eca502679dcc94a
bigcode/the-stack
train
a222eaf53e2425080cae3f7f
train
class
@flag_enabled('HIERARCHICAL_LOCATION_FIXTURE') class UnsetLocationGroupTest(LocationGroupBase): @classmethod def setUpClass(cls): super().setUpClass(set_location=False) @patch('corehq.apps.domain.models.Domain.uses_locations', lambda: True) def test_location_fixture_generator_no_user_location(...
@flag_enabled('HIERARCHICAL_LOCATION_FIXTURE') class UnsetLocationGroupTest(LocationGroupBase): @classmethod
def setUpClass(cls): super().setUpClass(set_location=False) @patch('corehq.apps.domain.models.Domain.uses_locations', lambda: True) def test_location_fixture_generator_no_user_location(self): """ Ensures that a user without a location will still receive an empty fixture """ ...
'commcare_location_foo': 'bar', 'commcare_location_fruit': 'banana' }, self.loc.sql_location.case_sharing_group_object().metadata ) @flag_enabled('HIERARCHICAL_LOCATION_FIXTURE') class UnsetLocationGroupTest(LocationGroupBase): @classmethod
65
65
219
26
39
akashkj/commcare-hq
corehq/apps/locations/tests/test_location_groups.py
Python
UnsetLocationGroupTest
UnsetLocationGroupTest
165
189
165
168
504c4a81acf857c297f152689856f0d714b47fbb
bigcode/the-stack
train