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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6b6f4a23f4896c44d635eece | train | function | def _get_struct_I():
global _struct_I
return _struct_I
| def _get_struct_I():
| global _struct_I
return _struct_I
| utf-8')
else:
val1.uuid = str[start:end]
self.sources.append(val1)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
def _get_struct_I():
| 64 | 64 | 18 | 6 | 57 | roop-pal/robotic-folding | catkin_ws/devel/.private/baxter_maintenance_msgs/lib/python2.7/dist-packages/baxter_maintenance_msgs/msg/_UpdateSources.py | Python | _get_struct_I | _get_struct_I | 276 | 278 | 276 | 276 | 72b073a01b474fd54b1e1016eaaaa07c0526f426 | bigcode/the-stack | train |
49c443ea844d66899bbed1ee | train | function | def decrypt_data(event, context):
class SIFPrivateMasterKeyProvider(RawMasterKeyProvider):
provider_id = provider_id
def __new__(cls, *args, **kwargs):
obj = super(SIFPrivateMasterKeyProvider, cls).__new__(cls)
return obj
def __init__(self, private_key_id, private_k... | def decrypt_data(event, context):
| class SIFPrivateMasterKeyProvider(RawMasterKeyProvider):
provider_id = provider_id
def __new__(cls, *args, **kwargs):
obj = super(SIFPrivateMasterKeyProvider, cls).__new__(cls)
return obj
def __init__(self, private_key_id, private_key_text):
RawMasterKey... | IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import os
import json
import boto3
import aws_encryption_sdk
from aws_encryption_sdk.internal.crypto import WrappingKey
from aws_e... | 158 | 158 | 527 | 7 | 151 | aws-samples/field-level-encryption-sample | lambda/fle_decrypt_data.py | Python | decrypt_data | decrypt_data | 31 | 90 | 31 | 31 | 4a78238d298cee62727d71e26c34dbdddccfc4ec | bigcode/the-stack | train |
33b22befab9ba335a3b158a6 | train | function | def main():
decrypt_data ("test", "test")
| def main():
| decrypt_data ("test", "test")
| Email']['S'],
'Phone Encrypted: ' + i['Phone']['S'][:30] + '...', 'Phone Decrypted: ' + PhoneDecrypted ] )
# remove private key from local memory
private_key_text = None
# return result
return d
def main():
| 64 | 64 | 12 | 3 | 60 | aws-samples/field-level-encryption-sample | lambda/fle_decrypt_data.py | Python | main | main | 92 | 93 | 92 | 92 | 1571361ef96da52728a8b9e73b69c2357c3f84c8 | bigcode/the-stack | train |
ea1fdf14a2e45b77ca772baa | train | class | class Worker(Substitution):
"""Worker class."""
def __init__(self, *args, **kwargs):
"""Initializes the worker."""
# defaults
# do not use self.utility (still initializing)
self.__utility = 1.0 # self.utility_fct.best()
"""Utility of the worker (maintained utility of th... | class Worker(Substitution):
| """Worker class."""
def __init__(self, *args, **kwargs):
"""Initializes the worker."""
# defaults
# do not use self.utility (still initializing)
self.__utility = 1.0 # self.utility_fct.best()
"""Utility of the worker (maintained utility of the underlying
substit... | """Substitution worker.
Proceeds along a specific substitution tree to find a possible substitution.
A variable node in the SHSA model may have more than one relation. Instead of
chosing a specific relation, i.e., fixing the substitution path, a worker for
each possible relation is created.
A worker is defined by th... | 121 | 256 | 1,870 | 5 | 115 | dratasich/shsa | shsa/engine/worker.py | Python | Worker | Worker | 21 | 233 | 21 | 21 | 06c3d813ba9313a068cef6f640507ced60bf1711 | bigcode/the-stack | train |
737dd2e19323f2e17ca5186e | train | class | class LoanedBookInstancesByUserListViewTest(TestCase):
def setUp(self):
# Create two users
test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK')
test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD')
test_user1.save()
... | class LoanedBookInstancesByUserListViewTest(TestCase):
| def setUp(self):
# Create two users
test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK')
test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD')
test_user1.save()
test_user2.save()
# Create a book
... | _template(self):
response = self.client.get(reverse('authors'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'catalog/author_list.html')
def test_pagination_is_ten(self):
response = self.client.get(reverse('authors'))
self.assertEqual(respons... | 256 | 256 | 1,029 | 13 | 242 | Adrizero10/django_local_library | catalog/tests/test_views.py | Python | LoanedBookInstancesByUserListViewTest | LoanedBookInstancesByUserListViewTest | 53 | 166 | 53 | 53 | e1bd0cb540625ecb408832761caae6d874192e34 | bigcode/the-stack | train |
7bf026f29c38c56d36868506 | train | class | class AuthorListViewTest(TestCase):
@classmethod
def setUpTestData(cls):
# Create 13 authors for pagination tests
number_of_authors = 13
for author_id in range(number_of_authors):
Author.objects.create(
first_name=f'Christian {author_id}',
las... | class AuthorListViewTest(TestCase):
@classmethod
| def setUpTestData(cls):
# Create 13 authors for pagination tests
number_of_authors = 13
for author_id in range(number_of_authors):
Author.objects.create(
first_name=f'Christian {author_id}',
last_name=f'Surname {author_id}',
)
def... | from django.test import TestCase
from django.urls import reverse
from catalog.models import Author
class AuthorListViewTest(TestCase):
@classmethod
| 31 | 106 | 355 | 12 | 18 | Adrizero10/django_local_library | catalog/tests/test_views.py | Python | AuthorListViewTest | AuthorListViewTest | 6 | 44 | 6 | 7 | 7d1f4df7dc476a260915ee5dc4ab1559375de95b | bigcode/the-stack | train |
2097ea0e3f42ad724c9e5fa8 | train | class | class AuthorCreateViewTest(TestCase):
"""Test case for the AuthorCreate view (Created as Challenge)."""
def setUp(self):
# Create a user
test_user1 = User.objects.create_user(username='alumnodb1', password='alumnodb1')
test_user2 = User.objects.create_user(username='alumnodb2', password... | class AuthorCreateViewTest(TestCase):
| """Test case for the AuthorCreate view (Created as Challenge)."""
def setUp(self):
# Create a user
test_user1 = User.objects.create_user(username='alumnodb1', password='alumnodb1')
test_user2 = User.objects.create_user(username='alumnodb2', password='alumnodb2')
test_user1.save... | (response.status_code, 200)
self.assertFormError(response, 'form', 'renewal_date', 'Invalid date - renewal in past')
def test_form_invalid_renewal_date_future(self):
login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD')
invalid_date_in_future = datetime.date.today() + da... | 167 | 168 | 562 | 8 | 159 | Adrizero10/django_local_library | catalog/tests/test_views.py | Python | AuthorCreateViewTest | AuthorCreateViewTest | 293 | 346 | 293 | 293 | bce84a2b16e30b138893483b87d8e9660957820e | bigcode/the-stack | train |
6108dcb19134b647b27c66fb | train | class | class RenewBookInstancesViewTest(TestCase):
def setUp(self):
# Create a user
test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK')
test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD')
test_user1.save()
test_use... | class RenewBookInstancesViewTest(TestCase):
| def setUp(self):
# Create a user
test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK')
test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD')
test_user1.save()
test_user2.save()
# Give test_user2 permiss... | self.assertEqual(bookitem.status, 'o')
def test_pages_ordered_by_due_date(self):
# Change all books to be on loan
for book in BookInstance.objects.all():
book.status='o'
book.save()
login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK')
r... | 256 | 256 | 1,431 | 9 | 247 | Adrizero10/django_local_library | catalog/tests/test_views.py | Python | RenewBookInstancesViewTest | RenewBookInstancesViewTest | 172 | 289 | 172 | 172 | 14b94635dce6d8b1af52f9b11e4bb49d67bdab8e | bigcode/the-stack | train |
48e7deaec2cd62bb5bb26828 | train | function | def handle_api_elv(latlong: dict) -> "json text":
elevation_http="http://open.mapquestapi.com/elevation/v1/profile?key=h9l8GngD4qpZ2qCfrc1KuGcx09tOELvt&shapeFormat=raw&unit=f&latLngCollection=" + str(latlong["lat"])+ "," + str(latlong["lng"])
response_elv = urllib.request.urlopen(elevation_http)
json_text_e... | def handle_api_elv(latlong: dict) -> "json text":
| elevation_http="http://open.mapquestapi.com/elevation/v1/profile?key=h9l8GngD4qpZ2qCfrc1KuGcx09tOELvt&shapeFormat=raw&unit=f&latLngCollection=" + str(latlong["lat"])+ "," + str(latlong["lng"])
response_elv = urllib.request.urlopen(elevation_http)
json_text_elv = response_elv.read().decode(encoding = "utf-8"... | _fin["info"]["messages"] == ["We are unable to route with the given locations."]:
raise RouteNotFoundError
return json_text_fin
# takes in dictionary (elevation api) lat and long, returns json text
def handle_api_elv(latlong: dict) -> "json text":
| 64 | 64 | 135 | 15 | 48 | iHuyTV/MapQuest-API | final_p_maps.py | Python | handle_api_elv | handle_api_elv | 32 | 37 | 32 | 32 | ea20c40b0dc1170fa787e13958d122198c097266 | bigcode/the-stack | train |
3e4fed945259f98ea199a372 | train | class | class RouteNotFoundError(Exception):
pass
| class RouteNotFoundError(Exception):
| pass
|
import json
import http.client
import urllib.request
import urllib.error
import urllib.parse
API_KEY = "LrWe3gQF9bX9EtX13O5dH3ALghMOnwTZ"
# if no route is found
class RouteNotFoundError(Exception):
| 64 | 64 | 10 | 7 | 56 | iHuyTV/MapQuest-API | final_p_maps.py | Python | RouteNotFoundError | RouteNotFoundError | 15 | 16 | 15 | 15 | 95472292782b7b012a772cc888267092180350ae | bigcode/the-stack | train |
c5fed2a631ef79127477ad49 | train | function | def handle_api_dir(start_end: tuple) -> "json text":
start_point,end_point = start_end
http="http://open.mapquestapi.com/directions/v2/route?key="+ API_KEY +"&ambiguities=ignore&from="+start_point+"&to="+end_point
response = urllib.request.urlopen(http)
json_text = response.read().decode(encoding = "utf... | def handle_api_dir(start_end: tuple) -> "json text":
| start_point,end_point = start_end
http="http://open.mapquestapi.com/directions/v2/route?key="+ API_KEY +"&ambiguities=ignore&from="+start_point+"&to="+end_point
response = urllib.request.urlopen(http)
json_text = response.read().decode(encoding = "utf-8")
json_text_fin = json.loads(json_text)
i... | 9EtX13O5dH3ALghMOnwTZ"
# if no route is found
class RouteNotFoundError(Exception):
pass
# Takes in tuple (direction api) start and end, returns the json text
def handle_api_dir(start_end: tuple) -> "json text":
| 64 | 64 | 131 | 14 | 49 | iHuyTV/MapQuest-API | final_p_maps.py | Python | handle_api_dir | handle_api_dir | 19 | 29 | 19 | 19 | 9ac1fc4c98e6d1639020f9d0a6e4c5dcc0907e67 | bigcode/the-stack | train |
7edb1b933269697e5059be4b | train | function | def handle(fileName: str):
pic = Image.open(fileName)
pxlist = findAvailablePixels(pic)
pic = pic.convert("RGB").quantize(palette = getPalette())
pxlist = attachColor(pic, pxlist)
with open("picture.json", "w", encoding = "UTF-8") as result:
result.write(json.dumps(pxlist, separators = (',',... | def handle(fileName: str):
| pic = Image.open(fileName)
pxlist = findAvailablePixels(pic)
pic = pic.convert("RGB").quantize(palette = getPalette())
pxlist = attachColor(pic, pxlist)
with open("picture.json", "w", encoding = "UTF-8") as result:
result.write(json.dumps(pxlist, separators = (',', ':')))
pic.save("previ... | , j][3] != 0]
def attachColor(pic: Image.Image, pxlist: list):
pxs = pic.load()
return [(px[0], px[1], pxs[px[0], px[1]]) for px in pxlist]
def handle(fileName: str):
| 64 | 64 | 93 | 7 | 57 | Nikaidou-Shinku/free-paint | pic2json.py | Python | handle | handle | 58 | 65 | 58 | 58 | d3ee9c191242d78b4715928db6056465f229e48e | bigcode/the-stack | train |
dea79724aa09f8ac6b50344e | train | function | def findAvailablePixels(pic: Image.Image):
w, h = pic.size
pxs = pic.load()
if (len(pxs[0, 0]) < 4):
return [(i, j) for i in range(w) for j in range(h)]
return [(i, j) for i in range(w) for j in range(h) if pxs[i, j][3] != 0]
| def findAvailablePixels(pic: Image.Image):
| w, h = pic.size
pxs = pic.load()
if (len(pxs[0, 0]) < 4):
return [(i, j) for i in range(w) for j in range(h)]
return [(i, j) for i in range(w) for j in range(h) if pxs[i, j][3] != 0]
| in color]
while len(PALETTE) < 768: PALETTE.append(0)
def getPalette():
pal_image = Image.new("P", (1, 1))
pal_image.putpalette(PALETTE)
return pal_image
def findAvailablePixels(pic: Image.Image):
| 64 | 64 | 91 | 9 | 54 | Nikaidou-Shinku/free-paint | pic2json.py | Python | findAvailablePixels | findAvailablePixels | 47 | 52 | 47 | 47 | 0b67ad68bda8db24cb2388eda8de9619691da258 | bigcode/the-stack | train |
9c227d2cf2fae4f8b34be192 | train | function | def getPalette():
pal_image = Image.new("P", (1, 1))
pal_image.putpalette(PALETTE)
return pal_image
| def getPalette():
| pal_image = Image.new("P", (1, 1))
pal_image.putpalette(PALETTE)
return pal_image
| (184, 63, 39),
(121, 85, 72)
]
PALETTE = [item for color in LUOGU_PAINTBOARD_COLORS for item in color]
while len(PALETTE) < 768: PALETTE.append(0)
def getPalette():
| 64 | 64 | 34 | 4 | 60 | Nikaidou-Shinku/free-paint | pic2json.py | Python | getPalette | getPalette | 42 | 45 | 42 | 42 | bf7e3b44cf39e939af128de5faab8b258ae2a7e2 | bigcode/the-stack | train |
de78c9a24f725343386e71f0 | train | function | def attachColor(pic: Image.Image, pxlist: list):
pxs = pic.load()
return [(px[0], px[1], pxs[px[0], px[1]]) for px in pxlist]
| def attachColor(pic: Image.Image, pxlist: list):
| pxs = pic.load()
return [(px[0], px[1], pxs[px[0], px[1]]) for px in pxlist]
| return [(i, j) for i in range(w) for j in range(h)]
return [(i, j) for i in range(w) for j in range(h) if pxs[i, j][3] != 0]
def attachColor(pic: Image.Image, pxlist: list):
| 64 | 64 | 48 | 13 | 51 | Nikaidou-Shinku/free-paint | pic2json.py | Python | attachColor | attachColor | 54 | 56 | 54 | 54 | fa04b2fb93cf6a684af4c2eeb19a58119f62f240 | bigcode/the-stack | train |
9847e89fd61fbbe0c6cda80f | train | class | class Language(NamedTuple):
name: str
# Use `None` for no installation / environment
ENVIRONMENT_DIR: Optional[str]
# return a value to replace `'default` for `language_version`
get_default_version: Callable[[], str]
# return whether the environment is healthy (or should be rebuilt)
healthy:... | class Language(NamedTuple):
| name: str
# Use `None` for no installation / environment
ENVIRONMENT_DIR: Optional[str]
# return a value to replace `'default` for `language_version`
get_default_version: Callable[[], str]
# return whether the environment is healthy (or should be rebuilt)
healthy: Callable[[Prefix, str], boo... | rep
from reformat.languages import python
from reformat.languages import r
from reformat.languages import ruby
from reformat.languages import rust
from reformat.languages import script
from reformat.languages import swift
from reformat.languages import system
from reformat.prefix import Prefix
class Language(NamedTuple... | 64 | 64 | 142 | 6 | 57 | DjKuj/reformat | reformat/languages/all.py | Python | Language | Language | 29 | 40 | 29 | 29 | 79bd13dcc29c8a6fa0401c69da9dfb5570bb3467 | bigcode/the-stack | train |
03d33bb467c40c008ea39293 | train | class | class Graph:
def __init__(self):
self.graph = defaultdict(list)#Create empty dictionary
def insertEdge(self, v1, v2):
self.graph[v1].append(v2)#Add v2 to list of v1
self.graph[v2].append(v1)#Add v1 to list of v2
def printGraph(self):
for node in self.graph:
... | class Graph:
| def __init__(self):
self.graph = defaultdict(list)#Create empty dictionary
def insertEdge(self, v1, v2):
self.graph[v1].append(v2)#Add v2 to list of v1
self.graph[v2].append(v1)#Add v1 to list of v2
def printGraph(self):
for node in self.graph:
print(... | from collections import defaultdict
class Graph:
| 8 | 64 | 137 | 3 | 4 | bpbpublications/Python-Quick-Interview-Guide | Chapter 04/graph.py | Python | Graph | Graph | 2 | 15 | 2 | 2 | 28023e6489c6a9d901c7bd77a261e57db3cf71c8 | bigcode/the-stack | train |
51b05ed2fbf35ef01525943c | train | class | class workDays():
def __init__(self, start_date, end_date, days_off=None):
self.start_date = start_date
self.end_date = end_date
self.days_off = days_off
if self.start_date > self.end_date:
self.start_date, self.end_date = self.end_date, self.start_date
if days_off is None:
self.days_off = 5, 6
... | class workDays():
| def __init__(self, start_date, end_date, days_off=None):
self.start_date = start_date
self.end_date = end_date
self.days_off = days_off
if self.start_date > self.end_date:
self.start_date, self.end_date = self.end_date, self.start_date
if days_off is None:
self.days_off = 5, 6
self.days_work =... | import MIMEText
import smtplib
import datetime, time
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
import mysql.connector
cardDetected = True
date = datetime.datetime.now().strftime('%Y-%m-%d')
#Generating day number
class workDays():
| 64 | 64 | 198 | 4 | 59 | Pteroindix/L.A.S.T. | Program_v3.py | Python | workDays | workDays | 15 | 41 | 15 | 15 | 38b13356150deac15c25e1c047c4651017a1a8a5 | bigcode/the-stack | train |
9f9fa3b5e2a409cc760ad188 | train | function | def mainPage():
value = "\n\n\nWelcome to SWIS Late System: L.A.S.T\n\n\nPlease scan your card if you are late. Detecting..."
global textLabel
textLabel = Label(root,text=value)
textLabel.grid(padx=80,pady=20)
stuID = scanner()
global STUDENT
STUDENT = sqlconnection(stuID,DAYNUM) #connect to database
#print(car... | def mainPage():
| value = "\n\n\nWelcome to SWIS Late System: L.A.S.T\n\n\nPlease scan your card if you are late. Detecting..."
global textLabel
textLabel = Label(root,text=value)
textLabel.grid(padx=80,pady=20)
stuID = scanner()
global STUDENT
STUDENT = sqlconnection(stuID,DAYNUM) #connect to database
#print(cardDetected)
#pri... | ')
y = int(dateinput[0])
m = int(dateinput[1])
d = int(dateinput[2])
b = datetime.date(y,m,d)
work = workDays(era,b)
global DAYNUM
DAYNUM = work.daysCount()%8
#The first GUI homepage
def mainPage():
| 64 | 64 | 124 | 4 | 59 | Pteroindix/L.A.S.T. | Program_v3.py | Python | mainPage | mainPage | 55 | 67 | 55 | 55 | 64f4696ae6ca84bb9d90cf273b60f2b1b0a0f7b3 | bigcode/the-stack | train |
c592122d9d15b2275041940e | train | function | def sqlconnection(ID_Number, Day_Number):
try:
cnx = mysql.connector.connect(user="root",password="31415926535",\
database="L.A.S.T.")
cursor = cnx.cursor()
query = ("SELECT * FROM `L.A.S.T.`.Day{};".format(Day_Number))
cursor.execute(query)
for each in cursor:
if ID_Number == each[0]:
return ea... | def sqlconnection(ID_Number, Day_Number):
| try:
cnx = mysql.connector.connect(user="root",password="31415926535",\
database="L.A.S.T.")
cursor = cnx.cursor()
query = ("SELECT * FROM `L.A.S.T.`.Day{};".format(Day_Number))
cursor.execute(query)
for each in cursor:
if ID_Number == each[0]:
return each[1], each[2], each[3]
except mysql.con... | ("Detecting...")
id, text = reader.read()
print("UID: ", id)
return id
except KeyboardInterrupt:
print('\t')
GPIO.cleanup()
#Connect to SQL server to get stuname, grade, and email for the ID
def sqlconnection(ID_Number, Day_Number):
| 64 | 64 | 118 | 9 | 54 | Pteroindix/L.A.S.T. | Program_v3.py | Python | sqlconnection | sqlconnection | 83 | 98 | 83 | 83 | b24a63e81d9606ca0a0d75a424aa02b25e029e4d | bigcode/the-stack | train |
e88da6fcf59626db6dc7a47c | train | function | def sentOutPage():
button1.grid_forget()
button2.grid_forget()
listEmails = []
listEmails.append(STUDENT[2])
listEmails.append("#admission@swis.cn")
time = datetime.datetime.now().strftime('%H:%M:%S')
sendEmail("LATE STUDENT - " + STUDENT[0],\
"Hello,\n\n" + STUDENT[0] + " from " + STUDENT[1] + " is late for sc... | def sentOutPage():
| button1.grid_forget()
button2.grid_forget()
listEmails = []
listEmails.append(STUDENT[2])
listEmails.append("#admission@swis.cn")
time = datetime.datetime.now().strftime('%H:%M:%S')
sendEmail("LATE STUDENT - " + STUDENT[0],\
"Hello,\n\n" + STUDENT[0] + " from " + STUDENT[1] + " is late for school on " + date\
... | sentOutPage)
button1.grid(row=1,pady=10)
global button2
button2 = Button(text="That's not me",command=secMainPage)
button2.grid(row=2,pady=10)
#Append email addresses and call sendEmail function to send emails
def sentOutPage():
| 64 | 64 | 166 | 5 | 58 | Pteroindix/L.A.S.T. | Program_v3.py | Python | sentOutPage | sentOutPage | 113 | 127 | 113 | 113 | 6b9f1469dd4f32fc20480aec19095ea9584fd811 | bigcode/the-stack | train |
49a4bc781c3219bd0e128db7 | train | function | def confirmPage():
value2 = "\n{0} from {1}\n\n\tIs this you? Click the buttom to confirm.\t\n".format(STUDENT[0], STUDENT[1])
textLabel.config(text=value2)
textLabel.grid(row=0,padx=50)
global button1
button1 = Button(text="Confirm",command=sentOutPage)
button1.grid(row=1,pady=10)
global button2
button2 = Butt... | def confirmPage():
| value2 = "\n{0} from {1}\n\n\tIs this you? Click the buttom to confirm.\t\n".format(STUDENT[0], STUDENT[1])
textLabel.config(text=value2)
textLabel.grid(row=0,padx=50)
global button1
button1 = Button(text="Confirm",command=sentOutPage)
button1.grid(row=1,pady=10)
global button2
button2 = Button(text="That's not... | .execute(query)
for each in cursor:
if ID_Number == each[0]:
return each[1], each[2], each[3]
except mysql.connector.Error as err:
print("Error:", err.msg)
#Allow the guards to confirm; protection for trigger by mistake
def confirmPage():
| 64 | 64 | 122 | 4 | 59 | Pteroindix/L.A.S.T. | Program_v3.py | Python | confirmPage | confirmPage | 101 | 110 | 101 | 101 | eb046e16cf6d155a4b8a6e6fcddc20d48e79282f | bigcode/the-stack | train |
8b07f746b12c94e3ce5464f6 | train | function | def sendEmail(title,messages,toAddr):
fromAddr= r'1121134659@qq.com' # sender's email address (using personal QQmail at the moment)
password = r'mvuewzosgrqwfjjc' # sender's email passwords
smtpServer = 'smtp.qq.com' # SMTP server
server = smtplib.SMTP(smtpServer, 25)
msg = MIMEText(messages, 'plain', 'utf-8')
... | def sendEmail(title,messages,toAddr):
| fromAddr= r'1121134659@qq.com' # sender's email address (using personal QQmail at the moment)
password = r'mvuewzosgrqwfjjc' # sender's email passwords
smtpServer = 'smtp.qq.com' # SMTP server
server = smtplib.SMTP(smtpServer, 25)
msg = MIMEText(messages, 'plain', 'utf-8')
if len(toAddr) == 1: # testing whethe... | the gates at " + time + ".\n\n\nSWIS Late System",\
listEmails)
value3="\nEmails have sent to admission office and your first class teacher."
textLabel.config(text=value3)
timer = threading.Timer(2,secMainPage)
timer.start()
#Send email function
def sendEmail(title,messages,toAddr):
| 72 | 72 | 243 | 9 | 62 | Pteroindix/L.A.S.T. | Program_v3.py | Python | sendEmail | sendEmail | 130 | 149 | 130 | 130 | a45ab2ab7bf15b144a221b144d8ffdd2c607e7e6 | bigcode/the-stack | train |
5017a091c1d2e6199ca85791 | train | function | def secMainPage():
button1.grid_forget()
button2.grid_forget()
value = "\n\n\nWelcome to SWIS Late System: L.A.S.T\n\n\nPlease scan your card if you are late. Detecting..."
textLabel.config(text=value)
if cardDetected == True:
timer = threading.Timer(2,confirmPage)
timer.start()
| def secMainPage():
| button1.grid_forget()
button2.grid_forget()
value = "\n\n\nWelcome to SWIS Late System: L.A.S.T\n\n\nPlease scan your card if you are late. Detecting..."
textLabel.config(text=value)
if cardDetected == True:
timer = threading.Timer(2,confirmPage)
timer.start()
| message using TLS
#server.set_debuglevel(1)
server.login(fromAddr, password) # login to sender's email sever
server.sendmail(fromAddr,toAddr, msg.as_string()) # send the email
print("Email sent.")
server.quit()
#Use for looping
def secMainPage():
| 64 | 64 | 76 | 5 | 58 | Pteroindix/L.A.S.T. | Program_v3.py | Python | secMainPage | secMainPage | 152 | 159 | 152 | 152 | 3fe6b7daa62756adac0af1fa3330c2d09a83159f | bigcode/the-stack | train |
daac79af866f28dc7841d695 | train | function | def scanner():
reader = SimpleMFRC522()
try:
while True:
print("Detecting...")
id, text = reader.read()
print("UID: ", id)
return id
except KeyboardInterrupt:
print('\t')
GPIO.cleanup()
| def scanner():
| reader = SimpleMFRC522()
try:
while True:
print("Detecting...")
id, text = reader.read()
print("UID: ", id)
return id
except KeyboardInterrupt:
print('\t')
GPIO.cleanup()
| ENT
STUDENT = sqlconnection(stuID,DAYNUM) #connect to database
#print(cardDetected)
#print(studentName + ' ' + studentGrade)
if cardDetected == True:
timer = threading.Timer(2,confirmPage)
timer.start()
#Reading RFID tag
def scanner():
| 64 | 64 | 55 | 3 | 60 | Pteroindix/L.A.S.T. | Program_v3.py | Python | scanner | scanner | 70 | 80 | 70 | 70 | 39b016f5b0f30d6438424220325235e3f3e916d1 | bigcode/the-stack | train |
829691c01f21baaebc3b50e5 | train | class | class VcsRecipe(PipBaseRecipe):
def __init__(self, *args, **kwargs):
super(VcsRecipe, self).__init__(*args, **kwargs)
self.pythons = ['python2']
self.name = 'vcs'
self.version = '0.4.0'
self.sha256 = '5e2e84d1448bd969a383796c62719952' \
'348cc9742f818f1... | class VcsRecipe(PipBaseRecipe):
| def __init__(self, *args, **kwargs):
super(VcsRecipe, self).__init__(*args, **kwargs)
self.pythons = ['python2']
self.name = 'vcs'
self.version = '0.4.0'
self.sha256 = '5e2e84d1448bd969a383796c62719952' \
'348cc9742f818f1bc95e94faf3d45451'
| from .base import PipBaseRecipe
class VcsRecipe(PipBaseRecipe):
| 17 | 64 | 111 | 9 | 7 | stangelandcl/hardhat | hardhat/recipes/python/vcs.py | Python | VcsRecipe | VcsRecipe | 4 | 12 | 4 | 4 | 85029291ba7572ca8c309158a149d14206fb2728 | bigcode/the-stack | train |
45a6ee49020c586f0de2d8e4 | train | class | class AccountInternalInterface(object):
def fw_getLeft(self): raise NotImplementedError
def fw_getRight(self): raise NotImplementedError
| class AccountInternalInterface(object):
| def fw_getLeft(self): raise NotImplementedError
def fw_getRight(self): raise NotImplementedError
| & contributors.
from typing import TypeVar, Union
from imapfw import runtime
from imapfw.types.repository import loadRepository
from .folder import Folders
# Annotations.
from imapfw.types.repository import Repository
AccountClass = TypeVar('Account based class')
class AccountInternalInterface(object):
| 64 | 64 | 32 | 6 | 58 | paralax/imapfw | imapfw/types/account.py | Python | AccountInternalInterface | AccountInternalInterface | 18 | 20 | 18 | 18 | ae301533e8aaf31c595685cb6f4f6abefa16f9ba | bigcode/the-stack | train |
1d49e194e80af06e24ae0a1c | train | class | class Account(AccountInterface, AccountInternalInterface):
"""The Account base class.
The namespace `fw_` is reserved for the framework internals."""
left = None
right = None
def fw_getSide(self, side: str) -> Repository:
if side == 'left':
return self.fw_getLeft()
if ... | class Account(AccountInterface, AccountInternalInterface):
| """The Account base class.
The namespace `fw_` is reserved for the framework internals."""
left = None
right = None
def fw_getSide(self, side: str) -> Repository:
if side == 'left':
return self.fw_getLeft()
if side == 'right':
return self.fw_getRight()
... | def fw_getLeft(self): raise NotImplementedError
def fw_getRight(self): raise NotImplementedError
class AccountInterface(object):
def getClassName(self): raise NotImplementedError
def syncFolders(self): raise NotImplementedError
class Account(AccountInterface, AccountInternalInterface):
| 64 | 64 | 190 | 9 | 54 | paralax/imapfw | imapfw/types/account.py | Python | Account | Account | 28 | 58 | 28 | 28 | 85f00a3e21d73a823b424d4701c3aec2e8d6bdd7 | bigcode/the-stack | train |
2345ddbc907029a3313a376c | train | class | class AccountInterface(object):
def getClassName(self): raise NotImplementedError
def syncFolders(self): raise NotImplementedError
| class AccountInterface(object):
| def getClassName(self): raise NotImplementedError
def syncFolders(self): raise NotImplementedError
| import Folders
# Annotations.
from imapfw.types.repository import Repository
AccountClass = TypeVar('Account based class')
class AccountInternalInterface(object):
def fw_getLeft(self): raise NotImplementedError
def fw_getRight(self): raise NotImplementedError
class AccountInterface(object):
| 64 | 64 | 29 | 5 | 58 | paralax/imapfw | imapfw/types/account.py | Python | AccountInterface | AccountInterface | 23 | 25 | 23 | 23 | c3cbb6b102d2eab086854109f67a478d762a11bd | bigcode/the-stack | train |
3b205eac7abb4b824b904652 | train | function | def loadAccount(obj: Union[AccountClass, str]) -> Account:
if isinstance(obj, str):
obj = runtime.rascal.get(obj, [Account, dict])
try:
if issubclass(obj, Account):
cls_account = obj
else:
raise TypeError()
except TypeError:
try:
if not ... | def loadAccount(obj: Union[AccountClass, str]) -> Account:
| if isinstance(obj, str):
obj = runtime.rascal.get(obj, [Account, dict])
try:
if issubclass(obj, Account):
cls_account = obj
else:
raise TypeError()
except TypeError:
try:
if not issubclass(obj, dict):
raise TypeError()
... | self.__class__.__name__
def init(self) -> None:
"""Override this method to make initialization in the rascal."""
pass
def syncFolders(self, folders: Folders) -> Folders:
return folders
def loadAccount(obj: Union[AccountClass, str]) -> Account:
| 64 | 64 | 172 | 15 | 48 | paralax/imapfw | imapfw/types/account.py | Python | loadAccount | loadAccount | 61 | 88 | 61 | 62 | 560f5bffb41483ff82f71668fb4442578df57f2f | bigcode/the-stack | train |
fe6275563dbc9a19210a2d22 | train | class | class Migration(migrations.Migration):
dependencies = [
('profiles_api', '0002_profilefeed'),
]
operations = [
migrations.RenameModel(
old_name='ProfileFeed',
new_name='ProfileFeedItem',
),
]
| class Migration(migrations.Migration):
| dependencies = [
('profiles_api', '0002_profilefeed'),
]
operations = [
migrations.RenameModel(
old_name='ProfileFeed',
new_name='ProfileFeedItem',
),
]
| # Generated by Django 2.2 on 2020-05-07 20:57
from django.db import migrations
class Migration(migrations.Migration):
| 34 | 64 | 53 | 7 | 26 | AndreWicaksono/profiles-rest-api | profiles_api/migrations/0003_auto_20200507_2057.py | Python | Migration | Migration | 6 | 17 | 6 | 7 | 597e830dc504605362fda288b989c94dc605a80d | bigcode/the-stack | train |
33b0d960ad315aef5aa0e811 | train | function | def _mp_fn(index):
# For xla_spawn (TPUs)
main()
| def _mp_fn(index):
# For xla_spawn (TPUs)
| main()
| _args.dataset_config_name
kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
else:
kwargs["dataset"] = data_args.dataset_name
trainer.push_to_hub(**kwargs)
def _mp_fn(index):
# For xla_spawn (TPUs)
| 64 | 64 | 19 | 16 | 48 | CaoHoangTung/transformers | examples/pytorch/language-modeling/run_clm.py | Python | _mp_fn | _mp_fn | 483 | 485 | 483 | 484 | 13fb2bf6d4faa81d8cc781a163be0a6ab3f2ef14 | bigcode/the-stack | train |
a3b8bc5ebcf81da7a9c21033 | train | function | def main():
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if len(sys.a... | def main():
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
| parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
model_args, data_args, trai... | "help": "The percentage of the train set used as validation set in case there's no validation split"
},
)
preprocessing_num_workers: Optional[int] = field(
default=None,
metadata={"help": "The number of processes to use for the preprocessing."},
)
def __post_init__(self):
... | 256 | 256 | 2,918 | 49 | 207 | CaoHoangTung/transformers | examples/pytorch/language-modeling/run_clm.py | Python | main | main | 184 | 480 | 184 | 188 | 9c02fa11d75a12acdb940d9d84a2d054df824e4a | bigcode/the-stack | train |
fe45a6fe7ff6edf8f8533817 | train | class | @dataclass
class DataTrainingArguments:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
dataset_name: Optional[str] = field(
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
)
dataset_config_na... | @dataclass
class DataTrainingArguments:
| """
Arguments pertaining to what data we are going to input our model for training and eval.
"""
dataset_name: Optional[str] = field(
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
)
dataset_config_name: Optional[str] = field(
defau... | backed by the tokenizers library) or not."},
)
model_revision: str = field(
default="main",
metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
)
use_auth_token: bool = field(
default=False,
metadata={
"help":... | 178 | 178 | 595 | 8 | 170 | CaoHoangTung/transformers | examples/pytorch/language-modeling/run_clm.py | Python | DataTrainingArguments | DataTrainingArguments | 118 | 181 | 118 | 119 | c0d7ebf9534f425997e2ca58238004889a6836ad | bigcode/the-stack | train |
a67efdccf3571b862f82de4b | train | class | @dataclass
class ModelArguments:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
"""
model_name_or_path: Optional[str] = field(
default=None,
metadata={
"help": "The model checkpoint for weights initialization."
... | @dataclass
class ModelArguments:
| """
Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
"""
model_name_or_path: Optional[str] = field(
default=None,
metadata={
"help": "The model checkpoint for weights initialization."
"Don't set if you want to... | _FOR_CAUSAL_LM_MAPPING,
AutoConfig,
AutoModelForCausalLM,
AutoTokenizer,
HfArgumentParser,
Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from transformers.testing_utils import CaptureLogger
from transformers.trainer_utils import get_last_checkpoint
from transformers.util... | 151 | 151 | 505 | 7 | 144 | CaoHoangTung/transformers | examples/pytorch/language-modeling/run_clm.py | Python | ModelArguments | ModelArguments | 61 | 115 | 61 | 62 | 62b04df4c5fe93af0516b786eed0d9ff8de8cc8e | bigcode/the-stack | train |
242543afc072db7b321c3295 | train | class | class RunDBInterface(ABC):
kind = ""
@abstractmethod
def connect(self, secrets=None):
return self
@abstractmethod
def store_log(self, uid, project="", body=None, append=False):
pass
@abstractmethod
def get_log(self, uid, project="", offset=0, size=0):
pass
@ab... | class RunDBInterface(ABC):
| kind = ""
@abstractmethod
def connect(self, secrets=None):
return self
@abstractmethod
def store_log(self, uid, project="", body=None, append=False):
pass
@abstractmethod
def get_log(self, uid, project="", offset=0, size=0):
pass
@abstractmethod
def store_... | # Copyright 2018 Iguazio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | 183 | 256 | 2,682 | 7 | 175 | zjzh/mlrun | mlrun/db/base.py | Python | RunDBInterface | RunDBInterface | 28 | 484 | 28 | 28 | 3e39d003f072d0fd360a26d4452449c632ed8b97 | bigcode/the-stack | train |
1745ec0194d970124af72cd7 | train | class | class RunDBError(Exception):
pass
| class RunDBError(Exception):
| pass
| .
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import warnings
from abc import ABC, abstractmethod
from typing import List, Optional, Union
from mlrun.api import schemas
from mlrun.api.schemas import ModelEndpoint
class RunDBError(Exception):
| 64 | 64 | 9 | 6 | 57 | zjzh/mlrun | mlrun/db/base.py | Python | RunDBError | RunDBError | 24 | 25 | 24 | 24 | e1fd9c85a1a0733ce0108bceb64317a1029a8808 | bigcode/the-stack | train |
4cf28438d810f3b5bd8ba48f | train | function | def fig_lcf(out: Dataset, offset: float=0.5,
annotate: bool=True, fontsize: float=8,
fig_pars: FigPars=None, **fig_kws: dict) -> Tuple[Figure,Axes]:
"""Plots the results of linear combination fit (LCF) on a collecton.
Parameters
----------
out
Valid Dataset from :func:`... | def fig_lcf(out: Dataset, offset: float=0.5,
annotate: bool=True, fontsize: float=8,
fig_pars: FigPars=None, **fig_kws: dict) -> Tuple[Figure,Axes]:
| """Plots the results of linear combination fit (LCF) on a collecton.
Parameters
----------
out
Valid Dataset from :func:`~araucaria.fit.lcfit.lcf`.
offset
Offset step value for plots.
The default is 0.5.
annotate
Indicates if the plot should be annotated.
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from typing import Tuple
from numpy import ptp
from matplotlib.pyplot import Axes, Figure
from .. import Group, Dataset
from .template import fig_xas_template, FigPars
from ..utils import check_objattrs
def fig_lcf(out: Dataset, offset: float=0.5,
annotate: bool=Tr... | 112 | 256 | 1,198 | 52 | 59 | marcoalsina/araucaria | araucaria/plot/fig_lcf.py | Python | fig_lcf | fig_lcf | 10 | 125 | 10 | 12 | 2e6d595b8dde9dfdc63b18d97da9ccdcf393a8fe | bigcode/the-stack | train |
aa06d57fb28e714dbd75b4c1 | train | class | class GraphicFrame(BaseShape):
"""Container shape for table, chart, smart art, and media objects.
Corresponds to a ``<p:graphicFrame>`` element in the shape tree.
"""
@property
def chart(self):
"""The |Chart| object containing the chart in this graphic frame.
Raises |ValueError| i... | class GraphicFrame(BaseShape):
| """Container shape for table, chart, smart art, and media objects.
Corresponds to a ``<p:graphicFrame>`` element in the shape tree.
"""
@property
def chart(self):
"""The |Chart| object containing the chart in this graphic frame.
Raises |ValueError| if this graphic frame does not c... | # encoding: utf-8
"""Graphic Frame shape and related objects.
A graphic frame is a common container for table, chart, smart art, and media
objects.
"""
from pptx.enum.shapes import MSO_SHAPE_TYPE
from pptx.shapes.base import BaseShape
from pptx.shared import ParentedElementProxy
from pptx.spec import (
GRAPHIC_D... | 113 | 236 | 789 | 6 | 106 | StephanEggermont/python-pptx | pptx/shapes/graphfrm.py | Python | GraphicFrame | GraphicFrame | 20 | 114 | 20 | 20 | e0c6064d308895bb5a04e546ba813de53d44e989 | bigcode/the-stack | train |
b9cd15eeb3afef202ef5e439 | train | class | class _OleFormat(ParentedElementProxy):
"""Provides attributes on an embedded OLE object."""
def __init__(self, graphicData, parent):
super(_OleFormat, self).__init__(graphicData, parent)
self._graphicData = graphicData
@property
def blob(self):
"""Optional bytes of OLE object,... | class _OleFormat(ParentedElementProxy):
| """Provides attributes on an embedded OLE object."""
def __init__(self, graphicData, parent):
super(_OleFormat, self).__init__(graphicData, parent)
self._graphicData = graphicData
@property
def blob(self):
"""Optional bytes of OLE object, suitable for loading or saving as a fil... | object contained in this graphic frame. Raises
|ValueError| if this graphic frame does not contain a table.
"""
if not self.has_table:
raise ValueError("shape does not contain a table")
tbl = self._element.graphic.graphicData.tbl
return Table(tbl, self)
class _OleFor... | 75 | 75 | 253 | 10 | 65 | StephanEggermont/python-pptx | pptx/shapes/graphfrm.py | Python | _OleFormat | _OleFormat | 117 | 145 | 117 | 117 | d7ea47cb7911e7e61dafd760c7d20372f0b52be7 | bigcode/the-stack | train |
c8be008fa94005d6b4314a9b | train | function | def get_bn_decay(batch):
bn_momentum = tf.train.exponential_decay(
BN_INIT_DECAY,
batch*BATCH_SIZE,
BN_DECAY_DECAY_STEP,
BN_DECAY_DECAY_RATE,
staircase=True)
bn_decay = tf.minimum(BN_DECAY_CLIP, 1 - bn_... | def get_bn_decay(batch):
| bn_momentum = tf.train.exponential_decay(
BN_INIT_DECAY,
batch*BATCH_SIZE,
BN_DECAY_DECAY_STEP,
BN_DECAY_DECAY_RATE,
staircase=True)
bn_decay = tf.minimum(BN_DECAY_CLIP, 1 - bn_momentum)
return bn_d... | the dataset.
DECAY_STEP, # Decay step.
DECAY_RATE, # Decay rate.
staircase=True)
learning_rate = tf.maximum(learning_rate, 0.00001) # CLIP THE LEARNING RATE!
return learning_rate
def get_bn_decay(batch):
| 64 | 64 | 75 | 6 | 57 | lingzhang1/ContrastNet | train_clusternet.py | Python | get_bn_decay | get_bn_decay | 92 | 100 | 92 | 92 | e19939a19187fde6cc6455660ac8e81fd3354657 | bigcode/the-stack | train |
b979b13778cfcc1674d5e87e | train | function | def train_one_epoch(sess, ops, train_writer):
""" ops: dict mapping from string to tf ops """
is_training = True
# Shuffle train files
train_file_idxs = np.arange(0, len(LABELS))
np.random.shuffle(train_file_idxs)
current_data = np.empty([len(LABELS), NUM_POINT, 3], dtype=float)
current_la... | def train_one_epoch(sess, ops, train_writer):
| """ ops: dict mapping from string to tf ops """
is_training = True
# Shuffle train files
train_file_idxs = np.arange(0, len(LABELS))
np.random.shuffle(train_file_idxs)
current_data = np.empty([len(LABELS), NUM_POINT, 3], dtype=float)
current_label = np.empty([len(LABELS),1], dtype=int)
... | ': pred,
'loss': loss,
'train_op': train_op,
'merged': merged,
'step': batch}
for epoch in range(MAX_EPOCH):
log_string('**** EPOCH %03d ****' % (epoch))
sys.stdout.flush()
train_one_epoch(sess, ops, train_writer)
... | 190 | 190 | 636 | 11 | 179 | lingzhang1/ContrastNet | train_clusternet.py | Python | train_one_epoch | train_one_epoch | 183 | 238 | 183 | 183 | f089f244c7ee28850e433708b2e6e434b0ef5472 | bigcode/the-stack | train |
545d8c2dfe49f6c6454f4b6b | train | function | def get_learning_rate(batch):
learning_rate = tf.train.exponential_decay(
BASE_LEARNING_RATE, # Base learning rate.
batch * BATCH_SIZE, # Current index into the dataset.
DECAY_STEP, # Decay step.
DECAY_RATE, ... | def get_learning_rate(batch):
| learning_rate = tf.train.exponential_decay(
BASE_LEARNING_RATE, # Base learning rate.
batch * BATCH_SIZE, # Current index into the dataset.
DECAY_STEP, # Decay step.
DECAY_RATE, # Decay rate.
... | = open("cluster_label.txt", "r")
LABELS = read_flabel.readlines()
LABELS = [int(i) for i in LABELS]
def log_string(out_str):
LOG_FOUT.write(out_str+'\n')
LOG_FOUT.flush()
print(out_str)
def get_learning_rate(batch):
| 64 | 64 | 98 | 6 | 58 | lingzhang1/ContrastNet | train_clusternet.py | Python | get_learning_rate | get_learning_rate | 82 | 90 | 82 | 82 | 4d9958eaed4eb36ef007f6055fefd8f89f7e6a8b | bigcode/the-stack | train |
1a4f96ce9be65893e9a7f673 | train | function | def log_string(out_str):
LOG_FOUT.write(out_str+'\n')
LOG_FOUT.flush()
print(out_str)
| def log_string(out_str):
| LOG_FOUT.write(out_str+'\n')
LOG_FOUT.flush()
print(out_str)
| /modelnet40_ply_hdf5_2048_cut/test_files.txt'))
# Get labels
LABELS = []
read_flabel = open("cluster_label.txt", "r")
LABELS = read_flabel.readlines()
LABELS = [int(i) for i in LABELS]
def log_string(out_str):
| 64 | 64 | 27 | 6 | 58 | lingzhang1/ContrastNet | train_clusternet.py | Python | log_string | log_string | 76 | 79 | 76 | 76 | 5d9fdb471434409730214250beed28ec170e83fa | bigcode/the-stack | train |
305f4f4fea906655a3ec8a0c | train | function | def train():
with tf.Graph().as_default():
with tf.device('/gpu:'+str(GPU_INDEX)):
pointclouds_pl, labels_pl = MODEL.placeholder_inputs(BATCH_SIZE, NUM_POINT)
is_training_pl = tf.placeholder(tf.bool, shape=())
print(is_training_pl)
# Note the global_step=batc... | def train():
| with tf.Graph().as_default():
with tf.device('/gpu:'+str(GPU_INDEX)):
pointclouds_pl, labels_pl = MODEL.placeholder_inputs(BATCH_SIZE, NUM_POINT)
is_training_pl = tf.placeholder(tf.bool, shape=())
print(is_training_pl)
# Note the global_step=batch parameter t... | [int(i) for i in LABELS]
def log_string(out_str):
LOG_FOUT.write(out_str+'\n')
LOG_FOUT.flush()
print(out_str)
def get_learning_rate(batch):
learning_rate = tf.train.exponential_decay(
BASE_LEARNING_RATE, # Base learning rate.
batch * BATCH_SIZE, # C... | 213 | 213 | 713 | 3 | 209 | lingzhang1/ContrastNet | train_clusternet.py | Python | train | train | 102 | 180 | 102 | 102 | 03f0a4d5a354606bb0d24b9b6459d0a026a5fd85 | bigcode/the-stack | train |
c3e9e96aba430b97d1f59131 | train | class | class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
#Load the UI Page
uic.loadUi('wetbar.ui', self)
if have_bmp183:
self.bmp = bmp183()
self.timer = QtCore.QTimer()
self.timer... | class MainWindow(QtWidgets.QMainWindow):
| def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
#Load the UI Page
uic.loadUi('wetbar.ui', self)
if have_bmp183:
self.bmp = bmp183()
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.update)
self... | /bin/python3
from PyQt5 import QtWidgets, uic, QtCore
import sys
import os
have_bmp183 = False
try:
from pigbmp183 import bmp183
have_bmp183 = True
except:
pass
class MainWindow(QtWidgets.QMainWindow):
| 64 | 64 | 187 | 9 | 54 | dakoner/wetbar | wetbar_gui.py | Python | MainWindow | MainWindow | 13 | 44 | 13 | 14 | c7e04ab3cd1007e84da7bf87f1951d01e39ec427 | bigcode/the-stack | train |
39ab20be94cd3324f71f7618 | train | function | def main():
app = QtWidgets.QApplication(sys.argv)
main = MainWindow()
main.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowCloseButtonHint);
main.showFullScreen();
sys.exit(app.exec_())
| def main():
| app = QtWidgets.QApplication(sys.argv)
main = MainWindow()
main.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowCloseButtonHint);
main.showFullScreen();
sys.exit(app.exec_())
| .t)
def measure(self):
if have_bmp183:
self.bmp.measure_pressure()
if (self.bmp.ID != 85):
print("Communication error!")
print("Measurement may not be reliable. Chip ID is incorrect.")
else:
self.t = bmp.temperature
def mai... | 63 | 64 | 59 | 3 | 59 | dakoner/wetbar | wetbar_gui.py | Python | main | main | 48 | 53 | 48 | 48 | 3d399985acc11124e118bf799538e4a462608e4b | bigcode/the-stack | train |
1638d76bf803e937226dff66 | train | function | @register.filter(name='markdown')
def markdown_format(text):
return mark_safe(markdown.markdown(text))
| @register.filter(name='markdown')
def markdown_format(text):
| return mark_safe(markdown.markdown(text))
| from django import template
from django.utils.safestring import mark_safe
import markdown
register = template.Library()
@register.filter(name='markdown')
def markdown_format(text):
| 36 | 64 | 22 | 12 | 24 | SuperLeet-CTF/SuperLeet-CTF | contests/templatetags/contests_tags.py | Python | markdown_format | markdown_format | 8 | 10 | 8 | 9 | 090a84c7e908358e00059f80fa93c666f930e238 | bigcode/the-stack | train |
b2ad6d2dc58570694e8f853f | train | class | class Grumpy(Dummy):
"""
Dummy script that simulates a slave component.
"""
def __init__(self):
super(Grumpy, self).__init__()
self.component_name = "GRUMPY"
self.principal_conf_name = "grumpy-site"
self.principal_name = "grumpy.grumpy.kerberos.principal"
self.keytab_conf_name = "grumpy-sit... | class Grumpy(Dummy):
| """
Dummy script that simulates a slave component.
"""
def __init__(self):
super(Grumpy, self).__init__()
self.component_name = "GRUMPY"
self.principal_conf_name = "grumpy-site"
self.principal_name = "grumpy.grumpy.kerberos.principal"
self.keytab_conf_name = "grumpy-site"
self.keytab_na... | AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Ambari Agent
"""
# Python Imports
# Local Imports
from resource_management.libraries.script.dummy import Dummy
class Grumpy(Dummy)... | 64 | 64 | 103 | 6 | 57 | likenamehaojie/Apache-Ambari-ZH | ambari-server/src/main/resources/stacks/PERF/1.0/services/GRUMPY/package/scripts/dwarf.py | Python | Grumpy | Grumpy | 28 | 39 | 28 | 28 | 05ec60c13ee2848068b38632568623c6c1d11382 | bigcode/the-stack | train |
8f2f8f7037254ee684068bf1 | train | class | class Test(unittest.TestCase):
def test(self):
import numpy as np
from openaerostruct.geometry.utils import generate_mesh
from openaerostruct.geometry.geometry_group import Geometry
from openaerostruct.aerodynamics.aero_groups import AeroPoint
import openmdao.api as om
... | class Test(unittest.TestCase):
| def test(self):
import numpy as np
from openaerostruct.geometry.utils import generate_mesh
from openaerostruct.geometry.geometry_group import Geometry
from openaerostruct.aerodynamics.aero_groups import AeroPoint
import openmdao.api as om
# Instantiate the problem ... | from openmdao.utils.assert_utils import assert_rel_error
import unittest
class Test(unittest.TestCase):
| 21 | 256 | 1,214 | 6 | 14 | mdolab/OpenAeroStruct | openaerostruct/tests/test_v1_aero_opt.py | Python | Test | Test | 5 | 116 | 5 | 5 | 35ed1938d6608a8df93eb042f29a8fd02ffe22ba | bigcode/the-stack | train |
975dfb6216b23efe6890a10d | train | class | class Migration(migrations.Migration):
dependencies = [
('main', '0004_demodata_20150215_2211'),
]
operations = [
migrations.CreateModel(
name='Reminder',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary... | class Migration(migrations.Migration):
| dependencies = [
('main', '0004_demodata_20150215_2211'),
]
operations = [
migrations.CreateModel(
name='Reminder',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('date', mo... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| 31 | 64 | 196 | 7 | 23 | oronibrian/Tenant | main/migrations/0005_reminder_remindersbytenant.py | Python | Migration | Migration | 7 | 37 | 7 | 8 | 518aac3db8fe2b6ab882644cb1f18b869e035dec | bigcode/the-stack | train |
364a15e5785d3e7587e56545 | train | class | class _DenseASPPConv(nn.Sequential):
def __init__(self,
in_channels,
inter_channels,
out_channels,
atrous_rate,
drop_rate=0.1,
norm_cfg=dict(type='GN', num_groups=32, requires_grad=True),
act_cfg=... | class _DenseASPPConv(nn.Sequential):
| def __init__(self,
in_channels,
inter_channels,
out_channels,
atrous_rate,
drop_rate=0.1,
norm_cfg=dict(type='GN', num_groups=32, requires_grad=True),
act_cfg=dict(type='ReLU', inplace=True)):
... | import torch.nn.functional as F
from mmcv.cnn import ConvModule, xavier_init
from mmcv.runner import auto_fp16
from ..builder import NECKS
# norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
# act_cfg = dict(type='ReLU', inplace=True),
class _DenseASPPConv(nn.Sequential):
| 77 | 78 | 261 | 9 | 68 | NEUdeep/TileDetection | mmdet/models/necks/acfpn.py | Python | _DenseASPPConv | _DenseASPPConv | 15 | 57 | 15 | 16 | 024b4c3ba1edd85a13a81c47c062943e7dab509e | bigcode/the-stack | train |
2f50f4c568d78ee757019af4 | train | class | class _DenseASPPBlock(nn.Module):
def __init__(
self,
in_channels=2048,
inter_channels1=512,
inter_channels2=256,
norm_cfg=dict(type='GN', num_groups=32, requires_grad=True),
):
super(_DenseASPPBlock, self).__init__()
self.aspp_3 = _De... | class _DenseASPPBlock(nn.Module):
| def __init__(
self,
in_channels=2048,
inter_channels1=512,
inter_channels2=256,
norm_cfg=dict(type='GN', num_groups=32, requires_grad=True),
):
super(_DenseASPPBlock, self).__init__()
self.aspp_3 = _DenseASPPConv(in_channels, inter_chan... | 1,
stride=1,
padding=0,
dilation=1,
groups=1,
norm_cfg=norm_cfg,
act_cfg=act_cfg),
),
self.add_module(
'conv2',
ConvModule(
inter_channels,
out_channels... | 164 | 164 | 548 | 9 | 154 | NEUdeep/TileDetection | mmdet/models/necks/acfpn.py | Python | _DenseASPPBlock | _DenseASPPBlock | 60 | 121 | 60 | 61 | 9e50025e9d7ed115d683462d5f1ccc3620d7f6dd | bigcode/the-stack | train |
7ac7171cbbfa1da3cf8dd653 | train | class | @NECKS.register_module()
class ACFPN(nn.Module):
def __init__(self,
in_channels,
out_channels,
num_outs,
start_level=0,
end_level=-1,
add_extra_convs=False,
extra_convs_on_inputs=True,
... | @NECKS.register_module()
class ACFPN(nn.Module):
| def __init__(self,
in_channels,
out_channels,
num_outs,
start_level=0,
end_level=-1,
add_extra_convs=False,
extra_convs_on_inputs=True,
relu_before_extra_convs=False,
... | ,
groups=1,
#conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
# norm_cfg=norm_cfg if not self.no_norm_on_lateral else None,
# act_cfg=act_cfg,
# inplace=False
)
def forward(self, x):
aspp3 = self.aspp_3(x)
x = torch.cat([aspp3, x]... | 256 | 256 | 1,517 | 14 | 241 | NEUdeep/TileDetection | mmdet/models/necks/acfpn.py | Python | ACFPN | ACFPN | 124 | 293 | 124 | 126 | 19fbb1f948095b0032f26457d22027de2c2a1a6c | bigcode/the-stack | train |
ceff0b05f0eee4a1f54a816b | train | function | def build_vocab(vocab_min, infile, vocab_filename):
"""
INPUTS:
vocab_min: how many documents a word must appear in to be kept
infile: (training) data file to build vocabulary from
vocab_filename: name for the file to output
"""
with open(infile, 'r') as csvfil... | def build_vocab(vocab_min, infile, vocab_filename):
| """
INPUTS:
vocab_min: how many documents a word must appear in to be kept
infile: (training) data file to build vocabulary from
vocab_filename: name for the file to output
"""
with open(infile, 'r') as csvfile:
reader = csv.reader(csvfile)
#header
... | """
This script reads a sorted training dataset and builds a vocabulary of terms of given size
Output: txt file with vocab words
Drops any token not appearing in at least vocab_min notes
This script could probably be replaced by using sklearn's CountVectorizer to build a vocab
"""
import csv
im... | 110 | 200 | 668 | 12 | 97 | franzbischoff/caml-mimic | dataproc/build_vocab.py | Python | build_vocab | build_vocab | 18 | 89 | 18 | 18 | 889c228b17cf14c8ae68db711feacae6b235fade | bigcode/the-stack | train |
078210efe31d0326b81afc33 | train | function | def extractMelody(data_file, fs=44100, hop=128):
# Load 30s sample and extract melody
mp3_f = urllib.request.urlretrieve(data_file)[0]
audio, sr = librosa.load(mp3_f, sr=44100, mono=True)
'''
Melodia Parameters
minfqr: minimum frequency in Hertz (default 55.0)
maxfqr: max... | def extractMelody(data_file, fs=44100, hop=128):
# Load 30s sample and extract melody
| mp3_f = urllib.request.urlretrieve(data_file)[0]
audio, sr = librosa.load(mp3_f, sr=44100, mono=True)
'''
Melodia Parameters
minfqr: minimum frequency in Hertz (default 55.0)
maxfqr: maximum frequency in Hertz (default 1760.0)
voicing: voicing tolerance. Greater values wil... | #!/usr/bin/env python
'''
Author: Alex Kim, Justin Salamon
Project: DeepMelodies
File: src/meloextract.py
Purpose: extract a melody
Borrowed heavily from Justin Salamon's
* [Melodia Jupyter Notebook](http://www.justinsalamon.com/news/melody-extraction-in-python-with-melodia)
'''
import urllib.r... | 130 | 165 | 550 | 28 | 101 | alexkim205/DeepSpotify | src/meloextract.py | Python | extractMelody | extractMelody | 20 | 66 | 20 | 22 | 35a1ccacaef5d0c9927ae4e3a045fb77f5e013a2 | bigcode/the-stack | train |
7b7520b086b83004185f4055 | train | function | def test_should_accept_improvements_given_benchmarks_in_the_old_format(capsys):
# Given
baseline = f"{FIXTURES_DIR}/old-csv-format/iosched/outdated-agp/benchmark.csv"
modified = f"{FIXTURES_DIR}/old-csv-format/iosched/updated-agp/benchmark.csv"
# When
argv = ["-b", baseline, "-m", modified]
ap... | def test_should_accept_improvements_given_benchmarks_in_the_old_format(capsys):
# Given
| baseline = f"{FIXTURES_DIR}/old-csv-format/iosched/outdated-agp/benchmark.csv"
modified = f"{FIXTURES_DIR}/old-csv-format/iosched/updated-agp/benchmark.csv"
# When
argv = ["-b", baseline, "-m", modified]
app.main(argv)
# Then
captured = capsys.readouterr()
assert "p-value is smaller th... | Then
captured = capsys.readouterr()
assert "p-value is greater than significance level" in captured.out
assert "we are lacking strong statistical evidence for improvements" in captured.out
def test_should_accept_improvements_given_benchmarks_in_the_old_format(capsys):
# Given
| 64 | 64 | 138 | 22 | 41 | dotanuki-labs/gradle-profiler-pttest | tests/test_app.py | Python | test_should_accept_improvements_given_benchmarks_in_the_old_format | test_should_accept_improvements_given_benchmarks_in_the_old_format | 27 | 40 | 27 | 29 | 810d282403de574e8a00b27e328ea932ee444014 | bigcode/the-stack | train |
05cc1cc6607e207aa5bebf9c | train | function | def test_should_report_execution_errors(caplog):
with pytest.raises(Exception):
# Given
baseline = f"{FIXTURES_DIR}/old-csv-format/iosched/outdated-agp/benchmark.csv"
modified = f"{FIXTURES_DIR}/old-csv-format/iosched/new-agp/benchmark.csv" # does not exist
# When
argv = ... | def test_should_report_execution_errors(caplog):
| with pytest.raises(Exception):
# Given
baseline = f"{FIXTURES_DIR}/old-csv-format/iosched/outdated-agp/benchmark.csv"
modified = f"{FIXTURES_DIR}/old-csv-format/iosched/new-agp/benchmark.csv" # does not exist
# When
argv = ["-b", baseline, "-m", modified]
app.main(... | baseline, "-m", modified]
app.main(argv)
# Then
captured = capsys.readouterr()
assert "p-value is smaller than significance level" in captured.out
assert "we have strong statistical evidence for improvements" in captured.out
def test_should_report_execution_errors(caplog):
| 64 | 64 | 127 | 9 | 54 | dotanuki-labs/gradle-profiler-pttest | tests/test_app.py | Python | test_should_report_execution_errors | test_should_report_execution_errors | 59 | 73 | 59 | 60 | 38ac0892b276d53cc230f7a273e8cfea184b8b42 | bigcode/the-stack | train |
8826e6c1299f52db056e5f18 | train | function | def test_should_accept_improvements_given_benchmarks_in_the_new_format(capsys):
# Given
baseline = f"{FIXTURES_DIR}/new-csv-format/h0/benchmark.csv"
modified = f"{FIXTURES_DIR}/new-csv-format/h1/benchmark.csv"
# When
argv = ["-b", baseline, "-m", modified]
app.main(argv)
# Then
captur... | def test_should_accept_improvements_given_benchmarks_in_the_new_format(capsys):
# Given
| baseline = f"{FIXTURES_DIR}/new-csv-format/h0/benchmark.csv"
modified = f"{FIXTURES_DIR}/new-csv-format/h1/benchmark.csv"
# When
argv = ["-b", baseline, "-m", modified]
app.main(argv)
# Then
captured = capsys.readouterr()
assert "p-value is smaller than significance level" in captured.... | # Then
captured = capsys.readouterr()
assert "p-value is smaller than significance level" in captured.out
assert "we have strong statistical evidence for improvements" in captured.out
def test_should_accept_improvements_given_benchmarks_in_the_new_format(capsys):
# Given
| 64 | 64 | 128 | 22 | 41 | dotanuki-labs/gradle-profiler-pttest | tests/test_app.py | Python | test_should_accept_improvements_given_benchmarks_in_the_new_format | test_should_accept_improvements_given_benchmarks_in_the_new_format | 43 | 56 | 43 | 45 | 23fc3284045157c4082085082d9d1d3db80631f1 | bigcode/the-stack | train |
996a9987adec272a72791bbd | train | function | def test_should_reject_improvements_given_benchmarks(capsys):
# Given
baseline = f"{FIXTURES_DIR}/old-csv-format/sdksearch/jdk8/benchmark.csv"
modified = f"{FIXTURES_DIR}/old-csv-format/sdksearch/jdk11/benchmark.csv"
# When
argv = ["-b", baseline, "-m", modified]
app.main(argv)
# Then
... | def test_should_reject_improvements_given_benchmarks(capsys):
# Given
| baseline = f"{FIXTURES_DIR}/old-csv-format/sdksearch/jdk8/benchmark.csv"
modified = f"{FIXTURES_DIR}/old-csv-format/sdksearch/jdk11/benchmark.csv"
# When
argv = ["-b", baseline, "-m", modified]
app.main(argv)
# Then
captured = capsys.readouterr()
assert "p-value is greater than signifi... | # test_app.py
import os
import pytest
from gradle_profiler_pttest import app
FIXTURES_DIR = f"{os.getcwd()}/tests/fixtures"
def test_should_reject_improvements_given_benchmarks(capsys):
# Given
| 55 | 64 | 132 | 19 | 36 | dotanuki-labs/gradle-profiler-pttest | tests/test_app.py | Python | test_should_reject_improvements_given_benchmarks | test_should_reject_improvements_given_benchmarks | 11 | 24 | 11 | 13 | 3c55e2f4eaeec4891337f240c2160c469aa62254 | bigcode/the-stack | train |
efa4dd6bef785b28ee6cbf9c | train | class | class TestRofi(unittest.TestCase):
def test_themes_finder(self):
rofi_file = "hapycolor/targets/rofi/__init__.py"
rofi_dir = pathlib.Path(rofi_file).parent
rasi_files = [t for t in rofi_dir.iterdir() if ".rasi" == t.suffix]
ThemeEnum = enum.Enum("ThemeEnum",
... | class TestRofi(unittest.TestCase):
| def test_themes_finder(self):
rofi_file = "hapycolor/targets/rofi/__init__.py"
rofi_dir = pathlib.Path(rofi_file).parent
rasi_files = [t for t in rofi_dir.iterdir() if ".rasi" == t.suffix]
ThemeEnum = enum.Enum("ThemeEnum",
[(t.stem.upper(), t.as_posix()... | import enum
import pathlib
import tests.helpers
import unittest
class TestRofi(unittest.TestCase):
| 21 | 64 | 162 | 8 | 12 | rvdz/hapycolor | tests/test_rofi.py | Python | TestRofi | TestRofi | 7 | 17 | 7 | 7 | 8b7035484e7866e8226ad52b132c23da6a3bd95d | bigcode/the-stack | train |
1af7c02676d888ccee255ba3 | train | class | class Project:
config = configparser.ConfigParser()
config.read("config.ini")
apptypes = json.loads(config.get("ProgramConfig", 'apptypes'))
src_filetypes = json.loads(config.get("ProgramConfig", 'src_filetypes'))
db_filetypes = json.loads(config.get("ProgramConfig", 'db_filetypes'))
query_impor... | class Project:
| config = configparser.ConfigParser()
config.read("config.ini")
apptypes = json.loads(config.get("ProgramConfig", 'apptypes'))
src_filetypes = json.loads(config.get("ProgramConfig", 'src_filetypes'))
db_filetypes = json.loads(config.get("ProgramConfig", 'db_filetypes'))
query_importance = config.... | import json
import ntpath
import os
import subprocess
import sys
import zipfile
from collections import OrderedDict
import configparser
from helpers.file import File
from helpers.logger import Logger
from helpers.searchwords import SearchLists
PATH = os.getcwd()
class Project:
| 58 | 256 | 1,430 | 3 | 55 | cqr-cryeye-forks/StaCoAn | src/helpers/project.py | Python | Project | Project | 18 | 149 | 18 | 18 | be061aec3a8c305c39486983dd51fddea4f5cb87 | bigcode/the-stack | train |
89b5284c001b7f5b94cfb5c5 | train | function | def get_formatted_name(first_name, last_name, middle_name=''):
"""Return a full name, neatly formatted."""
if middle_name:
full_name = f"{first_name} {middle_name} {last_name}"
else:
full_name = f"{first_name} {last_name}"
return full_name.title()
| def get_formatted_name(first_name, last_name, middle_name=''):
| """Return a full name, neatly formatted."""
if middle_name:
full_name = f"{first_name} {middle_name} {last_name}"
else:
full_name = f"{first_name} {last_name}"
return full_name.title()
| def get_formatted_name(first_name, last_name, middle_name=''):
| 15 | 64 | 69 | 15 | 0 | nv-krishna/python-crash-course | functions/optional_argument.py | Python | get_formatted_name | get_formatted_name | 1 | 7 | 1 | 1 | 2909030520b4b8f7fdd0d5f3a5210a9234a02b54 | bigcode/the-stack | train |
966b3a52efb2130079d14606 | train | class | class RadioType(enum.Enum):
"""Possible options for radio type."""
znp = (
"ZNP = Texas Instruments Z-Stack ZNP protocol: CC253x, CC26x2, CC13x2",
zigpy_znp.zigbee.application.ControllerApplication,
)
ezsp = (
"EZSP = Silicon Labs EmberZNet protocol: Elelabs, HUSBZB-1, Telegesis... | class RadioType(enum.Enum):
| """Possible options for radio type."""
znp = (
"ZNP = Texas Instruments Z-Stack ZNP protocol: CC253x, CC26x2, CC13x2",
zigpy_znp.zigbee.application.ControllerApplication,
)
ezsp = (
"EZSP = Silicon Labs EmberZNet protocol: Elelabs, HUSBZB-1, Telegesis",
bellows.zigbee.ap... | _IDS = "group_ids"
GROUP_NAME = "group_name"
MFG_CLUSTER_ID_START = 0xFC00
POWER_MAINS_POWERED = "Mains"
POWER_BATTERY_OR_UNKNOWN = "Battery or Unknown"
PRESET_SCHEDULE = "schedule"
PRESET_COMPLEX = "complex"
ZHA_ALARM_OPTIONS = "zha_alarm_options"
ZHA_OPTIONS = "zha_options"
ZHA_CONFIG_SCHEMAS = {
ZHA_OPTIONS... | 125 | 125 | 417 | 6 | 119 | tizzen33/core | homeassistant/components/zha/core/const.py | Python | RadioType | RadioType | 233 | 283 | 233 | 233 | e986c831c112271379bff30c2c3e50161bb3e8ea | bigcode/the-stack | train |
690cc5393777d0d1335bda57 | train | function | def debounce(wait_time):
"""
Decorator that will debounce a function so that it is called after wait_time seconds
If it is called multiple times, will wait for the last call to be debounced and run only this one.
See the test_debounce.py file for examples
"""
def decorator(function):
de... | def debounce(wait_time):
| """
Decorator that will debounce a function so that it is called after wait_time seconds
If it is called multiple times, will wait for the last call to be debounced and run only this one.
See the test_debounce.py file for examples
"""
def decorator(function):
def debounced(*args, **kwar... | All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
## via https://github.com/salesforce/decorator-operations/
import threading
def debounce(wait_time):
| 64 | 64 | 153 | 5 | 58 | bananahampster/inhouse-bot | debounce.py | Python | debounce | debounce | 11 | 33 | 11 | 11 | 3e2879f4fd80d21b84770f566b6eba9060aea2fe | bigcode/the-stack | train |
2e60951c1bbb2cf173f39b1d | train | function | def shade_test(func):
"""
decorator for function simply returning a shade
will check that the shade produces color for coords
"""
def _decorator(self):
shade = func(self)
color = shade.determine_shade((5, 5))
self.assertIsInstance(color, tuple)
for i in color:
... | def shade_test(func):
| """
decorator for function simply returning a shade
will check that the shade produces color for coords
"""
def _decorator(self):
shade = func(self)
color = shade.determine_shade((5, 5))
self.assertIsInstance(color, tuple)
for i in color:
self.assertIsInst... |
"""
def _decorator(self):
canvas_copy = self.canvas.copy()
func(self)
copy_array = np.array(canvas_copy)
canvas_array = np.array(self.canvas)
self.assertFalse((copy_array == canvas_array).all())
return _decorator
def shade_test(func):
| 64 | 64 | 98 | 5 | 58 | benrrutter/Shades | tests/test_shades.py | Python | shade_test | shade_test | 20 | 33 | 20 | 20 | 60dcb43835599574c5185812aa0b81cd71cac33c | bigcode/the-stack | train |
a84dc3622d155a8531132ad1 | train | function | def marks_canvas_test(func):
"""
works as a wrapper over drawing on self.canvas
to check that a mark is made
"""
def _decorator(self):
canvas_copy = self.canvas.copy()
func(self)
copy_array = np.array(canvas_copy)
canvas_array = np.array(self.canvas)
self.asse... | def marks_canvas_test(func):
| """
works as a wrapper over drawing on self.canvas
to check that a mark is made
"""
def _decorator(self):
canvas_copy = self.canvas.copy()
func(self)
copy_array = np.array(canvas_copy)
canvas_array = np.array(self.canvas)
self.assertFalse((copy_array == canvas... | import unittest
import shades
import numpy as np
def marks_canvas_test(func):
| 17 | 64 | 86 | 6 | 10 | benrrutter/Shades | tests/test_shades.py | Python | marks_canvas_test | marks_canvas_test | 6 | 17 | 6 | 6 | ebc1af1454f6d7181eb98370a9cec4f359cea5b1 | bigcode/the-stack | train |
6f074146fcf61a7dd87d0a35 | train | class | class TestShades(unittest.TestCase):
def setUp(self):
self.shade = shades.BlockColor()
self.canvas = shades.Canvas()
def test_adjust_point_returns_point(self):
adjusted_point = self.shade.adjust_point((4, 5))
self.assertIsInstance(adjusted_point, tuple)
def test_adjust_... | class TestShades(unittest.TestCase):
| def setUp(self):
self.shade = shades.BlockColor()
self.canvas = shades.Canvas()
def test_adjust_point_returns_point(self):
adjusted_point = self.shade.adjust_point((4, 5))
self.assertIsInstance(adjusted_point, tuple)
def test_adjust_point_affects_point(self):
poin... | import unittest
import shades
import numpy as np
def marks_canvas_test(func):
"""
works as a wrapper over drawing on self.canvas
to check that a mark is made
"""
def _decorator(self):
canvas_copy = self.canvas.copy()
func(self)
copy_array = np.array(canvas_copy)
can... | 204 | 256 | 1,259 | 9 | 194 | benrrutter/Shades | tests/test_shades.py | Python | TestShades | TestShades | 36 | 202 | 36 | 38 | c83d8a72cc0667d70520864941ec89ae5f444f1f | bigcode/the-stack | train |
e96992e7aab022094482bbc9 | train | function | def init_app(app):
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/petshop.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = '123452'
app.config['FLASK_ADMIN_SWATCH'] = 'cosmo'
| def init_app(app):
| app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/petshop.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = '123452'
app.config['FLASK_ADMIN_SWATCH'] = 'cosmo'
| def init_app(app):
| 5 | 64 | 69 | 5 | 0 | machado2077/admin-e-vendas-para-loja-com-flask | app/ext/config/__init__.py | Python | init_app | init_app | 1 | 5 | 1 | 1 | 055649c41c3208724e91cdc65cd4fb5a9822bacf | bigcode/the-stack | train |
ef3a2157a6ca90cde9ca8ab8 | train | function | def test_prop():
class TestClass:
test_field = 'test_field_value'
test_class_inst = TestClass()
actual_value = prop('test_field')
assert actual_value(test_class_inst) == 'test_field_value'
| def test_prop():
| class TestClass:
test_field = 'test_field_value'
test_class_inst = TestClass()
actual_value = prop('test_field')
assert actual_value(test_class_inst) == 'test_field_value'
| _3 = new_nethod_2(14, 16)
assert new_nethod_3() == 14.0
new_method_4 = curry(some_method)
assert new_method_4(4, 4)(4)() == 4.0
def test_prop():
| 64 | 64 | 49 | 4 | 59 | UnoYakshi/Mostly-Adequate-Guide-in-Python | src/tests/test_support.py | Python | test_prop | test_prop | 22 | 29 | 22 | 22 | 1f04dcecf929cfb43bc035c4898517fa36c9c022 | bigcode/the-stack | train |
4e3fa824b19bba6ed523052f | train | function | def test_curry():
def some_method(*args):
if not args:
return 0.0
return sum(args) / len(args)
# TODO: Refactor it...
new_nethod_1 = curry(some_method)
new_nethod_2 = new_nethod_1(14, 12)
new_nethod_3 = new_nethod_2(14, 16)
assert new_nethod_3() == 14.0
new_me... | def test_curry():
| def some_method(*args):
if not args:
return 0.0
return sum(args) / len(args)
# TODO: Refactor it...
new_nethod_1 = curry(some_method)
new_nethod_2 = new_nethod_1(14, 12)
new_nethod_3 = new_nethod_2(14, 16)
assert new_nethod_3() == 14.0
new_method_4 = curry(some... | from src.support import curry, prop
def test_curry():
| 13 | 64 | 135 | 5 | 7 | UnoYakshi/Mostly-Adequate-Guide-in-Python | src/tests/test_support.py | Python | test_curry | test_curry | 4 | 19 | 4 | 5 | a34a83943c66b566feb610fcd13a3a57abd81d26 | bigcode/the-stack | train |
4a8343b125ea475a88507571 | train | class | class TestFiles(unittest.TestCase):
def test_read_file_n_lines(self):
test_file = Path(os.path.dirname(os.path.realpath(__file__))).joinpath("resources/test_files_read_file_n_lines.txt")
assert files.read_file_n_lines(test_file, 1) == ["line1"]
assert files.read_file_n_lines(test_file, 2) == ["line1", "... | class TestFiles(unittest.TestCase):
| def test_read_file_n_lines(self):
test_file = Path(os.path.dirname(os.path.realpath(__file__))).joinpath("resources/test_files_read_file_n_lines.txt")
assert files.read_file_n_lines(test_file, 1) == ["line1"]
assert files.read_file_n_lines(test_file, 2) == ["line1", "line2"]
assert files.read_file_n_... | #!/usr/bin/env python
import os
import unittest
from pathlib import Path
from ltpylib import files
class TestFiles(unittest.TestCase):
| 32 | 91 | 304 | 7 | 24 | lancethomps/lt-pylib | ltpylibtests/test_files.py | Python | TestFiles | TestFiles | 9 | 27 | 9 | 10 | a3375957f394e3c5a1795f1316af81a7f165fd0b | bigcode/the-stack | train |
48a376ef3097c808dfcf1f2e | train | function | def main():
"""A multi-thread tool to crop sub imags."""
input_folder = '/mnt/SSD/xtwang/BasicSR_datasets/DIV2K800/DIV2K800'
save_folder = '/mnt/SSD/xtwang/BasicSR_datasets/DIV2K800/DIV2K800_sub'
n_thread = 20
crop_sz = 480
step = 240
thres_sz = 48
compression_level = 3 # 3 is the defau... | def main():
| """A multi-thread tool to crop sub imags."""
input_folder = '/mnt/SSD/xtwang/BasicSR_datasets/DIV2K800/DIV2K800'
save_folder = '/mnt/SSD/xtwang/BasicSR_datasets/DIV2K800/DIV2K800_sub'
n_thread = 20
crop_sz = 480
step = 240
thres_sz = 48
compression_level = 3 # 3 is the default value in ... | import os
import os.path as osp
import sys
from multiprocessing import Pool
import numpy as np
import cv2
try:
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from utils.util import ProgressBar
except ImportError:
pass
def main():
| 63 | 105 | 352 | 3 | 59 | prote376/real-world-sr | esrgan-fs/codes/scripts/extract_subimgs_single.py | Python | main | main | 14 | 50 | 14 | 14 | 31a59bd0c8a3f63ece970728df1e062ec852401c | bigcode/the-stack | train |
b381a5300f33d417d4a01681 | train | function | def worker(path, save_folder, crop_sz, step, thres_sz, compression_level):
img_name = os.path.basename(path)
img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
n_channels = len(img.shape)
if n_channels == 2:
h, w = img.shape
elif n_channels == 3:
h, w, c = img.shape
else:
rais... | def worker(path, save_folder, crop_sz, step, thres_sz, compression_level):
| img_name = os.path.basename(path)
img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
n_channels = len(img.shape)
if n_channels == 2:
h, w = img.shape
elif n_channels == 3:
h, w, c = img.shape
else:
raise ValueError('Wrong image shape - {}'.format(n_channels))
h_space = np... | only images in the input_folder
img_list.extend(path)
def update(arg):
pbar.update(arg)
pbar = ProgressBar(len(img_list))
pool = Pool(n_thread)
for path in img_list:
pool.apply_async(worker,
args=(path, save_folder, crop_sz, step, thres_sz, compressio... | 114 | 115 | 386 | 19 | 95 | prote376/real-world-sr | esrgan-fs/codes/scripts/extract_subimgs_single.py | Python | worker | worker | 53 | 87 | 53 | 53 | 621c1ddff604fe4fe7998a88656168b2e158e713 | bigcode/the-stack | train |
de3a652115d37c567402e404 | train | class | class TemplatesUpdate(CommandHelpers, Command):
"Update locally installed Cookiecutter templates"
def get_parser(self, prog_name):
parser = super(TemplatesUpdate, self).get_parser(prog_name)
parser.formatter_class = argparse.RawTextHelpFormatter
return parser
def take_action(self, ... | class TemplatesUpdate(CommandHelpers, Command):
| "Update locally installed Cookiecutter templates"
def get_parser(self, prog_name):
parser = super(TemplatesUpdate, self).get_parser(prog_name)
parser.formatter_class = argparse.RawTextHelpFormatter
return parser
def take_action(self, parsed_args):
cc_home = cc_config.DEFAUL... | import argparse
import cookiecutter.config as cc_config
from cliff.command import Command
from .command_helpers import CommandHelpers
from .help_text import TEMPLATE_STATUS_MSG
from datakit_project.cookiecutters import Cookiecutters
from datakit_project.prompt import read_multichoice_or_all_input
class TemplatesUpdate... | 69 | 104 | 349 | 8 | 60 | hs4man21/datakit-project | datakit_project/commands/templates_update.py | Python | TemplatesUpdate | TemplatesUpdate | 11 | 45 | 11 | 11 | 41cf7039f5fde9e025a143735e5dc1f1b527c81a | bigcode/the-stack | train |
93bfe86090362542adf63dec | train | function | def main(environment):
PRODUCTION_DOTENVS_DIR_PATH = ROOT_DIR_PATH / ".envs" / environment
PRODUCTION_DOTENV_FILE_PATHS = [
PRODUCTION_DOTENVS_DIR_PATH / ".django",
PRODUCTION_DOTENVS_DIR_PATH / ".postgres",
]
DOTENV_FILE_PATH = ROOT_DIR_PATH / ".env"
print(f"Merging {PRODUCTION_D... | def main(environment):
| PRODUCTION_DOTENVS_DIR_PATH = ROOT_DIR_PATH / ".envs" / environment
PRODUCTION_DOTENV_FILE_PATHS = [
PRODUCTION_DOTENVS_DIR_PATH / ".django",
PRODUCTION_DOTENVS_DIR_PATH / ".postgres",
]
DOTENV_FILE_PATH = ROOT_DIR_PATH / ".env"
print(f"Merging {PRODUCTION_DOTENV_FILE_PATHS} into {... | output_file:
for merged_file_path in merged_file_paths:
with open(merged_file_path, "r") as merged_file:
merged_file_content = merged_file.read()
output_file.write(merged_file_content)
if append_linesep:
output_file.write(os.linese... | 64 | 64 | 117 | 4 | 60 | SobolGaming/Trivianator | merge_dotenvs_in_dotenv.py | Python | main | main | 24 | 34 | 24 | 25 | 9fd9029177f1f01ac7a5ccde6c2579293ca4a4c9 | bigcode/the-stack | train |
dda20c76db605c4e88c995db | train | function | @pytest.mark.parametrize("merged_file_count", range(3))
@pytest.mark.parametrize("append_linesep", [True, False])
def test_merge(tmpdir_factory, merged_file_count: int, append_linesep: bool):
tmp_dir_path = Path(str(tmpdir_factory.getbasetemp()))
output_file_path = tmp_dir_path / ".env"
expected_output_fi... | @pytest.mark.parametrize("merged_file_count", range(3))
@pytest.mark.parametrize("append_linesep", [True, False])
def test_merge(tmpdir_factory, merged_file_count: int, append_linesep: bool):
| tmp_dir_path = Path(str(tmpdir_factory.getbasetemp()))
output_file_path = tmp_dir_path / ".env"
expected_output_file_content = ""
merged_file_paths = []
for i in range(merged_file_count):
merged_file_ord = i + 1
merged_filename = ".service{}".format(merged_file_ord)
merged... | OTENV_FILE_PATHS} into {DOTENV_FILE_PATH}")
merge(DOTENV_FILE_PATH, PRODUCTION_DOTENV_FILE_PATHS)
@pytest.mark.parametrize("merged_file_count", range(3))
@pytest.mark.parametrize("append_linesep", [True, False])
def test_merge(tmpdir_factory, merged_file_count: int, append_linesep: bool):
| 74 | 74 | 249 | 44 | 30 | SobolGaming/Trivianator | merge_dotenvs_in_dotenv.py | Python | test_merge | test_merge | 37 | 68 | 37 | 39 | 32fbd37f0138e82961ba5192a4f2937b4347f89e | bigcode/the-stack | train |
b8a1178fe74fcfe86f73ca5a | train | function | def merge(
output_file_path: str, merged_file_paths: Sequence[str], append_linesep: bool = True
) -> None:
with open(output_file_path, "w") as output_file:
for merged_file_path in merged_file_paths:
with open(merged_file_path, "r") as merged_file:
merged_file_content = merged... | def merge(
output_file_path: str, merged_file_paths: Sequence[str], append_linesep: bool = True
) -> None:
| with open(output_file_path, "w") as output_file:
for merged_file_path in merged_file_paths:
with open(merged_file_path, "r") as merged_file:
merged_file_content = merged_file.read()
output_file.write(merged_file_content)
if append_linesep:
... | import os
import sys
from pathlib import Path
from typing import Sequence
import pytest
ROOT_DIR_PATH = Path(__file__).parent.resolve()
def merge(
output_file_path: str, merged_file_paths: Sequence[str], append_linesep: bool = True
) -> None:
| 59 | 64 | 100 | 29 | 30 | SobolGaming/Trivianator | merge_dotenvs_in_dotenv.py | Python | merge | merge | 12 | 21 | 12 | 14 | b8b2571f2596dd003c828d8219d86e1aca28868d | bigcode/the-stack | train |
97383ed979ea5781053e8978 | train | function | def test_single_template_output(resource_dir):
expected_file = FileUtility('/'.join([resource_dir, 'simple_kickstart.good.txt']))
contents = expected_file.get_file_string()
config_file = FileUtility('/'.join([resource_dir, 'single_file_yaml_data.yml']))
config_data = config_file.get_yaml()
output... | def test_single_template_output(resource_dir):
| expected_file = FileUtility('/'.join([resource_dir, 'simple_kickstart.good.txt']))
contents = expected_file.get_file_string()
config_file = FileUtility('/'.join([resource_dir, 'single_file_yaml_data.yml']))
config_data = config_file.get_yaml()
output = Kickstart.render_template_from_dict(template_... | import pytest
from collector_kickstarts.render import Kickstart
from collector_kickstarts.utility import FileUtility
@pytest.fixture()
def resource_dir():
from collector_kickstarts.utility import find_subdir
return find_subdir('resources')
def test_single_template_output(resource_dir):
| 58 | 64 | 87 | 8 | 50 | mcapelli/collector_kickstarts | tests/test_render.py | Python | test_single_template_output | test_single_template_output | 12 | 21 | 12 | 13 | c54ee69e3cf2f85fddcccb45be25612e04a5b8e7 | bigcode/the-stack | train |
8bf30fb019bb9436efe2551e | train | function | @pytest.fixture()
def resource_dir():
from collector_kickstarts.utility import find_subdir
return find_subdir('resources')
| @pytest.fixture()
def resource_dir():
| from collector_kickstarts.utility import find_subdir
return find_subdir('resources')
| import pytest
from collector_kickstarts.render import Kickstart
from collector_kickstarts.utility import FileUtility
@pytest.fixture()
def resource_dir():
| 30 | 64 | 27 | 7 | 22 | mcapelli/collector_kickstarts | tests/test_render.py | Python | resource_dir | resource_dir | 6 | 9 | 6 | 7 | c764b31f2ff7fd2abda7313da7f621281ac3d11e | bigcode/the-stack | train |
c25a92148fc9f6367afba32b | train | function | def test_multi_template_output(resource_dir):
config_file = FileUtility('/'.join([resource_dir, 'render_multiple_files.yml']))
config_data = config_file.get_yaml()
assert len(Kickstart.render_files(template_data=config_data)) == 3
| def test_multi_template_output(resource_dir):
| config_file = FileUtility('/'.join([resource_dir, 'render_multiple_files.yml']))
config_data = config_file.get_yaml()
assert len(Kickstart.render_files(template_data=config_data)) == 3
| = expected_file.get_file_string()
config_file = FileUtility('/'.join([resource_dir, 'single_file_yaml_data.yml']))
config_data = config_file.get_yaml()
output = Kickstart.render_template_from_dict(template_data=config_data)
assert contents == output
def test_multi_template_output(resource_dir):
| 64 | 64 | 53 | 8 | 55 | mcapelli/collector_kickstarts | tests/test_render.py | Python | test_multi_template_output | test_multi_template_output | 24 | 29 | 24 | 25 | 0d7c9eabbebcc5da593dee0c700dc9f3fc077513 | bigcode/the-stack | train |
5884590768eff8039cd1dcbf | train | function | def test_create_kickstart_files(resource_dir, tmpdir):
import os
# get data from multi yaml file
fu = FileUtility('/'.join([resource_dir, 'render_multiple_files.yml']))
yaml_data = fu.get_yaml()
Kickstart.create_kickstart_files(yaml_data, tmpdir.dirname)
assert os.path.exists('/'.join([tmpdir... | def test_create_kickstart_files(resource_dir, tmpdir):
| import os
# get data from multi yaml file
fu = FileUtility('/'.join([resource_dir, 'render_multiple_files.yml']))
yaml_data = fu.get_yaml()
Kickstart.create_kickstart_files(yaml_data, tmpdir.dirname)
assert os.path.exists('/'.join([tmpdir.dirname, 'PROD01-ZDEL-FIRST_HOST_NAME.ks']))
asser... | _multi_template_output(resource_dir):
config_file = FileUtility('/'.join([resource_dir, 'render_multiple_files.yml']))
config_data = config_file.get_yaml()
assert len(Kickstart.render_files(template_data=config_data)) == 3
def test_create_kickstart_files(resource_dir, tmpdir):
| 64 | 64 | 143 | 13 | 50 | mcapelli/collector_kickstarts | tests/test_render.py | Python | test_create_kickstart_files | test_create_kickstart_files | 32 | 43 | 32 | 32 | 4feb0ce7a8700b6f545459b7c82d45ce3b33e5e1 | bigcode/the-stack | train |
f15e3d5eba220421c7c1b2ff | train | function | def test_broadcast4():
template(x0_shape=[2, 1, 4, 1], x1_shape=[1, 3, 1, 5])
| def test_broadcast4():
| template(x0_shape=[2, 1, 4, 1], x1_shape=[1, 3, 1, 5])
| 2, 3, 4, 5], x1_shape=[1, 5])
def test_broadcast3():
template(x0_shape=[2, 3, 4, 5], x1_shape=[1, 1, 1, 5])
def test_broadcast4():
| 64 | 64 | 38 | 6 | 58 | steerapi/webdnn | test/runtime/frontend_test/tensorflow_test/ops_test/gen_math_ops_test/mul_test.py | Python | test_broadcast4 | test_broadcast4 | 47 | 48 | 47 | 47 | a0c9d6b9551528ba548645816928cdf57062c2aa | bigcode/the-stack | train |
634d4d1f22285994fc7f1959 | train | function | def test():
template(x0_shape=[2, 3, 4, 5], x1_shape=[2, 3, 4, 5])
| def test():
| template(x0_shape=[2, 3, 4, 5], x1_shape=[2, 3, 4, 5])
| ], [y])
generate_kernel_test_case(
description=f"[TensorFlow] Mul {description}",
graph=graph,
inputs={
graph.inputs[0]: vx0,
graph.inputs[1]: vx1
},
expected={graph.outputs[0]: vy},
)
def test():
| 64 | 64 | 35 | 3 | 61 | steerapi/webdnn | test/runtime/frontend_test/tensorflow_test/ops_test/gen_math_ops_test/mul_test.py | Python | test | test | 31 | 32 | 31 | 31 | 53e8b5d70ce8639f4b16bb1e0db9900f48946ac6 | bigcode/the-stack | train |
44d18b83b392137da26ebc7c | train | function | def test_broadcast1():
template(x0_shape=[2, 3, 4, 5], x1_shape=[5])
| def test_broadcast1():
| template(x0_shape=[2, 3, 4, 5], x1_shape=[5])
| graph.inputs[1]: vx1
},
expected={graph.outputs[0]: vy},
)
def test():
template(x0_shape=[2, 3, 4, 5], x1_shape=[2, 3, 4, 5])
def test_broadcast1():
| 64 | 64 | 29 | 6 | 58 | steerapi/webdnn | test/runtime/frontend_test/tensorflow_test/ops_test/gen_math_ops_test/mul_test.py | Python | test_broadcast1 | test_broadcast1 | 35 | 36 | 35 | 35 | e088f54d4ee3a6679cc30dd78da8ab0b712b11e2 | bigcode/the-stack | train |
64765eae6fa880fdb8a044f9 | train | function | @wrap_template
def template(x0_shape, x1_shape, description: str = ""):
x0 = tf.placeholder(np.float32, x0_shape, "x0")
x1 = tf.placeholder(np.float32, x1_shape, "x1")
y = x0 * x1
vx0 = np.random.rand(*x0_shape).astype(np.float32)
vx1 = np.random.rand(*x1_shape).astype(np.float32)
with tf.Sessi... | @wrap_template
def template(x0_shape, x1_shape, description: str = ""):
| x0 = tf.placeholder(np.float32, x0_shape, "x0")
x1 = tf.placeholder(np.float32, x1_shape, "x1")
y = x0 * x1
vx0 = np.random.rand(*x0_shape).astype(np.float32)
vx1 = np.random.rand(*x1_shape).astype(np.float32)
with tf.Session() as sess:
vy, = sess.run([y], {x0: vx0, x1: vx1})
g... | import numpy as np
from test.runtime.frontend_test.tensorflow_test.util import TensorFlowConverter, tf
from test.util import generate_kernel_test_case, wrap_template
@wrap_template
def template(x0_shape, x1_shape, description: str = ""):
| 54 | 64 | 210 | 20 | 33 | steerapi/webdnn | test/runtime/frontend_test/tensorflow_test/ops_test/gen_math_ops_test/mul_test.py | Python | template | template | 7 | 28 | 7 | 8 | b36b493c524f7b68775e538e5f42a3f6a79e5ffe | bigcode/the-stack | train |
fc7ac7fb5b96311f9948714d | train | function | def test_broadcast2():
template(x0_shape=[2, 3, 4, 5], x1_shape=[1, 5])
| def test_broadcast2():
| template(x0_shape=[2, 3, 4, 5], x1_shape=[1, 5])
| 0_shape=[2, 3, 4, 5], x1_shape=[2, 3, 4, 5])
def test_broadcast1():
template(x0_shape=[2, 3, 4, 5], x1_shape=[5])
def test_broadcast2():
| 64 | 64 | 32 | 6 | 58 | steerapi/webdnn | test/runtime/frontend_test/tensorflow_test/ops_test/gen_math_ops_test/mul_test.py | Python | test_broadcast2 | test_broadcast2 | 39 | 40 | 39 | 39 | ba270e08417a98352d4c43fb47e66e98f2d81190 | bigcode/the-stack | train |
13f1b40bffbab85da8dfe036 | train | function | def test_broadcast3():
template(x0_shape=[2, 3, 4, 5], x1_shape=[1, 1, 1, 5])
| def test_broadcast3():
| template(x0_shape=[2, 3, 4, 5], x1_shape=[1, 1, 1, 5])
| roadcast1():
template(x0_shape=[2, 3, 4, 5], x1_shape=[5])
def test_broadcast2():
template(x0_shape=[2, 3, 4, 5], x1_shape=[1, 5])
def test_broadcast3():
| 64 | 64 | 38 | 6 | 58 | steerapi/webdnn | test/runtime/frontend_test/tensorflow_test/ops_test/gen_math_ops_test/mul_test.py | Python | test_broadcast3 | test_broadcast3 | 43 | 44 | 43 | 43 | 80bdaffa3efa6743637c3e13c0a2212f26f5964e | bigcode/the-stack | train |
56d441acb2c9044923114ad5 | train | function | def test_broadcast5():
template(x0_shape=[1, 1, 4, 1], x1_shape=[1, 1, 1, 5])
| def test_broadcast5():
| template(x0_shape=[1, 1, 4, 1], x1_shape=[1, 1, 1, 5])
| 4, 5], x1_shape=[1, 1, 1, 5])
def test_broadcast4():
template(x0_shape=[2, 1, 4, 1], x1_shape=[1, 3, 1, 5])
def test_broadcast5():
| 64 | 64 | 38 | 6 | 58 | steerapi/webdnn | test/runtime/frontend_test/tensorflow_test/ops_test/gen_math_ops_test/mul_test.py | Python | test_broadcast5 | test_broadcast5 | 51 | 52 | 51 | 51 | 789b08efd0a4d6c0853ed1e628dcd8faa7891c60 | bigcode/the-stack | train |
cd7eef0c277d71f5285a58e6 | train | class | class PositionValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="position", parent_name="pie.title", **kwargs):
super(PositionValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_... | class PositionValidator(_plotly_utils.basevalidators.EnumeratedValidator):
| def __init__(self, plotly_name="position", parent_name="pie.title", **kwargs):
super(PositionValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
values=kwargs.pop(
"values",
... | import _plotly_utils.basevalidators
class PositionValidator(_plotly_utils.basevalidators.EnumeratedValidator):
| 22 | 64 | 131 | 14 | 7 | mastermind88/plotly.py | packages/python/plotly/plotly/validators/pie/title/_position.py | Python | PositionValidator | PositionValidator | 4 | 23 | 4 | 4 | c9f399340a1eb2f61d57d90d79e7df663cfd05ef | bigcode/the-stack | train |
6d10418e52e3f5420ba6f822 | train | function | @app2.on_message(
(filters.text | filters.caption)
& ~filters.chat(BOT_ID)
& ~filters.chat(USERBOT_BOT_CHAT_COMMON)
& ~filters.me,
group=trust_group,
)
@app.on_message(
(filters.text | filters.caption)
& ~filters.chat(MESSAGE_DUMP_CHAT)
& ~filters.me
& ~filters.private,
group=tru... | @app2.on_message(
(filters.text | filters.caption)
& ~filters.chat(BOT_ID)
& ~filters.chat(USERBOT_BOT_CHAT_COMMON)
& ~filters.me,
group=trust_group,
)
@app.on_message(
(filters.text | filters.caption)
& ~filters.chat(MESSAGE_DUMP_CHAT)
& ~filters.me
& ~filters.private,
group=tru... | if message.command:
return
if not message.from_user:
return
user_id = message.from_user.id
text = message.text or message.caption
text = text.strip()
if not text:
return
if len(text) < 2:
return
data = await get_spam_data(message, text)
if isinstance(d... | @app2.on_message(
(filters.text | filters.caption)
& ~filters.chat(BOT_ID)
& ~filters.chat(USERBOT_BOT_CHAT_COMMON)
& ~filters.me,
group=trust_group,
)
@app.on_message(
(filters.text | filters.caption)
& ~filters.chat(MESSAGE_DUMP_CHAT)
& ~filters.me
& ~filters.private,
group=tru... | 124 | 67 | 226 | 124 | 0 | sampathsir/WilliamButcherBot | wbb/modules/trust.py | Python | trust_watcher_func | trust_watcher_func | 48 | 80 | 48 | 64 | 986276d0c4d24f3ee085d82af6e8edce7ee524d3 | bigcode/the-stack | train |
29624dbf0236296c2e19e5a3 | train | function | async def get_spam_data(message: Message, text: str):
async with lock_access:
c, m = message.chat.id, message.message_id
if c not in spam_db:
spam_db[c] = {}
if m not in spam_db[c]:
data = (await arq.nlp(text)).result[0]
spam_db[c][m] = data
return... | async def get_spam_data(message: Message, text: str):
| async with lock_access:
c, m = message.chat.id, message.message_id
if c not in spam_db:
spam_db[c] = {}
if m not in spam_db[c]:
data = (await arq.nlp(text)).result[0]
spam_db[c][m] = data
return spam_db[c][m]
| _BOT_CHAT_COMMON, app, app2,
arq)
from wbb.utils.dbfunctions import get_trust_db, update_trust_db
from wbb.utils.filter_groups import trust_group
spam_db = {}
lock_access = Lock()
async def get_spam_data(message: Message, text: str):
| 64 | 64 | 90 | 14 | 50 | sampathsir/WilliamButcherBot | wbb/modules/trust.py | Python | get_spam_data | get_spam_data | 37 | 45 | 37 | 37 | 05b3c719c5224f1909eb5277807c7e98894f21f8 | bigcode/the-stack | train |
bdd5f6bcff5fcec2aaea2391 | train | function | async def get_spam_probability(user_id) -> list:
data = await get_trust_db(user_id)
if not data:
return [0, 0]
mean = lambda x: sum(x) / len(x)
spam = [i for i in data]
return [mean(spam), len(spam)]
| async def get_spam_probability(user_id) -> list:
| data = await get_trust_db(user_id)
if not data:
return [0, 0]
mean = lambda x: sum(x) / len(x)
spam = [i for i in data]
return [mean(spam), len(spam)]
| if len(text) < 2:
return
data = await get_spam_data(message, text)
if isinstance(data, str):
return
spam = data.spam
await update_trust_db(user_id, spam)
async def get_spam_probability(user_id) -> list:
| 64 | 64 | 70 | 12 | 52 | sampathsir/WilliamButcherBot | wbb/modules/trust.py | Python | get_spam_probability | get_spam_probability | 83 | 89 | 83 | 83 | 5dabe98158f309a797d25aa7a9ec58b963f9827d | bigcode/the-stack | train |
6f7df68a717a71eed4099e54 | train | class | class PartInstancePin(PartClassPin):
"""Particular pin of a particular part instance. Can connect to nets. Knows the refdes of its part."""
_net = None
def __init__(self, part_instance, part_class_pin, inject_number=None):
# copy state of the Pin to be inherited, then continue as if the parent clas... | class PartInstancePin(PartClassPin):
| """Particular pin of a particular part instance. Can connect to nets. Knows the refdes of its part."""
_net = None
def __init__(self, part_instance, part_class_pin, inject_number=None):
# copy state of the Pin to be inherited, then continue as if the parent class always existed that way
sel... | """
pin.names = pin.names[1:] + (pin.names[0],)
Pin = PinFragment
class PartClassPin(object):
"""
Pin of a Part, but no particular Part instance.
Contains general information about the pin (but it could be for any
part of that type), nothing related to a specific part instance.
"""
wel... | 201 | 201 | 671 | 9 | 192 | maxschommer/pcbdl | pcbdl/base.py | Python | PartInstancePin | PartInstancePin | 366 | 440 | 366 | 366 | a9613296d21f63a0b8a58023d403de116d45968f | bigcode/the-stack | train |
06492035a90c66d9cd9fe5ec | train | class | class _PinList(collections.OrderedDict):
def __getitem__(self, pin_name):
if isinstance(pin_name, int):
return tuple(self.values())[pin_name]
pin_name = pin_name.upper()
try:
return super().__getitem__(pin_name)
except KeyError:
# try looking slowl... | class _PinList(collections.OrderedDict):
| def __getitem__(self, pin_name):
if isinstance(pin_name, int):
return tuple(self.values())[pin_name]
pin_name = pin_name.upper()
try:
return super().__getitem__(pin_name)
except KeyError:
# try looking slowly through the other names
for... | POWER_OUTPUT = 4
GROUND = 5
INPUT = 6
OUTPUT = 7
def _maybe_single(o):
if isinstance(o, collections.abc.Iterable):
yield from o
else:
yield o
class _PinList(collections.OrderedDict):
| 64 | 64 | 126 | 10 | 53 | maxschommer/pcbdl | pcbdl/base.py | Python | _PinList | _PinList | 77 | 96 | 77 | 77 | 3a9ad50cc6aba6da37dd11788fc638b7dc761c2b | bigcode/the-stack | train |
540d44e3dd3aaccec7701887 | train | class | class ConnectDirection(enum.Enum):
UNKNOWN = 0
IN = 1
OUT = 2
| class ConnectDirection(enum.Enum):
| UNKNOWN = 0
IN = 1
OUT = 2
| staticmethod
def init(instance):
"""Init plugins associated with this instance"""
try:
factories = instance.plugins
except AttributeError:
return
assert type(instance.plugins) is not dict
instance.plugins = {plugin: plugin(instance) for plugin in facto... | 64 | 64 | 24 | 6 | 58 | maxschommer/pcbdl | pcbdl/base.py | Python | ConnectDirection | ConnectDirection | 56 | 59 | 56 | 56 | e2998817376c3352c7c472086ad7e83dee938cee | bigcode/the-stack | train |
b03cd68e68414d68b97ea958 | train | class | class PinType(enum.Enum):
UNKNOWN = 0
PRIMARY = 1
SECONDARY = 2
POWER_INPUT = 3
POWER_OUTPUT = 4
GROUND = 5
INPUT = 6
OUTPUT = 7
| class PinType(enum.Enum):
| UNKNOWN = 0
PRIMARY = 1
SECONDARY = 2
POWER_INPUT = 3
POWER_OUTPUT = 4
GROUND = 5
INPUT = 6
OUTPUT = 7
|
except AttributeError:
return
assert type(instance.plugins) is not dict
instance.plugins = {plugin: plugin(instance) for plugin in factories}
class ConnectDirection(enum.Enum):
UNKNOWN = 0
IN = 1
OUT = 2
class PinType(enum.Enum):
| 64 | 64 | 58 | 6 | 57 | maxschommer/pcbdl | pcbdl/base.py | Python | PinType | PinType | 61 | 69 | 61 | 61 | 5dc0039b4a077a60d5f7b5636dea10cebcbe1a41 | bigcode/the-stack | train |
19d35bc598ae57569a802dd7 | train | class | class PinFragmentList(list):
"""Used as a marker that we have visited Part.PINS and converted all the elements to PinFragment."""
def __init__(self, part_cls):
self.part_cls = part_cls
list.__init__(self, part_cls.PINS)
for i, maybenames in enumerate(self):
# syntactic sugar,... | class PinFragmentList(list):
| """Used as a marker that we have visited Part.PINS and converted all the elements to PinFragment."""
def __init__(self, part_cls):
self.part_cls = part_cls
list.__init__(self, part_cls.PINS)
for i, maybenames in enumerate(self):
# syntactic sugar, .PIN list might have only na... | direction to that Net
net = Net() #defined_at: not here
net <<= self
return net >> others
def __str__(self):
return "%r.%s" % (self.part, self.name)
__repr__ = __str__
class PinFragmentList(list):
| 64 | 64 | 174 | 6 | 58 | maxschommer/pcbdl | pcbdl/base.py | Python | PinFragmentList | PinFragmentList | 442 | 457 | 442 | 442 | bafc650b5a2bae52b432bf58d28bf42c1f23bd41 | bigcode/the-stack | train |
92123bc78ed50e399afc30ad | train | function | def _maybe_single(o):
if isinstance(o, collections.abc.Iterable):
yield from o
else:
yield o
| def _maybe_single(o):
| if isinstance(o, collections.abc.Iterable):
yield from o
else:
yield o
| class PinType(enum.Enum):
UNKNOWN = 0
PRIMARY = 1
SECONDARY = 2
POWER_INPUT = 3
POWER_OUTPUT = 4
GROUND = 5
INPUT = 6
OUTPUT = 7
def _maybe_single(o):
| 64 | 64 | 29 | 6 | 57 | maxschommer/pcbdl | pcbdl/base.py | Python | _maybe_single | _maybe_single | 71 | 75 | 71 | 71 | 8658218e040370d8a1fb6c8feab97606a1e2b944 | bigcode/the-stack | train |
f8bea83830d9df0b52adf33e | train | class | class Net(object):
_name = None
has_name = False
def __init__(self, name=None):
if name is not None:
self.name = name.upper()
self._connections = []
Plugin.init(self)
def connect(self, others, direction=ConnectDirection.UNKNOWN, pin_type=PinType.PRIMARY):
t... | class Net(object):
| _name = None
has_name = False
def __init__(self, name=None):
if name is not None:
self.name = name.upper()
self._connections = []
Plugin.init(self)
def connect(self, others, direction=ConnectDirection.UNKNOWN, pin_type=PinType.PRIMARY):
try:
con... | = {plugin: plugin(instance) for plugin in factories}
class ConnectDirection(enum.Enum):
UNKNOWN = 0
IN = 1
OUT = 2
class PinType(enum.Enum):
UNKNOWN = 0
PRIMARY = 1
SECONDARY = 2
POWER_INPUT = 3
POWER_OUTPUT = 4
GROUND = 5
INPUT = 6
OUTPUT = 7
def _maybe_single(o):
if... | 253 | 253 | 846 | 4 | 249 | maxschommer/pcbdl | pcbdl/base.py | Python | Net | Net | 98 | 220 | 98 | 98 | 4166728fdd7202d491c0d5f817c362ade4ef35e1 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.