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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7cf81163d2486ea1de9ef07a | train | class | class RMapview(RPackage):
"""Interactive Viewing of Spatial Data in R
Quickly and conveniently create interactive visualisations of spatial data
with or without background maps. Attributes of displayed features are fully
queryable via pop-up windows. Additional functionality includes methods to
vis... | class RMapview(RPackage):
| """Interactive Viewing of Spatial Data in R
Quickly and conveniently create interactive visualisations of spatial data
with or without background maps. Attributes of displayed features are fully
queryable via pop-up windows. Additional functionality includes methods to
visualise true- and false-col... | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RMapview(RPackage):
| 61 | 123 | 413 | 7 | 54 | varioustoxins/spack | var/spack/repos/builtin/packages/r-mapview/package.py | Python | RMapview | RMapview | 9 | 38 | 9 | 9 | ebe36b16d99c30ccba8c10680fc63fbffc27af91 | bigcode/the-stack | train |
ea4618e19028234dbdffd56e | train | class | class FailedTest(HTTPException):
"""
Raised when a URL test fails.
"""
| class FailedTest(HTTPException):
| """
Raised when a URL test fails.
"""
| .__class__.__name__}: Got status {0.status} on URL {0.response.url}.".format(self)
def __repr__(self):
return f"{self.__class__.__name__}(response={self.response} message={self.message} status={self.status})"
class FailedTest(HTTPException):
| 64 | 64 | 19 | 7 | 57 | reejit/PostBin | postbin/v2/errors.py | Python | FailedTest | FailedTest | 48 | 51 | 48 | 48 | 00035ead4ad4edb225327d8157bc35576ee85434 | bigcode/the-stack | train |
68e3c69f36f9740a8b8ab004 | train | class | class HTTPException(Exception):
"""
Represents a HTTP Exception.
Attributes:
response - Union[ClientResponse, Response]: the response that was returned.
message - Optional[str]: A custom message as to why the error was raised.
status - int: The resolved status (so you don't have to ... | class HTTPException(Exception):
| """
Represents a HTTP Exception.
Attributes:
response - Union[ClientResponse, Response]: the response that was returned.
message - Optional[str]: A custom message as to why the error was raised.
status - int: The resolved status (so you don't have to dig between the two classes)
... | from typing import Union
try:
from requests import Response
except ImportError:
Response = None
try:
from aiohttp import ClientResponse
except ImportError:
ClientResponse = None
#
class HTTPException(Exception):
| 48 | 93 | 312 | 5 | 43 | reejit/PostBin | postbin/v2/errors.py | Python | HTTPException | HTTPException | 13 | 45 | 13 | 13 | fe52bef6c17de659ef3cb4ba53bb0b187125348e | bigcode/the-stack | train |
21bd943d6581373b7fa3c5ab | train | class | class OfflineServer(HTTPException):
"""The server provided wasn't online or valid."""
| class OfflineServer(HTTPException):
| """The server provided wasn't online or valid."""
| format(self)
def __repr__(self):
return f"{self.__class__.__name__}(response={self.response} message={self.message} status={self.status})"
class FailedTest(HTTPException):
"""
Raised when a URL test fails.
"""
class OfflineServer(HTTPException):
| 63 | 64 | 17 | 7 | 56 | reejit/PostBin | postbin/v2/errors.py | Python | OfflineServer | OfflineServer | 54 | 55 | 54 | 54 | 814a1d7d5d59801d3befc04354e220f495392bc4 | bigcode/the-stack | train |
ab3bc65c5a4760b063e62006 | train | class | class TextTooLarge(HTTPException):
"""Raised when the text provided to post was too large.
Bear in mind most template haste services have a paste size limit of 1mb."""
| class TextTooLarge(HTTPException):
| """Raised when the text provided to post was too large.
Bear in mind most template haste services have a paste size limit of 1mb."""
| __}(response={self.response} message={self.message} status={self.status})"
class FailedTest(HTTPException):
"""
Raised when a URL test fails.
"""
class OfflineServer(HTTPException):
"""The server provided wasn't online or valid."""
class TextTooLarge(HTTPException):
| 63 | 64 | 39 | 8 | 55 | reejit/PostBin | postbin/v2/errors.py | Python | TextTooLarge | TextTooLarge | 58 | 61 | 58 | 58 | 8983c217dbcf98292f2ee67917db8ae14a22084c | bigcode/the-stack | train |
d71faf06e6ca0b3309d5afd7 | train | function | def getregentry():
return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
| def getregentry():
| return (Codec.encode,Codec.decode,StreamReader,StreamWriter)
| init__(self,stream,errors='strict',mapping=None):
codecs.StreamReader.__init__(self,strict,errors)
self.mapping = mapping
def decode(self,input,errors='strict'):
return Codec.decode(input,errors,self.mapping)
### encodings module API
def getregentry():
| 64 | 64 | 20 | 5 | 58 | Lamouse/Evolutionary-Creativity | breveIDE_windows_2.7.2_2/breveIDE_2.7.2/lib/python2.3/encodings/charmap.py | Python | getregentry | getregentry | 48 | 50 | 48 | 49 | 29b6f695bef9ecb50139486ec98fbd74ac10246b | bigcode/the-stack | train |
30e082cf3307844fc7e1fe1b | train | class | class StreamWriter(Codec,codecs.StreamWriter):
def __init__(self,stream,errors='strict',mapping=None):
codecs.StreamWriter.__init__(self,stream,errors)
self.mapping = mapping
def encode(self,input,errors='strict'):
return Codec.encode(input,errors,self.mapping)
| class StreamWriter(Codec,codecs.StreamWriter):
| def __init__(self,stream,errors='strict',mapping=None):
codecs.StreamWriter.__init__(self,stream,errors)
self.mapping = mapping
def encode(self,input,errors='strict'):
return Codec.encode(input,errors,self.mapping)
|
class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is intended.
encode = codecs.charmap_encode
decode = codecs.charmap_decode
class StreamWriter(Codec,codecs.StreamWriter):
| 64 | 64 | 67 | 11 | 52 | Lamouse/Evolutionary-Creativity | breveIDE_windows_2.7.2_2/breveIDE_2.7.2/lib/python2.3/encodings/charmap.py | Python | StreamWriter | StreamWriter | 24 | 33 | 24 | 25 | d83b7ffdabcd3a47cdae0705f896e7fc73a60fe6 | bigcode/the-stack | train |
4d94a641422a4eb8e53ff775 | train | class | class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is intended.
encode = codecs.charmap_encode
decode = codecs.charmap_decode
| class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is intended.
| encode = codecs.charmap_encode
decode = codecs.charmap_decode
| mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is intended.
| 64 | 64 | 52 | 34 | 29 | Lamouse/Evolutionary-Creativity | breveIDE_windows_2.7.2_2/breveIDE_2.7.2/lib/python2.3/encodings/charmap.py | Python | Codec | Codec | 17 | 22 | 17 | 20 | 8dd47e57488b9aed5f106230222d44ab5639d97b | bigcode/the-stack | train |
b95bbe670a40ace752311451 | train | class | class StreamReader(Codec,codecs.StreamReader):
def __init__(self,stream,errors='strict',mapping=None):
codecs.StreamReader.__init__(self,strict,errors)
self.mapping = mapping
def decode(self,input,errors='strict'):
return Codec.decode(input,errors,self.mapping)
| class StreamReader(Codec,codecs.StreamReader):
| def __init__(self,stream,errors='strict',mapping=None):
codecs.StreamReader.__init__(self,strict,errors)
self.mapping = mapping
def decode(self,input,errors='strict'):
return Codec.decode(input,errors,self.mapping)
| init__(self,stream,errors='strict',mapping=None):
codecs.StreamWriter.__init__(self,stream,errors)
self.mapping = mapping
def encode(self,input,errors='strict'):
return Codec.encode(input,errors,self.mapping)
class StreamReader(Codec,codecs.StreamReader):
| 64 | 64 | 67 | 11 | 53 | Lamouse/Evolutionary-Creativity | breveIDE_windows_2.7.2_2/breveIDE_2.7.2/lib/python2.3/encodings/charmap.py | Python | StreamReader | StreamReader | 35 | 44 | 35 | 36 | 7f252aecab00463c620789d58099a76b7b659a5c | bigcode/the-stack | train |
26e980d01691ed592992524c | train | function | def limit_magnitude(vector, min_magnitude, max_magnitude):
mag = math.sqrt(sum(i ** 2 for i in vector))
if mag > max_magnitude:
normalizing_factor = max_magnitude / mag
elif mag < min_magnitude:
normalizing_factor = min_magnitude / mag
else:
return vector
return [value * nor... | def limit_magnitude(vector, min_magnitude, max_magnitude):
| mag = math.sqrt(sum(i ** 2 for i in vector))
if mag > max_magnitude:
normalizing_factor = max_magnitude / mag
elif mag < min_magnitude:
normalizing_factor = min_magnitude / mag
else:
return vector
return [value * normalizing_factor for value in vector]
| 225.0 # Distance units.
TOO_CLOSE_RANGE = 5.0
def dot(a, b):
"""Perform dot product on two vectors."""
return sum(i * j for i, j in zip(a, b))
def limit_magnitude(vector, min_magnitude, max_magnitude):
| 64 | 64 | 87 | 14 | 50 | donno/warehouse51 | boids/boids.py | Python | limit_magnitude | limit_magnitude | 43 | 52 | 43 | 43 | 67996c65f058f0a0ddf52c81f69f0f0ab211ca2c | bigcode/the-stack | train |
9f82e27e4c5c613deea5e982 | train | class | class Vector:
"""
Basic vector class with just enough to make pseudocode easily appliable.
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return 2
def __getitem__(self, index):
if index == 0:
return self.x
elif index ... | class Vector:
| """
Basic vector class with just enough to make pseudocode easily appliable.
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return 2
def __getitem__(self, index):
if index == 0:
return self.x
elif index == 1:
... | ):
if index == 0:
return self.x
elif index == 1:
return self.y
else:
raise IndexError()
def __iadd__(self, rhs):
self.x += rhs.x
self.y += rhs.y
return self
class Vector:
| 64 | 64 | 199 | 3 | 60 | donno/warehouse51 | boids/boids.py | Python | Vector | Vector | 84 | 117 | 84 | 84 | b8b91aa02067643865907e37272f8a71e6f2e8c7 | bigcode/the-stack | train |
dd7f2a2e947e05313cfff883 | train | function | def setup():
width = 600
height = 600
boids = [
Boid(
(random.uniform(0, width), random.uniform(0, height)),
(random.uniform(-20, 20), random.uniform(-20, 20.0)),
)
for _ in range(60)
]
return boids
| def setup():
| width = 600
height = 600
boids = [
Boid(
(random.uniform(0, width), random.uniform(0, height)),
(random.uniform(-20, 20), random.uniform(-20, 20.0)),
)
for _ in range(60)
]
return boids
| + v3
# Limit speed.
boid.velocity = Vector(
*limit_magnitude(boid.velocity, Boid.MIN_SPEED, Boid.MAX_SPEED))
boid.position += boid.velocity * 0.1
def draw_boids(boids):
pass
def setup():
| 64 | 64 | 77 | 3 | 60 | donno/warehouse51 | boids/boids.py | Python | setup | setup | 264 | 276 | 264 | 264 | 44a5535ac039eb0cd8c9a3025b4b0784668195b9 | bigcode/the-stack | train |
d8bb605c2138376b94b70c17 | train | function | def dot(a, b):
"""Perform dot product on two vectors."""
return sum(i * j for i, j in zip(a, b))
| def dot(a, b):
| """Perform dot product on two vectors."""
return sum(i * j for i, j in zip(a, b))
| ids Pseudocode" page above.
Essentially treat the edge like something they want to avoid so it
causes them to turn around.
"""
import math
import random
LOCAL_RANGE = 225.0 # Distance units.
TOO_CLOSE_RANGE = 5.0
def dot(a, b):
| 64 | 64 | 31 | 6 | 57 | donno/warehouse51 | boids/boids.py | Python | dot | dot | 38 | 40 | 38 | 38 | 4851233a50b59eed51141025f25a34a9332e3cb3 | bigcode/the-stack | train |
b421d360d99f647a5db2ce35 | train | function | def rule2(current_boid, all_boids):
"""
Rule 2: Boids try to keep a small distance away from other objects
(including other boids).
"""
x, y = current_boid.position
c_x = 0.0
c_y = 0.0
for boid in all_boids:
if boid != current_boid:
difference = (boid.position[0] -... | def rule2(current_boid, all_boids):
| """
Rule 2: Boids try to keep a small distance away from other objects
(including other boids).
"""
x, y = current_boid.position
c_x = 0.0
c_y = 0.0
for boid in all_boids:
if boid != current_boid:
difference = (boid.position[0] - x, boid.position[1] - y)
... | _of_mass = average_position(flockmates)
cohesion_vector = tuple(
(avg - p) * 0.03 for avg, p in zip(centre_of_mass, current_boid.position)
)
return Vector(*cohesion_vector)
def rule2(current_boid, all_boids):
| 64 | 64 | 216 | 11 | 53 | donno/warehouse51 | boids/boids.py | Python | rule2 | rule2 | 189 | 209 | 189 | 189 | dd471134ad2c431c97b34317be79effae2761c14 | bigcode/the-stack | train |
cded41acac38f25a27dc33cb | train | class | class Point:
"""
Basic point class with just enough to make pseudocode easily appliable.
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return 2
def __iter__(self):
return iter([self.x, self.y])
def __getitem__(self, index):
... | class Point:
| """
Basic point class with just enough to make pseudocode easily appliable.
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return 2
def __iter__(self):
return iter([self.x, self.y])
def __getitem__(self, index):
if index == ... | in vector))
if mag > max_magnitude:
normalizing_factor = max_magnitude / mag
elif mag < min_magnitude:
normalizing_factor = min_magnitude / mag
else:
return vector
return [value * normalizing_factor for value in vector]
class Point:
| 64 | 64 | 143 | 3 | 61 | donno/warehouse51 | boids/boids.py | Python | Point | Point | 55 | 81 | 55 | 55 | e60a21dbd6aad6ce145d643158844f99c06b3f2d | bigcode/the-stack | train |
656dd943611587ba6c1d0491 | train | function | def move_all_boids_to_new_positions(boids):
# Based on the pseudocode from:
# http://www.vergenet.net/~conrad/boids/pseudocode.html
for boid in boids:
flockmates = list(boid.find_local_flockmates(boids))
v1 = rule1(boid, flockmates)
v2 = rule2(boid, flockmates)
v3 = rule3(bo... | def move_all_boids_to_new_positions(boids):
# Based on the pseudocode from:
# http://www.vergenet.net/~conrad/boids/pseudocode.html
| for boid in boids:
flockmates = list(boid.find_local_flockmates(boids))
v1 = rule1(boid, flockmates)
v2 = rule2(boid, flockmates)
v3 = rule3(boid, flockmates)
boid.velocity += v1 + v2 + v3
# Limit speed.
boid.velocity = Vector(
*limit_magnitude(... | .045,
(velocity_y - current_boid.velocity[1]) * 0.045,
)
def move_all_boids_to_new_positions(boids):
# Based on the pseudocode from:
# http://www.vergenet.net/~conrad/boids/pseudocode.html
| 64 | 64 | 165 | 41 | 23 | donno/warehouse51 | boids/boids.py | Python | move_all_boids_to_new_positions | move_all_boids_to_new_positions | 241 | 257 | 241 | 243 | 4c0c727b104ddbc12dc32d2f211c440e68b5c52b | bigcode/the-stack | train |
84636f8b57cebae8e4349d78 | train | function | def run():
boids = setup()
while True:
draw_boids(boids)
move_all_boids_to_new_positions(boids)
| def run():
| boids = setup()
while True:
draw_boids(boids)
move_all_boids_to_new_positions(boids)
| boids = [
Boid(
(random.uniform(0, width), random.uniform(0, height)),
(random.uniform(-20, 20), random.uniform(-20, 20.0)),
)
for _ in range(60)
]
return boids
def run():
| 64 | 64 | 33 | 3 | 60 | donno/warehouse51 | boids/boids.py | Python | run | run | 279 | 283 | 279 | 279 | dc0ed4a5f9ab03b6c3129d557456b910286530dd | bigcode/the-stack | train |
40be139bc7caa162a8cbfa25 | train | function | def rule3(current_boid, flockmates):
"""
Rule 3: Boids try to match velocity with near boids
This is indirectly alignment as velocity is direction.
"""
if not flockmates:
# No nearby boids. maybe should fallback to using all of them.
return (0.0, 0.0)
velocity_x = 0.0
velo... | def rule3(current_boid, flockmates):
| """
Rule 3: Boids try to match velocity with near boids
This is indirectly alignment as velocity is direction.
"""
if not flockmates:
# No nearby boids. maybe should fallback to using all of them.
return (0.0, 0.0)
velocity_x = 0.0
velocity_y = 0.0
for mate in flockma... | 0] * inv_sqr_magnitude
c_y -= difference[1] * inv_sqr_magnitude
return Vector(*limit_magnitude([c_x, c_y], 0.0, 1.0)) * 7.5
def rule3(current_boid, flockmates):
| 64 | 64 | 207 | 10 | 53 | donno/warehouse51 | boids/boids.py | Python | rule3 | rule3 | 212 | 238 | 212 | 212 | 33c76985afe4076f5000a3d43a9a9515007c5827 | bigcode/the-stack | train |
d84cb2f4c595a0ff737e427c | train | function | def rule1(current_boid, flockmates):
"""
Rule 1: Boids try to fly towards the centre of mass of neighbouring boids.
This is cohesion.
"""
def average_position(boids):
if not boids:
# This maybe should be centre of screen (or find nearest flock).
return 0.0, 0.0
... | def rule1(current_boid, flockmates):
| """
Rule 1: Boids try to fly towards the centre of mass of neighbouring boids.
This is cohesion.
"""
def average_position(boids):
if not boids:
# This maybe should be centre of screen (or find nearest flock).
return 0.0, 0.0
sum_x = sum(boid.position[0] for... | ** 2))
# Determine the view angle
angle = math.degrees(
math.acos(dot(self.velocity, difference) / (speed * distance)))
if distance < LOCAL_RANGE and angle < self.VIEW_ANGLE:
yield boid
def rule1(current_boid, flockmates):
| 64 | 64 | 191 | 10 | 53 | donno/warehouse51 | boids/boids.py | Python | rule1 | rule1 | 164 | 186 | 164 | 164 | 14be65b3f0f7ce89b850b118c3ffd833b9cb17c1 | bigcode/the-stack | train |
45ffcc298990348f22838d19 | train | function | def draw_boids(boids):
pass
| def draw_boids(boids):
| pass
| += v1 + v2 + v3
# Limit speed.
boid.velocity = Vector(
*limit_magnitude(boid.velocity, Boid.MIN_SPEED, Boid.MAX_SPEED))
boid.position += boid.velocity * 0.1
def draw_boids(boids):
| 64 | 64 | 11 | 8 | 55 | donno/warehouse51 | boids/boids.py | Python | draw_boids | draw_boids | 260 | 261 | 260 | 260 | 30b9c80d362f83d0cd3d8b41cb5f01e61d268e9d | bigcode/the-stack | train |
c25ccc19a2bf4b50d4cdf125 | train | class | class Boid:
"""A generic simulated flocking creature"""
# This effects where the boid can see and thus where it can see its
# flockmates.
VIEW_ANGLE = 110 # Degrees
# Speed limits to avoid the boids from moving too quickly and stopping.
MIN_SPEED = 20.0
MAX_SPEED = 180.0
def __init__... | class Boid:
| """A generic simulated flocking creature"""
# This effects where the boid can see and thus where it can see its
# flockmates.
VIEW_ANGLE = 110 # Degrees
# Speed limits to avoid the boids from moving too quickly and stopping.
MIN_SPEED = 20.0
MAX_SPEED = 180.0
def __init__(self, initi... | def __add__(self, rhs):
if isinstance(rhs, tuple):
return Vector(self.x + rhs[0], self.y + rhs[1])
return Vector(self.x + rhs.x, self.y + rhs.y)
def __iadd__(self, rhs):
self.x += rhs.x
self.y += rhs.y
return self
def __mul__(self, rhs):
self.x *= r... | 105 | 105 | 352 | 4 | 100 | donno/warehouse51 | boids/boids.py | Python | Boid | Boid | 120 | 161 | 120 | 120 | 227a6ff38b9090459b41dcee053561267dc879f8 | bigcode/the-stack | train |
37cbaa8b01c38191ffd38eb0 | train | class | class MockRequest:
pass
| class MockRequest:
| pass
| ocompleteSelect,
AutocompleteSelectMultiple,
)
from django.contrib.auth.models import User
from django.db import models
from django.forms.widgets import Select
from django.test import SimpleTestCase, TestCase
from django.test.utils import isolate_apps
from .models import Band, Concert, Song
class MockRequest:
| 64 | 64 | 7 | 4 | 59 | txf626/django | tests/modeladmin/tests.py | Python | MockRequest | MockRequest | 23 | 24 | 23 | 23 | c2f32f11ababc05f5815092973121601b5e7d289 | bigcode/the-stack | train |
f901eb50072d35da9326af4c | train | class | class ModelAdminTests(TestCase):
def setUp(self):
self.band = Band.objects.create(
name='The Doors',
bio='',
sign_date=date(1965, 1, 1),
)
self.site = AdminSite()
def test_modeladmin_str(self):
ma = ModelAdmin(Band, self.site)
self.as... | class ModelAdminTests(TestCase):
| def setUp(self):
self.band = Band.objects.create(
name='The Doors',
bio='',
sign_date=date(1965, 1, 1),
)
self.site = AdminSite()
def test_modeladmin_str(self):
ma = ModelAdmin(Band, self.site)
self.assertEqual(str(ma), 'modeladmin.Mod... | from datetime import date
from django import forms
from django.contrib.admin.models import ADDITION, CHANGE, DELETION, LogEntry
from django.contrib.admin.options import (
HORIZONTAL, VERTICAL, ModelAdmin, TabularInline,
get_content_type_for_model,
)
from django.contrib.admin.sites import AdminSite
from django.... | 187 | 256 | 5,619 | 7 | 180 | txf626/django | tests/modeladmin/tests.py | Python | ModelAdminTests | ModelAdminTests | 36 | 698 | 36 | 37 | bd28ae12e838b476c2075bff3b8b48e5bdac6ba6 | bigcode/the-stack | train |
36a543f3faed64df437dafac | train | class | class MockSuperUser:
def has_perm(self, perm):
return True
| class MockSuperUser:
| def has_perm(self, perm):
return True
| ,
)
from django.contrib.auth.models import User
from django.db import models
from django.forms.widgets import Select
from django.test import SimpleTestCase, TestCase
from django.test.utils import isolate_apps
from .models import Band, Concert, Song
class MockRequest:
pass
class MockSuperUser:
| 64 | 64 | 17 | 5 | 58 | txf626/django | tests/modeladmin/tests.py | Python | MockSuperUser | MockSuperUser | 27 | 29 | 27 | 27 | d6093d11cf7b86052b502f746bb2800baaa3ae9c | bigcode/the-stack | train |
9bfc4c78736865b3af340e1f | train | class | class ModelAdminPermissionTests(SimpleTestCase):
class MockUser:
def has_module_perms(self, app_label):
return app_label == 'modeladmin'
class MockViewUser(MockUser):
def has_perm(self, perm):
return perm == 'modeladmin.view_band'
class MockAddUser(MockUser):
... | class ModelAdminPermissionTests(SimpleTestCase):
| class MockUser:
def has_module_perms(self, app_label):
return app_label == 'modeladmin'
class MockViewUser(MockUser):
def has_perm(self, perm):
return perm == 'modeladmin.view_band'
class MockAddUser(MockUser):
def has_perm(self, perm):
return pe... | model_count, perms_needed, protected = ma.get_deleted_objects([self.band], request)
self.assertEqual(deletable_objects, ['Band: The Doors'])
self.assertEqual(model_count, {'bands': 1})
self.assertEqual(perms_needed, set())
self.assertEqual(protected, [])
def test_get_deleted_object... | 255 | 256 | 1,055 | 9 | 246 | txf626/django | tests/modeladmin/tests.py | Python | ModelAdminPermissionTests | ModelAdminPermissionTests | 701 | 834 | 701 | 702 | f8ae35899605a1716735830aae56faeb1154968c | bigcode/the-stack | train |
8575a59f0da1428d2aef5b98 | train | class | @flow.unittest.skip_unless_1n1d()
class TestRepeatAcc(flow.unittest.TestCase):
def test_case(test_case):
arg_dict = OrderedDict()
arg_dict["device_type"] = ["gpu", "cpu"]
arg_dict["shape"] = [(1024, 1024, 4)]
arg_dict["dtype"] = ["float16", "float32", "double"]
arg_dict["acc_... | @flow.unittest.skip_unless_1n1d()
class TestRepeatAcc(flow.unittest.TestCase):
| def test_case(test_case):
arg_dict = OrderedDict()
arg_dict["device_type"] = ["gpu", "cpu"]
arg_dict["shape"] = [(1024, 1024, 4)]
arg_dict["dtype"] = ["float16", "float32", "double"]
arg_dict["acc_num"] = [5]
for arg in GenArgDict(arg_dict):
if arg["device... | ) * acc_num
z = z.astype(np.float32)
test_case.assertTrue(np.allclose(y, z, rtol=1e-5, atol=1e-5))
@flow.unittest.skip_unless_1n1d()
class TestRepeatAcc(flow.unittest.TestCase):
| 64 | 64 | 142 | 23 | 41 | wanghongsheng01/framework_enflame | oneflow/python/test/ops/test_repeat_acc.py | Python | TestRepeatAcc | TestRepeatAcc | 53 | 64 | 53 | 54 | d1fd850c62dd1b0afe6e7e2164f9c57ed6eca4b4 | bigcode/the-stack | train |
72836e8c4d70f97c03166ae6 | train | function | def test_repeat_acc(test_case, device_type, shape, dtype, acc_num):
flow.clear_default_session()
if flow.eager_execution_enabled():
return
@flow.global_function(function_config=func_config)
def RepeatAccJob(a: oft.Numpy.Placeholder(shape)):
if dtype == "float16":
return flow... | def test_repeat_acc(test_case, device_type, shape, dtype, acc_num):
| flow.clear_default_session()
if flow.eager_execution_enabled():
return
@flow.global_function(function_config=func_config)
def RepeatAccJob(a: oft.Numpy.Placeholder(shape)):
if dtype == "float16":
return flow.cast(
flow.acc(flow.repeat(flow.cast(a, flow.float1... | as oft
from collections import OrderedDict
from test_util import Args, GenArgDict
func_config = flow.FunctionConfig()
func_config.default_logical_view(flow.scope.mirrored_view())
func_config.default_data_type(flow.float)
def test_repeat_acc(test_case, device_type, shape, dtype, acc_num):
| 64 | 64 | 205 | 17 | 47 | wanghongsheng01/framework_enflame | oneflow/python/test/ops/test_repeat_acc.py | Python | test_repeat_acc | test_repeat_acc | 29 | 50 | 29 | 29 | f8e84a0eceb519dcc422bab95599ad10d6bc1f83 | bigcode/the-stack | train |
44334d7241c0a8b37fdaf7bc | train | function | def perhaps_convert_float(param, total):
if isinstance(param, float):
param = int(param * total)
return param
| def perhaps_convert_float(param, total):
| if isinstance(param, float):
param = int(param * total)
return param
| import logging
import math
import torch
from seq2seq.utils import gnmt_print
def perhaps_convert_float(param, total):
| 27 | 64 | 27 | 8 | 18 | danielsnider/ecosystem-project-website-template | samples/gnmt/seq2seq/train/lr_scheduler.py | Python | perhaps_convert_float | perhaps_convert_float | 9 | 12 | 9 | 9 | eaa0707f8af749aa9627a1bc3e685773956407d8 | bigcode/the-stack | train |
b8f1fdfb486eb53e7fd007e2 | train | class | class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler):
"""
Learning rate scheduler with exponential warmup and step decay.
"""
def __init__(self, optimizer, iterations, warmup_steps=0,
remain_steps=1.0, decay_interval=None, decay_steps=4,
decay_factor=0.5, last... | class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler):
| """
Learning rate scheduler with exponential warmup and step decay.
"""
def __init__(self, optimizer, iterations, warmup_steps=0,
remain_steps=1.0, decay_interval=None, decay_steps=4,
decay_factor=0.5, last_epoch=-1):
"""
Constructor of WarmupMultiStepLR... | import logging
import math
import torch
from seq2seq.utils import gnmt_print
def perhaps_convert_float(param, total):
if isinstance(param, float):
param = int(param * total)
return param
class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler):
| 61 | 222 | 740 | 15 | 45 | danielsnider/ecosystem-project-website-template | samples/gnmt/seq2seq/train/lr_scheduler.py | Python | WarmupMultiStepLR | WarmupMultiStepLR | 15 | 95 | 15 | 15 | 55ed232187f70c7d132fe04cbd250c00387e6637 | bigcode/the-stack | train |
54d3db89bc3666a9cc42a09e | train | class | class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', mod... | class Migration(migrations.Migration):
| dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(verbose_name='ID', seriali... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import mptt.fields
import django.utils.timezone
from django.conf import settings
from django.contrib.postgres.fields import JSONField
class Migration(migrations.Migration):
| 59 | 119 | 397 | 7 | 51 | smithlc/django-nested-comments | comments/migrations/0001_initial.py | Python | Migration | Migration | 11 | 51 | 11 | 12 | b837371d8e736dca36cebd5d284571126bfaa144 | bigcode/the-stack | train |
ea6d61e23f19443ee8dc11ce | train | class | class TestEditorConfig(AppConfig):
name = 'test_editor'
| class TestEditorConfig(AppConfig):
| name = 'test_editor'
| from django.apps import AppConfig
class TestEditorConfig(AppConfig):
| 14 | 64 | 14 | 7 | 6 | nvdungx/OCPP_TestTool | 02_BE/OCPP_TestSystem/test_editor/apps.py | Python | TestEditorConfig | TestEditorConfig | 4 | 5 | 4 | 4 | 30d7c64e57d3ab258c21ed87fed26c63f848c224 | bigcode/the-stack | train |
f276c9efa4f191c8d5407682 | train | function | def densenet_retinanet(num_classes, backbone='densenet121', inputs=None, modifier=None, **kwargs):
# choose default input
if inputs is None:
inputs = keras.layers.Input((None, None, 3))
blocks = allowed_backbones[backbone]
densenet = DenseNet(blocks=blocks, input_tensor=inputs, include_top=Fals... | def densenet_retinanet(num_classes, backbone='densenet121', inputs=None, modifier=None, **kwargs):
# choose default input
| if inputs is None:
inputs = keras.layers.Input((None, None, 3))
blocks = allowed_backbones[backbone]
densenet = DenseNet(blocks=blocks, input_tensor=inputs, include_top=False, pooling=None, weights=None)
# get last conv layer from the end of each dense block
layer_outputs = [densenet.get_l... | not in allowed_backbones:
raise ValueError('Backbone (\'{}\') not in allowed backbones ({}).'.format(backbone, list(allowed_backbones.keys())))
def densenet_retinanet(num_classes, backbone='densenet121', inputs=None, modifier=None, **kwargs):
# choose default input
| 69 | 70 | 236 | 32 | 37 | i008/keras-retinanet | keras_retinanet/models/densenet.py | Python | densenet_retinanet | densenet_retinanet | 59 | 80 | 59 | 60 | 254f29afb49d57d322263d7352d5848a9106a0fb | bigcode/the-stack | train |
75f560a5c1266dfca39536b0 | train | function | def download_imagenet(backbone):
""" Download pre-trained weights for the specified backbone name. This name is in the format
{backbone}_weights_tf_dim_ordering_tf_kernels_notop where backbone is the densenet + number of layers (e.g. densenet121).
For more info check the explanation from the keras d... | def download_imagenet(backbone):
| """ Download pre-trained weights for the specified backbone name. This name is in the format
{backbone}_weights_tf_dim_ordering_tf_kernels_notop where backbone is the densenet + number of layers (e.g. densenet121).
For more info check the explanation from the keras densenet script itself:
ht... | = {'densenet121': [6, 12, 24, 16], 'densenet169': [6, 12, 32, 32], 'densenet201': [6, 12, 48, 32]}
def download_imagenet(backbone):
| 63 | 64 | 184 | 8 | 55 | i008/keras-retinanet | keras_retinanet/models/densenet.py | Python | download_imagenet | download_imagenet | 30 | 46 | 30 | 30 | 378a2f3515a15eb86c0b889fd45415451a605a3a | bigcode/the-stack | train |
059b2dbb69e2a9237acc594d | train | function | def validate_backbone(backbone):
""" Validate the backbone choice.
# Arguments
backbone : Backbone name.
"""
if backbone not in allowed_backbones:
raise ValueError('Backbone (\'{}\') not in allowed backbones ({}).'.format(backbone, list(allowed_backbones.keys())))
| def validate_backbone(backbone):
| """ Validate the backbone choice.
# Arguments
backbone : Backbone name.
"""
if backbone not in allowed_backbones:
raise ValueError('Backbone (\'{}\') not in allowed backbones ({}).'.format(backbone, list(allowed_backbones.keys())))
| channels_first':
raise ValueError('Weights for "channels_first" format are not available.')
weights_url = origin + file_name.format(backbone)
weights_path = get_file(file_name.format(backbone), weights_url, cache_subdir='models')
return weights_path
def validate_backbone(backbone):
| 64 | 64 | 67 | 7 | 56 | i008/keras-retinanet | keras_retinanet/models/densenet.py | Python | validate_backbone | validate_backbone | 49 | 56 | 49 | 49 | cbba9edcf23e63eb8759f9209163b3cdf1247914 | bigcode/the-stack | train |
10145632fbd08b48c3b6168a | train | function | async def test_async_resolve_media_success(hass: HomeAssistant) -> None:
"""Test successful resolve media."""
client = create_mock_motioneye_client()
config = await setup_mock_motioneye_config_entry(hass, client=client)
device_registry = await dr.async_get_registry(hass)
device = device_registry.... | async def test_async_resolve_media_success(hass: HomeAssistant) -> None:
| """Test successful resolve media."""
client = create_mock_motioneye_client()
config = await setup_mock_motioneye_config_entry(hass, client=client)
device_registry = await dr.async_get_registry(hass)
device = device_registry.async_get_or_create(
config_entry_id=config.entry_id,
ide... | 74565ad414754616000674c87bdc876c#{device.id}#images#/2021-04-12/20-13-39.jpg",
"can_play": True,
"can_expand": False,
"children_media_class": None,
"thumbnail": "http://image",
}
],
}
async def test_async_resolve_media_success(hass:... | 89 | 89 | 297 | 17 | 72 | dermotduffy/hass-motioneye | tests/test_media_source.py | Python | test_async_resolve_media_success | test_async_resolve_media_success | 293 | 322 | 293 | 293 | c8bc05b614c55c36d910a19011472ce25a696227 | bigcode/the-stack | train |
3a5c1863b5a7a9bb5b353436 | train | function | async def test_async_browse_media_images_success(hass: HomeAssistant) -> None:
"""Test successful browse media of images."""
client = create_mock_motioneye_client()
config = await setup_mock_motioneye_config_entry(hass, client=client)
device_registry = await dr.async_get_registry(hass)
device = de... | async def test_async_browse_media_images_success(hass: HomeAssistant) -> None:
| """Test successful browse media of images."""
client = create_mock_motioneye_client()
config = await setup_mock_motioneye_config_entry(hass, client=client)
device_registry = await dr.async_get_registry(hass)
device = device_registry.async_get_or_create(
config_entry_id=config.entry_id,
... | "video",
"media_content_type": "video/mp4",
"media_content_id": f"media-source://motioneye/74565ad414754616000674c87bdc876c#{device.id}#movies#/2021-04-25/00-02-27.mp4",
"can_play": True,
"can_expand": False,
"children_media_class": None,
... | 119 | 119 | 399 | 18 | 101 | dermotduffy/hass-motioneye | tests/test_media_source.py | Python | test_async_browse_media_images_success | test_async_browse_media_images_success | 250 | 290 | 250 | 250 | 27b8fa737de8fd1d1ea46ac1e479a7c79d03c269 | bigcode/the-stack | train |
b9e278a81524b2f35df114d4 | train | function | async def test_async_resolve_media_failure(hass: HomeAssistant) -> None:
"""Test failed resolve media calls."""
client = create_mock_motioneye_client()
config = await setup_mock_motioneye_config_entry(hass, client=client)
device_registry = await dr.async_get_registry(hass)
device = device_registr... | async def test_async_resolve_media_failure(hass: HomeAssistant) -> None:
| """Test failed resolve media calls."""
client = create_mock_motioneye_client()
config = await setup_mock_motioneye_config_entry(hass, client=client)
device_registry = await dr.async_get_registry(hass)
device = device_registry.async_get_or_create(
config_entry_id=config.entry_id,
i... | a movie.
client.get_movie_url = Mock(return_value="http://movie-url")
media = await media_source.async_resolve_media(
hass,
f"{const.URI_SCHEME}{DOMAIN}/{TEST_CONFIG_ENTRY_ID}#{device.id}#movies#/foo.mp4",
)
assert media == PlayMedia(url="http://movie-url", mime_type="video/mp4")
as... | 218 | 218 | 727 | 17 | 201 | dermotduffy/hass-motioneye | tests/test_media_source.py | Python | test_async_resolve_media_failure | test_async_resolve_media_failure | 325 | 408 | 325 | 325 | 798fc2d8d01e5b661d3e2df6851f9dc3aadaff24 | bigcode/the-stack | train |
ebbdac2ebdbcbcc88976e657 | train | function | async def test_async_browse_media_success(hass: HomeAssistant) -> None:
"""Test successful browse media."""
client = create_mock_motioneye_client()
config = await setup_mock_motioneye_config_entry(hass, client=client)
device_registry = await dr.async_get_registry(hass)
device = device_registry.asy... | async def test_async_browse_media_success(hass: HomeAssistant) -> None:
| """Test successful browse media."""
client = create_mock_motioneye_client()
config = await setup_mock_motioneye_config_entry(hass, client=client)
device_registry = await dr.async_get_registry(hass)
device = device_registry.async_get_or_create(
config_entry_id=config.entry_id,
ident... | 25 April 2021, 00:37",
"path": "/2021-04-25/00-36-49.mp4",
},
{
"mimeType": "video/mp4",
"sizeStr": "28.3 MB",
"momentStrShort": "25 Apr, 00:03",
"timestamp": 1619334211.0403328,
"momentStr": "25 April 2021, 00:03",
"pat... | 256 | 256 | 1,626 | 17 | 239 | dermotduffy/hass-motioneye | tests/test_media_source.py | Python | test_async_browse_media_success | test_async_browse_media_success | 70 | 247 | 70 | 70 | 0fed30b72c9de0aa3e7167af3e97d7db0820e176 | bigcode/the-stack | train |
2d5324bd070a720ffd1093c0 | train | class | class TestLibdoc(unittest.TestCase):
def setUp(self):
sys.stdout = StringIO()
def tearDown(self):
sys.stdout = sys.__stdout__
def test_html(self):
output = tempfile.mkstemp(suffix='.html')[1]
libdoc.libdoc('String', output)
assert_equal(sys.stdout.getvalue().strip(... | class TestLibdoc(unittest.TestCase):
| def setUp(self):
sys.stdout = StringIO()
def tearDown(self):
sys.stdout = sys.__stdout__
def test_html(self):
output = tempfile.mkstemp(suffix='.html')[1]
libdoc.libdoc('String', output)
assert_equal(sys.stdout.getvalue().strip(), output)
with open(output) a... | from io import StringIO
import sys
import tempfile
import unittest
from robot import libdoc
from robot.utils.asserts import assert_equal
class TestLibdoc(unittest.TestCase):
| 38 | 85 | 284 | 8 | 29 | rdagum/robotframework | utest/libdoc/test_libdoc_api.py | Python | TestLibdoc | TestLibdoc | 10 | 44 | 10 | 11 | 6accd242e6c7d4399818d583daa19c1b0a18254f | bigcode/the-stack | train |
deed9ed47fbb023359448b2b | train | class | class AC:
def __init__(self, net_list, optimizers_list, action_range=1., gamma=0.9):
assert len(net_list) == 2
assert len(optimizers_list) == 2
self.name = 'AC'
self.actor, self.critic = net_list
assert isinstance(self.critic, ValueNetwork)
assert isinstance(self.acto... | class AC:
| def __init__(self, net_list, optimizers_list, action_range=1., gamma=0.9):
assert len(net_list) == 2
assert len(optimizers_list) == 2
self.name = 'AC'
self.actor, self.critic = net_list
assert isinstance(self.critic, ValueNetwork)
assert isinstance(self.actor, Stochas... | View more on MorvanZhou's tutorial page: https://morvanzhou.github.io/tutorials/
Environment
------------
CartPole-v0: https://gym.openai.com/envs/CartPole-v0
A pole is attached by an un-actuated joint to a cart, which moves along a
frictionless track. The system is controlled by applying a force of +1 or -1
to the c... | 256 | 256 | 1,163 | 3 | 253 | Ericcsr/RLzoo | baselines/algorithms/ac/ac.py | Python | AC | AC | 62 | 186 | 62 | 62 | 8a34cb278256c6241f0c6f96a9e08386fa84125b | bigcode/the-stack | train |
06699f62ca54e6f6b25e1da4 | train | function | def find_template():
default_datasource = get_default_datasource()
if settings.STORAGE_ENGINE == MONGO:
from watchmen_boot.storage.mongo.mongo_client import MongoEngine
from watchmen_boot.guid.storage.mongo.mongo_template import MongoStorage
engine = MongoEngine(default_datasource)
... | def find_template():
| default_datasource = get_default_datasource()
if settings.STORAGE_ENGINE == MONGO:
from watchmen_boot.storage.mongo.mongo_client import MongoEngine
from watchmen_boot.guid.storage.mongo.mongo_template import MongoStorage
engine = MongoEngine(default_datasource)
return MongoStorag... | from watchmen_boot.config.config import settings
from watchmen_boot.constants.database.constant import MONGO, MYSQL, ORACLE
from watchmen_boot.utils.datasource_utils import get_default_datasource
def find_template():
| 42 | 64 | 175 | 4 | 37 | Indexical-Metrics-Measure-Advisory/watchmen-boot | watchmen_boot/guid/storage/choise_storage.py | Python | find_template | find_template | 6 | 22 | 6 | 6 | 2466654d3a76029446342ce1d3533977ee7dd37b | bigcode/the-stack | train |
d4d3d4e8ad394e423d03e8d2 | train | function | def get_integration_runtime_connection_info(integration_runtime_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
workspace_name: Optional[str] = None,
opts: Optional[... | def get_integration_runtime_connection_info(integration_runtime_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
workspace_name: Optional[str] = None,
opts: Optional[... | """
Connection information for encrypting the on-premises data source credentials.
:param str integration_runtime_name: Integration runtime name
:param str resource_group_name: The name of the resource group. The name is case insensitive.
:param str workspace_name: The name of the workspace.
"... | _cert_thumbprint,
is_identity_cert_exprired=self.is_identity_cert_exprired,
public_key=self.public_key,
service_token=self.service_token,
version=self.version)
def get_integration_runtime_connection_info(integration_runtime_name: Optional[str] = None,
... | 98 | 98 | 327 | 62 | 36 | pulumi-bot/pulumi-azure-native | sdk/python/pulumi_azure_native/synapse/v20210301/get_integration_runtime_connection_info.py | Python | get_integration_runtime_connection_info | get_integration_runtime_connection_info | 105 | 133 | 105 | 108 | 69c0ac8328a191e239e3d42fe82017e551f1bd98 | bigcode/the-stack | train |
fecaa5477de86bc825991fc7 | train | class | @pulumi.output_type
class GetIntegrationRuntimeConnectionInfoResult:
"""
Connection information for encrypting the on-premises data source credentials.
"""
def __init__(__self__, host_service_uri=None, identity_cert_thumbprint=None, is_identity_cert_exprired=None, public_key=None, service_token=None, ve... | @pulumi.output_type
class GetIntegrationRuntimeConnectionInfoResult:
| """
Connection information for encrypting the on-premises data source credentials.
"""
def __init__(__self__, host_service_uri=None, identity_cert_thumbprint=None, is_identity_cert_exprired=None, public_key=None, service_token=None, version=None):
if host_service_uri and not isinstance(host_serv... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__a... | 124 | 201 | 672 | 14 | 110 | pulumi-bot/pulumi-azure-native | sdk/python/pulumi_azure_native/synapse/v20210301/get_integration_runtime_connection_info.py | Python | GetIntegrationRuntimeConnectionInfoResult | GetIntegrationRuntimeConnectionInfoResult | 17 | 88 | 17 | 18 | 2070b04856c7cc648b07918eee61f0185ffc6266 | bigcode/the-stack | train |
33ce4393f2da6fc96e9be65d | train | class | class AwaitableGetIntegrationRuntimeConnectionInfoResult(GetIntegrationRuntimeConnectionInfoResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetIntegrationRuntimeConnectionInfoResult(
host_service_uri=self.host_service_uri,
... | class AwaitableGetIntegrationRuntimeConnectionInfoResult(GetIntegrationRuntimeConnectionInfoResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return GetIntegrationRuntimeConnectionInfoResult(
host_service_uri=self.host_service_uri,
identity_cert_thumbprint=self.identity_cert_thumbprint,
is_identity_cert_exprired=self.is_identity_cert_exprired,
... | property
@pulumi.getter
def version(self) -> str:
"""
The integration runtime version.
"""
return pulumi.get(self, "version")
class AwaitableGetIntegrationRuntimeConnectionInfoResult(GetIntegrationRuntimeConnectionInfoResult):
# pylint: disable=using-constant-test
| 64 | 64 | 103 | 27 | 37 | pulumi-bot/pulumi-azure-native | sdk/python/pulumi_azure_native/synapse/v20210301/get_integration_runtime_connection_info.py | Python | AwaitableGetIntegrationRuntimeConnectionInfoResult | AwaitableGetIntegrationRuntimeConnectionInfoResult | 91 | 102 | 91 | 92 | 8f1a0accfe2c19b5bb43f32c9b3128ed56f33f33 | bigcode/the-stack | train |
999cf2943e613c145132db3b | train | function | def process_part2(file: Path) -> int:
"""
Process input file yielding the submission value
:param file: file containing the input values
:return: value to submit
"""
lines = (l for l in open(file))
next(lines) # skip timestamp
bus_id_offsets = {int(bus_id): -i
fo... | def process_part2(file: Path) -> int:
| """
Process input file yielding the submission value
:param file: file containing the input values
:return: value to submit
"""
lines = (l for l in open(file))
next(lines) # skip timestamp
bus_id_offsets = {int(bus_id): -i
for i, bus_id in enumerate(next(lines).s... | _id == 0 for bus_id in bus_id_list):
time += 1
earliest_bus = next(bus_id for bus_id in bus_id_list if time % bus_id == 0)
submission = (time - timestamp) * earliest_bus
return submission
def process_part2(file: Path) -> int:
| 68 | 68 | 228 | 11 | 56 | MatthieuMichon/advent-of-code | 2020/day-13/process.py | Python | process_part2 | process_part2 | 36 | 64 | 36 | 36 | 73a6856bcf0e9d7fa7ef67d68206643027ec0929 | bigcode/the-stack | train |
308ddb409ca974683bf1a262 | train | function | def process(file: Path) -> int:
"""
Process input file yielding the submission value
:param file: file containing the input values
:return: value to submit
"""
lines = (l for l in open(file))
timestamp = int(next(lines))
bus_id_list = [int(bus_id) for bus_id in next(lines).strip().spli... | def process(file: Path) -> int:
| """
Process input file yielding the submission value
:param file: file containing the input values
:return: value to submit
"""
lines = (l for l in open(file))
timestamp = int(next(lines))
bus_id_list = [int(bus_id) for bus_id in next(lines).strip().split(',')
if bus... | #!/usr/bin/env python
"""
Advent of Code 2020: Day 13
"""
import sys
from pathlib import Path
import os
TXT_FILES = [Path(f) for f in os.listdir('./') if '.txt' in f]
def process(file: Path) -> int:
| 61 | 64 | 157 | 9 | 52 | MatthieuMichon/advent-of-code | 2020/day-13/process.py | Python | process | process | 14 | 33 | 14 | 14 | c41eb32d6b92c7219ef1c6dd457ab8dd3ccac521 | bigcode/the-stack | train |
21a7335c4cfd949ac78b9b7e | train | function | def main() -> int:
"""
Main function
:return: Shell exit code
"""
for file in TXT_FILES:
submission = process(file=Path(file))
print(f'In file {file}, submission: {submission}')
print('Part 2')
for file in TXT_FILES:
submission = process_part2(file=Path(file))
... | def main() -> int:
| """
Main function
:return: Shell exit code
"""
for file in TXT_FILES:
submission = process(file=Path(file))
print(f'In file {file}, submission: {submission}')
print('Part 2')
for file in TXT_FILES:
submission = process_part2(file=Path(file))
print(f'In fil... | ())
for t in range(time-5, time+max(bus_id_list)):
print(f'{t}\t{" ".join("D" if (t % b == 0) else "." for b in bus_id_list)}')
submission = time
return submission
def main() -> int:
| 64 | 64 | 96 | 6 | 57 | MatthieuMichon/advent-of-code | 2020/day-13/process.py | Python | main | main | 67 | 84 | 67 | 67 | 702dc824786e70c5b4804dad5c3d885d7a61bb38 | bigcode/the-stack | train |
b0a20d9f3d84aa3eef2fd346 | train | class | class TokenValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name='token',
parent_name='scattermapbox.stream',
**kwargs
):
super(TokenValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | class TokenValidator(_plotly_utils.basevalidators.StringValidator):
| def __init__(
self,
plotly_name='token',
parent_name='scattermapbox.stream',
**kwargs
):
super(TokenValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'calc'),
no_b... | import _plotly_utils.basevalidators
class TokenValidator(_plotly_utils.basevalidators.StringValidator):
| 20 | 64 | 119 | 12 | 7 | gnestor/plotly.py | plotly/validators/scattermapbox/stream/_token.py | Python | TokenValidator | TokenValidator | 4 | 20 | 4 | 5 | 08a21f14187d6c7acbd53da161e6347dc6106e5e | bigcode/the-stack | train |
66a3cc6b6fc409915b508b86 | train | class | class TestSelectGate(unittest.TestCase):
def test_get_full_display_string(self):
"""
Tests that the method get_full_display_string returns the correct
string.
"""
#Initialize the circuit:
circuit = ic.IBMCircuit(10)
#Initialize the input wires:
w1 = i... | class TestSelectGate(unittest.TestCase):
| def test_get_full_display_string(self):
"""
Tests that the method get_full_display_string returns the correct
string.
"""
#Initialize the circuit:
circuit = ic.IBMCircuit(10)
#Initialize the input wires:
w1 = iw.IBMInputWire("w1", circuit)
w2 =... | Date Name Modification
# ---- ---- ------------
# 17 Oct 2012 SY Original Version
# *****************************************************************
import ibm_batch as ib
import ibm_wire as iw
import ibm_gate_select as igs
import ibm_circuit as ic
import unitte... | 86 | 86 | 289 | 8 | 77 | y4n9squared/HEtest | hetest/python/circuit_generation/ibm/ibm_gate_select_test.py | Python | TestSelectGate | TestSelectGate | 31 | 59 | 31 | 32 | 6153f4400546cf65c25ab2e56f74b9ea06f3dfe8 | bigcode/the-stack | train |
00d30312f9afd2146fff16b0 | train | function | @pytest.mark.version('>=3.0')
def test_1(act_1: Action):
act_1.expected_stderr = expected_stderr_1
act_1.execute()
assert act_1.clean_expected_stderr == act_1.clean_stderr
| @pytest.mark.version('>=3.0')
def test_1(act_1: Action):
| act_1.expected_stderr = expected_stderr_1
act_1.execute()
assert act_1.clean_expected_stderr == act_1.clean_stderr
| arithmetic exception, numeric overflow, or string truncation
-string right truncation
-expected length 14, actual 16
-At block line: 4, col: 9
"""
@pytest.mark.version('>=3.0')
def test_1(act_1: Action):
| 64 | 64 | 56 | 19 | 45 | reevespaul/firebird-qa | tests/bugs/core_4082_test.py | Python | test_1 | test_1 | 45 | 49 | 45 | 46 | c78d4962b63add1ebe8bc0140a86c90d20bd349f | bigcode/the-stack | train |
e957a104e48b9dcb2e599549 | train | function | def create(kernel):
result = Creature()
result.template = "object/creature/npc/droid/crafted/shared_tt_8l_y7_droid.iff"
result.attribute_template_id = 3
result.stfName("droid_name","tt_8l_y7_crafted")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | def create(kernel):
| result = Creature()
result.template = "object/creature/npc/droid/crafted/shared_tt_8l_y7_droid.iff"
result.attribute_template_id = 3
result.stfName("droid_name","tt_8l_y7_crafted")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
| 46 | 64 | 81 | 4 | 42 | obi-two/GameServer | data/scripts/templates/object/creature/npc/droid/crafted/shared_tt_8l_y7_droid.py | Python | create | create | 7 | 17 | 7 | 7 | 60264f80890df757cfb431e8f3bf890067f8c6e4 | bigcode/the-stack | train |
b5bf329fd4d3c6591fda4d38 | train | function | def update_node(self, context):
if self.operate_type in {'=', '>', '<'}:
if self.operate_type == '=': self.create_input('SimpleNodeSocketFloat', 'epsilon', 'Epsilon')
self.create_output('SimpleNodeSocketBool', 'bool_output', 'OutBool')
else:
self.remove_input('epsilon')
self.remo... | def update_node(self, context):
| if self.operate_type in {'=', '>', '<'}:
if self.operate_type == '=': self.create_input('SimpleNodeSocketFloat', 'epsilon', 'Epsilon')
self.create_output('SimpleNodeSocketBool', 'bool_output', 'OutBool')
else:
self.remove_input('epsilon')
self.remove_output('bool_output')
if... | import bpy
from bpy.props import *
from ...nodes.BASE.node_base import RenderNodeBase
# from ...utility import source_attr
from mathutils import Color, Vector
from math import degrees,radians
from math import sin, cos, tan, asin, acos, atan
def update_node(self, context):
| 64 | 64 | 149 | 7 | 56 | atticus-lv/RenderStackNode | nodes/Utility/Math.py | Python | update_node | update_node | 10 | 24 | 10 | 10 | 995315e6692200f709a24efc1f83f98b01150e90 | bigcode/the-stack | train |
8b1f07bb5d7060c5fbdbb216 | train | function | def register():
bpy.utils.register_class(RenderNodeMath)
| def register():
| bpy.utils.register_class(RenderNodeMath)
| .inputs['value2'].get_value()
self.outputs['output'].set_value(max(s1, s2))
elif self.operate_type == 'min':
s2 = self.inputs['value2'].get_value()
self.outputs['output'].set_value(min(s1, s2))
def register():
| 64 | 64 | 12 | 3 | 61 | atticus-lv/RenderStackNode | nodes/Utility/Math.py | Python | register | register | 124 | 125 | 124 | 124 | 66ebd205c48841792638c8e3218079adadd97d09 | bigcode/the-stack | train |
d9bb5234abf7726e2dc0a555 | train | function | def unregister():
bpy.utils.unregister_class(RenderNodeMath)
| def unregister():
| bpy.utils.unregister_class(RenderNodeMath)
| output'].set_value(max(s1, s2))
elif self.operate_type == 'min':
s2 = self.inputs['value2'].get_value()
self.outputs['output'].set_value(min(s1, s2))
def register():
bpy.utils.register_class(RenderNodeMath)
def unregister():
| 64 | 64 | 12 | 3 | 61 | atticus-lv/RenderStackNode | nodes/Utility/Math.py | Python | unregister | unregister | 128 | 129 | 128 | 128 | c7e3f5a77c73b87c9e131bd9e862a1651fb2e82f | bigcode/the-stack | train |
ff707a444006fef3d2f24d0e | train | class | class RenderNodeMath(RenderNodeBase):
bl_idname = 'RenderNodeMath'
bl_label = 'Math'
operate_type: EnumProperty(
name='Type',
items=[
("", "Function", ""),
('+', 'Add', ''),
('-', 'Subtract', ''),
('*', 'Muitiply', ''),
('/', 'Div... | class RenderNodeMath(RenderNodeBase):
| bl_idname = 'RenderNodeMath'
bl_label = 'Math'
operate_type: EnumProperty(
name='Type',
items=[
("", "Function", ""),
('+', 'Add', ''),
('-', 'Subtract', ''),
('*', 'Muitiply', ''),
('/', 'Divide', ''),
('', 'Comparis... | import bpy
from bpy.props import *
from ...nodes.BASE.node_base import RenderNodeBase
# from ...utility import source_attr
from mathutils import Color, Vector
from math import degrees,radians
from math import sin, cos, tan, asin, acos, atan
def update_node(self, context):
if self.operate_type in {'=', '>', '<'}:
... | 214 | 247 | 826 | 8 | 206 | atticus-lv/RenderStackNode | nodes/Utility/Math.py | Python | RenderNodeMath | RenderNodeMath | 27 | 121 | 27 | 27 | 8f20a969f64b1947579e989ecae629409d8ecadc | bigcode/the-stack | train |
d127b173749c6304e848a08d | train | class | class CocoEval(tf.keras.callbacks.Callback):
""" Performs COCO evaluation on each epoch.
"""
def __init__(self, generator, tensorboard=None, threshold=0.05):
""" CocoEval callback intializer.
Args
generator : The generator used for creating validation data.
tensorb... | class CocoEval(tf.keras.callbacks.Callback):
| """ Performs COCO evaluation on each epoch.
"""
def __init__(self, generator, tensorboard=None, threshold=0.05):
""" CocoEval callback intializer.
Args
generator : The generator used for creating validation data.
tensorboard : If given, the results will be written ... | """
Copyright 2017-2018 Fizyr (https://fizyr.com)
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 w... | 151 | 178 | 594 | 8 | 142 | Accioy/keras-retinanet | keras_retinanet/callbacks/coco.py | Python | CocoEval | CocoEval | 21 | 66 | 21 | 21 | 05d45c30e17f29a26b89453fd918cd38ec35d1f4 | bigcode/the-stack | train |
3cb950d83b613950d2d1d6f6 | train | function | def test_apply_cleaning_windographer():
data = bw.load_campbell_scientific(bw.demo_datasets.demo_campbell_scientific_data)
data_clnd = bw.apply_cleaning_windographer(data, bw.demo_datasets.demo_windographer_flagging_log)
data_clnd2 = bw.apply_cleaning_windographer(data, bw.demo_datasets.demo_windographer_fl... | def test_apply_cleaning_windographer():
| data = bw.load_campbell_scientific(bw.demo_datasets.demo_campbell_scientific_data)
data_clnd = bw.apply_cleaning_windographer(data, bw.demo_datasets.demo_windographer_flagging_log)
data_clnd2 = bw.apply_cleaning_windographer(data, bw.demo_datasets.demo_windographer_flagging_log2, dayfirst=True)
assert ... | import pytest
import brightwind as bw
import os
DEMO_DATA_FOLDER = os.path.join(os.path.dirname(__file__), '../brightwind/demo_datasets')
def test_apply_cleaning_windographer():
| 42 | 64 | 117 | 9 | 33 | altosphere/brightwind | tests/test_load.py | Python | test_apply_cleaning_windographer | test_apply_cleaning_windographer | 8 | 13 | 8 | 8 | d51d5324720b17692534f8497d03742776164438 | bigcode/the-stack | train |
c886098d5744dc22ef60a404 | train | function | def test_load_csv():
data = bw.load_csv(os.path.join(DEMO_DATA_FOLDER, 'demo_data.csv'))
data2 = bw.load_csv(os.path.join(DEMO_DATA_FOLDER, 'demo_data2.csv'), dayfirst=True)
data3 = bw.load_csv(os.path.join(DEMO_DATA_FOLDER, 'demo_data3.csv'), dayfirst=True)
data4 = bw.load_csv(os.path.join(DEMO_DATA_FO... | def test_load_csv():
| data = bw.load_csv(os.path.join(DEMO_DATA_FOLDER, 'demo_data.csv'))
data2 = bw.load_csv(os.path.join(DEMO_DATA_FOLDER, 'demo_data2.csv'), dayfirst=True)
data3 = bw.load_csv(os.path.join(DEMO_DATA_FOLDER, 'demo_data3.csv'), dayfirst=True)
data4 = bw.load_csv(os.path.join(DEMO_DATA_FOLDER, 'demo_data4.csv... | (-999) ==
data_clnd4.drop(['RECORD', 'Site', 'LoggerID'], axis=1).fillna(-999)).all().all()
assert (data_clnd3.drop(['RECORD', 'Site', 'LoggerID'], axis=1).fillna(-999) ==
data_clnd5.drop(['RECORD', 'Site', 'LoggerID'], axis=1).fillna(-999)).all().all()
def test_load_csv():
| 98 | 98 | 327 | 5 | 93 | altosphere/brightwind | tests/test_load.py | Python | test_load_csv | test_load_csv | 33 | 44 | 33 | 33 | 2852a01f1748bb42ca3578c798441b7bd1607dfc | bigcode/the-stack | train |
28f4d4798b40024ace92c41f | train | function | def test_load_campbell_scientific():
data = bw.load_campbell_scientific(os.path.join(DEMO_DATA_FOLDER, 'campbell_scientific_demo_data.csv'))
data1 = bw.load_campbell_scientific(os.path.join(DEMO_DATA_FOLDER, 'campbell_scientific_demo_data1.csv'), dayfirst=True)
assert (data['2016-01-09 15:30:00':'2016-01-1... | def test_load_campbell_scientific():
| data = bw.load_campbell_scientific(os.path.join(DEMO_DATA_FOLDER, 'campbell_scientific_demo_data.csv'))
data1 = bw.load_campbell_scientific(os.path.join(DEMO_DATA_FOLDER, 'campbell_scientific_demo_data1.csv'), dayfirst=True)
assert (data['2016-01-09 15:30:00':'2016-01-10 23:50:00'].fillna(-999) ==
... | -10 23:50:00'].fillna(-999) ==
data2['2016-01-09 15:30:00':'2016-01-10 23:50:00'].fillna(-999)).all().all()
def test_load_campbell_scientific():
| 64 | 64 | 150 | 10 | 54 | altosphere/brightwind | tests/test_load.py | Python | test_load_campbell_scientific | test_load_campbell_scientific | 58 | 63 | 58 | 58 | 8b3d58bf7b6b409d8d3398fac986c2e4a0040ea0 | bigcode/the-stack | train |
aa758268f39c7f97ed86af2b | train | function | def test_apply_cleaning():
data = bw.load_campbell_scientific(bw.demo_datasets.demo_campbell_scientific_data)
data_clnd2 = bw.apply_cleaning_windographer(data, bw.demo_datasets.demo_windographer_flagging_log2, dayfirst=True)
data_clnd3 = bw.apply_cleaning(data, bw.demo_datasets.demo_cleaning_file)
data_... | def test_apply_cleaning():
| data = bw.load_campbell_scientific(bw.demo_datasets.demo_campbell_scientific_data)
data_clnd2 = bw.apply_cleaning_windographer(data, bw.demo_datasets.demo_windographer_flagging_log2, dayfirst=True)
data_clnd3 = bw.apply_cleaning(data, bw.demo_datasets.demo_cleaning_file)
data_clnd4 = bw.apply_cleaning(d... | _campbell_scientific_data)
data_clnd = bw.apply_cleaning_windographer(data, bw.demo_datasets.demo_windographer_flagging_log)
data_clnd2 = bw.apply_cleaning_windographer(data, bw.demo_datasets.demo_windographer_flagging_log2, dayfirst=True)
assert (data_clnd2.fillna(-999) == data_clnd.fillna(-999)).all().al... | 97 | 97 | 325 | 6 | 91 | altosphere/brightwind | tests/test_load.py | Python | test_apply_cleaning | test_apply_cleaning | 16 | 30 | 16 | 16 | 2b1616ea747834fd5d162a3ec196bd2605d22ede | bigcode/the-stack | train |
0859d3edd127fbca75e910f8 | train | function | def test_load_windographer_txt():
data = bw.load_windographer_txt(os.path.join(DEMO_DATA_FOLDER, 'windographer_demo_data.txt'))
data1 = bw.load_windographer_txt(os.path.join(DEMO_DATA_FOLDER, 'windographer_demo_data1.txt'), dayfirst=True)
data2 = bw.load_windographer_txt(os.path.join(DEMO_DATA_FOLDER, 'wind... | def test_load_windographer_txt():
| data = bw.load_windographer_txt(os.path.join(DEMO_DATA_FOLDER, 'windographer_demo_data.txt'))
data1 = bw.load_windographer_txt(os.path.join(DEMO_DATA_FOLDER, 'windographer_demo_data1.txt'), dayfirst=True)
data2 = bw.load_windographer_txt(os.path.join(DEMO_DATA_FOLDER, 'windographer_demo_data2.txt'), dayfirs... | 15:30:00':'2016-01-10 23:50:00'].fillna(-999) ==
data4['2016-01-09 15:30:00':'2016-01-10 23:50:00'].fillna(-999)).all().all()
def test_load_windographer_txt():
| 73 | 73 | 244 | 8 | 65 | altosphere/brightwind | tests/test_load.py | Python | test_load_windographer_txt | test_load_windographer_txt | 47 | 55 | 47 | 47 | 49a0e58286548c40c9a3c089c8f4ca53567d9477 | bigcode/the-stack | train |
a2ad8799babfee709c242038 | train | function | @Client.on_message(filters.command("help", ["/", "!"]))
async def help(c, m):
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="💵 Colabore", callback_data="donate")],
[InlineKeyboardButton(text="💻 Meu desenvolvedor", url="t.me/khaledsecond")],
]... | @Client.on_message(filters.command("help", ["/", "!"]))
async def help(c, m):
| keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text="💵 Colabore", callback_data="donate")],
[InlineKeyboardButton(text="💻 Meu desenvolvedor", url="t.me/khaledsecond")],
]
)
await m.reply_text(hlp, reply_markup=keyboard)
| Button(
text="🔎 Consulte inline", switch_inline_query_current_chat=""
)
]
]
)
await m.reply_text(strt, reply_markup=keybaard)
# HELP COMMAND
@Client.on_message(filters.command("help", ["/", "!"]))
async def help(c, m):
| 64 | 64 | 93 | 21 | 42 | joaokhaled/InfoPlaca | plugins/start.py | Python | help | help | 28 | 36 | 28 | 29 | cbce5a8adba319b0cc633b2a8b8f89333521cbca | bigcode/the-stack | train |
b907cb8494a863157f4f2910 | train | function | @Client.on_message(filters.command("start", ["/", "!"]))
async def start(c, m):
add_user(user_id=m.from_user.id)
keybaard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="🔎 Consulte inline", switch_inline_query_current_chat=""
... | @Client.on_message(filters.command("start", ["/", "!"]))
async def start(c, m):
| add_user(user_id=m.from_user.id)
keybaard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="🔎 Consulte inline", switch_inline_query_current_chat=""
)
]
]
)
await m.reply_text(strt, reply_ma... | from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from bot_strings import strt, hlp
from daba import add_user
# START COMMAND
@Client.on_message(filters.command("start", ["/", "!"]))
async def start(c, m):
| 62 | 64 | 88 | 21 | 40 | joaokhaled/InfoPlaca | plugins/start.py | Python | start | start | 12 | 24 | 12 | 13 | 70f3b5c403fe2585e4777292aea364d259798dc9 | bigcode/the-stack | train |
96d4b9fd73c1a54f9eeb4eb3 | train | class | class GroupAdmin(admin.ModelAdmin):
form = GroupAdminForm
prepopulated_fields = {"slug": ("name",)}
search_fields = ('name', 'description')
list_filter = ('is_active',)
| class GroupAdmin(admin.ModelAdmin):
| form = GroupAdminForm
prepopulated_fields = {"slug": ("name",)}
search_fields = ('name', 'description')
list_filter = ('is_active',)
| from django.contrib import admin
from .forms import GroupAdminForm
from .models import Group
class GroupAdmin(admin.ModelAdmin):
| 27 | 64 | 46 | 7 | 19 | rva-data/rvaconnect | rvaconnect/circles/admin.py | Python | GroupAdmin | GroupAdmin | 7 | 11 | 7 | 7 | 8225dd2cfd633f6bc6bfc21f6fdb76d53ac5c03c | bigcode/the-stack | train |
0c462f28fc429e79e5a94444 | train | function | def draw():
pygame.draw.circle(screen, (0, 0, 0), (250, 250), 125)
pygame.display.update()
button1 = Button(buttonwin, text='Draw', command=draw)
button1.pack(side=LEFT)
root.update()
| def draw():
| pygame.draw.circle(screen, (0, 0, 0), (250, 250), 125)
pygame.display.update()
button1 = Button(buttonwin, text='Draw', command=draw)
button1.pack(side=LEFT)
root.update()
| )
os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
os.environ['SDL_VIDEODRIVER'] = 'windib'
screen = pygame.display.set_mode((500, 500))
screen.fill((255, 255, 255))
pygame.display.init()
pygame.display.update()
def draw():
| 64 | 64 | 60 | 3 | 61 | bigfoolliu/liu_aistuff | projects/tk_projects/happyBirthday/learning_code/learning_code2.py | Python | draw | draw | 26 | 31 | 26 | 26 | 6cf3a5b48155950311a122bf9b75812431a919f4 | bigcode/the-stack | train |
1d8867009bc46cba120f5c76 | train | function | @app.route('/', methods=['POST'])
def post_request():
action = request.headers.get('x-amz-target')
data = json.loads(to_str(request.data))
response = None
if action == '%s.ListDeliveryStreams' % ACTION_HEADER_PREFIX:
response = {
'DeliveryStreamNames': get_delivery_stream_names(),
... | @app.route('/', methods=['POST'])
def post_request():
| action = request.headers.get('x-amz-target')
data = json.loads(to_str(request.data))
response = None
if action == '%s.ListDeliveryStreams' % ACTION_HEADER_PREFIX:
response = {
'DeliveryStreamNames': get_delivery_stream_names(),
'HasMoreDeliveryStreams': False
}
... | _STREAM,
payload={'n': event_publisher.get_hash(stream_name)})
return {}
def get_stream(stream_name):
if stream_name not in DELIVERY_STREAMS:
return None
return DELIVERY_STREAMS[stream_name]
def bucket_name(bucket_arn):
return bucket_arn.split(':::')[-1]
def role_arn(stream_name):... | 200 | 200 | 669 | 11 | 189 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | post_request | post_request | 209 | 276 | 209 | 210 | af19a3dad1b841ad48691a31729aa453cd915c17 | bigcode/the-stack | train |
81ea96ab6faf6fc0218b2f41 | train | function | def error_response(msg, code=500, error_type='InternalFailure'):
return aws_responses.flask_error_response(msg, code=code, error_type=error_type)
| def error_response(msg, code=500, error_type='InternalFailure'):
| return aws_responses.flask_error_response(msg, code=code, error_type=error_type)
| _not_found(stream_name):
msg = 'Firehose %s under account %s not found.' % (stream_name, TEST_AWS_ACCOUNT_ID)
return error_response(msg, code=400, error_type='ResourceNotFoundException')
def error_response(msg, code=500, error_type='InternalFailure'):
| 64 | 64 | 36 | 15 | 49 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | error_response | error_response | 205 | 206 | 205 | 205 | 88224623b5cf39ddac20bc00155efad7ee3dc387 | bigcode/the-stack | train |
dd1f4f1f1d4dc95522767fd5 | train | function | def serve(port, quiet=True):
generic_proxy.serve_flask_app(app=app, port=port, quiet=quiet)
| def serve(port, quiet=True):
| generic_proxy.serve_flask_app(app=app, port=port, quiet=quiet)
| StartTagKey'),
data.get('Limit', 50))
else:
response = error_response('Unknown action "%s"' % action, code=400, error_type='InvalidAction')
if isinstance(response, dict):
response = jsonify(response)
return response
def serve(port, quiet=True):
| 64 | 64 | 27 | 7 | 56 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | serve | serve | 279 | 280 | 279 | 279 | 551cc0b2c8879e5cc743fbea1ee80ed088dbe8be | bigcode/the-stack | train |
350c82f340698033fe651047 | train | function | def role_arn(stream_name):
return 'arn:aws:iam::%s:role/%s' % (TEST_AWS_ACCOUNT_ID, stream_name)
| def role_arn(stream_name):
| return 'arn:aws:iam::%s:role/%s' % (TEST_AWS_ACCOUNT_ID, stream_name)
| _hash(stream_name)})
return {}
def get_stream(stream_name):
if stream_name not in DELIVERY_STREAMS:
return None
return DELIVERY_STREAMS[stream_name]
def bucket_name(bucket_arn):
return bucket_arn.split(':::')[-1]
def role_arn(stream_name):
| 64 | 64 | 34 | 7 | 57 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | role_arn | role_arn | 196 | 197 | 196 | 196 | 4939107250693d7b0716787e64e0f9b0217b487f | bigcode/the-stack | train |
06519108d04ca25a2ed3be1b | train | function | def delete_stream(stream_name):
stream = DELIVERY_STREAMS.pop(stream_name, {})
if not stream:
return error_not_found(stream_name)
# record event
event_publisher.fire_event(event_publisher.EVENT_FIREHOSE_DELETE_STREAM,
payload={'n': event_publisher.get_hash(stream_name)})
return {}
| def delete_stream(stream_name):
| stream = DELIVERY_STREAMS.pop(stream_name, {})
if not stream:
return error_not_found(stream_name)
# record event
event_publisher.fire_event(event_publisher.EVENT_FIREHOSE_DELETE_STREAM,
payload={'n': event_publisher.get_hash(stream_name)})
return {}
| kinesis_connector.listen_to_kinesis(
stream_name=kinesis_stream_name, fh_d_stream=stream_name,
listener_func=process_records, wait_until_started=True,
ddb_lease_table_suffix='-firehose', region_name=region_name)
return stream
def delete_stream(stream_name):
| 64 | 64 | 68 | 6 | 57 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | delete_stream | delete_stream | 174 | 183 | 174 | 174 | 01f6ace5bf46dd6b9119a4d70e9202c9cde252a5 | bigcode/the-stack | train |
44339b9db2d279334d1074d2 | train | function | def process_records(records, shard_id, fh_d_stream):
put_records(fh_d_stream, records)
| def process_records(records, shard_id, fh_d_stream):
| put_records(fh_d_stream, records)
| :
if 'S3DestinationDescription' not in dest:
dest['S3DestinationDescription'] = {}
for k, v in iteritems(s3_update):
dest['S3DestinationDescription'][k] = v
return dest
def process_records(records, shard_id, fh_d_stream):
| 64 | 64 | 22 | 12 | 51 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | process_records | process_records | 134 | 135 | 134 | 134 | 00dc1c2ddf67b57fe95563897100d95efb559951 | bigcode/the-stack | train |
1f117f84bad176e0e005626c | train | function | def get_delivery_stream_tags(stream_name, exclusive_start_tag_key=None, limit=50):
stream = DELIVERY_STREAMS[stream_name]
response = {}
start_i = -1
if exclusive_start_tag_key is not None:
start_i = next(iter([i for i, tag in enumerate(stream['Tags']) if tag['Key'] == exclusive_start_tag_key]))
... | def get_delivery_stream_tags(stream_name, exclusive_start_tag_key=None, limit=50):
| stream = DELIVERY_STREAMS[stream_name]
response = {}
start_i = -1
if exclusive_start_tag_key is not None:
start_i = next(iter([i for i, tag in enumerate(stream['Tags']) if tag['Key'] == exclusive_start_tag_key]))
response['Tags'] = [tag for i, tag in enumerate(stream['Tags']) if start_i < i... | deserializer
deser = TypeDeserializer()
def get_delivery_stream_names():
names = []
for name, stream in iteritems(DELIVERY_STREAMS):
names.append(stream['DeliveryStreamName'])
return names
def get_delivery_stream_tags(stream_name, exclusive_start_tag_key=None, limit=50):
| 64 | 64 | 126 | 18 | 45 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | get_delivery_stream_tags | get_delivery_stream_tags | 42 | 51 | 42 | 42 | 2da407ad4e03cfc0618338e5708dc56977eca8cd | bigcode/the-stack | train |
b62f411728fae6000116f9fd | train | function | def get_destination(stream_name, destination_id):
stream = get_stream(stream_name)
destinations = stream['Destinations']
for dest in destinations:
if dest['DestinationId'] == destination_id:
return dest
dest = {}
dest['DestinationId'] = destination_id
destinations.append(dest... | def get_destination(stream_name, destination_id):
| stream = get_stream(stream_name)
destinations = stream['Destinations']
for dest in destinations:
if dest['DestinationId'] == destination_id:
return dest
dest = {}
dest['DestinationId'] = destination_id
destinations.append(dest)
return dest
| '/', obj_name)
try:
s3.Object(bucket, obj_path).put(Body=data)
except Exception as e:
LOG.error('Unable to put record to stream: %s %s' % (e, traceback.format_exc()))
raise e
def get_destination(stream_name, destination_id):
| 64 | 64 | 69 | 9 | 54 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | get_destination | get_destination | 106 | 115 | 106 | 106 | 11555d5cccd3856ddd9b64401bd65a7268f266f5 | bigcode/the-stack | train |
efe2cec82b7bfba3644a3658 | train | function | def create_stream(stream_name, delivery_stream_type='DirectPut', delivery_stream_type_configuration=None,
s3_destination=None, elasticsearch_destination=None, tags=None, region_name=None):
tags = tags or {}
stream = {
'DeliveryStreamType': delivery_stream_type,
'KinesisStreamSo... | def create_stream(stream_name, delivery_stream_type='DirectPut', delivery_stream_type_configuration=None,
s3_destination=None, elasticsearch_destination=None, tags=None, region_name=None):
| tags = tags or {}
stream = {
'DeliveryStreamType': delivery_stream_type,
'KinesisStreamSourceConfiguration': delivery_stream_type_configuration,
'HasMoreDestinations': False,
'VersionId': '1',
'CreateTimestamp': time.time(),
'DeliveryStreamARN': firehose_stream_ar... | in dest:
dest['S3DestinationDescription'] = {}
for k, v in iteritems(s3_update):
dest['S3DestinationDescription'][k] = v
return dest
def process_records(records, shard_id, fh_d_stream):
put_records(fh_d_stream, records)
def create_stream(stream_name, delivery_stream_type='Dire... | 101 | 101 | 339 | 37 | 64 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | create_stream | create_stream | 138 | 171 | 138 | 139 | 2bb6986926176e93a6fc23d31fc4bf91be8096d6 | bigcode/the-stack | train |
327447007314c05673c560e3 | train | function | def get_delivery_stream_names():
names = []
for name, stream in iteritems(DELIVERY_STREAMS):
names.append(stream['DeliveryStreamName'])
return names
| def get_delivery_stream_names():
| names = []
for name, stream in iteritems(DELIVERY_STREAMS):
names.append(stream['DeliveryStreamName'])
return names
| firehose_api'
app = Flask(APP_NAME)
ACTION_HEADER_PREFIX = 'Firehose_20150804'
# logger
LOG = logging.getLogger(__name__)
# maps stream names to details
DELIVERY_STREAMS = {}
# dynamodb deserializer
deser = TypeDeserializer()
def get_delivery_stream_names():
| 64 | 64 | 37 | 6 | 58 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | get_delivery_stream_names | get_delivery_stream_names | 35 | 39 | 35 | 35 | 2e092253801f1f4648a0c46990eb6ace894b0801 | bigcode/the-stack | train |
4854324aada95686d07cecec | train | function | def get_stream(stream_name):
if stream_name not in DELIVERY_STREAMS:
return None
return DELIVERY_STREAMS[stream_name]
| def get_stream(stream_name):
| if stream_name not in DELIVERY_STREAMS:
return None
return DELIVERY_STREAMS[stream_name]
| S.pop(stream_name, {})
if not stream:
return error_not_found(stream_name)
# record event
event_publisher.fire_event(event_publisher.EVENT_FIREHOSE_DELETE_STREAM,
payload={'n': event_publisher.get_hash(stream_name)})
return {}
def get_stream(stream_name):
| 63 | 64 | 29 | 6 | 57 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | get_stream | get_stream | 186 | 189 | 186 | 186 | abdddc628c0f06ea6ec50da0c3feffe96362ae35 | bigcode/the-stack | train |
78958d6f99e489a3a286c9cf | train | function | def bucket_name(bucket_arn):
return bucket_arn.split(':::')[-1]
| def bucket_name(bucket_arn):
| return bucket_arn.split(':::')[-1]
| (event_publisher.EVENT_FIREHOSE_DELETE_STREAM,
payload={'n': event_publisher.get_hash(stream_name)})
return {}
def get_stream(stream_name):
if stream_name not in DELIVERY_STREAMS:
return None
return DELIVERY_STREAMS[stream_name]
def bucket_name(bucket_arn):
| 64 | 64 | 19 | 7 | 57 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | bucket_name | bucket_name | 192 | 193 | 192 | 192 | c17c9906e39c36b8068f06d6bee4344515080f07 | bigcode/the-stack | train |
c832740e1feb9fe3866deaec | train | function | def error_not_found(stream_name):
msg = 'Firehose %s under account %s not found.' % (stream_name, TEST_AWS_ACCOUNT_ID)
return error_response(msg, code=400, error_type='ResourceNotFoundException')
| def error_not_found(stream_name):
| msg = 'Firehose %s under account %s not found.' % (stream_name, TEST_AWS_ACCOUNT_ID)
return error_response(msg, code=400, error_type='ResourceNotFoundException')
| [stream_name]
def bucket_name(bucket_arn):
return bucket_arn.split(':::')[-1]
def role_arn(stream_name):
return 'arn:aws:iam::%s:role/%s' % (TEST_AWS_ACCOUNT_ID, stream_name)
def error_not_found(stream_name):
| 64 | 64 | 51 | 7 | 57 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | error_not_found | error_not_found | 200 | 202 | 200 | 200 | 2b07c5811f7cf3111e424b2b89446cf6ded8da73 | bigcode/the-stack | train |
a179816da097e6ccd2e306e5 | train | function | def put_records(stream_name, records):
stream = get_stream(stream_name)
for dest in stream['Destinations']:
if 'ESDestinationDescription' in dest:
es_dest = dest['ESDestinationDescription']
es_index = es_dest['IndexName']
es_type = es_dest['TypeName']
es =... | def put_records(stream_name, records):
| stream = get_stream(stream_name)
for dest in stream['Destinations']:
if 'ESDestinationDescription' in dest:
es_dest = dest['ESDestinationDescription']
es_index = es_dest['IndexName']
es_type = es_dest['TypeName']
es = connect_elasticsearch()
fo... | start_i = -1
if exclusive_start_tag_key is not None:
start_i = next(iter([i for i, tag in enumerate(stream['Tags']) if tag['Key'] == exclusive_start_tag_key]))
response['Tags'] = [tag for i, tag in enumerate(stream['Tags']) if start_i < i < limit]
response['HasMore'] = len(response['Tags']) < l... | 120 | 120 | 400 | 8 | 112 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | put_records | put_records | 58 | 103 | 58 | 58 | e59829e95fe2b67ca04ca12073368663ae4d3414 | bigcode/the-stack | train |
2722e0d6b4f0b7bcfc18ece8 | train | function | def put_record(stream_name, record):
return put_records(stream_name, [record])
| def put_record(stream_name, record):
| return put_records(stream_name, [record])
| Key'] == exclusive_start_tag_key]))
response['Tags'] = [tag for i, tag in enumerate(stream['Tags']) if start_i < i < limit]
response['HasMore'] = len(response['Tags']) < len(stream['Tags'])
return response
def put_record(stream_name, record):
| 64 | 64 | 18 | 8 | 55 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | put_record | put_record | 54 | 55 | 54 | 54 | baedae42951ed5be0f30af7c2bb4d6cbadf01c4b | bigcode/the-stack | train |
2d4ceb336093eb990dad1de3 | train | function | def update_destination(stream_name, destination_id,
s3_update=None, elasticsearch_update=None, version_id=None):
dest = get_destination(stream_name, destination_id)
if elasticsearch_update:
if 'ESDestinationDescription' not in dest:
dest['ESDestinationDescription'] = {... | def update_destination(stream_name, destination_id,
s3_update=None, elasticsearch_update=None, version_id=None):
| dest = get_destination(stream_name, destination_id)
if elasticsearch_update:
if 'ESDestinationDescription' not in dest:
dest['ESDestinationDescription'] = {}
for k, v in iteritems(elasticsearch_update):
dest['ESDestinationDescription'][k] = v
if s3_update:
if ... | destinations:
if dest['DestinationId'] == destination_id:
return dest
dest = {}
dest['DestinationId'] = destination_id
destinations.append(dest)
return dest
def update_destination(stream_name, destination_id,
s3_update=None, elasticsearch_update=None, version_... | 64 | 64 | 142 | 24 | 39 | texxIO/localstack | localstack/services/firehose/firehose_api.py | Python | update_destination | update_destination | 118 | 131 | 118 | 119 | c89560c7a55847b40980e44feb504f392c1e9d34 | bigcode/the-stack | train |
3d2c58603b6539e6ecf42427 | train | class | class QueryableApi(object):
"""Base implementation for Queryable API."""
def _to_tables(self, response: HTTPResponse, query_options=None,
response_metadata_mode: FluxResponseMetadataMode = FluxResponseMetadataMode.full) -> List[FluxTable]:
"""Parse HTTP response to FluxTables."""
... | class QueryableApi(object):
| """Base implementation for Queryable API."""
def _to_tables(self, response: HTTPResponse, query_options=None,
response_metadata_mode: FluxResponseMetadataMode = FluxResponseMetadataMode.full) -> List[FluxTable]:
"""Parse HTTP response to FluxTables."""
_parser = FluxCsvParser... | """Helper to share queryable function between APIs - query_api, invocable_scripts_api."""
import codecs
import csv
from typing import List, Iterator, Generator, Any
from urllib3 import HTTPResponse
from influxdb_client.client.flux_csv_parser import FluxCsvParser, FluxSerializationMode, FluxResponseMetadataMode
from i... | 95 | 124 | 414 | 6 | 88 | mmatl/influxdb-client-python | influxdb_client/client/queryable_api.py | Python | QueryableApi | QueryableApi | 13 | 53 | 13 | 13 | 49c81cbea4b4e09328f63598e7d584f09f9f4afc | bigcode/the-stack | train |
2b92c4c2a5b0c4c370d9db7d | train | function | def c2x2_dl(A, C, T, verbosity=0):
# C--1 0--T--1
# 0 2
C2x2 = torch.tensordot(C, T, ([1],[0]))
# C------T--1->0
# 0 2->1
# 0
# T--2->3
# 1->2
C2x2 = torch.tensordot(C2x2, T, ([0],[0]))
# C-------T--0
# | 1
# | 0
# T--3 1--A--3
# 2->1 ... | def c2x2_dl(A, C, T, verbosity=0):
# C--1 0--T--1
# 0 2
| C2x2 = torch.tensordot(C, T, ([1],[0]))
# C------T--1->0
# 0 2->1
# 0
# T--2->3
# 1->2
C2x2 = torch.tensordot(C2x2, T, ([0],[0]))
# C-------T--0
# | 1
# | 0
# T--3 1--A--3
# 2->1 2
C2x2 = torch.tensordot(C2x2, A, ([1,3],[0,1]))
# permute 01... | import torch
def c2x2_dl(A, C, T, verbosity=0):
# C--1 0--T--1
# 0 2
| 39 | 87 | 292 | 36 | 2 | tateobori/AD-peps | ctm/one_site_c4v/ctm_components_c4v.py | Python | c2x2_dl | c2x2_dl | 3 | 31 | 3 | 5 | 5f441a7a89811425c8c03fa5d121830eb0cd3e3d | bigcode/the-stack | train |
907ef45726e4cc6fb17e0d7b | train | function | def c2x2_sl(a, C, T, verbosity=0):
# C--1 0--T--1
# 0 2
C2x2 = torch.tensordot(C, T, ([1],[0]))
# C------T--1->0
# 0 2->1
# 0
# T--2->3
# 1->2
C2x2 = torch.tensordot(C2x2, T, ([0],[0]))
# C-------T--0
# | 1
# | 0
# T--3 1--A--3
# 2->1 ... | def c2x2_sl(a, C, T, verbosity=0):
# C--1 0--T--1
# 0 2
| C2x2 = torch.tensordot(C, T, ([1],[0]))
# C------T--1->0
# 0 2->1
# 0
# T--2->3
# 1->2
C2x2 = torch.tensordot(C2x2, T, ([0],[0]))
# C-------T--0
# | 1
# | 0
# T--3 1--A--3
# 2->1 2
# C2x2 = torch.tensordot(C2x2, A, ([1,3],[0,1]))
# 4) doubl... | 2
C2x2 = torch.tensordot(C2x2, T, ([0],[0]))
# C-------T--0
# | 1
# | 0
# T--3 1--A--3
# 2->1 2
C2x2 = torch.tensordot(C2x2, A, ([1,3],[0,1]))
# permute 0123->1203
# reshape (12)(03)->01
C2x2 = C2x2.permute(1,2,0,3).contiguous().view(T.size()[1]*A.size()[3],T.si... | 234 | 234 | 780 | 36 | 197 | tateobori/AD-peps | ctm/one_site_c4v/ctm_components_c4v.py | Python | c2x2_sl | c2x2_sl | 33 | 110 | 33 | 35 | 298f4739b628df097e4b6f658e4ed0e87b67091f | bigcode/the-stack | train |
39f366bee100ca1f6d85aa89 | train | function | def load_serialized_clvm(clvm_filename, package_or_requirement=__name__) -> SerializedProgram:
"""
This function takes a .clvm file in the given package and compiles it to a
.clvm.hex file if the .hex file is missing or older than the .clvm file, then
returns the contents of the .hex file as a `Program`... | def load_serialized_clvm(clvm_filename, package_or_requirement=__name__) -> SerializedProgram:
| """
This function takes a .clvm file in the given package and compiles it to a
.clvm.hex file if the .hex file is missing or older than the .clvm file, then
returns the contents of the .hex file as a `Program`.
clvm_filename: file name
package_or_requirement: usually `__name__` if the clvm file... | import pathlib
import pkg_resources
from clvm_tools.clvmc import compile_clvm
from wheat.types.blockchain_format.program import Program, SerializedProgram
def load_serialized_clvm(clvm_filename, package_or_requirement=__name__) -> SerializedProgram:
| 53 | 79 | 264 | 21 | 31 | grayfallstown/wheat-blockchain | wheat/wallet/puzzles/load_clvm.py | Python | load_serialized_clvm | load_serialized_clvm | 9 | 33 | 9 | 9 | f4e7b0891bd2409a3a5d410aad3b810ad0674bb6 | bigcode/the-stack | train |
e3b66369386350dda0b6c3af | train | function | def load_clvm(clvm_filename, package_or_requirement=__name__) -> Program:
return Program.from_bytes(bytes(load_serialized_clvm(clvm_filename, package_or_requirement=package_or_requirement)))
| def load_clvm(clvm_filename, package_or_requirement=__name__) -> Program:
| return Program.from_bytes(bytes(load_serialized_clvm(clvm_filename, package_or_requirement=package_or_requirement)))
| pass
clvm_hex = pkg_resources.resource_string(package_or_requirement, hex_filename).decode("utf8")
clvm_blob = bytes.fromhex(clvm_hex)
return SerializedProgram.from_bytes(clvm_blob)
def load_clvm(clvm_filename, package_or_requirement=__name__) -> Program:
| 64 | 64 | 41 | 18 | 46 | grayfallstown/wheat-blockchain | wheat/wallet/puzzles/load_clvm.py | Python | load_clvm | load_clvm | 36 | 37 | 36 | 36 | d3a874411d421d4f1589613153ca89205185b71c | bigcode/the-stack | train |
d223ada2166a7375e17264b5 | train | class | class SnapshotInfoPanel(InfoPanel):
"""Contains functionality specific to snapshot info panel."""
@property
def snapshot_version_el(self):
"""Returns snapshot version element."""
return self._root.element(class_name="state-value snapshot")
@property
def _link_to_get_latest_version(self):
"""Retu... | class SnapshotInfoPanel(InfoPanel):
| """Contains functionality specific to snapshot info panel."""
@property
def snapshot_version_el(self):
"""Returns snapshot version element."""
return self._root.element(class_name="state-value snapshot")
@property
def _link_to_get_latest_version(self):
"""Returns `Get the latest version` link.""... | @property
def button_maximize(self):
"""Return maximize button"""
return self._root.element(class_name='fa-expand')
@property
def button_close(self):
"""Return close button"""
return self._root.element(class_name='close-pane')
class SnapshotInfoPanel(InfoPanel):
| 64 | 64 | 209 | 8 | 56 | pavelglebov/ggrc-core | test/selenium/src/lib/page/widget/info_panel.py | Python | SnapshotInfoPanel | SnapshotInfoPanel | 53 | 79 | 53 | 53 | 4d4e779998661379af432e43f40df55e03bfa611 | bigcode/the-stack | train |
b3882a61dd6f31e8bfae3356 | train | class | class InfoPanel(object):
"""Contains functionality specific to info panel."""
# pylint: disable=too-few-public-methods
def __init__(self, root):
self._root = root
@property
def title(self):
"""Return panel title"""
return self._root.element(
class_name='general-page-header__title-details... | class InfoPanel(object):
| """Contains functionality specific to info panel."""
# pylint: disable=too-few-public-methods
def __init__(self, root):
self._root = root
@property
def title(self):
"""Return panel title"""
return self._root.element(
class_name='general-page-header__title-details').h3().text
@property... | # Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Contains Info Widget functionality specific to info panels
(split done as `info_widget` module is too large.
"""
from lib.page.modal import update_object
class InfoPanel(object):
| 66 | 81 | 270 | 5 | 60 | pavelglebov/ggrc-core | test/selenium/src/lib/page/widget/info_panel.py | Python | InfoPanel | InfoPanel | 9 | 50 | 9 | 9 | f0a2623e59fa89f0db2b382ae55330e7f0ec8db6 | bigcode/the-stack | train |
dc7da2a17805bdc78d02c4b6 | train | class | class TicktextValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self,
plotly_name='ticktext',
parent_name='scatterpolar.marker.colorbar',
**kwargs
):
super(TicktextValidator, self).__init__(
plotly_name=plotly_name,
parent_... | class TicktextValidator(_plotly_utils.basevalidators.DataArrayValidator):
| def __init__(
self,
plotly_name='ticktext',
parent_name='scatterpolar.marker.colorbar',
**kwargs
):
super(TicktextValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type='colorbars',
role='data... | import _plotly_utils.basevalidators
class TicktextValidator(_plotly_utils.basevalidators.DataArrayValidator):
| 22 | 64 | 91 | 14 | 7 | faezs/plotly.py | plotly/validators/scatterpolar/marker/colorbar/_ticktext.py | Python | TicktextValidator | TicktextValidator | 4 | 18 | 4 | 5 | 72ce6cfa8ec17114a33791feae1dbc50a8cda0da | bigcode/the-stack | train |
71d22c08c6726f8807351270 | train | function | def get_page_code(url, issue_date, comment_number, page_number, header):
# 爬取所有页面
url_list = get_url(url, page_number)
count = 0
code_list = []
for url in url_list:
count += 1
print('*' * 40, f'第{count}页', '*' * 40)
web_data = requests.get(url, headers=header)
... | def get_page_code(url, issue_date, comment_number, page_number, header):
# 爬取所有页面
| url_list = get_url(url, page_number)
count = 0
code_list = []
for url in url_list:
count += 1
print('*' * 40, f'第{count}页', '*' * 40)
web_data = requests.get(url, headers=header)
soup = BeautifulSoup(web_data.text, 'lxml')
get_code(soup, issue_date, commen... | print('>下载成功...')
print('\n')
break
except:
# print(format_exc())
print(' >下载失败,重新下载...')
continue
def get_page_code(url, issue_date, comment_number, page_number, h... | 64 | 64 | 120 | 25 | 38 | wuhuan172/Lizard_house | jav-1.2.2.py | Python | get_page_code | get_page_code | 77 | 87 | 77 | 78 | c53abd9f6e1ea4e0fa7f393fb72f630b68fc0b8e | bigcode/the-stack | train |
bbd6f49b78fc2613fc499f65 | train | function | def steal_library_header(url):
print('\n正在尝试通过', url, '的5秒检测...')
for retry in range(10):
try:
cookie_value, user_agent = get_cookie_string(url, timeout=15)
print('通过5秒检测!\n')
return {'User-Agent': user_agent, 'Cookie': cookie_value}
except:
... | def steal_library_header(url):
| print('\n正在尝试通过', url, '的5秒检测...')
for retry in range(10):
try:
cookie_value, user_agent = get_cookie_string(url, timeout=15)
print('通过5秒检测!\n')
return {'User-Agent': user_agent, 'Cookie': cookie_value}
except:
print('通过失败,重新尝试...')
... | import requests
from bs4 import BeautifulSoup
import re
import time
import os
from cfscrape import get_cookie_string
from re import search
# 通过cloudscraper获取可用的cookie以通过5s检测
def steal_library_header(url):
| 57 | 64 | 110 | 6 | 50 | wuhuan172/Lizard_house | jav-1.2.2.py | Python | steal_library_header | steal_library_header | 11 | 21 | 11 | 11 | 182827b3ec850636f44dd5800ddd79386dc69549 | bigcode/the-stack | train |
21d3b440d5dffb3eb81d614a | train | function | def get_url(url, page_number):
url_list = []
url_initial = url
for page in range(1, page_number + 1):
url = f"{url_initial}{page}"
url_list.append(url)
return url_list
| def get_url(url, page_number):
| url_list = []
url_initial = url
for page in range(1, page_number + 1):
url = f"{url_initial}{page}"
url_list.append(url)
return url_list
| {'User-Agent': user_agent, 'Cookie': cookie_value}
except:
print('通过失败,重新尝试...')
continue
print('>>无法通过javlibrary的5秒检测:', url)
# 找到访问页面所有页码的网址
def get_url(url, page_number):
| 64 | 64 | 55 | 8 | 55 | wuhuan172/Lizard_house | jav-1.2.2.py | Python | get_url | get_url | 25 | 31 | 25 | 25 | e837f7a4fcc0755d7e16f39311e0ee30e5002152 | bigcode/the-stack | train |
7e1bc3d8713bd5c08d016175 | train | function | def get_code(soup, issue_date, comment_number, header):
path_page = 'D:/我/'
for item in soup.find_all(name='div', id=re.compile('vid_javli')):
path = f'{path_page}{soup.title.string}/'
if not os.path.isdir(path):
os.makedirs(f'{path}/')
address = item.a['href'].replace(... | def get_code(soup, issue_date, comment_number, header):
| path_page = 'D:/我/'
for item in soup.find_all(name='div', id=re.compile('vid_javli')):
path = f'{path_page}{soup.title.string}/'
if not os.path.isdir(path):
os.makedirs(f'{path}/')
address = item.a['href'].replace('./', '')
link = 'http://www.n43a.com/cn/' + add... | {'User-Agent': user_agent, 'Cookie': cookie_value}
except:
print('通过失败,重新尝试...')
continue
print('>>无法通过javlibrary的5秒检测:', url)
# 找到访问页面所有页码的网址
def get_url(url, page_number):
url_list = []
url_initial = url
for page in range(1, page_number + 1):
url ... | 138 | 138 | 463 | 14 | 123 | wuhuan172/Lizard_house | jav-1.2.2.py | Python | get_code | get_code | 35 | 74 | 35 | 35 | f3441070a3b0f9d9bd5537351554a844ca31bd27 | bigcode/the-stack | train |
5d588c8beadbe1c2b7aa3c93 | train | class | @pytest.mark.usefixtures("ppg2_per_test")
class TestPruning:
def test_basic_prune(self):
ppg.FileGeneratingJob("A", lambda of: write("A", "A"))
b = ppg.FileGeneratingJob("B", lambda of: write("B", "B"))
b.prune()
ppg.run()
assert Path("A").read_text() == "A"
assert no... | @pytest.mark.usefixtures("ppg2_per_test")
class TestPruning:
| def test_basic_prune(self):
ppg.FileGeneratingJob("A", lambda of: write("A", "A"))
b = ppg.FileGeneratingJob("B", lambda of: write("B", "B"))
b.prune()
ppg.run()
assert Path("A").read_text() == "A"
assert not Path("B").exists()
def test_basic_prune2(self):
... | from pathlib import Path
import pytest
import pypipegraph2 as ppg
from .shared import write, read
@pytest.mark.usefixtures("ppg2_per_test")
class TestPruning:
| 42 | 226 | 755 | 16 | 25 | IMTMarburg/pypipegraph2 | tests/test_prune.py | Python | TestPruning | TestPruning | 7 | 75 | 7 | 8 | 0f2555a4df21e45e09f343f8540dad15e1931ffd | bigcode/the-stack | train |
126f08e2bd2a5b478c603fed | train | function | async def got_vote(vote, secret):
print("Got vote:", vote, "with secret:", secret)
| async def got_vote(vote, secret):
| print("Got vote:", vote, "with secret:", secret)
| import IBLPy, asyncio, discord
from testcfg import TOKEN
async def got_vote(vote, secret):
| 24 | 64 | 23 | 9 | 14 | Fates-List/fateslist.py | example/test.py | Python | got_vote | got_vote | 4 | 5 | 4 | 4 | fcefd70be753515ccc4aa2de6917e7272c553fe7 | bigcode/the-stack | train |
d34fad0a0b863846e41fc8f0 | train | function | @client.event
async def on_message(msg):
print(msg)
| @client.event
async def on_message(msg):
| print(msg)
| SpwGd9Azt2l2XDh3CmPIzKmeXcmHznMntMC3ghKmmKWQ5iQuhpyYPzSI2XSvm1kZ")
client = discord.AutoShardedClient()
@client.event
async def on_message(msg):
| 64 | 64 | 14 | 10 | 54 | Fates-List/fateslist.py | example/test.py | Python | on_message | on_message | 13 | 15 | 13 | 14 | 8be6fb90c2538ecae1fd56238291dd4214d85344 | bigcode/the-stack | train |
de6535681fd2f3dd234de732 | train | function | async def test_poster(gc, sc, res):
print(gc, sc, res)
| async def test_poster(gc, sc, res):
| print(gc, sc, res)
| import IBLPy, asyncio, discord
from testcfg import TOKEN
async def got_vote(vote, secret):
print("Got vote:", vote, "with secret:", secret)
async def test_poster(gc, sc, res):
| 49 | 64 | 19 | 11 | 38 | Fates-List/fateslist.py | example/test.py | Python | test_poster | test_poster | 7 | 8 | 7 | 7 | 9ff22c5944c6786348af53b5ae41829cce320c6c | bigcode/the-stack | train |
fcf573c4e7b1b44efd315ea2 | train | function | @client.event
async def on_ready():
print(f"Ready! {client.user}")
#ibl.get_bot()
a = IBLPy.Webhook(botcli = ibl, secret = "MY_SECRET", coro = got_vote)
ap = IBLPy.AutoPoster(interval = 300, botcli = ibl, discli = client, on_post = test_poster, sharding = True)
ap.start()
a.start_ws_task(route =... | @client.event
async def on_ready():
| print(f"Ready! {client.user}")
#ibl.get_bot()
a = IBLPy.Webhook(botcli = ibl, secret = "MY_SECRET", coro = got_vote)
ap = IBLPy.AutoPoster(interval = 300, botcli = ibl, discli = client, on_post = test_poster, sharding = True)
ap.start()
a.start_ws_task(route = "/ibl", port = 8016)
| CmPIzKmeXcmHznMntMC3ghKmmKWQ5iQuhpyYPzSI2XSvm1kZ")
client = discord.AutoShardedClient()
@client.event
async def on_message(msg):
print(msg)
@client.event
async def on_ready():
| 64 | 64 | 106 | 9 | 55 | Fates-List/fateslist.py | example/test.py | Python | on_ready | on_ready | 17 | 24 | 17 | 18 | 6c67a69d77b4da93ecc17bc6044b0771d10d8815 | bigcode/the-stack | train |
cfff6a0e52261c39cca73315 | train | class | class MyCustomESC(EarlyStoppingCriterion):
def _reset(self):
pass
def _should_stop(self) -> Tuple[bool, float]:
pass
def _on_stop(self) -> Tuple[int, gpytorch.models.ExactGP]:
pass
def _on_continue(self):
pass
| class MyCustomESC(EarlyStoppingCriterion):
| def _reset(self):
pass
def _should_stop(self) -> Tuple[bool, float]:
pass
def _on_stop(self) -> Tuple[int, gpytorch.models.ExactGP]:
pass
def _on_continue(self):
pass
| from typing import Tuple
import gpytorch
from GPErks.train.early_stop import EarlyStoppingCriterion
class MyCustomESC(EarlyStoppingCriterion):
| 32 | 64 | 66 | 9 | 22 | stelong/GPErks | GPErks/deprecated/tests/custom_esc.py | Python | MyCustomESC | MyCustomESC | 8 | 19 | 8 | 8 | 574d1a727ee2e2e2928ff8377bbb97c3e8bf91a1 | bigcode/the-stack | train |
105fb1f6acce0d9de3ca8757 | train | class | class MemPriority(b3.Composite):
def __init__(self, children=None):
super(MemPriority, self).__init__(children)
def open(self, tick):
tick.blackboard.set('running_child', 0, tick.tree.id, self.id)
def tick(self, tick):
idx = tick.blackboard.get('running_child', tick.tree.id, self.i... | class MemPriority(b3.Composite):
| def __init__(self, children=None):
super(MemPriority, self).__init__(children)
def open(self, tick):
tick.blackboard.set('running_child', 0, tick.tree.id, self.id)
def tick(self, tick):
idx = tick.blackboard.get('running_child', tick.tree.id, self.id)
for i in range(idx, l... | import b3
__all__ = ['MemPriority']
class MemPriority(b3.Composite):
| 19 | 64 | 167 | 7 | 12 | benfrussell/behavior3py | b3/composites/mempriority.py | Python | MemPriority | MemPriority | 5 | 26 | 5 | 5 | abdc53b86c3c87fae6061456adb1a08cd6986fc5 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.