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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
43edbc385c3cc86e3c6eee1f | train | function | async def handle_webhook(hass, webhook_id, request):
"""Handle webhook callback."""
try:
data = await request.json()
except ValueError:
return None
_LOGGER.debug("Got webhook data: %s", data)
published_data = {
ATTR_EVENT_TYPE: data.get(ATTR_EVENT_TYPE),
ATTR_HOME_NA... | async def handle_webhook(hass, webhook_id, request):
| """Handle webhook callback."""
try:
data = await request.json()
except ValueError:
return None
_LOGGER.debug("Got webhook data: %s", data)
published_data = {
ATTR_EVENT_TYPE: data.get(ATTR_EVENT_TYPE),
ATTR_HOME_NAME: data.get(ATTR_HOME_NAME),
ATTR_CAMERA_ID:... | (url)
hass.services.register(
DOMAIN,
SERVICE_ADDWEBHOOK,
_service_addwebhook,
schema=SCHEMA_SERVICE_ADDWEBHOOK,
)
def _service_dropwebhook(service):
"""Service to drop webhooks during runtime."""
_LOGGER.info("Dropping webhook")
auth.dropwebhook()
... | 151 | 151 | 505 | 13 | 138 | joopert/home-assistant | homeassistant/components/netatmo/__init__.py | Python | handle_webhook | handle_webhook | 163 | 203 | 163 | 163 | a15f924109ae2b30846fc3b3a98cc5f189808117 | bigcode/the-stack | train |
4f408d5190b538bd450d939c | train | class | class CameraData:
"""Get the latest data from Netatmo."""
def __init__(self, hass, auth, home=None):
"""Initialize the data object."""
self._hass = hass
self.auth = auth
self.camera_data = None
self.camera_names = []
self.module_names = []
self.home = hom... | class CameraData:
| """Get the latest data from Netatmo."""
def __init__(self, hass, auth, home=None):
"""Initialize the data object."""
self._hass = hass
self.auth = auth
self.camera_data = None
self.camera_names = []
self.module_names = []
self.home = home
self.cam... | == EVENT_ANIMAL:
published_data[ATTR_VIGNETTE_URL] = data.get(ATTR_VIGNETTE_URL)
published_data[ATTR_SNAPSHOT_URL] = data.get(ATTR_SNAPSHOT_URL)
hass.bus.async_fire(EVENT_BUS_ANIMAL, published_data)
elif data.get(ATTR_EVENT_TYPE) == EVENT_VEHICLE:
hass.bus.async_fire(EVENT_BUS_VEHIC... | 145 | 145 | 486 | 4 | 141 | joopert/home-assistant | homeassistant/components/netatmo/__init__.py | Python | CameraData | CameraData | 206 | 262 | 206 | 206 | 68c542026bdec28adbdd570d3034829dc7b4207a | bigcode/the-stack | train |
96545acb049a90457fcf20a3 | train | function | def setup(hass, config):
"""Set up the Netatmo devices."""
hass.data[DATA_PERSONS] = {}
try:
auth = pyatmo.ClientAuth(
config[DOMAIN][CONF_API_KEY],
config[DOMAIN][CONF_SECRET_KEY],
config[DOMAIN][CONF_USERNAME],
config[DOMAIN][CONF_PASSWORD],
... | def setup(hass, config):
| """Set up the Netatmo devices."""
hass.data[DATA_PERSONS] = {}
try:
auth = pyatmo.ClientAuth(
config[DOMAIN][CONF_API_KEY],
config[DOMAIN][CONF_SECRET_KEY],
config[DOMAIN][CONF_USERNAME],
config[DOMAIN][CONF_PASSWORD],
"read_station read_c... | (
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_SECRET_KEY): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Optional(CONF_WEBHOOKS, d... | 140 | 141 | 472 | 7 | 134 | joopert/home-assistant | homeassistant/components/netatmo/__init__.py | Python | setup | setup | 91 | 154 | 91 | 91 | a2af0175199cee745ac77c6189f601e6eaed23c6 | bigcode/the-stack | train |
8251e03f2f0ecb7e7da8f6f6 | train | function | def dropwebhook(hass):
"""Drop the webhook subscription."""
auth = hass.data[DATA_NETATMO_AUTH]
auth.dropwebhook()
| def dropwebhook(hass):
| """Drop the webhook subscription."""
auth = hass.data[DATA_NETATMO_AUTH]
auth.dropwebhook()
| webhooks during runtime."""
_LOGGER.info("Dropping webhook")
auth.dropwebhook()
hass.services.register(
DOMAIN,
SERVICE_DROPWEBHOOK,
_service_dropwebhook,
schema=SCHEMA_SERVICE_DROPWEBHOOK,
)
return True
def dropwebhook(hass):
| 64 | 64 | 32 | 7 | 56 | joopert/home-assistant | homeassistant/components/netatmo/__init__.py | Python | dropwebhook | dropwebhook | 157 | 160 | 157 | 157 | c7c2ef0699bdbf09e96a47ca5087a934b4fb3dec | bigcode/the-stack | train |
b7515191860e5acc130ba5a6 | train | class | class Solution:
def canMeasureWater(self, x: int, y: int, z: int) -> bool:
# return self.canMeasureWater_math(x,y,z)
# return self.canMeasureWater_bfs(x,y,z)
return self.canMeasureWater_dfs(x,y,z)
def canMeasureWater_math(self, x: int, y: int, z: int) -> bool:
if x + y < z: ret... | class Solution:
| def canMeasureWater(self, x: int, y: int, z: int) -> bool:
# return self.canMeasureWater_math(x,y,z)
# return self.canMeasureWater_bfs(x,y,z)
return self.canMeasureWater_dfs(x,y,z)
def canMeasureWater_math(self, x: int, y: int, z: int) -> bool:
if x + y < z: return False
... | b)是整数且 z <= a+b
另外 贝祖定理 表明 z = ax + by 要有解,z必须是x,y的最大公约数的倍数。
二、深度优先dfs(用栈),或者宽度优先bsf(用队列)
在任意一个时刻,我们可以且仅可以采取以下几种操作:
把 X 壶的水灌进 Y 壶,直至灌满或倒空;
把 Y 壶的水灌进 X 壶,直至灌满或倒空;
把 X 壶灌满;
把 Y 壶灌满;
把 X 壶倒空;
把 Y 壶倒空。
'''
import math
from collections import deque
class Solution:
| 182 | 182 | 609 | 3 | 178 | passionzhan/LeetCode | canMeasureWater.py | Python | Solution | Solution | 50 | 111 | 50 | 50 | c6674a54e10ffa7f109b6c8c2564da837e85ab8a | bigcode/the-stack | train |
0f5bb16e1e9071d36282d59a | train | class | class State_Flag():
def __init__(self,Arm,Strategy):
self.Arm = Arm
self.Strategy = Strategy
def feedback(self):
return self.Arm,self.Strategy
| class State_Flag():
| def __init__(self,Arm,Strategy):
self.Arm = Arm
self.Strategy = Strategy
def feedback(self):
return self.Arm,self.Strategy
| from ROS_Socket.msg import *
import math
import enum
NAME = 'strategy_server'
pos_feedback_times = 0
mode_feedback_times = 0
msg_feedback = 1
Arm_state_flag = 0
strategy_flag = 0
arm_move_times = 1
class State_Flag():
| 64 | 64 | 44 | 5 | 58 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | State_Flag | State_Flag | 21 | 26 | 21 | 21 | f1b1adc3fb5f6dcbe2d3b5c194ecec517a107ccb | bigcode/the-stack | train |
457bf28a3c0b6cabaad7e810 | train | function | def strategy_client_Arm_Mode(action,ra,grip,vel,both):
global mode_feedback_times
rospy.wait_for_service('arm_mode')
try:
# create a handle to the add_two_ints service
Arm_mode_client = rospy.ServiceProxy('arm_mode', arm_mode)
mode_feedback = Arm_mode_client(grip,ra,action,vel,both)... | def strategy_client_Arm_Mode(action,ra,grip,vel,both):
| global mode_feedback_times
rospy.wait_for_service('arm_mode')
try:
# create a handle to the add_two_ints service
Arm_mode_client = rospy.ServiceProxy('arm_mode', arm_mode)
mode_feedback = Arm_mode_client(grip,ra,action,vel,both)
mode_feedback_times = mode_feedback.mode
... | rospy.ServiceException as e:
print ("Service call failed: %s"%e)
def usage():
return "%s [x y]"%sys.argv[0]
##---------strategy_client mode data 20190315
def strategy_client_Arm_Mode(action,ra,grip,vel,both):
| 64 | 64 | 116 | 17 | 46 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | strategy_client_Arm_Mode | strategy_client_Arm_Mode | 102 | 113 | 102 | 102 | 6089a969e9d1688a05640987ee783b5ae0fd2365 | bigcode/the-stack | train |
2f39e75290d9cf551fc31227 | train | function | def usage():
return "%s [x y]"%sys.argv[0]
| def usage():
| return "%s [x y]"%sys.argv[0]
| .ServiceProxy('arm_pos', arm_data)
pos_feedback = Arm_pos_client(x,y,z,pitch,roll,yaw)
pos_feedback_times = pos_feedback.response
return pos_feedback_times
except rospy.ServiceException as e:
print ("Service call failed: %s"%e)
def usage():
| 64 | 64 | 17 | 3 | 61 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | usage | usage | 99 | 100 | 99 | 99 | 1eeccb513123d9ca7dac7689a63b584332c15ad2 | bigcode/the-stack | train |
3e7c03e610e0622a9f26d1ad | train | function | def strategy_client_pos_move(x,y,z,pitch,roll,yaw):
global pos_feedback_times
rospy.wait_for_service('arm_pos')
try:
# create a handle to the add_two_ints service
Arm_pos_client = rospy.ServiceProxy('arm_pos', arm_data)
pos_feedback = Arm_pos_client(x,y,z,pitch,roll,yaw)
po... | def strategy_client_pos_move(x,y,z,pitch,roll,yaw):
| global pos_feedback_times
rospy.wait_for_service('arm_pos')
try:
# create a handle to the add_two_ints service
Arm_pos_client = rospy.ServiceProxy('arm_pos', arm_data)
pos_feedback = Arm_pos_client(x,y,z,pitch,roll,yaw)
pos_feedback_times = pos_feedback.response
ret... | (NAME)
s = rospy.Service('arm_state',arm_state, Arm_state) ##server arm point data
#rospy.spin() #spinone
##-----------server feedback arm state end----------
#---------strategy_client pos data------------------
def strategy_client_pos_move(x,y,z,pitch,roll,yaw):
| 64 | 64 | 113 | 15 | 49 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | strategy_client_pos_move | strategy_client_pos_move | 86 | 98 | 86 | 86 | 2568da096d60a0f8272c2ecd41ba42d834b31bcc | bigcode/the-stack | train |
987961fa864e95ff31955ede | train | class | class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case su... | class switch(object):
| def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self... |
Error = 2
shutdown = 6
##-------------enum actionflag
class Action_Type(enum.IntEnum):
SetVel = 0
Delay = 1
PtoP = 2
Line = 3
##-----------switch define------------##
class switch(object):
| 64 | 64 | 124 | 4 | 60 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | switch | switch | 41 | 59 | 41 | 41 | 5546836776eb15562ca1a9953f4dd7ed4a551708 | bigcode/the-stack | train |
30db6597a9dbafa93013d936 | train | class | class Action_Type(enum.IntEnum):
SetVel = 0
Delay = 1
PtoP = 2
Line = 3
| class Action_Type(enum.IntEnum):
| SetVel = 0
Delay = 1
PtoP = 2
Line = 3
| ):
return self.Arm,self.Strategy
## ------------enum action flag ------#
class msg_feedback_Type(enum.IntEnum):
Idle = 0
Isbusy = 1
Error = 2
shutdown = 6
##-------------enum actionflag
class Action_Type(enum.IntEnum):
| 64 | 64 | 34 | 7 | 56 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | Action_Type | Action_Type | 35 | 39 | 35 | 35 | 939b5d5df262ac200d1583e04e062f8164788813 | bigcode/the-stack | train |
13c52e0ed4f2b1d49dc5b4e0 | train | function | def strategy_client_Speed_Mode(Speedmode):
global speed_mode_feedback_times
rospy.wait_for_service('speed_mode')
try:
# create a handle to the add_two_ints service
Speed_mode_client = rospy.ServiceProxy('speed_mode', speed_mode)
speed_mode_feedback = Speed_mode_client(Speedmode)
... | def strategy_client_Speed_Mode(Speedmode):
| global speed_mode_feedback_times
rospy.wait_for_service('speed_mode')
try:
# create a handle to the add_two_ints service
Speed_mode_client = rospy.ServiceProxy('speed_mode', speed_mode)
speed_mode_feedback = Speed_mode_client(Speedmode)
speed_mode_feedback_times = speed_mode... | (grip,ra,action,vel,both)
mode_feedback_times = mode_feedback.mode
return mode_feedback_times
except rospy.ServiceException as e:
print ("Service call failed: %s"%e)
##---------strategy_client Speed mode data
def strategy_client_Speed_Mode(Speedmode):
| 64 | 64 | 107 | 10 | 53 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | strategy_client_Speed_Mode | strategy_client_Speed_Mode | 115 | 126 | 115 | 115 | 82c4544d47524a86adab640462066c849d32beff | bigcode/the-stack | train |
b89e5878f407960a51d4ed51 | train | class | class msg_feedback_Type(enum.IntEnum):
Idle = 0
Isbusy = 1
Error = 2
shutdown = 6
| class msg_feedback_Type(enum.IntEnum):
| Idle = 0
Isbusy = 1
Error = 2
shutdown = 6
| _times = 1
class State_Flag():
def __init__(self,Arm,Strategy):
self.Arm = Arm
self.Strategy = Strategy
def feedback(self):
return self.Arm,self.Strategy
## ------------enum action flag ------#
class msg_feedback_Type(enum.IntEnum):
| 64 | 64 | 33 | 8 | 56 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | msg_feedback_Type | msg_feedback_Type | 29 | 33 | 29 | 29 | a1969c7791ccda8afdeccac20e280bf9a39ce024 | bigcode/the-stack | train |
b957c69ac8818dfcd0734444 | train | class | class point():
def __init__(self,x,y,z,pitch,roll,yaw):
self.x = x
self.y = y
self.z = z
self.pitch = pitch
self.roll = roll
self.yaw = yaw
| class point():
| def __init__(self,x,y,z,pitch,roll,yaw):
self.x = x
self.y = y
self.z = z
self.pitch = pitch
self.roll = roll
self.yaw = yaw
| _mode)
speed_mode_feedback = Speed_mode_client(Speedmode)
speed_mode_feedback_times = speed_mode_feedback.feedback
return speed_mode_feedback_times
except rospy.ServiceException as e:
print ("Service call failed: %s"%e)
##------------client end-------
##------------class-------
class... | 64 | 64 | 56 | 3 | 61 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | point | point | 129 | 136 | 129 | 129 | aaa1c0d6c484e826fa2e3fb4bcc89005b9530872 | bigcode/the-stack | train |
562c9a55f049adaa7bf57858 | train | function | def Arm_state(req):
global CurrentMissionType
Arm.state_flag= int('%s'%req.Arm_state)
if Arm.state_flag == 1: #表示手臂忙碌
Strategy.state_flag = 0
return(1)
if Arm.state_flag == 0: #表示手臂閒置
Strategy.state_flag = 1
return(0)
if Arm.state_flag == 6: #表示程式中斷
Strategy.s... | def Arm_state(req):
| global CurrentMissionType
Arm.state_flag= int('%s'%req.Arm_state)
if Arm.state_flag == 1: #表示手臂忙碌
Strategy.state_flag = 0
return(1)
if Arm.state_flag == 0: #表示手臂閒置
Strategy.state_flag = 1
return(0)
if Arm.state_flag == 6: #表示程式中斷
Strategy.state_flag = 6
... | True
else:
return False
class state_flag():
def __init__(self,Arm,Strategy):
self.Arm = Arm
self.Strategy = Strategy
def feedback(self):
return self.Arm,self.Strategy
##-----------server feedback arm state----------
def Arm_state(req):
| 64 | 64 | 117 | 5 | 59 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | Arm_state | Arm_state | 67 | 78 | 67 | 67 | 6678dea6b7139530f4e6404bd07102088743e873 | bigcode/the-stack | train |
e0bf15a8e8d6e7bbc9717494 | train | class | class state_flag():
def __init__(self,Arm,Strategy):
self.Arm = Arm
self.Strategy = Strategy
def feedback(self):
return self.Arm,self.Strategy
| class state_flag():
| def __init__(self,Arm,Strategy):
self.Arm = Arm
self.Strategy = Strategy
def feedback(self):
return self.Arm,self.Strategy
| Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
class state_flag():
| 64 | 64 | 43 | 4 | 59 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | state_flag | state_flag | 60 | 65 | 60 | 60 | 81efa1bea2811902a83a6ff81bc057afbf1c79ba | bigcode/the-stack | train |
25e2ed2c725d5f681ec46e18 | train | function | def strategy_server():
#rospy.init_node(NAME)
s = rospy.Service('arm_state',arm_state, Arm_state) ##server arm point data
| def strategy_server():
#rospy.init_node(NAME)
| s = rospy.Service('arm_state',arm_state, Arm_state) ##server arm point data
| #表示手臂閒置
Strategy.state_flag = 1
return(0)
if Arm.state_flag == 6: #表示程式中斷
Strategy.state_flag = 6
return(6)
def strategy_server():
#rospy.init_node(NAME)
| 64 | 64 | 33 | 12 | 52 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | strategy_server | strategy_server | 79 | 81 | 79 | 80 | 870957b46027bb8e1135da90c24fbbc8634b13c3 | bigcode/the-stack | train |
dc5bef690a998ad63e708d7d | train | function | def myhook():
print ("shutdown time!")
| def myhook():
| print ("shutdown time!")
| .pitch = pitch
self.roll = roll
self.yaw = yaw
#action: ptp line
#ra : abs rel
#grip 夾爪
#vel speed
#both : Ctrl_Mode
##-------------strategy end ------------
def myhook():
| 64 | 64 | 10 | 4 | 59 | SamKaiYang/2019_Hiwin_Shaking | src/.history/Test/Hiwin_RT605_ROS_20190617125022.py | Python | myhook | myhook | 144 | 145 | 144 | 144 | 8976692cc69baef8a22465169005f89b495b9fa3 | bigcode/the-stack | train |
99b5d4dcede26daf910012f2 | train | class | @pytest.mark.category3
@pytest.mark.ipus(1)
class TestCifar10SqueezeNetFullTraining(unittest.TestCase):
"""Fast training of Cifar-10 to good accuracy"""
@classmethod
def setUpClass(cls):
out = run_train(**{'--data-dir': cifar10_data_dir,
'--epochs': 400,
... | @pytest.mark.category3
@pytest.mark.ipus(1)
class TestCifar10SqueezeNetFullTraining(unittest.TestCase):
| """Fast training of Cifar-10 to good accuracy"""
@classmethod
def setUpClass(cls):
out = run_train(**{'--data-dir': cifar10_data_dir,
'--epochs': 400,
'--model': "squeezenet",
'--use-bypass': '',
... | .assertLess(final_acc, 65)
# test_learning_rates
self.assertEqual(self.training['lr'][0], 0.1)
self.assertAlmostEqual(self.training['lr'][-1], 0.0001, places=3)
# test_epochs_completed
self.assertEqual(round(self.training['epoch'][-1]), 10)
@pytest.mark.category3
@pytest.mark.i... | 101 | 101 | 337 | 26 | 75 | xihuaiwen/chinese_bert | applications/tensorflow/cnns/training/test/test_squeezenet.py | Python | TestCifar10SqueezeNetFullTraining | TestCifar10SqueezeNetFullTraining | 48 | 83 | 48 | 50 | 208f8b414ea32ddb5e83314fcf3169f082dcbfe1 | bigcode/the-stack | train |
3802e77893e72aba519ecab5 | train | class | @pytest.mark.category2
@pytest.mark.ipus(1)
class TestCifar10SqueezeNetTraining(unittest.TestCase):
"""Testing some basic training parameters"""
@classmethod
def setUpClass(cls):
out = run_train(**{'--data-dir': cifar10_data_dir,
'--model': "squeezenet",
... | @pytest.mark.category2
@pytest.mark.ipus(1)
class TestCifar10SqueezeNetTraining(unittest.TestCase):
| """Testing some basic training parameters"""
@classmethod
def setUpClass(cls):
out = run_train(**{'--data-dir': cifar10_data_dir,
'--model': "squeezenet",
'--epochs': 10,
'--use-bypass': '',
... | # Copyright 2019 Graphcore Ltd.
"""
Tests covering SqueezeNet training.
"""
import pytest
import unittest
import statistics
from test_common import get_csv, run_train, cifar10_data_dir
@pytest.mark.category2
@pytest.mark.ipus(1)
class TestCifar10SqueezeNetTraining(unittest.TestCase):
| 68 | 91 | 305 | 25 | 42 | xihuaiwen/chinese_bert | applications/tensorflow/cnns/training/test/test_squeezenet.py | Python | TestCifar10SqueezeNetTraining | TestCifar10SqueezeNetTraining | 12 | 45 | 12 | 14 | fc97109e0641296a7c83627e8aa2f7f3e1da7a9d | bigcode/the-stack | train |
c8be823c22141a3dbf00c51d | train | class | class AboutTuples(Koan):
def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three[2] = "three"
exc... | class AboutTuples(Koan):
| def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three[2] = "three"
except TypeError as ex:
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutTuples(Koan):
| 28 | 197 | 658 | 7 | 21 | nsimoneaux/pykoans | python2/koans/about_tuples.py | Python | AboutTuples | AboutTuples | 7 | 70 | 7 | 7 | 7d947b739cb2b9b2ad7401e3d7334483f00a17f5 | bigcode/the-stack | train |
6ceaa3c39ca8a2fb52dd928f | train | function | def click_and_select(event, x, y, flags, param):
global refPt
if event == cv2.EVENT_LBUTTONDBLCLK:
print("Point selected: ", (x, y))
refPt.append((x, y))
| def click_and_select(event, x, y, flags, param):
| global refPt
if event == cv2.EVENT_LBUTTONDBLCLK:
print("Point selected: ", (x, y))
refPt.append((x, y))
| , y):
return (x + y)/2.0
refPt = [] # list of reference points of the corners
# callback function to select corners of the book cover and relative shape
# responds if left button is clicked twice
def click_and_select(event, x, y, flags, param):
| 64 | 64 | 53 | 14 | 49 | krshrimali/Dimensionality-Calculation-using-Homography-Matrix-and-QR-Code-Detection | book_dimensions.py | Python | click_and_select | click_and_select | 50 | 55 | 50 | 50 | 81a2effa35b3466f80dc4c668c7d95f7212ebcb4 | bigcode/the-stack | train |
8497ad93f67fe9a8e6c6029e | train | function | def avg(x, y):
return (x + y)/2.0
| def avg(x, y):
| return (x + y)/2.0
| import cv2 as cv
import math
def distance(x0,y0,x1,y1):
sq1 = (x0 - x1)**2
sq2 = (y0 - y1)**2
return math.sqrt(abs(sq1 + sq2))
def avg(x, y):
| 64 | 64 | 17 | 6 | 58 | krshrimali/Dimensionality-Calculation-using-Homography-Matrix-and-QR-Code-Detection | book_dimensions.py | Python | avg | avg | 43 | 44 | 43 | 43 | c2d6d5801a29960642e483646d1e46b663291817 | bigcode/the-stack | train |
993586e48e2239880ab6b904 | train | function | def distance(x0,y0,x1,y1):
sq1 = (x0 - x1)**2
sq2 = (y0 - y1)**2
return math.sqrt(abs(sq1 + sq2))
| def distance(x0,y0,x1,y1):
| sq1 = (x0 - x1)**2
sq2 = (y0 - y1)**2
return math.sqrt(abs(sq1 + sq2))
| done,
if QR code in the book. Ratio used to calculate the height and width of the book.
'''
# Python 2/3 compatibility
from __future__ import print_function
import argparse
import sys
import cv2 as cv
import math
def distance(x0,y0,x1,y1):
| 64 | 64 | 49 | 11 | 52 | krshrimali/Dimensionality-Calculation-using-Homography-Matrix-and-QR-Code-Detection | book_dimensions.py | Python | distance | distance | 38 | 41 | 38 | 38 | e7079a338084ed37219309fc497231cbf1ddba81 | bigcode/the-stack | train |
a224a0ecf7711158afed852d | train | function | def match(j, args, params, tags, tasklet):
return True
| def match(j, args, params, tags, tasklet):
| return True
| ):
params.merge(args)
doc = params.doc
tags = params.tags
params.result = "h5. hello\nThis content is from the included macro\n"
params.result = (params.result, doc)
return params
def match(j, args, params, tags, tasklet):
| 64 | 64 | 17 | 13 | 50 | threefoldtech/jumpscale_portal_classic | apps/portalbase/wiki/TestSpace/.macros/wiki/testwikiout2/1_main.py | Python | match | match | 15 | 16 | 15 | 15 | 7aa65fe21f91f377cd2903f15c00857b0f2e9074 | bigcode/the-stack | train |
1f92caca1143f8671eaeeef5 | train | function | def main(j, args, params, tags, tasklet):
params.merge(args)
doc = params.doc
tags = params.tags
params.result = "h5. hello\nThis content is from the included macro\n"
params.result = (params.result, doc)
return params
| def main(j, args, params, tags, tasklet):
| params.merge(args)
doc = params.doc
tags = params.tags
params.result = "h5. hello\nThis content is from the included macro\n"
params.result = (params.result, doc)
return params
| def main(j, args, params, tags, tasklet):
| 13 | 64 | 63 | 13 | 0 | threefoldtech/jumpscale_portal_classic | apps/portalbase/wiki/TestSpace/.macros/wiki/testwikiout2/1_main.py | Python | main | main | 2 | 12 | 2 | 2 | 564007480eb10c2d8cb08871e5c0875a6997139a | bigcode/the-stack | train |
6d3d98d554cdc8372203c3df | train | function | def main(in_file):
"""
Main function to handle operation
:param in_file: string path to Windows 7 setupapi.dev.log
:return: None
"""
if os.path.isfile(in_file):
print('{:=^22}'.format(''))
print('{} {}'.format('SetupAPI Parser, v', __date__))
print('{:=^22} \n'.format('')... | def main(in_file):
| """
Main function to handle operation
:param in_file: string path to Windows 7 setupapi.dev.log
:return: None
"""
if os.path.isfile(in_file):
print('{:=^22}'.format(''))
print('{} {}'.format('SetupAPI Parser, v', __date__))
print('{:=^22} \n'.format(''))
device_in... | THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
__authors__ = ["Chapin Bryce", "Preston Miller"]
__date__ = 20181027
__description__ = """This scripts reads a Windows 7 Setup API
log and prints USB Devices to the user"""
def main(in_file):
| 64 | 64 | 131 | 5 | 59 | noorf/Learning-Python-for-Forensics-Second-Edition | Chapter03/setupapi_parser_v2.py | Python | main | main | 42 | 57 | 42 | 42 | 9fe5f36743b0d6f4077dd54257cc7dd10e3b3ea6 | bigcode/the-stack | train |
41058b7584972a8cd203c55e | train | function | def print_output(usb_name, usb_date):
"""
Print the information discovered
:param usb_name: String USB Name to print
:param usb_date: String USB Date to print
:return: None
"""
print('Device: {}'.format(usb_name))
print('First Install: {}\n'.format(usb_date))
| def print_output(usb_name, usb_date):
| """
Print the information discovered
:param usb_name: String USB Name to print
:param usb_date: String USB Date to print
:return: None
"""
print('Device: {}'.format(usb_name))
print('First Install: {}\n'.format(usb_date))
| relevant so please always validate that
# the data reduction does not remove results
# of interest to you.
date = next(in_file).split('start')[1].strip()
device_list.append((device_name, date))
return device_list
def print_output(usb_name, u... | 64 | 64 | 75 | 10 | 53 | noorf/Learning-Python-for-Forensics-Second-Edition | Chapter03/setupapi_parser_v2.py | Python | print_output | print_output | 93 | 101 | 93 | 93 | 97d25b35a16b3379c6536e4187527f3bcb074ec0 | bigcode/the-stack | train |
b3f1f732f8b37a42d5828270 | train | function | def parse_setupapi(setup_log):
"""
Read data from provided file for Device Install Events for
USB Devices
:param setup_log: str - Path to valid setup api log
:return: list of tuples - Tuples contain device name and date
in that order
"""
device_list = list()
with open(setup_l... | def parse_setupapi(setup_log):
| """
Read data from provided file for Device Install Events for
USB Devices
:param setup_log: str - Path to valid setup api log
:return: list of tuples - Tuples contain device name and date
in that order
"""
device_list = list()
with open(setup_log) as in_file:
for lin... | Parser, v', __date__))
print('{:=^22} \n'.format(''))
device_information = parse_setupapi(in_file)
for device in device_information:
print_output(device[0], device[1])
else:
print('Input is not a file.')
sys.exit(1)
def parse_setupapi(setup_log):
| 74 | 74 | 247 | 8 | 66 | noorf/Learning-Python-for-Forensics-Second-Edition | Chapter03/setupapi_parser_v2.py | Python | parse_setupapi | parse_setupapi | 60 | 90 | 60 | 60 | 28951415816fc5e39a4b5a512eb9b37aeaebc518 | bigcode/the-stack | train |
c527acb61663d04a40560638 | train | function | def exec_music(goal):
r = MusicResult()
fb = MusicFeedback()
for i, f in enumerate(goal.freqs):
fb.remaining_steps = len(goal.freqs) - 1
music.publish_feedback(fb)
if music.is_preempt_requested():
write_freq(0)
r.finished = False
music.set_preempted(r)
return
write_freq(f)
rospy.... | def exec_music(goal):
| r = MusicResult()
fb = MusicFeedback()
for i, f in enumerate(goal.freqs):
fb.remaining_steps = len(goal.freqs) - 1
music.publish_feedback(fb)
if music.is_preempt_requested():
write_freq(0)
r.finished = False
music.set_preempted(r)
return
write_freq(f)
rospy.sleep(1.0 if i >= len(... | /rtbuzzer0"
try:
with open(bfile,"w") as f:
f.write(str(hz) + "\n")
except IOError:
rospy.logerr("can't write to " + bfile)
def recv_buzzer(data):
write_freq(data.data)
def exec_music(goal):
| 64 | 64 | 121 | 5 | 59 | matsumotokoki/pimouse_ros | scripts/buzzer.py | Python | exec_music | exec_music | 19 | 36 | 19 | 19 | 91547533666faaa96fd43f4338ae0db58bac2d57 | bigcode/the-stack | train |
7488c35ae239bd6099e24431 | train | function | def write_freq(hz=0):
bfile = "/dev/rtbuzzer0"
try:
with open(bfile,"w") as f:
f.write(str(hz) + "\n")
except IOError:
rospy.logerr("can't write to " + bfile)
| def write_freq(hz=0):
| bfile = "/dev/rtbuzzer0"
try:
with open(bfile,"w") as f:
f.write(str(hz) + "\n")
except IOError:
rospy.logerr("can't write to " + bfile)
| #!/usr/bin/env python
#encoding: utf-8
import rospy, actionlib
from std_msgs.msg import UInt16
from pimouse_ros.msg import MusicResult, MusicFeedback, MusicAction
def write_freq(hz=0):
| 50 | 64 | 61 | 8 | 41 | matsumotokoki/pimouse_ros | scripts/buzzer.py | Python | write_freq | write_freq | 7 | 13 | 7 | 7 | ef7eaf781648121ac0c476e4396a53187fd0aec6 | bigcode/the-stack | train |
89a0ec055ab09628bf70f176 | train | function | def recv_buzzer(data):
write_freq(data.data)
| def recv_buzzer(data):
| write_freq(data.data)
| (hz=0):
bfile = "/dev/rtbuzzer0"
try:
with open(bfile,"w") as f:
f.write(str(hz) + "\n")
except IOError:
rospy.logerr("can't write to " + bfile)
def recv_buzzer(data):
| 64 | 64 | 11 | 6 | 58 | matsumotokoki/pimouse_ros | scripts/buzzer.py | Python | recv_buzzer | recv_buzzer | 16 | 17 | 16 | 16 | 5e0631bc09421395c1aa60358234e12b1a4f2f8f | bigcode/the-stack | train |
293579d99f6348c2cfc1e681 | train | class | class VirtCPUFeature(base.NovaObject):
VERSION = VirtCPUModel.VERSION
fields = {
'policy': fields.EnumField(nullable=True,
valid_values=cpumodel.ALL_POLICIES),
'name': fields.StringField(nullable=False),
}
def obj_load_attr(self, attrname):
se... | class VirtCPUFeature(base.NovaObject):
| VERSION = VirtCPUModel.VERSION
fields = {
'policy': fields.EnumField(nullable=True,
valid_values=cpumodel.ALL_POLICIES),
'name': fields.StringField(nullable=False),
}
def obj_load_attr(self, attrname):
setattr(self, attrname, None)
| .instance_extra_get_by_instance_uuid(
context, instance_uuid, columns=['vcpu_model'])
if not db_extra or not db_extra['vcpu_model']:
return None
return cls.obj_from_primitive(jsonutils.loads(db_extra['vcpu_model']))
class VirtCPUFeature(base.NovaObject):
| 63 | 64 | 74 | 9 | 54 | bopopescu/nova-17 | nova/objects/vcpu_model.py | Python | VirtCPUFeature | VirtCPUFeature | 65 | 75 | 65 | 65 | 7184279cce612f32e0277477e4460bd336aa2ad7 | bigcode/the-stack | train |
6c45fd2c59b3b81fbf09997b | train | class | class VirtCPUModel(base.NovaObject):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'arch': fields.EnumField(nullable=True,
valid_values=arch.ALL),
'vendor': fields.StringField(nullable=True),
'topology': fields.ObjectField('VirtCPUTopolog... | class VirtCPUModel(base.NovaObject):
# Version 1.0: Initial version
| VERSION = '1.0'
fields = {
'arch': fields.EnumField(nullable=True,
valid_values=arch.ALL),
'vendor': fields.StringField(nullable=True),
'topology': fields.ObjectField('VirtCPUTopology',
nullable=True),
'feat... | " BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from nova.compute import arch
from nova.compute import cpumodel
from nova import ... | 99 | 99 | 331 | 20 | 78 | bopopescu/nova-17 | nova/objects/vcpu_model.py | Python | VirtCPUModel | VirtCPUModel | 22 | 62 | 22 | 23 | 38a0b2e2243bf753622f6d15a4d5b2e5dde1d24d | bigcode/the-stack | train |
b3d9c7ea1322c280e1f9971f | train | class | class StringFormatterChecker:
"""String interpolation/formatter type checker.
This class works closely together with checker.ExpressionChecker.
"""
# Some services are provided by a TypeChecker instance.
chk = None # type: mypy.checker.TypeChecker
# This is shared with TypeChecker, but stored... | class StringFormatterChecker:
| """String interpolation/formatter type checker.
This class works closely together with checker.ExpressionChecker.
"""
# Some services are provided by a TypeChecker instance.
chk = None # type: mypy.checker.TypeChecker
# This is shared with TypeChecker, but stored also here for convenience.
... | of flags.
width_re = r'(\*|[1-9][0-9]*)?' # (optional) minimum field width (* or numbers).
precision_re = r'(?:\.(\*|[0-9]+)?)?' # (optional) . followed by * of numbers.
length_mod_re = r'[hlL]?' # (optional) length modifier (unused).
type_re = r'(.)?' # conversion type.
format_re = '%' + key_r... | 256 | 256 | 2,700 | 5 | 250 | RafaelReder/mypy | mypy/checkstrformat.py | Python | StringFormatterChecker | StringFormatterChecker | 57 | 353 | 57 | 57 | cbf8c09297eb3365e507234abb2621711905a379 | bigcode/the-stack | train |
534925706ab9927081bb0529 | train | function | def compile_format_re() -> Pattern[str]:
key_re = r'(\(([^()]*)\))?' # (optional) parenthesised sequence of characters.
flags_re = r'([#0\-+ ]*)' # (optional) sequence of flags.
width_re = r'(\*|[1-9][0-9]*)?' # (optional) minimum field width (* or numbers).
precision_re = r'(?:\.(\*|[0-9]+)?)?' # (... | def compile_format_re() -> Pattern[str]:
| key_re = r'(\(([^()]*)\))?' # (optional) parenthesised sequence of characters.
flags_re = r'([#0\-+ ]*)' # (optional) sequence of flags.
width_re = r'(\*|[1-9][0-9]*)?' # (optional) minimum field width (* or numbers).
precision_re = r'(?:\.(\*|[0-9]+)?)?' # (optional) . followed by * of numbers.
... | from typing_extensions import Final
from mypy import message_registry
from mypy.messages import MessageBuilder
FormatStringExpr = Union[StrExpr, BytesExpr, UnicodeExpr]
Checkers = Tuple[Callable[[Expression], None], Callable[[Type], None]]
def compile_format_re() -> Pattern[str]:
| 63 | 64 | 187 | 9 | 54 | RafaelReder/mypy | mypy/checkstrformat.py | Python | compile_format_re | compile_format_re | 27 | 35 | 27 | 27 | 8f79619d31236f1675f40a32069561975b8ed692 | bigcode/the-stack | train |
08df1a361c3d53d0f5e67fc5 | train | class | class ConversionSpecifier:
def __init__(self, key: Optional[str],
flags: str, width: str, precision: str, type: str) -> None:
self.key = key
self.flags = flags
self.width = width
self.precision = precision
self.type = type
def has_key(self) -> bool:
... | class ConversionSpecifier:
| def __init__(self, key: Optional[str],
flags: str, width: str, precision: str, type: str) -> None:
self.key = key
self.flags = flags
self.width = width
self.precision = precision
self.type = type
def has_key(self) -> bool:
return self.key is not ... | unused).
type_re = r'(.)?' # conversion type.
format_re = '%' + key_re + flags_re + width_re + precision_re + length_mod_re + type_re
return re.compile(format_re)
FORMAT_RE = compile_format_re() # type: Final
class ConversionSpecifier:
| 64 | 64 | 106 | 4 | 59 | RafaelReder/mypy | mypy/checkstrformat.py | Python | ConversionSpecifier | ConversionSpecifier | 41 | 54 | 41 | 41 | 3d6d4eabb9219f941cba3e6d313a977ea30742e0 | bigcode/the-stack | train |
960a51de89e5b7b2ff75c172 | train | class | class Resource(object):
@falcon.before(Actions.validate_account_server_access)
def on_get(self, req, resp, account_id):
"""Handles GET requests"""
watched = Actions.get_watched(account_id)
if watched is None:
resp.status = falcon.HTTP_404
return
servers = ... | class Resource(object):
@falcon.before(Actions.validate_account_server_access)
| def on_get(self, req, resp, account_id):
"""Handles GET requests"""
watched = Actions.get_watched(account_id)
if watched is None:
resp.status = falcon.HTTP_404
return
servers = Actions.get_servers(account_id)
resp.status = falcon.HTTP_200 # This is th... | items):
return _r.srem(Actions.get_account_key(account_id), *items)
@staticmethod
def add_server(account_id, server_id):
return _r.sadd(Actions.get_account_server_relation_key(account_id), server_id)
@staticmethod
def remove_server(account_id, server_id):
return _r.srem(Action... | 134 | 134 | 449 | 16 | 118 | fiLLLip/plex-watched-sync | server/account.py | Python | Resource | Resource | 68 | 121 | 68 | 69 | 29250017e481fb450e38185e193cc002c7f42618 | bigcode/the-stack | train |
792ec47eb1cb2260468a39a4 | train | class | class Actions(object):
@staticmethod
def get_account_key(account_id):
return 'account:' + str(account_id)
@staticmethod
def get_account_server_relation_key(account_id):
return 'account:' + str(account_id) + ':servers'
@staticmethod
def validate_account_server_access(req, resp, ... | class Actions(object):
@staticmethod
| def get_account_key(account_id):
return 'account:' + str(account_id)
@staticmethod
def get_account_server_relation_key(account_id):
return 'account:' + str(account_id) + ':servers'
@staticmethod
def validate_account_server_access(req, resp, resource, params):
if 'X-SERVER-I... | # account.py
import json
import falcon
import redis_plex
import server
_r = redis_plex.connection()
class Actions(object):
@staticmethod
| 34 | 129 | 430 | 8 | 26 | fiLLLip/plex-watched-sync | server/account.py | Python | Actions | Actions | 11 | 65 | 11 | 12 | 8904c77836d341ac59f2c6cfdee798b174065445 | bigcode/the-stack | train |
c37c10937c9f8f74c6e6883b | train | class | class PythonApp(AppBase):
"""A deployable Python application.
Invoking the ``bundle`` goal on one of these targets creates a
self-contained artifact suitable for deployment on some other machine.
The artifact contains the executable pex, its dependencies, and
extra files like config files, startup ... | class PythonApp(AppBase):
| """A deployable Python application.
Invoking the ``bundle`` goal on one of these targets creates a
self-contained artifact suitable for deployment on some other machine.
The artifact contains the executable pex, its dependencies, and
extra files like config files, startup scripts, etc.
:API: p... | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.python.targets.python_binary import PythonBinary
from pants.build_graph.app_base import AppBase
class PythonApp(AppBase):
| 56 | 64 | 126 | 6 | 49 | revl/pants | src/python/pants/backend/python/targets/python_app.py | Python | PythonApp | PythonApp | 8 | 29 | 8 | 8 | ec117268e15cdbc2517beefe370fb94fd4a3abcd | bigcode/the-stack | train |
19ccf881a408b5c3a86dfcaa | train | function | @event('plugin.register')
def register_plugin():
plugin.register(PluginSortBy, 'sort_by', api_ver=2)
| @event('plugin.register')
def register_plugin():
| plugin.register(PluginSortBy, 'sort_by', api_ver=2)
| .get('reverse', False)
log.debug('sorting entries by: %s' % config)
if not field:
task.all_entries.reverse()
return
task.all_entries.sort(key=lambda e: e.get(field, 0), reverse=reverse)
@event('plugin.register')
def register_plugin():
| 64 | 64 | 27 | 10 | 54 | davidcollom/Flexget | flexget/plugins/modify/sort_by.py | Python | register_plugin | register_plugin | 63 | 65 | 63 | 64 | 3314a0eb064de0bb4996266a64b87252ad7ab029 | bigcode/the-stack | train |
e6cd90cbb8160454cae4b0ee | train | class | class PluginSortBy(object):
"""
Sort task entries based on a field
Example::
sort_by: title
More complex::
sort_by:
field: imdb_score
reverse: yes
Reverse the order of the entries, without sorting on a field::
sort_by:
reverse: yes
"""
schema ... | class PluginSortBy(object):
| """
Sort task entries based on a field
Example::
sort_by: title
More complex::
sort_by:
field: imdb_score
reverse: yes
Reverse the order of the entries, without sorting on a field::
sort_by:
reverse: yes
"""
schema = {
'oneOf': [
... | __ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from past.builtins import basestring
import logging
from flexget import plugin
from flexget.event import event
log = logging.getLogger('sort_by')
class PluginSortBy(object):
| 70 | 70 | 235 | 6 | 64 | davidcollom/Flexget | flexget/plugins/modify/sort_by.py | Python | PluginSortBy | PluginSortBy | 13 | 60 | 13 | 13 | 64ed1e959e828af9c13d4c463742b315cc244d0b | bigcode/the-stack | train |
9c44e0a8f344db09c8522690 | train | class | class Coordinate(Point2D):
""""
This is a user-friendly wrapper for arrays of 2D vectors that represent 2D spatial coordinates
(longitude and latitude) in radians.
"""
class Units(metaclass=FastEnum):
RADIANS = 0
DEGREES = 1
def __new__(cls,
*, # make lat, lon ... | class Coordinate(Point2D):
| """"
This is a user-friendly wrapper for arrays of 2D vectors that represent 2D spatial coordinates
(longitude and latitude) in radians.
"""
class Units(metaclass=FastEnum):
RADIANS = 0
DEGREES = 1
def __new__(cls,
*, # make lat, lon and units keyword-only argu... | from __future__ import annotations
import math
from typing import Tuple, Iterable, Union
import numpy as np
from fast_enum import FastEnum
from numba import njit
from vectorized2d import Point2D
from vectorized2d.utils import units as units
class Coordinate(Point2D):
| 65 | 256 | 2,278 | 6 | 58 | mishana/Vectorized2D | vectorized2d/coordinate.py | Python | Coordinate | Coordinate | 14 | 230 | 14 | 14 | 0136237eefbcfe8756136ebdcbb1fcf62224dc54 | bigcode/the-stack | train |
298e658606412dcaf1bf02f8 | train | class | class TestLogtailHandler(unittest2.TestCase):
source_token = 'dummy_source_token'
host = 'dummy_host'
@mock.patch('logtail.handler.FlushWorker')
def test_handler_creates_uploader_from_args(self, MockWorker):
handler = LogtailHandler(source_token=self.source_token, host=self.host)
self.a... | class TestLogtailHandler(unittest2.TestCase):
| source_token = 'dummy_source_token'
host = 'dummy_host'
@mock.patch('logtail.handler.FlushWorker')
def test_handler_creates_uploader_from_args(self, MockWorker):
handler = LogtailHandler(source_token=self.source_token, host=self.host)
self.assertEqual(handler.uploader.source_token, self... | # coding: utf-8
from __future__ import print_function, unicode_literals
import mock
import time
import threading
import unittest2
import logging
from logtail.handler import LogtailHandler
class TestLogtailHandler(unittest2.TestCase):
| 53 | 250 | 834 | 10 | 42 | logtail/logtail-python | tests/test_handler.py | Python | TestLogtailHandler | TestLogtailHandler | 12 | 129 | 12 | 12 | 07051663b3485a7f6d074e68084d3637feb56784 | bigcode/the-stack | train |
f099eba64a62d0a7e788272c | train | class | class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
return self.helper(root, 0)
def helper(self, root, base):
if not root:
return 0
if not root.left and not root.right:
return 2 * base + root.val
base = 2 * base + root.val
return self.... | class Solution:
| def sumRootToLeaf(self, root: TreeNode) -> int:
return self.helper(root, 0)
def helper(self, root, base):
if not root:
return 0
if not root.left and not root.right:
return 2 * base + root.val
base = 2 * base + root.val
return self.helper(root.left... | -cn.com/problems/sum-of-root-to-leaf-binary-numbers
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
| 64 | 64 | 95 | 3 | 60 | dylanlee101/leetcode | code_week3_511_517/sum_of_root_to_leaf_numbers.py | Python | Solution | Solution | 36 | 46 | 36 | 36 | 77819e1e39573e79d9c84632173db85ce1a9d375 | bigcode/the-stack | train |
cea471836654b7458b4ca865 | train | class | class Migration(migrations.Migration):
dependencies = [
('dropkickApp', '0007_auto_20220323_1402'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='name',
field=models.CharField(max_length=50),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('dropkickApp', '0007_auto_20220323_1402'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='name',
field=models.CharField(max_length=50),
),
]
| # Generated by Django 3.2 on 2022-03-23 19:03
from django.db import migrations, models
class Migration(migrations.Migration):
| 36 | 64 | 65 | 7 | 28 | wangvictoria/dropkick | dropkickApp/migrations/0008_alter_contact_name.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | 4b25d5d7c93b7be979b12a0ece63f58ead90f2fa | bigcode/the-stack | train |
30093b9bcb8a7bbd254d46b5 | train | class | class CapsDatasetRoi(CapsDataset):
def __init__(
self,
caps_directory,
data_file,
roi_list=None,
cropped_roi=True,
roi_index=None,
preprocessing="t1-linear",
train_transformations=None,
prepare_dl=False,
label_presence=True,
lab... | class CapsDatasetRoi(CapsDataset):
| def __init__(
self,
caps_directory,
data_file,
roi_list=None,
cropped_roi=True,
roi_index=None,
preprocessing="t1-linear",
train_transformations=None,
prepare_dl=False,
label_presence=True,
label=None,
label_code=None,
... | fold(3, self.patch_size, self.stride_size)
.contiguous()
)
patches_tensor = patches_tensor.view(
-1, self.patch_size, self.patch_size, self.patch_size
)
num_patches = patches_tensor.shape[0]
return num_patches
def extract_patch_from_mri(self, image_te... | 256 | 256 | 2,010 | 9 | 246 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | CapsDatasetRoi | CapsDatasetRoi | 506 | 762 | 506 | 506 | ab8124a264cd7b77503ec7004677bb85966880f0 | bigcode/the-stack | train |
49b971a7773680f0cf0fad20 | train | class | class CapsDatasetImage(CapsDataset):
"""Dataset of MRI organized in a CAPS folder."""
def __init__(
self,
caps_directory,
data_file,
preprocessing="t1-linear",
train_transformations=None,
label_presence=True,
label=None,
label_code=None,
a... | class CapsDatasetImage(CapsDataset):
| """Dataset of MRI organized in a CAPS folder."""
def __init__(
self,
caps_directory,
data_file,
preprocessing="t1-linear",
train_transformations=None,
label_presence=True,
label=None,
label_code=None,
all_transformations=None,
mult... | ): ID of the session,
- f"{self.mode}_id" (int): number of the element,
- "image_path": path to the image loaded in CAPS.
"""
pass
@abc.abstractmethod
def num_elem_per_image(self):
"""Computes the number of elements per image based on the full image."""
... | 146 | 146 | 489 | 8 | 137 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | CapsDatasetImage | CapsDatasetImage | 294 | 363 | 294 | 294 | 5745684a63db4ae01d453b1b56abd07132456c1a | bigcode/the-stack | train |
2b759317b3c22f1178271eac | train | class | class RandomNoising(object):
"""Applies a random zoom to a tensor"""
def __init__(self, sigma=0.1):
self.sigma = sigma
def __call__(self, image):
import random
sigma = random.uniform(0, self.sigma)
dist = torch.distributions.normal.Normal(0, sigma)
return image + d... | class RandomNoising(object):
| """Applies a random zoom to a tensor"""
def __init__(self, sigma=0.1):
self.sigma = sigma
def __call__(self, image):
import random
sigma = random.uniform(0, self.sigma)
dist = torch.distributions.normal.Normal(0, sigma)
return image + dist.sample(image.shape)
| ,
label_presence=label_presence,
label=label,
label_code=label_code,
multi_cohort=multi_cohort,
)
else:
raise ValueError("Mode %s is not implemented." % mode)
##################################
# Transformations
##################################
cla... | 63 | 64 | 84 | 6 | 57 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | RandomNoising | RandomNoising | 1,013 | 1,024 | 1,013 | 1,013 | fefb8211b24a4a8d17190f9d4117ff443ae2fefc | bigcode/the-stack | train |
19a7ea1a5094297a9938733d | train | class | class CapsDataset(Dataset):
"""Abstract class for all derived CapsDatasets."""
def __init__(
self,
caps_directory,
data_df,
preprocessing,
transformations,
label_presence,
label=None,
label_code=None,
augmentation_transformations=None,
... | class CapsDataset(Dataset):
| """Abstract class for all derived CapsDatasets."""
def __init__(
self,
caps_directory,
data_df,
preprocessing,
transformations,
label_presence,
label=None,
label_code=None,
augmentation_transformations=None,
multi_cohort=False,
... | # coding: utf8
import abc
from os import path
import numpy as np
import pandas as pd
import torch
import torchvision.transforms as transforms
from torch.utils.data import Dataset
from clinicadl.utils.inputs import FILENAME_TYPE, MASK_PATTERN
#################################
# Datasets loaders
#####################... | 68 | 256 | 1,951 | 6 | 62 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | CapsDataset | CapsDataset | 19 | 291 | 19 | 19 | 8a211eedd4e0063c7340978323782b6e644ced21 | bigcode/the-stack | train |
f761eed1bd2c0bea7380b85a | train | function | def load_data_test_single(test_path, diagnoses_list, baseline=True):
if test_path.endswith(".tsv"):
test_df = pd.read_csv(test_path, sep="\t")
if "diagnosis" not in test_df.columns.values:
raise ValueError(
f"'diagnosis' column must be present in TSV file {test_path}."
... | def load_data_test_single(test_path, diagnoses_list, baseline=True):
| if test_path.endswith(".tsv"):
test_df = pd.read_csv(test_path, sep="\t")
if "diagnosis" not in test_df.columns.values:
raise ValueError(
f"'diagnosis' column must be present in TSV file {test_path}."
)
test_df = test_df[test_df.diagnosis.isin(diagnose... | .values):
raise ValueError(
"To use multi-cohort framework, please add --multi_cohort flag."
)
test_df = load_data_test_single(test_path, diagnoses_list, baseline=baseline)
test_df["cohort"] = "single"
return test_df
def load_data_test_single(test... | 74 | 74 | 247 | 14 | 59 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | load_data_test_single | load_data_test_single | 1,203 | 1,232 | 1,203 | 1,204 | 7a01983829e4a94bd9e8fc76f0ab51978261807b | bigcode/the-stack | train |
2b7b106df855c6ecd2fb2af7 | train | class | class RandomSmoothing(object):
"""Applies a random zoom to a tensor"""
def __init__(self, sigma=1):
self.sigma = sigma
def __call__(self, image):
import random
from scipy.ndimage import gaussian_filter
sigma = random.uniform(0, self.sigma)
image = gaussian_filter(... | class RandomSmoothing(object):
| """Applies a random zoom to a tensor"""
def __init__(self, sigma=1):
self.sigma = sigma
def __call__(self, image):
import random
from scipy.ndimage import gaussian_filter
sigma = random.uniform(0, self.sigma)
image = gaussian_filter(image, sigma) # smoothing of d... | 0.1):
self.sigma = sigma
def __call__(self, image):
import random
sigma = random.uniform(0, self.sigma)
dist = torch.distributions.normal.Normal(0, sigma)
return image + dist.sample(image.shape)
class RandomSmoothing(object):
| 64 | 64 | 98 | 6 | 58 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | RandomSmoothing | RandomSmoothing | 1,027 | 1,041 | 1,027 | 1,027 | 1b7cf8df60e82e444d0f69c41bfcded7e6453416 | bigcode/the-stack | train |
e578cc9206067c1769c2c56c | train | class | class MinMaxNormalization(object):
"""Normalizes a tensor between 0 and 1"""
def __call__(self, image):
return (image - image.min()) / (image.max() - image.min())
| class MinMaxNormalization(object):
| """Normalizes a tensor between 0 and 1"""
def __call__(self, image):
return (image - image.min()) / (image.max() - image.min())
| class ToTensor(object):
"""Convert image type to Tensor and diagnosis to diagnosis code"""
def __call__(self, image):
np.nan_to_num(image, copy=False)
image = image.astype(float)
return torch.from_numpy(image[np.newaxis, :]).float()
class MinMaxNormalization(object):
| 64 | 64 | 45 | 6 | 58 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | MinMaxNormalization | MinMaxNormalization | 1,089 | 1,093 | 1,089 | 1,089 | 948fb820428320d411e3621faef63f6662b908c7 | bigcode/the-stack | train |
c6d1373126d82c8f7656699a | train | class | class CapsDatasetPatch(CapsDataset):
def __init__(
self,
caps_directory,
data_file,
patch_size,
stride_size,
train_transformations=None,
prepare_dl=False,
patch_index=None,
preprocessing="t1-linear",
label_presence=True,
label=N... | class CapsDatasetPatch(CapsDataset):
| def __init__(
self,
caps_directory,
data_file,
patch_size,
stride_size,
train_transformations=None,
prepare_dl=False,
patch_index=None,
preprocessing="t1-linear",
label_presence=True,
label=None,
label_code=None,
... | to a TSV file linking cohort names and paths.
"""
self.mode = "image"
super().__init__(
caps_directory,
data_file,
preprocessing,
augmentation_transformations=train_transformations,
label_presence=label_presence,
label=lab... | 256 | 256 | 1,054 | 8 | 247 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | CapsDatasetPatch | CapsDatasetPatch | 366 | 503 | 366 | 366 | 99cb42201d843f9f7645632402329bcd5a01c6c1 | bigcode/the-stack | train |
4737d18cbdbed80bba5f824f | train | function | def check_multi_cohort_tsv(tsv_df, purpose):
"""
Checks that a multi-cohort TSV file is valid.
Args:
tsv_df (pd.DataFrame): DataFrame of multi-cohort definition.
purpose (str): what the TSV file describes (CAPS or TSV).
Raises:
ValueError: if the TSV file is badly formatted.
... | def check_multi_cohort_tsv(tsv_df, purpose):
| """
Checks that a multi-cohort TSV file is valid.
Args:
tsv_df (pd.DataFrame): DataFrame of multi-cohort definition.
purpose (str): what the TSV file describes (CAPS or TSV).
Raises:
ValueError: if the TSV file is badly formatted.
"""
if purpose.upper() == "CAPS":
... | test_diagnosis_df = pd.read_csv(test_diagnosis_path, sep="\t")
test_df = pd.concat([test_df, test_diagnosis_df])
test_df.reset_index(inplace=True, drop=True)
return test_df
def check_multi_cohort_tsv(tsv_df, purpose):
| 64 | 64 | 161 | 13 | 50 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | check_multi_cohort_tsv | check_multi_cohort_tsv | 1,235 | 1,252 | 1,235 | 1,235 | 093c6bd2f659b9e086fd34e3a92f68b7c4718288 | bigcode/the-stack | train |
4e19b7096f2b57fdadcf9c48 | train | class | class GaussianSmoothing(object):
def __init__(self, sigma):
self.sigma = sigma
def __call__(self, sample):
from scipy.ndimage.filters import gaussian_filter
image = sample["image"]
np.nan_to_num(image, copy=False)
smoothed_image = gaussian_filter(image, sigma=self.sigma... | class GaussianSmoothing(object):
| def __init__(self, sigma):
self.sigma = sigma
def __call__(self, sample):
from scipy.ndimage.filters import gaussian_filter
image = sample["image"]
np.nan_to_num(image, copy=False)
smoothed_image = gaussian_filter(image, sigma=self.sigma)
sample["image"] = smoot... | , (-crop[0], crop[0], -crop[1], crop[1], -crop[2], crop[2])
)
else:
raise ValueError("RandomCropPad is only available for 2D or 3D data.")
return output
class GaussianSmoothing(object):
| 64 | 64 | 86 | 6 | 57 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | GaussianSmoothing | GaussianSmoothing | 1,064 | 1,076 | 1,064 | 1,064 | f2dd776b77a6fa8b2dd5d0621efeef143ed7f038 | bigcode/the-stack | train |
ebdbd112e3b51af01d11054c | train | class | class CapsDatasetSlice(CapsDataset):
def __init__(
self,
caps_directory,
data_file,
slice_index=None,
preprocessing="t1-linear",
train_transformations=None,
mri_plane=0,
prepare_dl=False,
discarded_slices=20,
label_presence=True,
... | class CapsDatasetSlice(CapsDataset):
| def __init__(
self,
caps_directory,
data_file,
slice_index=None,
preprocessing="t1-linear",
train_transformations=None,
mri_plane=0,
prepare_dl=False,
discarded_slices=20,
label_presence=True,
label=None,
label_code=None... | self.cropped_roi:
image_descriptors = self.insert_descriptor(
image_descriptors, "desc-CropRoi", "space"
)
elif "desc-Crop" in image_descriptors:
image_descriptors = [
descriptor
for descriptor in image_descriptors
... | 256 | 256 | 1,168 | 8 | 247 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | CapsDatasetSlice | CapsDatasetSlice | 765 | 902 | 765 | 765 | c0948bd8552644dcfc0dc4eb50fd00da8da26dee | bigcode/the-stack | train |
42f19f71323a925a12cdbb36 | train | class | class RandomCropPad(object):
def __init__(self, length):
self.length = length
def __call__(self, image):
dimensions = len(image.shape) - 1
crop = np.random.randint(-self.length, self.length, dimensions)
if dimensions == 2:
output = torch.nn.functional.pad(
... | class RandomCropPad(object):
| def __init__(self, length):
self.length = length
def __call__(self, image):
dimensions = len(image.shape) - 1
crop = np.random.randint(-self.length, self.length, dimensions)
if dimensions == 2:
output = torch.nn.functional.pad(
image, (-crop[0], crop[... | self, image):
import random
from scipy.ndimage import gaussian_filter
sigma = random.uniform(0, self.sigma)
image = gaussian_filter(image, sigma) # smoothing of data
image = torch.from_numpy(image).float()
return image
class RandomCropPad(object):
| 64 | 64 | 169 | 6 | 57 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | RandomCropPad | RandomCropPad | 1,044 | 1,061 | 1,044 | 1,044 | e44e4c8d62d649abf47fce5bf17daac4b3df8a4e | bigcode/the-stack | train |
0c57988992dc678598ceb3f4 | train | function | def return_dataset(
mode,
input_dir,
data_df,
preprocessing,
all_transformations,
params,
label=None,
label_code=None,
train_transformations=None,
cnn_index=None,
label_presence=True,
multi_cohort=False,
prepare_dl=False,
):
"""
Return appropriate Dataset acco... | def return_dataset(
mode,
input_dir,
data_df,
preprocessing,
all_transformations,
params,
label=None,
label_code=None,
train_transformations=None,
cnn_index=None,
label_presence=True,
multi_cohort=False,
prepare_dl=False,
):
| """
Return appropriate Dataset according to given options.
Args:
mode (str): input used by the network. Chosen from ['image', 'patch', 'roi', 'slice'].
input_dir (str): path to a directory containing a CAPS structure.
data_df (pd.DataFrame): List subjects, sessions and diagnoses.
... | , index_slice):
"""
This function extracts one slice along one axis and creates a RGB image
(the slice is duplicated in each channel).
To note:
Axial_view = "[:, :, slice_i]"
Coronal_view = "[:, slice_i, :]"
Sagittal_view= "[slice_i, :, :]"
Args:
... | 232 | 232 | 776 | 63 | 168 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | return_dataset | return_dataset | 905 | 1,005 | 905 | 919 | dcd0a2d5d09a9644fb734671b430e941058c1f7d | bigcode/the-stack | train |
2febff2c48009dade3f4f0aa | train | function | def get_transforms(mode, minmaxnormalization=True, data_augmentation=None):
"""
Outputs the transformations that will be applied to the dataset
Args:
mode (str): input used by the network. Chosen from ['image', 'patch', 'roi', 'slice'].
minmaxnormalization (bool): if True will perform MinMa... | def get_transforms(mode, minmaxnormalization=True, data_augmentation=None):
| """
Outputs the transformations that will be applied to the dataset
Args:
mode (str): input used by the network. Chosen from ['image', 'patch', 'roi', 'slice'].
minmaxnormalization (bool): if True will perform MinMaxNormalization.
data_augmentation (List[str]): list of data augmenta... | image):
np.nan_to_num(image, copy=False)
image = image.astype(float)
return torch.from_numpy(image[np.newaxis, :]).float()
class MinMaxNormalization(object):
"""Normalizes a tensor between 0 and 1"""
def __call__(self, image):
return (image - image.min()) / (image.max() - im... | 95 | 95 | 318 | 17 | 78 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | get_transforms | get_transforms | 1,096 | 1,138 | 1,096 | 1,096 | 74193b6749304c1b5f133e1a193c0b9f36009288 | bigcode/the-stack | train |
3f66ac340d32fcd92ed5d73d | train | class | class ToTensor(object):
"""Convert image type to Tensor and diagnosis to diagnosis code"""
def __call__(self, image):
np.nan_to_num(image, copy=False)
image = image.astype(float)
return torch.from_numpy(image[np.newaxis, :]).float()
| class ToTensor(object):
| """Convert image type to Tensor and diagnosis to diagnosis code"""
def __call__(self, image):
np.nan_to_num(image, copy=False)
image = image.astype(float)
return torch.from_numpy(image[np.newaxis, :]).float()
| self, sample):
from scipy.ndimage.filters import gaussian_filter
image = sample["image"]
np.nan_to_num(image, copy=False)
smoothed_image = gaussian_filter(image, sigma=self.sigma)
sample["image"] = smoothed_image
return sample
class ToTensor(object):
| 64 | 64 | 58 | 5 | 58 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | ToTensor | ToTensor | 1,079 | 1,086 | 1,079 | 1,079 | d5bfe76dd191e5f9aa946ef33c1783c262aeabf1 | bigcode/the-stack | train |
fce2a0d44b4be508b91e1dd1 | train | function | def load_data_test(test_path, diagnoses_list, baseline=True, multi_cohort=False):
"""
Load data not managed by split_manager.
Args:
test_path (str): path to the test TSV files / split directory / TSV file for multi-cohort
diagnoses_list (List[str]): list of the diagnoses wanted in case of s... | def load_data_test(test_path, diagnoses_list, baseline=True, multi_cohort=False):
| """
Load data not managed by split_manager.
Args:
test_path (str): path to the test TSV files / split directory / TSV file for multi-cohort
diagnoses_list (List[str]): list of the diagnoses wanted in case of split_dir or multi-cohort
baseline (bool): If True baseline sessions only u... | Smoothing": RandomSmoothing(),
"None": None,
}
if data_augmentation:
augmentation_list = [
augmentation_dict[augmentation] for augmentation in data_augmentation
]
else:
augmentation_list = []
if minmaxnormalization:
transformations_list = [MinMaxNorma... | 174 | 174 | 580 | 18 | 155 | Raelag0112/clinicadl | clinicadl/utils/caps_dataset/data.py | Python | load_data_test | load_data_test | 1,144 | 1,200 | 1,144 | 1,144 | a95fa96f04fd3d4be0b3cb7384e7860651e9eee5 | bigcode/the-stack | train |
432afeacb57a31dbb0c07c81 | train | class | class SoftlearningEnv(Serializable, metaclass=ABCMeta):
"""The abstract Softlearning environment class.
It's an abstract class defining the interface an adapter needs to implement
in order to function with softlearning algorithms. It closely follows the
gym.Env, yet that may not be the case in the... | class SoftlearningEnv(Serializable, metaclass=ABCMeta):
| """The abstract Softlearning environment class.
It's an abstract class defining the interface an adapter needs to implement
in order to function with softlearning algorithms. It closely follows the
gym.Env, yet that may not be the case in the future.
The main API methods that users of this c... | """Implements the SoftlearningEnv that is usable in softlearning algorithms."""
from abc import ABCMeta, abstractmethod
from collections import defaultdict
import numpy as np
from serializable import Serializable
class SoftlearningEnv(Serializable, metaclass=ABCMeta):
| 54 | 256 | 1,657 | 13 | 40 | YaoYao1995/mbpo | softlearning/environments/adapters/softlearning_env.py | Python | SoftlearningEnv | SoftlearningEnv | 10 | 242 | 10 | 10 | 19ee355385bb2eec359b33d490356d9c5658d201 | bigcode/the-stack | train |
7b6a751459a0de9b89e49de6 | train | function | def get_foursquare_location(config):
f = Foursquare(client_id=config['client_id'],
client_secret=config['client_secret'],
access_token=config['access_token'])
checkins = f.users.checkins(params={'limit': 1, 'sort': 'newestfirst'})
checkin = checkins['checkins']['items'... | def get_foursquare_location(config):
| f = Foursquare(client_id=config['client_id'],
client_secret=config['client_secret'],
access_token=config['access_token'])
checkins = f.users.checkins(params={'limit': 1, 'sort': 'newestfirst'})
checkin = checkins['checkins']['items'][0]
created_at = datetime.datet... | import datetime
import humanize
from foursquare import Foursquare
def get_foursquare_location(config):
| 21 | 64 | 113 | 7 | 13 | myles/telegram-myles-bot | myles_bot/ext/ext_foursquare.py | Python | get_foursquare_location | get_foursquare_location | 7 | 19 | 7 | 7 | 9d3d959a34e45a64dd1002d8a497b588d7de9264 | bigcode/the-stack | train |
6d72d6c5a48e1580350db488 | train | function | def main():
coin_pair = coin + "/" + coin_2
try:
balance_coin_2_is_enough = check_balance_before_start(
coin_2, stake_per_trade
)
if balance_coin_2_is_enough is True:
tiker = fetch_ticker(coin_pair)
if tiker == coin_pair:
if start_b... | def main():
| coin_pair = coin + "/" + coin_2
try:
balance_coin_2_is_enough = check_balance_before_start(
coin_2, stake_per_trade
)
if balance_coin_2_is_enough is True:
tiker = fetch_ticker(coin_pair)
if tiker == coin_pair:
if start_buy_trail_on_b... | id : " + show_bot_id())
stake_per_trade = get_stake_size(coin_2)
if use_bnb_for_fee == "YES":
notificator("We will be use BNB for fee")
notificator("BNB balance " + str(fetch_balance("BNB")))
def main():
| 63 | 64 | 169 | 3 | 60 | alex-bormotov/AXE-Bot-open | bot_original.py | Python | main | main | 38 | 60 | 38 | 39 | c3b18421fba2e6bdd78e00b600ccfd55764db27f | bigcode/the-stack | train |
5d65d98fff37a043acbe5b6f | train | class | class Test(TestInput):
pass
| class Test(TestInput):
| pass
| from __future__ import absolute_import
input_name = '../examples/acoustics/vibro_acoustic3d.py'
output_name = 'test_vibro_acoustic3d'
from tests_basic import TestInput
class Test(TestInput):
| 50 | 64 | 8 | 5 | 44 | clazaro/sfepy | tests/test_input_vibro_acoustic3d.py | Python | Test | Test | 6 | 7 | 6 | 6 | 30e3827ca32c4c255fb07975ad8af1eec91d36bf | bigcode/the-stack | train |
e7249d556c09dab518782b34 | train | function | def train(RL, steps_limit):
# env.render()
steps_num = 0
solved = False
sumreward = 1
account = 0
sess.run(tf.global_variables_initializer())
RL.initiate_common_par()
observation = env.reset()
episodes_reward = []
episodes = []
done = False
action = 0
true_end = 0
... | def train(RL, steps_limit):
# env.render()
| steps_num = 0
solved = False
sumreward = 1
account = 0
sess.run(tf.global_variables_initializer())
RL.initiate_common_par()
observation = env.reset()
episodes_reward = []
episodes = []
done = False
action = 0
true_end = 0
for _ in range(MEMORY_SIZE):
if done:
... | },
reward_threshold=475.0,
kwargs={'change_len': 1.0},
)
env = gym.make('CartPole_long_pole-v0')
gym.envs.register(
id='CartPole_evaluate-v0',
entry_point='gym.envs.classic_control:CartPoleEnv',
tags={'wrapper_config.TimeLimit.max_episode_steps': 10000... | 240 | 241 | 804 | 13 | 227 | silentobservers/Regularization-in-DQN | CartPole/dropout/run_Pendulum.py | Python | train | train | 44 | 150 | 44 | 45 | dbcbc52970f0c554122a60f43b2c2882f8abbf1b | bigcode/the-stack | train |
213220fca8b2a75a585b7c9e | train | class | class MessageContainer(TLObject):
CONSTRUCTOR_ID = 0x73f1f8dc
# Maximum size in bytes for the inner payload of the container.
# Telegram will close the connection if the payload is bigger.
# The overhead of the container itself is subtracted.
MAXIMUM_SIZE = 1044456 - 8
def __init__(self, messa... | class MessageContainer(TLObject):
| CONSTRUCTOR_ID = 0x73f1f8dc
# Maximum size in bytes for the inner payload of the container.
# Telegram will close the connection if the payload is bigger.
# The overhead of the container itself is subtracted.
MAXIMUM_SIZE = 1044456 - 8
def __init__(self, messages):
self.messages = mess... | import logging
import struct
from .tlmessage import TLMessage
from ..tlobject import TLObject
__log__ = logging.getLogger(__name__)
class MessageContainer(TLObject):
| 38 | 90 | 302 | 6 | 32 | s3mple/Telethon | telethon/tl/core/messagecontainer.py | Python | MessageContainer | MessageContainer | 10 | 47 | 10 | 10 | 4c2c7b1836830ab7491e2eda53020e87fed54107 | bigcode/the-stack | train |
76d914669aa7c798898e522b | train | class | @enum.unique
class BugStatus(enum.Enum):
new = 7
incomplete = 6
invalid = 5
wont_fix = 4
in_progress = 3
fix_committed = 2
fix_released = 1
# This will trigger an error with unique applied.
by_design = 4
closed = 1
| @enum.unique
class BugStatus(enum.Enum):
| new = 7
incomplete = 6
invalid = 5
wont_fix = 4
in_progress = 3
fix_committed = 2
fix_released = 1
# This will trigger an error with unique applied.
by_design = 4
closed = 1
| import enum
@enum.unique
class BugStatus(enum.Enum):
| 14 | 64 | 83 | 11 | 2 | jasonwee/asus-rt-n14uhp-mrtg | src/lesson_data_structures/enum_unique_enforce.py | Python | BugStatus | BugStatus | 4 | 18 | 4 | 7 | 66c1e015608965ee35932b53dafba3b2f5074291 | bigcode/the-stack | train |
6d3df93f94fe84aced24fbcb | train | class | class MDNSAdvertiser(object):
def __init__(self, type_, name, port, properties, server, interface):
self.type = type_
self.name = name
self.interface = interface if interface else "eth0"
self.address = self.get_network_ip_address(interface)
self.port = port
self.prope... | class MDNSAdvertiser(object):
| def __init__(self, type_, name, port, properties, server, interface):
self.type = type_
self.name = name
self.interface = interface if interface else "eth0"
self.address = self.get_network_ip_address(interface)
self.port = port
self.properties = properties
sel... | #!/usr/bin/env python
import logging
import socket
import time
import threading
import netifaces as ni
from zeroconf import ServiceInfo, Zeroconf
logger = logging.getLogger(__name__)
class MDNSAdvertiser(object):
| 52 | 164 | 547 | 7 | 45 | bodiroga/rfc2217-gateway | src/mdns_advertiser.py | Python | MDNSAdvertiser | MDNSAdvertiser | 14 | 84 | 14 | 14 | f934dfb7b573dc4bed0bf7bb8e01d73f87b52aa6 | bigcode/the-stack | train |
e332b9303e4a7dd7ca44c92c | train | function | def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('roles',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('users',
sa.Column('id', sa.Intege... | def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
| op.create_table('roles',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=255), nullable=T... | e6b6
Revises:
Create Date: 2020-12-10 08:14:31.109444
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '30103fe2e6b6'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
| 98 | 98 | 327 | 18 | 79 | Preston-Too/Pomodoro-Timer | migrations/versions/30103fe2e6b6_initial_migration.py | Python | upgrade | upgrade | 19 | 47 | 19 | 20 | fbb55f54f715d2424b75087fddcb9b6ae49ef039 | bigcode/the-stack | train |
5178aa244621fa0907e53e75 | train | function | def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('reason')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')
op.drop_table('roles')
| def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
| op.drop_table('reason')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')
op.drop_table('roles')
| sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
| 63 | 64 | 71 | 18 | 45 | Preston-Too/Pomodoro-Timer | migrations/versions/30103fe2e6b6_initial_migration.py | Python | downgrade | downgrade | 51 | 57 | 51 | 52 | c08ba821f25b77817a65008fff384f507f1e40cc | bigcode/the-stack | train |
c7014d7ca2d8a711fdc576ed | train | function | def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Specific humidity', 'units': 'kg/kg'},
{'abbr': 1, 'code': 1, 'title': 'Relative humidity', 'units': '%'},
{'abbr': 2, 'code': 2, 'title': 'Humidity mixing ratio', 'units': 'kg/kg'},
{'abbr': 3, 'code': 3, 'title': 'Precipitab... | def load(h):
| return ({'abbr': 0, 'code': 0, 'title': 'Specific humidity', 'units': 'kg/kg'},
{'abbr': 1, 'code': 1, 'title': 'Relative humidity', 'units': '%'},
{'abbr': 2, 'code': 2, 'title': 'Humidity mixing ratio', 'units': 'kg/kg'},
{'abbr': 3, 'code': 3, 'title': 'Precipitable water', 'u... | def load(h):
| 4 | 256 | 2,996 | 4 | 0 | ecmwf/pyeccodes | pyeccodes/defs/grib2/tables/9/4_2_0_1_table.py | Python | load | load | 1 | 253 | 1 | 1 | fa363041ad86c2d8387bdee19f4acf08c83c3a09 | bigcode/the-stack | train |
c4b774dcfb882dfc8b1f89e8 | train | function | @login_required(login_url='/users/login/')
def place_stake(request):
stake_form = StakeForm()
if request.method == 'POST':
stake_form = StakeForm(data=request.POST)
if stake_form.is_valid():
stake_form.save()
print('STAKE DONE')
# return redirect(reverse('cas... | @login_required(login_url='/users/login/')
def place_stake(request):
| stake_form = StakeForm()
if request.method == 'POST':
stake_form = StakeForm(data=request.POST)
if stake_form.is_valid():
stake_form.save()
print('STAKE DONE')
# return redirect(reverse('cash_trans:trans_log'))
else:
print('ERRRRR',stake_fo... | ',form.errors)
# return render(request, '/.html', {'form': form})
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.shortcuts import render, redirect
from gwheel.forms import StakeForm
@login_required(login_url='/users/login/')
def place_stake(request):
| 64 | 64 | 114 | 14 | 49 | gibeongideon/daruwheel | gwheel/template_view.py | Python | place_stake | place_stake | 26 | 41 | 26 | 28 | 139f938441ad94eb0629c394c60547694e7123a2 | bigcode/the-stack | train |
4e04c4c63429654544eb7915 | train | class | class Scheduled_queryScenarioTest(ScenarioTest):
@ResourceGroupPreparer(name_prefix='cli_test_scheduled_query', location='eastus')
def test_scheduled_query(self, resource_group):
from azure.mgmt.core.tools import resource_id
import time
import mock
self.kwargs.update({
... | class Scheduled_queryScenarioTest(ScenarioTest):
@ResourceGroupPreparer(name_prefix='cli_test_scheduled_query', location='eastus')
| def test_scheduled_query(self, resource_group):
from azure.mgmt.core.tools import resource_id
import time
import mock
self.kwargs.update({
'name1': 'sq01',
'name2': 'sq02',
'rg': resource_group,
'vm': 'myvm1',
'ws': self.cre... | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | 104 | 256 | 979 | 29 | 75 | needuv/azure-cli-extensions | src/scheduled-query/azext_scheduled_query/tests/latest/test_scheduled_query_scenario.py | Python | Scheduled_queryScenarioTest | Scheduled_queryScenarioTest | 15 | 84 | 15 | 17 | 15922f8b4f5fe5af9ae782875268d16fb1755482 | bigcode/the-stack | train |
50adea1e801b77b1c33886c5 | train | class | class ScheduledQueryCondtionTest(unittest.TestCase):
def _build_namespace(self, name_or_id=None, resource_group=None, provider_namespace=None, parent=None,
resource_type=None):
from argparse import Namespace
return Namespace()
def call_condition(self, ns, value):
... | class ScheduledQueryCondtionTest(unittest.TestCase):
| def _build_namespace(self, name_or_id=None, resource_group=None, provider_namespace=None, parent=None,
resource_type=None):
from argparse import Namespace
return Namespace()
def call_condition(self, ns, value):
from azext_scheduled_query._actions import Schedule... | ('criteria.allOf[0].query', 'union Event | where TimeGenerated > ago(2h)'),
self.check('criteria.allOf[0].threshold', 260),
self.check('criteria.allOf[0].timeAggregation', 'Count'),
self.check('criteria.allOf[0].operator', 'LessThan'),
... | 255 | 256 | 1,077 | 10 | 245 | needuv/azure-cli-extensions | src/scheduled-query/azext_scheduled_query/tests/latest/test_scheduled_query_scenario.py | Python | ScheduledQueryCondtionTest | ScheduledQueryCondtionTest | 87 | 150 | 87 | 88 | efb68c7434e5dafc0aa9383615d542c887afe856 | bigcode/the-stack | train |
b20cc72b241203eaf13aab22 | train | class | class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_l... | # Generated by Django 2.1.15 on 2020-09-26 08:12
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 51 | 64 | 103 | 7 | 43 | sshekhas/recipe-app-api | app/core/migrations/0002_tag.py | Python | Migration | Migration | 8 | 23 | 8 | 9 | b457c9f3c62c1da9cf44712b03eede8dbf0be2c0 | bigcode/the-stack | train |
b0fbbce426c3269fbac79b64 | train | class | class MsgPack:
def __init__(self, pack=None, unpack=None):
self.proto = "msgpack"
self.pack_hook = pack
self.unpack_hook = unpack
# if pack:
# self.p = msgpack.Packer(default=pack, use_bin_type=True, strict_types=True)
# else:
# self.p = msgpack.Packer... | class MsgPack:
| def __init__(self, pack=None, unpack=None):
self.proto = "msgpack"
self.pack_hook = pack
self.unpack_hook = unpack
# if pack:
# self.p = msgpack.Packer(default=pack, use_bin_type=True, strict_types=True)
# else:
# self.p = msgpack.Packer(use_bin_type=T... | ##############################################
# The MIT License (MIT)
# Copyright (c) 2017 Kevin Walchko
# see LICENSE for full details
##############################################
import msgpack
class MsgPack:
| 42 | 78 | 261 | 4 | 37 | walchko/the-collector | archive/archive/extra_msgpack.py | Python | MsgPack | MsgPack | 10 | 39 | 10 | 10 | c344d95aa54c8e7070dc6ce05b4c25dc05bbaa1a | bigcode/the-stack | train |
097d370ffecdfdbdc2978fe5 | train | class | @actions.register
class Action(ActionBase):
"""Run the builder subcommand."""
KEGEX = "^b(?:uilder)?$"
def __init__(self, args: ApplicationConfiguration):
"""Initialize the action.
:param args: The current application configuration
"""
super().__init__(args=args, logger_na... | @actions.register
class Action(ActionBase):
| """Run the builder subcommand."""
KEGEX = "^b(?:uilder)?$"
def __init__(self, args: ApplicationConfiguration):
"""Initialize the action.
:param args: The current application configuration
"""
super().__init__(args=args, logger_name=__name__, name="builder")
def run_st... | """Builder subcommand implementation.
Importing this module registers this subcommand in the external
global subcommand registry.
"""
import os
import shutil
from typing import Optional
from typing import Tuple
from ..action_base import ActionBase
from ..action_defs import RunStdoutReturn
from ..configuration_subsys... | 100 | 202 | 675 | 9 | 90 | goneri/ansible-navigator | src/ansible_navigator/actions/builder.py | Python | Action | Action | 20 | 102 | 20 | 21 | 73a5a82e2f0b559ed4500bb7e3fb7ca18bcdddbe | bigcode/the-stack | train |
ec7655b7cc02007adf77a557 | train | class | class OptTypes:
BAYES = BayesOpt
NESTED = NestedOpt | class OptTypes:
| BAYES = BayesOpt
NESTED = NestedOpt | , Output_strategy_parameters
class NestedOpt(Opt):
def run(*args, **kwargs):
#args[3] devuelve los parámetros
# Rellenar
return 'PRUEBA!!! -> ({}), {}, {}'.format(args[0], args[1:], kwargs)
class OptTypes:
| 64 | 64 | 19 | 4 | 60 | faprieto96/pystrategy | pystrategy/classes_strategies/Optimizers.py | Python | OptTypes | OptTypes | 30 | 32 | 30 | 30 | 98fa84449d5a5ec09f61fc3231c42db0c6a28799 | bigcode/the-stack | train |
4517cd4c823a0d7cd0aaa524 | train | class | class Opt:
@abstractmethod
def run(*args, **kwargs):
...
def __call__(self, *args, **kwargs):
return self.run(*args, **kwargs)
| class Opt:
@abstractmethod
| def run(*args, **kwargs):
...
def __call__(self, *args, **kwargs):
return self.run(*args, **kwargs)
|
from config_libaries import *
class Opt:
@abstractmethod
| 15 | 64 | 42 | 8 | 7 | faprieto96/pystrategy | pystrategy/classes_strategies/Optimizers.py | Python | Opt | Opt | 4 | 10 | 4 | 5 | 7825a7c26a95899d84d37612f42989602feff69a | bigcode/the-stack | train |
838af79d5693b38279b7e54c | train | class | class NestedOpt(Opt):
def run(*args, **kwargs):
#args[3] devuelve los parámetros
# Rellenar
return 'PRUEBA!!! -> ({}), {}, {}'.format(args[0], args[1:], kwargs)
| class NestedOpt(Opt):
| def run(*args, **kwargs):
#args[3] devuelve los parámetros
# Rellenar
return 'PRUEBA!!! -> ({}), {}, {}'.format(args[0], args[1:], kwargs)
| ]['lambda'], 'val_beta':args[2]['beta']}
Output_strategy_parameters=args[3]
#return 'bayes -> ({}), {}, {}'.format(args[0], args[1:], kwargs, output_optimization)
return output_optimization, Output_strategy_parameters
class NestedOpt(Opt):
| 64 | 64 | 55 | 6 | 57 | faprieto96/pystrategy | pystrategy/classes_strategies/Optimizers.py | Python | NestedOpt | NestedOpt | 22 | 27 | 22 | 22 | 09ca89677cb29f7ba5bf1ccbc00318098f67e7f2 | bigcode/the-stack | train |
408e878b3bedab4b5918349f | train | class | class BayesOpt(Opt):
def run(*args, **kwargs):
# Rellenar
output_optimization={'val_lambda':args[2]['lambda'], 'val_beta':args[2]['beta']}
Output_strategy_parameters=args[3]
#return 'bayes -> ({}), {}, {}'.format(args[0], args[1:], kwargs, output_optimization)
return output_o... | class BayesOpt(Opt):
| def run(*args, **kwargs):
# Rellenar
output_optimization={'val_lambda':args[2]['lambda'], 'val_beta':args[2]['beta']}
Output_strategy_parameters=args[3]
#return 'bayes -> ({}), {}, {}'.format(args[0], args[1:], kwargs, output_optimization)
return output_optimization, Output_s... |
from config_libaries import *
class Opt:
@abstractmethod
def run(*args, **kwargs):
...
def __call__(self, *args, **kwargs):
return self.run(*args, **kwargs)
class BayesOpt(Opt):
| 56 | 64 | 91 | 7 | 49 | faprieto96/pystrategy | pystrategy/classes_strategies/Optimizers.py | Python | BayesOpt | BayesOpt | 13 | 19 | 13 | 13 | a0ef1b5906306ff8d163734ec405f2b99ffc0474 | bigcode/the-stack | train |
d39617cc1ffd04ad731904c8 | train | class | class TestModelAnalysisDashboard:
def validate_rai_dashboard_data(self, rai_widget):
assert isinstance(
rai_widget.input.dashboard_input.dataset,
Dataset)
assert isinstance(
rai_widget.input.dashboard_input.modelExplanationData[0],
ModelExplanationDat... | class TestModelAnalysisDashboard:
| def validate_rai_dashboard_data(self, rai_widget):
assert isinstance(
rai_widget.input.dashboard_input.dataset,
Dataset)
assert isinstance(
rai_widget.input.dashboard_input.modelExplanationData[0],
ModelExplanationData)
assert isinstance(
... | # Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
import pytest
import shap
import sklearn
from sklearn.model_selection import train_test_split
from raiwidgets import ModelAnalysisDashboard
from responsibleai import RAIInsights
from responsibleai._interfaces import (CausalData, CounterfactualDat... | 82 | 151 | 505 | 6 | 76 | kkasravi/responsible-ai-toolbox | raiwidgets/tests/test_model_analysis_dashboard.py | Python | TestModelAnalysisDashboard | TestModelAnalysisDashboard | 15 | 79 | 15 | 16 | 13bb932663c802b0dbf2b305f8014c1795dc5737 | bigcode/the-stack | train |
5ec65dcd9fe27c922ae2708d | train | class | class OGCtemplate():
# Input parameters
#variable = ""
def createOGCtemplate(self, base):
"""
Define parts of the file and how they correspond to the UBO ontology in a dictionary
Based on definitions in PDF document for Figure 3: Illustration of spatial data
From Figure 3 i... | class OGCtemplate():
# Input parameters
#variable = ""
| def createOGCtemplate(self, base):
"""
Define parts of the file and how they correspond to the UBO ontology in a dictionary
Based on definitions in PDF document for Figure 3: Illustration of spatial data
From Figure 3 in standard documentation: http://www.opengeospatial.org/standards... | #-------------------------------------------------------------------------------
# Name: OGCtemplate.py
# Purpose: Create OGC GeoSPARQL File Template
#
# Author: Holly Tina Ferguson hfergus2@nd.edu
#
# Created: 07/27/2015
# Copyright: (c) Holly Tina Ferguson 2015
# Licence: The University of N... | 157 | 256 | 3,469 | 16 | 140 | Green-Resilience/wfRunner | gsr/graphlib/OGCtemplate.py | Python | OGCtemplate | OGCtemplate | 24 | 288 | 24 | 28 | c2d2d86ecef1c1433b0ddaf7bda5dd715b9a6e38 | bigcode/the-stack | train |
222c785efa1ded9f3be1cbb1 | train | class | class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger):
payment_request_ok_signal = pyqtSignal()
payment_request_error_signal = pyqtSignal()
network_signal = pyqtSignal(str, object)
#ln_payment_attempt_signal = pyqtSignal(str)
alias_received_signal = pyqtSignal()
computing_privkeys_signal =... | class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger):
| payment_request_ok_signal = pyqtSignal()
payment_request_error_signal = pyqtSignal()
network_signal = pyqtSignal(str, object)
#ln_payment_attempt_signal = pyqtSignal(str)
alias_received_signal = pyqtSignal()
computing_privkeys_signal = pyqtSignal()
show_privkeys_signal = pyqtSignal()
sho... | Cursor(Qt.PointingHandCursor))
def onPress(self, checked=False):
'''Drops the unwanted PyQt5 "checked" argument'''
self.func()
def keyPressEvent(self, e):
if e.key() in [ Qt.Key_Return, Qt.Key_Enter ]:
self.func()
def protected(func):
'''Password request wrapper. The... | 256 | 256 | 29,249 | 14 | 241 | multibit2016/electrum | electrum/gui/qt/main_window.py | Python | ElectrumWindow | ElectrumWindow | 160 | 3,383 | 160 | 161 | 6e6a526a11e4438caa12202baad466f52656f21c | bigcode/the-stack | train |
b2fd84e0056d9c8906f6b2d2 | train | function | def protected(func):
'''Password request wrapper. The password is passed to the function
as the 'password' named argument. "None" indicates either an
unencrypted wallet, or the user cancelled the password request.
An empty input is passed as the empty string.'''
def request_password(se... | def protected(func):
| '''Password request wrapper. The password is passed to the function
as the 'password' named argument. "None" indicates either an
unencrypted wallet, or the user cancelled the password request.
An empty input is passed as the empty string.'''
def request_password(self, *args, **kwargs):... | ingHandCursor))
def onPress(self, checked=False):
'''Drops the unwanted PyQt5 "checked" argument'''
self.func()
def keyPressEvent(self, e):
if e.key() in [ Qt.Key_Return, Qt.Key_Enter ]:
self.func()
def protected(func):
| 64 | 64 | 179 | 4 | 60 | multibit2016/electrum | electrum/gui/qt/main_window.py | Python | protected | protected | 135 | 157 | 135 | 135 | b25d546f9b5b0881de4c3df8dd0439462f472bc9 | bigcode/the-stack | train |
fff0d5ae35ea83509066e064 | train | class | class StatusBarButton(QToolButton):
# note: this class has a custom stylesheet applied in stylesheet_patcher.py
def __init__(self, icon, tooltip, func):
QToolButton.__init__(self)
self.setText('')
self.setIcon(icon)
self.setToolTip(tooltip)
self.setToolButtonStyle(Qt.Tool... | class StatusBarButton(QToolButton):
# note: this class has a custom stylesheet applied in stylesheet_patcher.py
| def __init__(self, icon, tooltip, func):
QToolButton.__init__(self)
self.setText('')
self.setIcon(icon)
self.setToolTip(tooltip)
self.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self.setAutoRaise(True)
self.setMaximumWidth(25)
self.clicked.connect(... | _tx_dialog import ConfirmTxDialog
from .transaction_dialog import PreviewTxDialog
if TYPE_CHECKING:
from . import ElectrumGui
LN_NUM_PAYMENT_ATTEMPTS = 10
class StatusBarButton(QToolButton):
# note: this class has a custom stylesheet applied in stylesheet_patcher.py
| 64 | 64 | 189 | 25 | 38 | multibit2016/electrum | electrum/gui/qt/main_window.py | Python | StatusBarButton | StatusBarButton | 111 | 132 | 111 | 112 | 726ea35cf7d9c5a0188aa9f5fdd84e1c65040c74 | bigcode/the-stack | train |
d7f00a792bd383f12b3bfe0f | train | function | def get_dict_data(raw_pcd):
data = {
'point': raw_pcd,
'full_point': None,
'feat': None,
'calib': None,
}
return data
| def get_dict_data(raw_pcd):
| data = {
'point': raw_pcd,
'full_point': None,
'feat': None,
'calib': None,
}
return data
| cfg.model)
# cfg.dataset['dataset_path'] = "/home/amlab/KITTI_point"
# cfg.dataset['dataset_path'] = "/home/amlab/vtd_kitti_format"
# cfg.dataset['dataset_path'] = "/home/amlab/os_test"
def get_dict_data(raw_pcd):
| 64 | 64 | 46 | 8 | 56 | Jaein94/Open3D-ML | raw_data_test.py | Python | get_dict_data | get_dict_data | 18 | 27 | 18 | 19 | 3d38936ad217bb36e94077f5b2499b7a7c8dec61 | bigcode/the-stack | train |
490d0c86d315c5e857c78809 | train | class | class HistogramData:
"""
Class which represents the frequency distribution of given data.
"""
def __init__(self, intervals, data):
self.interval_dict = OrderedDict() # structure: key (if value > key and value < key+1) => amount
self.amount_data = 0
for index, element in en... | class HistogramData:
| """
Class which represents the frequency distribution of given data.
"""
def __init__(self, intervals, data):
self.interval_dict = OrderedDict() # structure: key (if value > key and value < key+1) => amount
self.amount_data = 0
for index, element in enumerate(data):
... | from collections import OrderedDict
__author__ = "Vincent Levorato"
__credits__ = "https://github.com/octo-technology/bdacore"
__license__ = "Apache 2.0"
class HistogramData:
| 49 | 121 | 404 | 4 | 45 | Pandinosaurus/dsbox | dsbox/ml/markov/histrogramdata.py | Python | HistogramData | HistogramData | 8 | 65 | 8 | 8 | a5643899522e5dc1457019fb039a3e88b8f8288e | bigcode/the-stack | train |
1554ed238b9624a62cb9e408 | train | function | def remove_omit_entries(thing, omit_marker=OMIT_MARKER):
"""
Removes dict entries whose value is OMIT_MARKER:
>>> remove_omit_entries({'key1': 'some_value', 'key2': OMIT_MARKER})
{'key1': 'some_value'}
Removes list items whose value is OMIT_MARKER:
>>> remove_omit_entries([OMIT_MARKER])
[]
... | def remove_omit_entries(thing, omit_marker=OMIT_MARKER):
| """
Removes dict entries whose value is OMIT_MARKER:
>>> remove_omit_entries({'key1': 'some_value', 'key2': OMIT_MARKER})
{'key1': 'some_value'}
Removes list items whose value is OMIT_MARKER:
>>> remove_omit_entries([OMIT_MARKER])
[]
Works recursively:
>>> remove_omit_entries({'key... | OMIT_MARKER = '__designated_omit_marker_that_results_in_deletion_of_the_corresponding_entry_in_dict_or_item_in_list'
def remove_omit_entries(thing, omit_marker=OMIT_MARKER):
| 45 | 87 | 290 | 16 | 29 | blue-yonder/ansible-remove-omit-entries | filter_plugins/remove_omit_entries.py | Python | remove_omit_entries | remove_omit_entries | 4 | 41 | 4 | 4 | 86fc2c45e6ac013276f69b3a9de4653d84bb3ee8 | bigcode/the-stack | train |
34fb1e118f9a14de423a4226 | train | class | class FilterModule(object):
def filters(self):
return dict(remove_omit_entries=remove_omit_entries, remove_omit_entries_get_marker=remove_omit_entries_get_marker)
| class FilterModule(object):
| def filters(self):
return dict(remove_omit_entries=remove_omit_entries, remove_omit_entries_get_marker=remove_omit_entries_get_marker)
| elif isinstance(thing, list):
cleaned = []
for item in thing:
if item != omit_marker:
cleaned.append(remove_omit_entries(item))
return cleaned
else:
return thing
def remove_omit_entries_get_marker(arg):
return OMIT_MARKER
class FilterModule(object):... | 64 | 64 | 37 | 5 | 58 | blue-yonder/ansible-remove-omit-entries | filter_plugins/remove_omit_entries.py | Python | FilterModule | FilterModule | 48 | 51 | 48 | 49 | bbc9e737b986be03a7f46b500bd2811ed515de6e | bigcode/the-stack | train |
6592c9219c5d7d7a3b606ebc | train | function | def remove_omit_entries_get_marker(arg):
return OMIT_MARKER
| def remove_omit_entries_get_marker(arg):
| return OMIT_MARKER
| cleaned[key] = value
return cleaned
elif isinstance(thing, list):
cleaned = []
for item in thing:
if item != omit_marker:
cleaned.append(remove_omit_entries(item))
return cleaned
else:
return thing
def remove_omit_entries_get_marker(arg):
| 64 | 64 | 15 | 9 | 54 | blue-yonder/ansible-remove-omit-entries | filter_plugins/remove_omit_entries.py | Python | remove_omit_entries_get_marker | remove_omit_entries_get_marker | 44 | 45 | 44 | 44 | 0fa1042ee75eaab8d759f21a541c4d7535b197e2 | bigcode/the-stack | train |
b765865afb8ae2c1517cde4e | train | class | class CoreConfig(AppConfig):
name = 'hseng.core'
| class CoreConfig(AppConfig):
| name = 'hseng.core'
| from django.apps import AppConfig
class CoreConfig(AppConfig):
| 13 | 64 | 14 | 6 | 6 | dark-codr/henroposki | hseng/core/apps.py | Python | CoreConfig | CoreConfig | 4 | 5 | 4 | 4 | 7b2423a7da7abe4c32acd83ab3de85ce5f43a9cf | bigcode/the-stack | train |
11cb463292910b97fb827b83 | train | class | class TestSQLModel(BaseTestCase):
@pytest.fixture(autouse=True)
def setup(self, request):
sql = """
create table if not exists sql_model_test_product (
id int(11) not null auto_increment primary key,
name varchar(255) not null,
created datetime not null
... | class TestSQLModel(BaseTestCase):
@pytest.fixture(autouse=True)
| def setup(self, request):
sql = """
create table if not exists sql_model_test_product (
id int(11) not null auto_increment primary key,
name varchar(255) not null,
created datetime not null
);
create table if not exists sql_model_test_cat (
... | .CharField(max_length=255)
total = models.IntegerField()
latest_product_date = models.DateTimeField()
def base_query(self):
return {
'select': {
'category': 'c.name',
'total': 'count(*)',
'latest_product_date': 'max(p.created)'
... | 256 | 256 | 1,998 | 17 | 239 | muffinresearch/addons-server | apps/editors/tests/test_sql_model.py | Python | TestSQLModel | TestSQLModel | 65 | 286 | 65 | 67 | 1252e6d6c087c4f5a77f29e1b82faa8f0c9bea24 | bigcode/the-stack | train |
34821862f21a33dce1f1dbc4 | train | class | class Summary(RawSQLModel):
category = models.CharField(max_length=255)
total = models.IntegerField()
latest_product_date = models.DateTimeField()
def base_query(self):
return {
'select': {
'category': 'c.name',
'total': 'count(*)',
'l... | class Summary(RawSQLModel):
| category = models.CharField(max_length=255)
total = models.IntegerField()
latest_product_date = models.DateTimeField()
def base_query(self):
return {
'select': {
'category': 'c.name',
'total': 'count(*)',
'latest_product_date': 'max(p.... | .tools import eq_, raises
from amo.tests import BaseTestCase
from editors.sql_model import RawSQLModel
def execute_all(statements):
cursor = connection.cursor()
for sql in statements:
if not sql.strip():
continue
cursor.execute(sql, [])
class Summary(RawSQLModel):
| 63 | 64 | 137 | 7 | 56 | muffinresearch/addons-server | apps/editors/tests/test_sql_model.py | Python | Summary | Summary | 26 | 44 | 26 | 26 | 2bcaedee2976453a33cdb0476b260e3660da9dbd | bigcode/the-stack | train |
cbdfe24328adb37d24920582 | train | class | class ProductDetail(RawSQLModel):
product = models.CharField(max_length=255)
category = models.CharField(max_length=255)
def base_query(self):
return {
'select': {
'product': 'p.name',
'category': 'c.name'
},
'from': [
... | class ProductDetail(RawSQLModel):
| product = models.CharField(max_length=255)
category = models.CharField(max_length=255)
def base_query(self):
return {
'select': {
'product': 'p.name',
'category': 'c.name'
},
'from': [
'sql_model_test_product p',
... | ': [
'sql_model_test_product p',
'join sql_model_test_product_cat x on x.product_id=p.id',
'join sql_model_test_cat c on x.cat_id=c.id'],
'where': [],
'group_by': 'category'
}
class ProductDetail(RawSQLModel):
| 64 | 64 | 113 | 8 | 56 | muffinresearch/addons-server | apps/editors/tests/test_sql_model.py | Python | ProductDetail | ProductDetail | 47 | 62 | 47 | 47 | 05cf6cf5c73abf9fb10ffb44858a222054cedef0 | bigcode/the-stack | train |
3c6c1f0dda538a8bfe54c1c9 | train | function | def execute_all(statements):
cursor = connection.cursor()
for sql in statements:
if not sql.strip():
continue
cursor.execute(sql, [])
| def execute_all(statements):
| cursor = connection.cursor()
for sql in statements:
if not sql.strip():
continue
cursor.execute(sql, [])
| are coupled tighly with MySQL
"""
from datetime import datetime
from django.db import connection, models
from django.db.models import Q
import pytest
from nose.tools import eq_, raises
from amo.tests import BaseTestCase
from editors.sql_model import RawSQLModel
def execute_all(statements):
| 64 | 64 | 33 | 6 | 57 | muffinresearch/addons-server | apps/editors/tests/test_sql_model.py | Python | execute_all | execute_all | 18 | 23 | 18 | 18 | 37d82598f9fac4cfe4e81dca6c00e1068babc805 | bigcode/the-stack | train |
53c6dfbb7d7387a8a6db3ebd | train | function | def remove_border(img, threshold=0):
"Crop image, throwing away the border below the threshold"
mask = img > threshold
return img[np.ix_(mask.any(1), mask.any(0))]
| def remove_border(img, threshold=0):
| "Crop image, throwing away the border below the threshold"
mask = img > threshold
return img[np.ix_(mask.any(1), mask.any(0))]
| import os
import sys
import numpy as np
import imageio
import skimage.transform
def remove_border(img, threshold=0):
| 29 | 64 | 46 | 9 | 19 | Dani-97/tbcnn | preprocess.py | Python | remove_border | remove_border | 7 | 10 | 7 | 7 | 771a1a7910d75d45f02edeb31ca3e046cab03462 | bigcode/the-stack | train |
7c1b2d080cdc8b63bbfe4c67 | train | function | def crop_center(img, size):
"Crop center sizexsize of the image"
y, x = img.shape
startx = (x - size) // 2
starty = (y - size) // 2
return img[starty:starty+size, startx:startx+size]
| def crop_center(img, size):
| "Crop center sizexsize of the image"
y, x = img.shape
startx = (x - size) // 2
starty = (y - size) // 2
return img[starty:starty+size, startx:startx+size]
|
import imageio
import skimage.transform
def remove_border(img, threshold=0):
"Crop image, throwing away the border below the threshold"
mask = img > threshold
return img[np.ix_(mask.any(1), mask.any(0))]
def crop_center(img, size):
| 63 | 64 | 69 | 7 | 57 | Dani-97/tbcnn | preprocess.py | Python | crop_center | crop_center | 12 | 17 | 12 | 12 | 73d60e4d543888d6437609dcc509c639f2ba7d02 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.