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
e6955bc9f40ab3a6bd6a6197
train
class
class BaseActivity: """The base activity that all user-settable activities inherit from. A user-settable activity is one that can be used in :meth:`Client.change_presence`. The following types currently count as user-settable: - :class:`Activity` - :class:`Game` - :class:`Streaming` - :cla...
class BaseActivity:
"""The base activity that all user-settable activities inherit from. A user-settable activity is one that can be used in :meth:`Client.change_presence`. The following types currently count as user-settable: - :class:`Activity` - :class:`Game` - :class:`Streaming` - :class:`CustomActivity` ...
{ INSTANCE: 1, JOIN: 2, SPECTATE: 4, JOIN_REQUEST: 8, SYNC: 16, PLAY: 32 } """ if TYPE_CHECKING: from .types.activity import ( Activity as ActivityPayload, ActivityTimestamps, ActivityParty, ActivityAssets, ActivityButton, ) class BaseActivity:
84
84
282
4
80
DTS-11/VectorCord
discord/activity.py
Python
BaseActivity
BaseActivity
103
137
103
103
c83fd85e0c474edcfc83fb0c4a35b101585b651b
bigcode/the-stack
train
e1901e5c2699ccfc6d5130a0
train
function
def _main_(): current_time = time.time() print('Welcome to the Countdown Clock 9000. It is currently {0}'.format( current_time)) units = _dateFormatChoice() dateFormat = _dateFormatter(units) #~# lets create a new function to parse the user input and convert it to a #~# true...
def _main_():
current_time = time.time() print('Welcome to the Countdown Clock 9000. It is currently {0}'.format( current_time)) units = _dateFormatChoice() dateFormat = _dateFormatter(units) #~# lets create a new function to parse the user input and convert it to a #~# true date value (i.e. 1...
what date format they would like to use # Receive the user's input and parse it to properly ID it as a datetime # Let the user know how long until their specified time # Print out every x seconds # Check if current_time > userTime # Print out ALERT when time == userTime # Ask the us...
111
111
372
6
104
CamFlawless/fsociety
baby-steps/countdown.py
Python
_main_
_main_
29
77
29
30
54fb837b61875e9e35e4c4a799cd9eb445fc958e
bigcode/the-stack
train
594c88cfbd2a1ee486a44731
train
function
def _dateFormatChoice(): print("\t1.)hh:mm:ss\n\t2.)hh:mm\n\t3.)mm:ss\n") user_choice = input('Which of the following date formats would you like to' ' use?\t>\t') try: if int(user_choice) in (1,2,3): user_choice = int(user_choice) return user_choice else: ...
def _dateFormatChoice():
print("\t1.)hh:mm:ss\n\t2.)hh:mm\n\t3.)mm:ss\n") user_choice = input('Which of the following date formats would you like to' ' use?\t>\t') try: if int(user_choice) in (1,2,3): user_choice = int(user_choice) return user_choice else: print('Please enter ...
timerCheck(userTime) time.sleep(1) print('ALERT! Your time of {0} has arrived!'.format(userTime)) time.sleep(1.5) # allows the user to specify how they would like to enter the time to countdown def _dateFormatChoice():
64
64
122
6
57
CamFlawless/fsociety
baby-steps/countdown.py
Python
_dateFormatChoice
_dateFormatChoice
122
135
122
122
9ec26f26a442a0c21e0d7ec0dc6abcba71fdc268
bigcode/the-stack
train
b9c2899fdff1d916884c2c89
train
function
def _timerCheck(userTime): if userTime < time.time(): return False else: return True
def _timerCheck(userTime):
if userTime < time.time(): return False else: return True
while j > 0: j = j - 1 time.sleep(0.1) print('\t' + '.' * j) exit # basic function return status of countdown (if time here --> True; else False) def _timerCheck(userTime):
63
64
26
7
56
CamFlawless/fsociety
baby-steps/countdown.py
Python
_timerCheck
_timerCheck
81
85
81
81
109a394bfab9fd357244d4c8a0665dcab539d87b
bigcode/the-stack
train
7a387dd9d632114b6adb50f3
train
function
def _countdown(units,dateFormat): userTime = input('Please enter your desired date using the format you ' 'specified ({0})\t'.format(dateFormat)) userTime = int(userTime) status = True # need both conditions so that it will not print a negative time amount while status != False and user...
def _countdown(units,dateFormat):
userTime = input('Please enter your desired date using the format you ' 'specified ({0})\t'.format(dateFormat)) userTime = int(userTime) status = True # need both conditions so that it will not print a negative time amount while status != False and userTime > time.time(): print(...
. Please try again.') _restartUI() elif response == 'y': return True elif response == 'n': return False # function to handle the countdown towards the user's time # use as function and place inside master WHILE loop def _countdown(units,dateFormat):
64
64
174
9
54
CamFlawless/fsociety
baby-steps/countdown.py
Python
_countdown
_countdown
102
119
102
102
580c0a46c76348c278b537b21251451c737d2141
bigcode/the-stack
train
0e2234b170f49ee859728351
train
function
def _change_dateFormat(): response = input('Would you like to change the date format? (y/n)\t') response = response.strip().lower() if response != 'y' and response != 'n': print('Please enter a valid response - y for yes or n for no.') _change_dateFormat() elif response == 'y': ...
def _change_dateFormat():
response = input('Would you like to change the date format? (y/n)\t') response = response.strip().lower() if response != 'y' and response != 'n': print('Please enter a valid response - y for yes or n for no.') _change_dateFormat() elif response == 'y': return True elif respon...
,2,3): user_choice = int(user_choice) return user_choice else: print('Please enter a valid response.') _dateFormatChoice() except ValueError: print('Please enter a valid response.') _dateFormatChoice() def _change_dateFormat():
63
64
93
7
56
CamFlawless/fsociety
baby-steps/countdown.py
Python
_change_dateFormat
_change_dateFormat
137
146
137
137
f552e95508039550c4ff3f2754ccb572c0ac38fe
bigcode/the-stack
train
66fb4b4d4e2a1863892f337c
train
function
def _restartUI(): print('It looks like your selected time has passed.') response = input('Would you like to use my countdown capabilities again? ' '(y/n)\t> ') response = response.strip().lower() if response != 'y' and response != 'n': print('That was not a valid response. Please try again...
def _restartUI():
print('It looks like your selected time has passed.') response = input('Would you like to use my countdown capabilities again? ' '(y/n)\t> ') response = response.strip().lower() if response != 'y' and response != 'n': print('That was not a valid response. Please try again.') _resta...
print('\t' + '.' * j) exit # basic function return status of countdown (if time here --> True; else False) def _timerCheck(userTime): if userTime < time.time(): return False else: return True def _restartUI():
64
64
104
5
58
CamFlawless/fsociety
baby-steps/countdown.py
Python
_restartUI
_restartUI
87
98
87
87
85c709c4c7799bfce3ecbd61903f5321502c577f
bigcode/the-stack
train
c776ac4b2f210c8b3c24dcc8
train
function
def _dateFormatter(units): if units == 1: dateFormat = 'hh:mm:ss' elif units == 2: dateFormat = 'hh:mm' elif units == 3: dateFormat = 'mm:ss' return dateFormat
def _dateFormatter(units):
if units == 1: dateFormat = 'hh:mm:ss' elif units == 2: dateFormat = 'hh:mm' elif units == 3: dateFormat = 'mm:ss' return dateFormat
if response != 'y' and response != 'n': print('Please enter a valid response - y for yes or n for no.') _change_dateFormat() elif response == 'y': return True elif response == 'n': return False def _dateFormatter(units):
64
64
59
7
56
CamFlawless/fsociety
baby-steps/countdown.py
Python
_dateFormatter
_dateFormatter
148
156
148
148
7d244b1a8466028a5a183d1c801c5dbf76ba363f
bigcode/the-stack
train
704d4d8d19d6bf6bde7cd49e
train
class
class TestPlayers: def test_default_num_players(self): players = str(Players()) assert players == "10" def test_set_num_players(self): players = str(Players(6)) assert players == "6"
class TestPlayers:
def test_default_num_players(self): players = str(Players()) assert players == "10" def test_set_num_players(self): players = str(Players(6)) assert players == "6"
from app.players import Players class TestPlayers:
10
64
50
4
5
JasonCaldwellMBA/Winning_Texas_Holdem_Strategy
tests/test_players.py
Python
TestPlayers
TestPlayers
4
11
4
4
ba662c8a0f912678817cc0b6ef0a38e2fbd62246
bigcode/the-stack
train
fe30a00733cf1770a93d2a1d
train
function
@TestSuite def privileges_granted_via_role(self, node=None): """Check that a user is able to execute `DROP QUOTA` with privileges are granted through a role. """ user_name = f"user_{getuid()}" role_name = f"role_{getuid()}" if node is None: node = self.context.node with user(node, f"{...
@TestSuite def privileges_granted_via_role(self, node=None):
"""Check that a user is able to execute `DROP QUOTA` with privileges are granted through a role. """ user_name = f"user_{getuid()}" role_name = f"role_{getuid()}" if node is None: node = self.context.node with user(node, f"{user_name}"), role(node, f"{role_name}"): with When(...
examples=Examples("privilege grant_target_name user_name", [ tuple(list(row)+[user_name,user_name]) for row in drop_quota.examples ], args=Args(name="privilege={privilege}", format_name=True))) @TestSuite def privileges_granted_via_role(self, node=None):
64
64
186
15
49
edani/ClickHouse
tests/testflows/rbac/tests/privileges/drop/drop_quota.py
Python
privileges_granted_via_role
privileges_granted_via_role
25
44
25
26
069624d424a4b539d273e53a476e4ab310ae776d
bigcode/the-stack
train
64b267459ce942d0f552aca8
train
function
@TestOutline(Suite) @Examples("privilege",[ ("ACCESS MANAGEMENT",), ("DROP QUOTA",), ]) def drop_quota(self, privilege, grant_target_name, user_name, node=None): """Check that user is only able to execute `DROP QUOTA` when they have the necessary privilege. """ exitcode, message = errors.not_enough_...
@TestOutline(Suite) @Examples("privilege",[ ("ACCESS MANAGEMENT",), ("DROP QUOTA",), ]) def drop_quota(self, privilege, grant_target_name, user_name, node=None):
"""Check that user is only able to execute `DROP QUOTA` when they have the necessary privilege. """ exitcode, message = errors.not_enough_privileges(name=user_name) if node is None: node = self.context.node with Scenario("DROP QUOTA without privilege"): drop_row_policy_name = f"dro...
ia_role(self, node=None): """Check that a user is able to execute `DROP QUOTA` with privileges are granted through a role. """ user_name = f"user_{getuid()}" role_name = f"role_{getuid()}" if node is None: node = self.context.node with user(node, f"{user_name}"), role(node, f"{role_na...
222
222
742
44
178
edani/ClickHouse
tests/testflows/rbac/tests/privileges/drop/drop_quota.py
Python
drop_quota
drop_quota
46
126
46
51
b490c8935a27e71e23fbb58cab9bbd0c2ba13e15
bigcode/the-stack
train
5d5bf54c46434e191821d6ee
train
function
@TestSuite def privileges_granted_directly(self, node=None): """Check that a user is able to execute `DROP QUOTA` with privileges are granted directly. """ user_name = f"user_{getuid()}" if node is None: node = self.context.node with user(node, f"{user_name}"): Suite(run=drop_quo...
@TestSuite def privileges_granted_directly(self, node=None):
"""Check that a user is able to execute `DROP QUOTA` with privileges are granted directly. """ user_name = f"user_{getuid()}" if node is None: node = self.context.node with user(node, f"{user_name}"): Suite(run=drop_quota, flags=TE, examples=Examples("privilege grant_...
from testflows.core import * from testflows.asserts import error from rbac.requirements import * from rbac.helper.common import * import rbac.helper.errors as errors @TestSuite def privileges_granted_directly(self, node=None):
50
64
134
14
35
edani/ClickHouse
tests/testflows/rbac/tests/privileges/drop/drop_quota.py
Python
privileges_granted_directly
privileges_granted_directly
8
23
8
9
c99b2cbf6ece97d1f0522e42247b3d01a5c26e05
bigcode/the-stack
train
cee3803ad2b441f07f3363d6
train
function
@TestFeature @Name("drop quota") @Requirements( RQ_SRS_006_RBAC_Privileges_DropQuota("1.0"), ) def feature(self, node="clickhouse1"): """Check the RBAC functionality of DROP QUOTA. """ self.context.node = self.context.cluster.node(node) Suite(run=privileges_granted_directly, setup=instrument_clickh...
@TestFeature @Name("drop quota") @Requirements( RQ_SRS_006_RBAC_Privileges_DropQuota("1.0"), ) def feature(self, node="clickhouse1"):
"""Check the RBAC functionality of DROP QUOTA. """ self.context.node = self.context.cluster.node(node) Suite(run=privileges_granted_directly, setup=instrument_clickhouse_server_log) Suite(run=privileges_granted_via_role, setup=instrument_clickhouse_server_log)
I drop the quota"): node.query(f"DROP QUOTA IF EXISTS {drop_row_policy_name}") @TestFeature @Name("drop quota") @Requirements( RQ_SRS_006_RBAC_Privileges_DropQuota("1.0"), ) def feature(self, node="clickhouse1"):
64
64
107
43
21
edani/ClickHouse
tests/testflows/rbac/tests/privileges/drop/drop_quota.py
Python
feature
feature
128
139
128
133
9cd2bf3e1b9d531f615d744aac8d4f8458521899
bigcode/the-stack
train
cd60a3669f7cc5e9ce43a98e
train
class
class TradingPairFetcher: _sf_shared_instance: "TradingPairFetcher" = None _tpf_logger: Optional[HummingbotLogger] = None _tpf_http_client: Optional[aiohttp.ClientSession] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._tpf_logger is None: cls._tpf_logger = logg...
class TradingPairFetcher:
_sf_shared_instance: "TradingPairFetcher" = None _tpf_logger: Optional[HummingbotLogger] = None _tpf_http_client: Optional[aiohttp.ClientSession] = None @classmethod def logger(cls) -> HummingbotLogger: if cls._tpf_logger is None: cls._tpf_logger = logging.getLogger(__name__) ...
safe_ensure_future from .ssl_client_request import SSLClientRequest BINANCE_ENDPOINT = "https://api.binance.com/api/v1/exchangeInfo" RADAR_RELAY_ENDPOINT = "https://api.radarrelay.com/v3/markets" BAMBOO_RELAY_ENDPOINT = "https://rest.bamboorelay.com/main/0x/markets" COINBASE_PRO_ENDPOINT = "https://api.pro.coinbase.c...
256
256
3,329
5
250
Loopring/hummingbot-deprecated
hummingbot/core/utils/trading_pair_fetcher.py
Python
TradingPairFetcher
TradingPairFetcher
32
390
32
32
7301f381a1cfd51f5fb648d433d674ddd15bd95f
bigcode/the-stack
train
09937625b0867f9c49b675f5
train
function
def remove_part_from_disk(node, table, part_name): part_path = node.query( "SELECT path FROM system.parts WHERE table = '{}' and name = '{}'".format( table, part_name ) ).strip() if not part_path: raise Exception("Part " + part_name + "doesn't exist") node.exec_in_con...
def remove_part_from_disk(node, table, part_name):
part_path = node.query( "SELECT path FROM system.parts WHERE table = '{}' and name = '{}'".format( table, part_name ) ).strip() if not part_path: raise Exception("Part " + part_name + "doesn't exist") node.exec_in_container( ["bash", "-c", "rm -r {p}/*".format...
_instance("node2", with_zookeeper=True, stay_alive=True) @pytest.fixture(scope="module") def start_cluster(): try: cluster.start() yield cluster except Exception as ex: print(ex) finally: cluster.shutdown() def remove_part_from_disk(node, table, part_name):
64
64
103
12
52
zzachimed/ClickHouse
tests/integration/test_lost_part_during_startup/test.py
Python
remove_part_from_disk
remove_part_from_disk
25
35
25
25
6eee372d8a736205c2981cd8d4841221fe8d718a
bigcode/the-stack
train
c8bb8149f7024c22fabd68b7
train
function
def test_lost_part_during_startup(start_cluster): for i, node in enumerate([node1, node2]): node.query( f"CREATE TABLE test_lost (value UInt64) Engine = ReplicatedMergeTree('/clickhouse/test_lost', '{i + 1}') ORDER BY tuple()" ) for i in range(4): node2.query(f"INSERT INTO t...
def test_lost_part_during_startup(start_cluster):
for i, node in enumerate([node1, node2]): node.query( f"CREATE TABLE test_lost (value UInt64) Engine = ReplicatedMergeTree('/clickhouse/test_lost', '{i + 1}') ORDER BY tuple()" ) for i in range(4): node2.query(f"INSERT INTO test_lost VALUES({i})") node2.query("OPTIMIZE ...
", with_zookeeper=True, stay_alive=True) @pytest.fixture(scope="module") def start_cluster(): try: cluster.start() yield cluster except Exception as ex: print(ex) finally: cluster.shutdown() def remove_part_from_disk(node, table, part_name): part_path = node.query( ...
163
163
546
12
151
zzachimed/ClickHouse
tests/integration/test_lost_part_during_startup/test.py
Python
test_lost_part_during_startup
test_lost_part_during_startup
38
93
38
38
7a65ac48e9f3485c7a738871d253d919429b6a29
bigcode/the-stack
train
ab671f41c1446a8646387ac2
train
function
@pytest.fixture(scope="module") def start_cluster(): try: cluster.start() yield cluster except Exception as ex: print(ex) finally: cluster.shutdown()
@pytest.fixture(scope="module") def start_cluster():
try: cluster.start() yield cluster except Exception as ex: print(ex) finally: cluster.shutdown()
from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) node1 = cluster.add_instance("node1", with_zookeeper=True, stay_alive=True) node2 = cluster.add_instance("node2", with_zookeeper=True, stay_alive=True) @pytest.fixture(scope="module") def start_cluster():
64
64
38
10
54
zzachimed/ClickHouse
tests/integration/test_lost_part_during_startup/test.py
Python
start_cluster
start_cluster
12
22
12
13
641af307c6092417cf9967a0ae35c2891af013ad
bigcode/the-stack
train
c8324fbb8034b9ead32a0822
train
function
def indentify_photo(img): retinaface = Retinaface() image = cv2.imread(img) if image is None: print('Open Error! Try again!') return "" else: image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) r_image = retinaface.detect_image(image) r_image = cv2.cvtColor(r_image, cv...
def indentify_photo(img):
retinaface = Retinaface() image = cv2.imread(img) if image is None: print('Open Error! Try again!') return "" else: image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) r_image = retinaface.detect_image(image) r_image = cv2.cvtColor(r_image, cv2.COLOR_RGB2BGR) #...
# 将单张图片预测、摄像头检测和FPS测试功能 # 整合到了一个py文件中,通过指定mode进行模式的修改。 # ----------------------------------------------------# import time import cv2 import numpy as np from retinaface import Retinaface def indentify_photo(img):
64
64
109
6
57
chennnnnnnnn/face_detection
face_identify.py
Python
indentify_photo
indentify_photo
17
29
17
17
7a107a046877001001b49e12872a1365464c7618
bigcode/the-stack
train
2456e62cc1a27b88e2bafd44
train
function
def identify_camera(): video_path = 0 video_save_path = "" video_fps = 25.0 retinaface = Retinaface() capture = cv2.VideoCapture(video_path) if video_save_path != "": fourcc = cv2.VideoWriter_fourcc(*'XVID') size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2...
def identify_camera():
video_path = 0 video_save_path = "" video_fps = 25.0 retinaface = Retinaface() capture = cv2.VideoCapture(video_path) if video_save_path != "": fourcc = cv2.VideoWriter_fourcc(*'XVID') size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)...
# -*- coding=utf-8 -*- # name: nan chen # date: 2021/7/4 15:53 # ----------------------------------------------------# # 对视频中的predict.py进行了修改, # 将单张图片预测、摄像头检测和FPS测试功能 # 整合到了一个py文件中,通过指定mode进行模式的修改。 # ----------------------------------------------------# import time import cv2 import numpy as np from retinaface ...
213
256
1,322
4
208
chennnnnnnnn/face_detection
face_identify.py
Python
identify_camera
identify_camera
32
154
32
32
11176ca3a6d9d3f59e21ec349dd16afcc0d452ab
bigcode/the-stack
train
e7d7242e512dfba5558f229c
train
function
def save_universal_model(model, save_data, epochs = None): checkpoint = save_data checkpoint["state_dict"] = model.state_dict() if epochs: checkpoint["epochs"] = epochs file_name = f'{save_data["model_name"]}_checkpoints_{time}.pth'.replace(":", "-").replace(" ", "_") file_path = path.joi...
def save_universal_model(model, save_data, epochs = None):
checkpoint = save_data checkpoint["state_dict"] = model.state_dict() if epochs: checkpoint["epochs"] = epochs file_name = f'{save_data["model_name"]}_checkpoints_{time}.pth'.replace(":", "-").replace(" ", "_") file_path = path.join(save_dir, file_name) try: torch.save(checkpo...
.now() save_dir = 'checkpoint/' def set_path(newPath): if path.isdir(newPath): save_dir = newPath else: raise "Save path is not valid directory. Create it or double check your path" def save_universal_model(model, save_data, epochs = None):
64
64
142
14
50
JeffreyStocker/Cat-vs-Dog-Image-Identifier
model_save.py
Python
save_universal_model
save_universal_model
15
33
15
15
d316315187accc290ede20521ceff2c41025c7ba
bigcode/the-stack
train
b27a78f8322a89fd22bd691b
train
function
def set_path(newPath): if path.isdir(newPath): save_dir = newPath else: raise "Save path is not valid directory. Create it or double check your path"
def set_path(newPath):
if path.isdir(newPath): save_dir = newPath else: raise "Save path is not valid directory. Create it or double check your path"
import torch import os import datetime from os import path time = datetime.datetime.now() save_dir = 'checkpoint/' def set_path(newPath):
32
64
41
6
26
JeffreyStocker/Cat-vs-Dog-Image-Identifier
model_save.py
Python
set_path
set_path
9
13
9
9
a8999f4ee384caa2affca90ebce5a3854c33dd83
bigcode/the-stack
train
a00f7fb52b826e16b50ce74a
train
class
class TestIoTDeviceIdentity(IoTLiveScenarioTest): def __init__(self, test_case): super(TestIoTDeviceIdentity, self).__init__( test_case, LIVE_HUB, LIVE_RG, LIVE_HUB_CS ) pass
class TestIoTDeviceIdentity(IoTLiveScenarioTest):
def __init__(self, test_case): super(TestIoTDeviceIdentity, self).__init__( test_case, LIVE_HUB, LIVE_RG, LIVE_HUB_CS ) pass
Settings(ENV_SET_TEST_IOTHUB_BASIC) LIVE_HUB = settings.env.azext_iot_testhub LIVE_RG = settings.env.azext_iot_testrg LIVE_HUB_CS = settings.env.azext_iot_testhub_cs class TestIoTDeviceIdentity(IoTLiveScenarioTest):
64
64
56
13
50
SpaceKatt/azure-iot-cli-extension
azext_iot/tests/iothub/device_identity/test_iot_device_identity_int.py
Python
TestIoTDeviceIdentity
TestIoTDeviceIdentity
16
22
16
16
6e5f76284432a612e51a5e7fe675c2e0a023e439
bigcode/the-stack
train
00652cfdb43c4f5d326e4ce9
train
class
class HostnameTestCase(TestCase): """ """ def setUp(self): self.mock_execute = mock.patch('akanda.router.utils.execute').start() self.mock_replace_file = mock.patch( 'akanda.router.utils.replace_file' ).start() self.addCleanup(mock.patch.stopall) self.mgr...
class HostnameTestCase(TestCase):
""" """ def setUp(self): self.mock_execute = mock.patch('akanda.router.utils.execute').start() self.mock_replace_file = mock.patch( 'akanda.router.utils.replace_file' ).start() self.addCleanup(mock.patch.stopall) self.mgr = hostname.HostnameManager() ...
writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from unittest2 import TestCase import mock from aka...
94
94
314
8
86
fzylogic/akanda-appliance
test/unit/drivers/test_hostname.py
Python
HostnameTestCase
HostnameTestCase
28
62
28
28
ac7171f2aaf09dc3519dcae111240b21750e92c2
bigcode/the-stack
train
87b2877ebd83a27e30faa99d
train
class
class HTTP11DownloadHandler(object): def __init__(self, settings): self._pool = HTTPConnectionPool(reactor, persistent=True) self._pool.maxPersistentPerHost = settings.getint('CONCURRENT_REQUESTS_PER_DOMAIN') self._pool._factory.noisy = False self._contextFactoryClass = load_object(...
class HTTP11DownloadHandler(object):
def __init__(self, settings): self._pool = HTTPConnectionPool(reactor, persistent=True) self._pool.maxPersistentPerHost = settings.getint('CONCURRENT_REQUESTS_PER_DOMAIN') self._pool._factory.noisy = False self._contextFactoryClass = load_object(settings['DOWNLOADER_CLIENTCONTEXTFACT...
.tx import Agent, ProxyAgent, ResponseDone, \ HTTPConnectionPool, TCP4ClientEndpoint from scrapy.http import Headers from scrapy.responsetypes import responsetypes from scrapy.core.downloader.webclient import _parse from scrapy.utils.misc import load_object class HTTP11DownloadHandler(object):
64
64
153
7
56
hobson/scrapy
scrapy/core/downloader/handlers/http11.py
Python
HTTP11DownloadHandler
HTTP11DownloadHandler
24
39
24
25
8cf37ff8c5754eb9987dd18e56829ca87ed8c45b
bigcode/the-stack
train
65e7f02492217646df75fbb7
train
class
class TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint): """An endpoint that tunnels through proxies to allow HTTPS downloads. To accomplish that, this endpoint sends an HTTP CONNECT to the proxy. The HTTP CONNECT is always sent when using this endpoint, I think this could be improved as the CONNECT will ...
class TunnelingTCP4ClientEndpoint(TCP4ClientEndpoint):
"""An endpoint that tunnels through proxies to allow HTTPS downloads. To accomplish that, this endpoint sends an HTTP CONNECT to the proxy. The HTTP CONNECT is always sent when using this endpoint, I think this could be improved as the CONNECT will be redundant if the connection associated with this...
__(self, settings): self._pool = HTTPConnectionPool(reactor, persistent=True) self._pool.maxPersistentPerHost = settings.getint('CONCURRENT_REQUESTS_PER_DOMAIN') self._pool._factory.noisy = False self._contextFactoryClass = load_object(settings['DOWNLOADER_CLIENTCONTEXTFACTORY']) ...
175
176
589
14
161
hobson/scrapy
scrapy/core/downloader/handlers/http11.py
Python
TunnelingTCP4ClientEndpoint
TunnelingTCP4ClientEndpoint
46
105
46
46
5aa25640c2ac9b47c8d12ce5235f6b7fdc8232a7
bigcode/the-stack
train
6d5e3ae3fcc84393a17adb19
train
class
class _RequestBodyProducer(object): implements(IBodyProducer) def __init__(self, body): self.body = body self.length = len(body) def startProducing(self, consumer): consumer.write(self.body) return defer.succeed(None) def pauseProducing(self): pass def sto...
class _RequestBodyProducer(object):
implements(IBodyProducer) def __init__(self, body): self.body = body self.length = len(body) def startProducing(self, consumer): consumer.write(self.body) return defer.succeed(None) def pauseProducing(self): pass def stopProducing(self): pass
status = int(txresponse.code) headers = Headers(txresponse.headers.getAllRawHeaders()) respcls = responsetypes.from_args(headers=headers, url=url) return respcls(url=url, status=status, headers=headers, body=body, flags=flags) class _RequestBodyProducer(object):
64
64
78
7
57
hobson/scrapy
scrapy/core/downloader/handlers/http11.py
Python
_RequestBodyProducer
_RequestBodyProducer
213
228
213
213
ead4e63e81f5efce1793b9d46a423afa618c236b
bigcode/the-stack
train
501249ba29f288fbdb6b16ec
train
class
class TunnelingAgent(Agent): """An agent that uses a L{TunnelingTCP4ClientEndpoint} to make HTTPS downloads. It may look strange that we have chosen to subclass Agent and not ProxyAgent but consider that after the tunnel is opened the proxy is transparent to the client; thus the agent should behave like...
class TunnelingAgent(Agent):
"""An agent that uses a L{TunnelingTCP4ClientEndpoint} to make HTTPS downloads. It may look strange that we have chosen to subclass Agent and not ProxyAgent but consider that after the tunnel is opened the proxy is transparent to the client; thus the agent should behave like there is no proxy involv...
self._protocolFactory = protocolFactory connectDeferred = super(TunnelingTCP4ClientEndpoint, self).connect(protocolFactory) connectDeferred.addCallback(self.requestTunnel) connectDeferred.addErrback(self.connectFailed) return self._tunnelReadyDeferred cla...
64
64
199
8
55
hobson/scrapy
scrapy/core/downloader/handlers/http11.py
Python
TunnelingAgent
TunnelingAgent
108
125
108
108
84c1dcec9c0bd6b95544dd32103c6d7f00c1ab1a
bigcode/the-stack
train
0e42b17f633fcf376c7d5555
train
class
class _ResponseReader(protocol.Protocol): def __init__(self, finished, txresponse, request): self._finished = finished self._txresponse = txresponse self._request = request self._bodybuf = StringIO() def dataReceived(self, bodyBytes): self._bodybuf.write(bodyBytes) ...
class _ResponseReader(protocol.Protocol):
def __init__(self, finished, txresponse, request): self._finished = finished self._txresponse = txresponse self._request = request self._bodybuf = StringIO() def dataReceived(self, bodyBytes): self._bodybuf.write(bodyBytes) def connectionLost(self, reason): ...
body): self.body = body self.length = len(body) def startProducing(self, consumer): consumer.write(self.body) return defer.succeed(None) def pauseProducing(self): pass def stopProducing(self): pass class _ResponseReader(protocol.Protocol):
64
64
157
7
56
hobson/scrapy
scrapy/core/downloader/handlers/http11.py
Python
_ResponseReader
_ResponseReader
231
252
231
232
ed1f21180ec17cd288cddcc15295322dd95ccb09
bigcode/the-stack
train
4eab47a5832766199afa9656
train
class
class TunnelError(Exception): """An HTTP CONNECT tunnel could not be established by the proxy."""
class TunnelError(Exception):
"""An HTTP CONNECT tunnel could not be established by the proxy."""
def download_request(self, request, spider): """Return a deferred for the HTTP download""" agent = ScrapyAgent(contextFactory=self._contextFactory, pool=self._pool) return agent.download_request(request) def close(self): return self._pool.closeCachedConnections() class TunnelErr...
64
64
19
5
59
hobson/scrapy
scrapy/core/downloader/handlers/http11.py
Python
TunnelError
TunnelError
42
43
42
42
4de490ff00343c41e848fe93e2463eaa10e297f2
bigcode/the-stack
train
131dcf79cc386338096714bc
train
class
class ScrapyAgent(object): _Agent = Agent _ProxyAgent = ProxyAgent _TunnelingAgent = TunnelingAgent def __init__(self, contextFactory=None, connectTimeout=10, bindAddress=None, pool=None): self._contextFactory = contextFactory self._connectTimeout = connectTimeout self._bindAdd...
class ScrapyAgent(object):
_Agent = Agent _ProxyAgent = ProxyAgent _TunnelingAgent = TunnelingAgent def __init__(self, contextFactory=None, connectTimeout=10, bindAddress=None, pool=None): self._contextFactory = contextFactory self._connectTimeout = connectTimeout self._bindAddress = bindAddress s...
Deferred.addCallback(self.requestTunnel) connectDeferred.addErrback(self.connectFailed) return self._tunnelReadyDeferred class TunnelingAgent(Agent): """An agent that uses a L{TunnelingTCP4ClientEndpoint} to make HTTPS downloads. It may look strange that we have chosen to subclass Agent and no...
231
231
772
6
225
hobson/scrapy
scrapy/core/downloader/handlers/http11.py
Python
ScrapyAgent
ScrapyAgent
128
210
128
129
1b5bdd75fe3225f8bf63f39d439cb598ff56cc4d
bigcode/the-stack
train
e9a20c8026c386cba14d7ceb
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, ...
class Migration(migrations.Migration):
initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
# Generated by Django 2.1.15 on 2020-10-13 10:58 from django.db import migrations, models class Migration(migrations.Migration):
38
94
314
7
30
SyedShahiq/recipe-app-api
app/core/migrations/0001_initial.py
Python
Migration
Migration
6
33
6
7
889e72eff2df7e61ebc154c7e408bb4a3170504c
bigcode/the-stack
train
f9ef144467c15debf95ea4cf
train
class
class Num(Constant, metaclass=_ABC): _fields = ('n',) __new__ = _new
class Num(Constant, metaclass=_ABC):
_fields = ('n',) __new__ = _new
cls] return type.__instancecheck__(cls, inst) def _new(cls, *args, **kwargs): if cls in _const_types: return Constant(*args, **kwargs) return Constant.__new__(cls, *args, **kwargs) class Num(Constant, metaclass=_ABC):
64
64
25
9
55
livioso/cpython
Lib/ast.py
Python
Num
Num
357
359
357
357
8f68c3b548d1c74ad8467b14d34c2937223c3055
bigcode/the-stack
train
263b12d69dff497f80f8c722
train
class
class NameConstant(Constant, metaclass=_ABC): __new__ = _new
class NameConstant(Constant, metaclass=_ABC):
__new__ = _new
= _new class Str(Constant, metaclass=_ABC): _fields = ('s',) __new__ = _new class Bytes(Constant, metaclass=_ABC): _fields = ('s',) __new__ = _new class NameConstant(Constant, metaclass=_ABC):
64
64
18
10
53
livioso/cpython
Lib/ast.py
Python
NameConstant
NameConstant
369
370
369
369
9cbcff7658ef737fd4fdc95b25e212b6e6c7d5b3
bigcode/the-stack
train
50d632fb2e7a6f7dce2c5057
train
function
def dump(node, annotate_fields=True, include_attributes=False): """ Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wante...
def dump(node, annotate_fields=True, include_attributes=False):
""" Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as li...
and isinstance(node.op, (Add, Sub)): left = _convert_signed_num(node.left) right = _convert_num(node.right) if isinstance(left, (int, float)) and isinstance(right, complex): if isinstance(node.op, Add): return left + right else: ...
96
96
320
12
84
livioso/cpython
Lib/ast.py
Python
dump
dump
86
113
86
86
61f7c9eae3dfbc217566bf865118fbede138575c
bigcode/the-stack
train
13c4074e1cafaa150da2e45b
train
class
class _ABC(type): def __instancecheck__(cls, inst): if not isinstance(inst, Constant): return False if cls in _const_types: try: value = inst.value except AttributeError: return False else: return type(v...
class _ABC(type):
def __instancecheck__(cls, inst): if not isinstance(inst, Constant): return False if cls in _const_types: try: value = inst.value except AttributeError: return False else: return type(value) in _const_typ...
The following code is for backward compatibility. # It will be removed in future. def _getter(self): return self.value def _setter(self, value): self.value = value Constant.n = property(_getter, _setter) Constant.s = property(_getter, _setter) class _ABC(type):
64
64
79
5
59
livioso/cpython
Lib/ast.py
Python
_ABC
_ABC
338
350
338
339
a60460d330b34e30aedf739aec244cf0ac7b213b
bigcode/the-stack
train
8756bcf1c71f85fe4d9f2c44
train
function
def _setter(self, value): self.value = value
def _setter(self, value):
self.value = value
if new_node is None: delattr(node, field) else: setattr(node, field, new_node) return node # The following code is for backward compatibility. # It will be removed in future. def _getter(self): return self.value def _setter(self, val...
64
64
13
7
56
livioso/cpython
Lib/ast.py
Python
_setter
_setter
332
333
332
332
28677946694e1009649cd789f3200c42acf6b9f2
bigcode/the-stack
train
fef3e13bdf64b2aa0c1497f5
train
class
class Bytes(Constant, metaclass=_ABC): _fields = ('s',) __new__ = _new
class Bytes(Constant, metaclass=_ABC):
_fields = ('s',) __new__ = _new
args, **kwargs) class Num(Constant, metaclass=_ABC): _fields = ('n',) __new__ = _new class Str(Constant, metaclass=_ABC): _fields = ('s',) __new__ = _new class Bytes(Constant, metaclass=_ABC):
64
64
25
9
54
livioso/cpython
Lib/ast.py
Python
Bytes
Bytes
365
367
365
365
08c8e7ca030ec345885166fa29465de0855828d3
bigcode/the-stack
train
9cb0c87ac5786255b1763017
train
function
def _new(cls, *args, **kwargs): if cls in _const_types: return Constant(*args, **kwargs) return Constant.__new__(cls, *args, **kwargs)
def _new(cls, *args, **kwargs):
if cls in _const_types: return Constant(*args, **kwargs) return Constant.__new__(cls, *args, **kwargs)
if cls in _const_types: try: value = inst.value except AttributeError: return False else: return type(value) in _const_types[cls] return type.__instancecheck__(cls, inst) def _new(cls, *args, **kwargs):
64
64
42
11
53
livioso/cpython
Lib/ast.py
Python
_new
_new
352
355
352
352
f1b17fedb4d760b9df18b8a9f5d3aed6e37a29fb
bigcode/the-stack
train
e72ef638876b941aa8f37097
train
function
def increment_lineno(node, n=1): """ Increment the line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file. """ for child in walk(node): if 'lineno' in child._attributes: child.lineno = getattr(child, 'lineno...
def increment_lineno(node, n=1):
""" Increment the line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file. """ for child in walk(node): if 'lineno' in child._attributes: child.lineno = getattr(child, 'lineno', 0) + n return node
'): node.col_offset = col_offset else: col_offset = node.col_offset for child in iter_child_nodes(node): _fix(child, lineno, col_offset) _fix(node, 1, 0) return node def increment_lineno(node, n=1):
64
64
91
9
54
livioso/cpython
Lib/ast.py
Python
increment_lineno
increment_lineno
153
161
153
153
d8f4e8d1b2f78f6f9c72379f212eaddfeed015e2
bigcode/the-stack
train
0563d3be341920aa09746f9b
train
function
def copy_location(new_node, old_node): """ Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. """ for attr in 'lineno', 'col_offset': if attr in old_node._attributes and attr in new_node._attributes \ and h...
def copy_location(new_node, old_node):
""" Copy source location (`lineno` and `col_offset` attributes) from *old_node* to *new_node* if possible, and return *new_node*. """ for attr in 'lineno', 'col_offset': if attr in old_node._attributes and attr in new_node._attributes \ and hasattr(old_node, attr): set...
'[%s]' % ', '.join(_format(x) for x in node) return repr(node) if not isinstance(node, AST): raise TypeError('expected AST, got %r' % node.__class__.__name__) return _format(node) def copy_location(new_node, old_node):
64
64
104
9
55
livioso/cpython
Lib/ast.py
Python
copy_location
copy_location
116
125
116
116
b9054c7c4a168c59f9c2c6b6f8df4edc91582103
bigcode/the-stack
train
6633f5168388c5ed54601c4f
train
function
def parse(source, filename='<unknown>', mode='exec'): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). """ return compile(source, filename, mode, PyCF_ONLY_AST)
def parse(source, filename='<unknown>', mode='exec'):
""" Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). """ return compile(source, filename, mode, PyCF_ONLY_AST)
is to provide an easy to use interface for libraries that work tightly with the python syntax (template engines for example). :copyright: Copyright 2008 by Armin Ronacher. :license: Python License. """ from _ast import * def parse(source, filename='<unknown>', mode='exec'):
64
64
54
12
52
livioso/cpython
Lib/ast.py
Python
parse
parse
30
35
30
30
5c8bb162753b1cdb15f728bd1fbdcff1defe9873
bigcode/the-stack
train
783de590ea81ce95e080fdf9
train
function
def _getter(self): return self.value
def _getter(self):
return self.value
, AST): new_node = self.visit(old_value) if new_node is None: delattr(node, field) else: setattr(node, field, new_node) return node # The following code is for backward compatibility. # It will be removed in future. def _g...
64
64
10
5
59
livioso/cpython
Lib/ast.py
Python
_getter
_getter
329
330
329
329
9f1f2bcf85426feb093a338ea16e0bfcf8b05f2a
bigcode/the-stack
train
b7fe7d1a7ba86686509fb979
train
function
def iter_child_nodes(node): """ Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. """ for name, field in iter_fields(node): if isinstance(field, AST): yield field elif isinstance(field, list): ...
def iter_child_nodes(node):
""" Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. """ for name, field in iter_fields(node): if isinstance(field, AST): yield field elif isinstance(field, list): for item in field: ...
of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ for field in node._fields: try: yield field, getattr(node, field) except AttributeError: pass def iter_child_nodes(node):
64
64
86
6
57
livioso/cpython
Lib/ast.py
Python
iter_child_nodes
iter_child_nodes
176
187
176
176
fd8d01519a9b53e6f9e27567afcaa99409932838
bigcode/the-stack
train
03bba65e7322665c6c87989a
train
class
class Ellipsis(Constant, metaclass=_ABC): _fields = () def __new__(cls, *args, **kwargs): if cls is Ellipsis: return Constant(..., *args, **kwargs) return Constant.__new__(cls, *args, **kwargs)
class Ellipsis(Constant, metaclass=_ABC):
_fields = () def __new__(cls, *args, **kwargs): if cls is Ellipsis: return Constant(..., *args, **kwargs) return Constant.__new__(cls, *args, **kwargs)
s',) __new__ = _new class Bytes(Constant, metaclass=_ABC): _fields = ('s',) __new__ = _new class NameConstant(Constant, metaclass=_ABC): __new__ = _new class Ellipsis(Constant, metaclass=_ABC):
64
64
60
10
53
livioso/cpython
Lib/ast.py
Python
Ellipsis
Ellipsis
372
378
372
372
10064125214478e376129333bb0797a97d0d38bc
bigcode/the-stack
train
9b0a540e95e4214f49d1c35e
train
function
def literal_eval(node_or_string): """ Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. """ if isins...
def literal_eval(node_or_string):
""" Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. """ if isinstance(node_or_string, str): ...
intention of the helper functions and this module in general is to provide an easy to use interface for libraries that work tightly with the python syntax (template engines for example). :copyright: Copyright 2008 by Armin Ronacher. :license: Python License. """ from _ast import * def parse(source,...
125
125
417
7
118
livioso/cpython
Lib/ast.py
Python
literal_eval
literal_eval
38
83
38
38
f733628001b977aafe7e1a8df4eb7b0a51e1a0bf
bigcode/the-stack
train
8165ee83dab98df71367bbe8
train
function
def fix_missing_locations(node): """ When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, b...
def fix_missing_locations(node):
""" When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of t...
*. """ for attr in 'lineno', 'col_offset': if attr in old_node._attributes and attr in new_node._attributes \ and hasattr(old_node, attr): setattr(new_node, attr, getattr(old_node, attr)) return new_node def fix_missing_locations(node):
64
64
216
6
57
livioso/cpython
Lib/ast.py
Python
fix_missing_locations
fix_missing_locations
128
150
128
128
80ac8511db51901285e91ac9d90da8e4f7d68620
bigcode/the-stack
train
2a7bf45844dcc20cea1defc2
train
function
def get_docstring(node, clean=True): """ Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised. If *clean* is `True`, all tabs are expanded to spaces and any whitespace that can be uniformly remove...
def get_docstring(node, clean=True):
""" Return the docstring for the given node or None if no docstring can be found. If the node provided does not have docstrings a TypeError will be raised. If *clean* is `True`, all tabs are expanded to spaces and any whitespace that can be uniformly removed from the second line onwards is rem...
of fields that are lists of nodes. """ for name, field in iter_fields(node): if isinstance(field, AST): yield field elif isinstance(field, list): for item in field: if isinstance(item, AST): yield item def get_docstring(node, clean=Tru...
64
64
213
9
54
livioso/cpython
Lib/ast.py
Python
get_docstring
get_docstring
190
213
190
190
3bb9f3b1d16e8070e1b2851bd36ed97b01477fd5
bigcode/the-stack
train
1fa5fed7377066f33610bb03
train
class
class Str(Constant, metaclass=_ABC): _fields = ('s',) __new__ = _new
class Str(Constant, metaclass=_ABC):
_fields = ('s',) __new__ = _new
if cls in _const_types: return Constant(*args, **kwargs) return Constant.__new__(cls, *args, **kwargs) class Num(Constant, metaclass=_ABC): _fields = ('n',) __new__ = _new class Str(Constant, metaclass=_ABC):
64
64
25
9
54
livioso/cpython
Lib/ast.py
Python
Str
Str
361
363
361
361
3b2728b46dd4436a2ea1caf4444201ec52ef2132
bigcode/the-stack
train
8ae53a1f1004f2b7152e7bbd
train
class
class NodeVisitor(object): """ A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclass adding visitor meth...
class NodeVisitor(object):
""" A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclass adding visitor methods. Per default the v...
Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. """ from collections import deque todo = deque([node]) while todo: node = t...
92
92
307
5
86
livioso/cpython
Lib/ast.py
Python
NodeVisitor
NodeVisitor
230
264
230
230
f554573c360616a8d535f861bcfbd088f9aaab3b
bigcode/the-stack
train
273f3ad3f3ba0897b93b60db
train
function
def walk(node): """ Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. """ from collections import deque todo = deque([node]) w...
def walk(node):
""" Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context. """ from collections import deque todo = deque([node]) while todo: ...
isinstance(node, Str): text = node.s elif isinstance(node, Constant) and isinstance(node.value, str): text = node.value else: return None if clean: import inspect text = inspect.cleandoc(text) return text def walk(node):
64
64
94
4
59
livioso/cpython
Lib/ast.py
Python
walk
walk
216
227
216
216
b95252cbca04ed41fbb8521a3daea7384632e3a1
bigcode/the-stack
train
e259ce6ebe6790977a5e5c2a
train
function
def iter_fields(node): """ Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ for field in node._fields: try: yield field, getattr(node, field) except AttributeError: pass
def iter_fields(node):
""" Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*. """ for field in node._fields: try: yield field, getattr(node, field) except AttributeError: pass
This is useful to "move code" to a different location in a file. """ for child in walk(node): if 'lineno' in child._attributes: child.lineno = getattr(child, 'lineno', 0) + n return node def iter_fields(node):
64
64
69
5
58
livioso/cpython
Lib/ast.py
Python
iter_fields
iter_fields
164
173
164
164
67298f694d1a3009a13083d4c7c8cf19f668be60
bigcode/the-stack
train
877f09f8e65844df5239afca
train
class
class NodeTransformer(NodeVisitor): """ A :class:`NodeVisitor` subclass that walks the abstract syntax tree and allows modification of nodes. The `NodeTransformer` will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the vi...
class NodeTransformer(NodeVisitor):
""" A :class:`NodeVisitor` subclass that walks the abstract syntax tree and allows modification of nodes. The `NodeTransformer` will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is ``None``, the node w...
visitor exists (`NodeTransformer`) that allows modifications. """ def visit(self, node): """Visit a node.""" method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.generic_visit) return visitor(node) def generic_visit(self, node): """C...
131
131
437
6
125
livioso/cpython
Lib/ast.py
Python
NodeTransformer
NodeTransformer
267
323
267
267
dc6d70430c6f21486937ecf2100f679475515f97
bigcode/the-stack
train
2bd5d2aefd3fa514738a0fb0
train
function
def zero_points(expr: sympy.Expr) -> sympy.Expr: substitutions = {} for sym in expr.free_symbols: if _POINT_SYMBOL_RE.match(sym.name): substitutions[sym] = 0 return expr.subs(substitutions)
def zero_points(expr: sympy.Expr) -> sympy.Expr:
substitutions = {} for sym in expr.free_symbols: if _POINT_SYMBOL_RE.match(sym.name): substitutions[sym] = 0 return expr.subs(substitutions)
import re import sympy _POINT_SYMBOL_RE = re.compile(r"^p(\d+)$") class FloorDiv(sympy.Function): nargs = 2 def zero_points(expr: sympy.Expr) -> sympy.Expr:
49
64
54
14
34
samkaufman/morello
morello/codegen/expr_utils.py
Python
zero_points
zero_points
12
17
12
12
902b094e2b1eb93b6393425114a9d5247314bcf7
bigcode/the-stack
train
21548aedb8294b3d1aafe5d8
train
class
class FloorDiv(sympy.Function): nargs = 2
class FloorDiv(sympy.Function):
nargs = 2
import re import sympy _POINT_SYMBOL_RE = re.compile(r"^p(\d+)$") class FloorDiv(sympy.Function):
29
64
13
7
22
samkaufman/morello
morello/codegen/expr_utils.py
Python
FloorDiv
FloorDiv
8
9
8
8
f94a06a864acc3760c7b439aa09bb6315fb37f44
bigcode/the-stack
train
1abbaa0454fe8ba6c2c28855
train
function
def sanitize(txt): return txt
def sanitize(txt):
return txt
connection_type"] JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" URL_ENCODED = "application/x-www-form-urlencoded" JSON_ENCODED = "application/json" JOSE_ENCODED = "application/jose" def sanitize(txt):
64
64
8
4
60
cnjlq84/oidc-op
src/oidcop/__init__.py
Python
sanitize
sanitize
22
23
22
22
a3dc628c2f02e2fdb4e512433b818ddccfb0423f
bigcode/the-stack
train
20b3774db40f9e061cdc7b7e
train
function
def rndstr(size=16): """ Returns a string of random url safe characters :param size: The length of the string :return: string """ return secrets.token_urlsafe(size)
def rndstr(size=16):
""" Returns a string of random url safe characters :param size: The length of the string :return: string """ return secrets.token_urlsafe(size)
ietf:params:oauth:client-assertion-type:jwt-bearer" URL_ENCODED = "application/x-www-form-urlencoded" JSON_ENCODED = "application/json" JOSE_ENCODED = "application/jose" def sanitize(txt): return txt def rndstr(size=16):
64
64
46
7
56
cnjlq84/oidc-op
src/oidcop/__init__.py
Python
rndstr
rndstr
26
33
26
26
4593a6e01a8f1d98e9499aebb4f12269a8e0c538
bigcode/the-stack
train
cc57fdd993d7dba079d807f6
train
class
class PakistanPPRAReleases(SimpleSpider): """ Domain Pakistan Public Procurement Regulatory Authority (PPRA) API documentation https://www.ppra.org.pk/api/ """ name = 'pakistan_ppra_releases' # SimpleSpider data_type = 'release_package' def start_requests(self): yie...
class PakistanPPRAReleases(SimpleSpider):
""" Domain Pakistan Public Procurement Regulatory Authority (PPRA) API documentation https://www.ppra.org.pk/api/ """ name = 'pakistan_ppra_releases' # SimpleSpider data_type = 'release_package' def start_requests(self): yield scrapy.Request( 'https://ww...
import json import scrapy from kingfisher_scrapy.base_spider import SimpleSpider from kingfisher_scrapy.util import components, handle_http_error class PakistanPPRAReleases(SimpleSpider):
42
64
193
9
32
bidhive/kingfisher-collect
kingfisher_scrapy/spiders/pakistan_ppra_releases.py
Python
PakistanPPRAReleases
PakistanPPRAReleases
9
33
9
9
b2f59954ae736f816ac9b15e87734809e4ec147b
bigcode/the-stack
train
b113f2e94d7b87874bfa915f
train
class
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestSensorsBattery(unittest.TestCase): def test_has_battery(self): if win32api.GetPwrCapabilities()['SystemBatteriesPresent']: self.assertIsNotNone(psutil.sensors_battery()) else: self.assertIsNone(psutil.sensors_battery())...
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestSensorsBattery(unittest.TestCase):
def test_has_battery(self): if win32api.GetPwrCapabilities()['SystemBatteriesPresent']: self.assertIsNotNone(psutil.sensors_battery()) else: self.assertIsNone(psutil.sensors_battery()) @unittest.skipIf(not HAS_BATTERY, "no battery") def test_percent(self): w ...
/issues/1007 with mock.patch('psutil._pswindows.cext.boot_time', return_value=5): self.assertEqual(psutil.boot_time(), 5) with mock.patch('psutil._pswindows.cext.boot_time', return_value=4): self.assertEqual(psutil.boot_time(), 5) with mock.patch('psutil._pswindows.cext.b...
165
166
555
21
144
glandium/psutil
psutil/tests/test_windows.py
Python
TestSensorsBattery
TestSensorsBattery
232
285
232
234
bce2124be6de9e96e31179be4ab195532ff30b2e
bigcode/the-stack
train
04b4f53986d3b0833b12d85d
train
class
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestSystemAPIs(unittest.TestCase): def test_nic_names(self): out = sh('ipconfig /all') nics = psutil.net_io_counters(pernic=True).keys() for nic in nics: if "pseudo-interface" in nic.replace(' ', '-').lower(): c...
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestSystemAPIs(unittest.TestCase):
def test_nic_names(self): out = sh('ipconfig /all') nics = psutil.net_io_counters(pernic=True).keys() for nic in nics: if "pseudo-interface" in nic.replace(' ', '-').lower(): continue if nic not in out: self.fail( "%...
fail on many-cores systems: # https://stackoverflow.com/questions/31209256 sys_value = win32api.GetSystemInfo()[5] psutil_value = psutil.cpu_count() self.assertEqual(sys_value, psutil_value) def test_cpu_count_logical_vs_wmi(self): w = wmi.WMI() proc = w.Win32_Proce...
256
256
1,273
22
234
glandium/psutil
psutil/tests/test_windows.py
Python
TestSystemAPIs
TestSystemAPIs
108
224
108
110
1516ae30878f3b24985d0b5b35db613154e78cfe
bigcode/the-stack
train
a8e11f5a01b74b2eaeb30cae
train
function
def wrap_exceptions(fun): def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except OSError as err: from psutil._pswindows import ACCESS_DENIED_SET if err.errno in ACCESS_DENIED_SET: raise psutil.AccessDenied(None, None) ...
def wrap_exceptions(fun):
def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except OSError as err: from psutil._pswindows import ACCESS_DENIED_SET if err.errno in ACCESS_DENIED_SET: raise psutil.AccessDenied(None, None) if err.errno == e...
win32process import wmi # requires "pip install wmi" / "make setup-dev-env" cext = psutil._psplatform.cext # are we a 64 bit process IS_64_BIT = sys.maxsize > 2**32 def wrap_exceptions(fun):
64
64
102
6
57
glandium/psutil
psutil/tests/test_windows.py
Python
wrap_exceptions
wrap_exceptions
50
61
50
50
5366d76faa9dbd72d44a9eaa675575dfc67087eb
bigcode/the-stack
train
6f75e18635fed727e279fccf
train
class
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestServices(unittest.TestCase): def test_win_service_iter(self): valid_statuses = set([ "running", "paused", "start", "pause", "continue", "stop", "stopped", ]) ...
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestServices(unittest.TestCase):
def test_win_service_iter(self): valid_statuses = set([ "running", "paused", "start", "pause", "continue", "stop", "stopped", ]) valid_start_types = set([ "automatic", "manual", ...
def test_cmdline_64(self): p = psutil.Process(self.proc64.pid) self.assertEqual(len(p.cmdline()), 3) self.assertEqual(p.cmdline()[1:], self.test_args) def test_cwd_32(self): p = psutil.Process(self.proc32.pid) self.assertEqual(p.cwd(), os.getcwd()) def test_cwd_64(self...
228
229
764
20
208
glandium/psutil
psutil/tests/test_windows.py
Python
TestServices
TestServices
783
875
783
785
a97fba8915546b486b9cf21cf49c86d5b4b1b02c
bigcode/the-stack
train
4a9eed086a8f91b13f8588d1
train
class
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestProcessWMI(unittest.TestCase): """Compare Process API results with WMI.""" @classmethod def setUpClass(cls): cls.pid = get_test_subprocess().pid @classmethod def tearDownClass(cls): reap_children() def test_name(self): ...
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestProcessWMI(unittest.TestCase):
"""Compare Process API results with WMI.""" @classmethod def setUpClass(cls): cls.pid = get_test_subprocess().pid @classmethod def tearDownClass(cls): reap_children() def test_name(self): w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0] p = psutil.Process(sel...
cnt = ctypes.wintypes.DWORD() ctypes.windll.kernel32.GetProcessHandleCount( handle, ctypes.byref(hndcnt)) sys_value = hndcnt.value psutil_value = psutil.Process(self.pid).num_handles() self.assertEqual(psutil_value, sys_value) def test_error_partial_copy(self): #...
188
188
629
22
166
glandium/psutil
psutil/tests/test_windows.py
Python
TestProcessWMI
TestProcessWMI
528
591
528
529
847af3c68007c2189dccc80a70bb24104b61d68a
bigcode/the-stack
train
f681ce64f4b104eaf7cad9a4
train
class
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestCpuAPIs(unittest.TestCase): @unittest.skipIf('NUMBER_OF_PROCESSORS' not in os.environ, 'NUMBER_OF_PROCESSORS env var is not available') def test_cpu_count_vs_NUMBER_OF_PROCESSORS(self): # Will likely fail on many-cores systems...
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestCpuAPIs(unittest.TestCase): @unittest.skipIf('NUMBER_OF_PROCESSORS' not in os.environ, 'NUMBER_OF_PROCESSORS env var is not available')
def test_cpu_count_vs_NUMBER_OF_PROCESSORS(self): # Will likely fail on many-cores systems: # https://stackoverflow.com/questions/31209256 num_cpus = int(os.environ['NUMBER_OF_PROCESSORS']) self.assertEqual(num_cpus, psutil.cpu_count()) def test_cpu_count_vs_GetSystemInfo(self):...
in ACCESS_DENIED_SET: raise psutil.AccessDenied(None, None) if err.errno == errno.ESRCH: raise psutil.NoSuchProcess(None, None) raise return wrapper # =================================================================== # System APIs # ======================...
107
108
362
51
56
glandium/psutil
psutil/tests/test_windows.py
Python
TestCpuAPIs
TestCpuAPIs
69
105
69
73
5ffe18494144cee0ab9c0d4c8451c1ab3003c605
bigcode/the-stack
train
828715edd8da3092b2ebb9d0
train
class
@unittest.skipIf(not WINDOWS, "WINDOWS only") class RemoteProcessTestCase(unittest.TestCase): """Certain functions require calling ReadProcessMemory. This trivially works when called on the current process. Check that this works on other processes, especially when they have a different bitness. """ ...
@unittest.skipIf(not WINDOWS, "WINDOWS only") class RemoteProcessTestCase(unittest.TestCase):
"""Certain functions require calling ReadProcessMemory. This trivially works when called on the current process. Check that this works on other processes, especially when they have a different bitness. """ @staticmethod def find_other_interpreter(): # find a python interpreter that ...
def test_num_handles(self): num_handles = psutil.Process(self.pid).num_handles() with mock.patch("psutil._psplatform.cext.proc_num_handles", side_effect=OSError(errno.EPERM, "msg")) as fun: self.assertEqual(psutil.Process(self.pid).num_handles(), ...
206
206
687
22
184
glandium/psutil
psutil/tests/test_windows.py
Python
RemoteProcessTestCase
RemoteProcessTestCase
687
775
687
688
b954e5f377d79cce0f4f6346f41e19655b5982de
bigcode/the-stack
train
13399cbdf672a655dc753869
train
class
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestProcess(unittest.TestCase): @classmethod def setUpClass(cls): cls.pid = get_test_subprocess().pid @classmethod def tearDownClass(cls): reap_children() def test_issue_24(self): p = psutil.Process(0) self.assert...
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestProcess(unittest.TestCase): @classmethod
def setUpClass(cls): cls.pid = get_test_subprocess().pid @classmethod def tearDownClass(cls): reap_children() def test_issue_24(self): p = psutil.Process(0) self.assertRaises(psutil.AccessDenied, p.kill) def test_special_pid(self): p = psutil.Process(4) ...
.called def test_emulate_power_connected(self): with mock.patch("psutil._pswindows.cext.sensors_battery", return_value=(1, 0, 0, 0)) as m: self.assertEqual(psutil.sensors_battery().secsleft, psutil.POWER_TIME_UNLIMITED) assert m.c...
255
256
2,070
24
231
glandium/psutil
psutil/tests/test_windows.py
Python
TestProcess
TestProcess
293
525
293
296
1bff175558e3e9734f648d42bec96dad38515e12
bigcode/the-stack
train
7d079f9b99eafbefcb700106
train
class
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestDualProcessImplementation(unittest.TestCase): """ Certain APIs on Windows have 2 internal implementations, one based on documented Windows APIs, another one based NtQuerySystemInformation() which gets called as fallback in case the first fails ...
@unittest.skipIf(not WINDOWS, "WINDOWS only") class TestDualProcessImplementation(unittest.TestCase):
""" Certain APIs on Windows have 2 internal implementations, one based on documented Windows APIs, another one based NtQuerySystemInformation() which gets called as fallback in case the first fails because of limited permission error. Here we test that the two methods return the exact same value...
mi.WMI().Win32_Process(ProcessId=self.pid)[0] p = psutil.Process(self.pid) vms = p.memory_info().vms # http://msdn.microsoft.com/en-us/library/aa394372(VS.85).aspx # ...claims that PageFileUsage is represented in Kilo # bytes but funnily enough on certain platforms bytes are ...
256
256
884
22
234
glandium/psutil
psutil/tests/test_windows.py
Python
TestDualProcessImplementation
TestDualProcessImplementation
594
684
594
595
7586acaa70ff70f920c3dfda26efc9635bc8038f
bigcode/the-stack
train
d1d65ed56e0670633907a0cb
train
class
class JunctionCapacity(Capacity): def __init__(self, nodes, name, value, superComponent, **kwargs): super(JunctionCapacity, self).__init__(nodes, name, value, superComponent, **kwargs) self.parseArgs(**kwargs) self.fak = eval(self.getMyParameterFromDictionary("fak",self.paramDict,"1")) ...
class JunctionCapacity(Capacity):
def __init__(self, nodes, name, value, superComponent, **kwargs): super(JunctionCapacity, self).__init__(nodes, name, value, superComponent, **kwargs) self.parseArgs(**kwargs) self.fak = eval(self.getMyParameterFromDictionary("fak",self.paramDict,"1")) self.Udifu = eval(self.getMyP...
import numpy as np from OSIM.Modeling.Components.Capacity import Capacity from OSIM.Modeling.CircuitSystemEquations import CircuitSystemEquations class JunctionCapacity(Capacity):
39
111
373
7
31
tmaiwald/OSIM
OSIM/Modeling/Components/NPN_Gummel_Poon_Model/JunctionCapacity.py
Python
JunctionCapacity
JunctionCapacity
6
42
6
7
1245526a1ba5b6feb90a0da3753c4ee933c14bb0
bigcode/the-stack
train
236fbd3e5a787032aad3b79f
train
class
class BaseEntity(Model): id = PrimaryKeyField() class Meta: database = database
class BaseEntity(Model):
id = PrimaryKeyField() class Meta: database = database
from peewee import Model, PrimaryKeyField from model import database class BaseEntity(Model):
20
64
22
5
14
Djaler/ZloyBot
model/base_entity.py
Python
BaseEntity
BaseEntity
6
10
6
6
8164be345f00c4920cb7ce7df4a8ea6934b1aaa1
bigcode/the-stack
train
a4c0885fbe5a0cfc23768e60
train
class
class Human: """ body_parts: list of BodyPart """ __slots__ = ('body_parts', 'pairs', 'uidx_list', 'score') def __init__(self, pairs): self.pairs = [] self.uidx_list = set() self.body_parts = {} for pair in pairs: self.add_pair(pair) self.score = ...
class Human:
""" body_parts: list of BodyPart """ __slots__ = ('body_parts', 'pairs', 'uidx_list', 'score') def __init__(self, pairs): self.pairs = [] self.uidx_list = set() self.body_parts = {} for pair in pairs: self.add_pair(pair) self.score = 0.0 @sta...
from tf_pose.common import CocoPart from tf_pose.tensblur.smoother import Smoother _tf_pose_estimator_tensorrt_disabled=False try: import tensorflow.contrib.tensorrt as trt except ModuleNotFoundError: _tf_pose_estimator_tensorrt_disabled=True try: from tf_pose.pafprocess import pafprocess except ModuleNot...
256
256
2,090
3
252
shunya-toyokawa/pose_estimation_new
tf_pose/estimator.py
Python
Human
Human
50
248
50
50
2f2e6cadf95fdc44a536220120db4301df4b056f
bigcode/the-stack
train
1c400b9167f60ff8205ca795
train
function
def _round(v): return int(round(v))
def _round(v):
return int(round(v))
logger.handlers.clear() logger.setLevel(logging.INFO) ch = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) logger.setLevel(logging.INFO) def _round(v):
64
64
11
5
59
shunya-toyokawa/pose_estimation_new
tf_pose/estimator.py
Python
_round
_round
39
40
39
39
04b8fce87311a8d8032ff4a465496f2df1998b07
bigcode/the-stack
train
b4d13ff9b0180f07c9641e7c
train
class
class PoseEstimator: def __init__(self): pass @staticmethod def estimate_paf(peaks, heat_mat, paf_mat): pafprocess.process_paf(peaks, heat_mat, paf_mat) humans = [] for human_id in range(pafprocess.get_num_humans()): human = Human([]) is_added = Fals...
class PoseEstimator:
def __init__(self): pass @staticmethod def estimate_paf(peaks, heat_mat, paf_mat): pafprocess.process_paf(peaks, heat_mat, paf_mat) humans = [] for human_id in range(pafprocess.get_num_humans()): human = Human([]) is_added = False for pa...
return CocoPart(self.part_idx) def __str__(self): return 'BodyPart:%d-(%.2f, %.2f) score=%.2f' % (self.part_idx, self.x, self.y, self.score) def __repr__(self): return self.__str__() class PoseEstimator:
68
69
230
4
65
shunya-toyokawa/pose_estimation_new
tf_pose/estimator.py
Python
PoseEstimator
PoseEstimator
275
306
275
275
e3725df1d05e62d457d69722d7791bda8fb963b6
bigcode/the-stack
train
e7cb53b6d4f480e48a2af21f
train
class
class BodyPart: """ part_idx : part index(eg. 0 for nose) x, y: coordinate of body part score : confidence score """ __slots__ = ('uidx', 'part_idx', 'x', 'y', 'score') def __init__(self, uidx, part_idx, x, y, score): self.uidx = uidx self.part_idx = part_idx self.x,...
class BodyPart:
""" part_idx : part index(eg. 0 for nose) x, y: coordinate of body part score : confidence score """ __slots__ = ('uidx', 'part_idx', 'x', 'y', 'score') def __init__(self, uidx, part_idx, x, y, score): self.uidx = uidx self.part_idx = part_idx self.x, self.y = x, y ...
"w": _round(x2 - x), "h": _round(y2 - y)} def __str__(self): return ' '.join([str(x) for x in self.body_parts.values()]) def __repr__(self): return self.__str__() class BodyPart:
63
64
184
4
60
shunya-toyokawa/pose_estimation_new
tf_pose/estimator.py
Python
BodyPart
BodyPart
251
272
251
251
5d8c0cc7a04b70559a560e06417f0003d9584898
bigcode/the-stack
train
8b9faa78f5457b748bcb575b
train
class
class TfPoseEstimator: # TODO : multi-scale def __init__(self, graph_path, target_size=(320, 240), tf_config=None, trt_bool=False): self.target_size = target_size if _tf_pose_estimator_tensorrt_disabled: trt_bool = False # load graph logger.info('loading graph from...
class TfPoseEstimator: # TODO : multi-scale
def __init__(self, graph_path, target_size=(320, 240), tf_config=None, trt_bool=False): self.target_size = target_size if _tf_pose_estimator_tensorrt_disabled: trt_bool = False # load graph logger.info('loading graph from %s(default size=%dx%d)' % (graph_path, target_si...
def __repr__(self): return self.__str__() class PoseEstimator: def __init__(self): pass @staticmethod def estimate_paf(peaks, heat_mat, paf_mat): pafprocess.process_paf(peaks, heat_mat, paf_mat) humans = [] for human_id in range(pafprocess.get_num_humans()): ...
256
256
3,352
12
243
shunya-toyokawa/pose_estimation_new
tf_pose/estimator.py
Python
TfPoseEstimator
TfPoseEstimator
309
591
309
311
1e149c148c55ec816e7ad4b2b936843961ea6aea
bigcode/the-stack
train
20210ab23996633cfc784ec0
train
function
def _include_part(part_list, part_idx): for part in part_list: if part_idx == part.part_idx: return True, part return False, None
def _include_part(part_list, part_idx):
for part in part_list: if part_idx == part.part_idx: return True, part return False, None
formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) logger.setLevel(logging.INFO) def _round(v): return int(round(v)) def _include_part(part_list, part_idx):
64
64
38
10
54
shunya-toyokawa/pose_estimation_new
tf_pose/estimator.py
Python
_include_part
_include_part
43
47
43
43
0a7371d6ec1b43c8d086151f6d5953299ca84c54
bigcode/the-stack
train
4484a71c41e794f864fe46c6
train
function
@core_swagger_router.get("/docs", include_in_schema=False, name="core_swagger") async def get_swagger(request: Request): swagger_ui_html = get_swagger_ui_html( openapi_url="openapi.json", title=request.app.title + " - Swagger UI", oauth2_redirect_url="/api/docs/oauth2-redirect", init...
@core_swagger_router.get("/docs", include_in_schema=False, name="core_swagger") async def get_swagger(request: Request):
swagger_ui_html = get_swagger_ui_html( openapi_url="openapi.json", title=request.app.title + " - Swagger UI", oauth2_redirect_url="/api/docs/oauth2-redirect", init_oauth={ "usePkceWithAuthorizationCodeGrant": True, "clientId": config.SWAGGER_UI_CLIENT_ID, ...
=config.API_DESCRIPTION, version=config.VERSION, routes=core_router.routes, tags=core_tags_metadata ) return openapi_definitions["core"] @core_swagger_router.get("/docs", include_in_schema=False, name="core_swagger") async def get_swagger(request: Request):
63
64
141
29
34
marrobi/AzureTRE
api_app/api/routes/api.py
Python
get_swagger
get_swagger
64
77
64
65
7564c67c8d73f41545e5db44933a348aa828e623
bigcode/the-stack
train
48670cfa0ff7a84aa415aaeb
train
function
@core_swagger_router.get('/docs/oauth2-redirect', include_in_schema=False) async def swagger_ui_redirect(): return get_swagger_ui_oauth2_redirect_html()
@core_swagger_router.get('/docs/oauth2-redirect', include_in_schema=False) async def swagger_ui_redirect():
return get_swagger_ui_oauth2_redirect_html()
_CLIENT_ID, "scopes": ["openid", "offline_access", f"api://{config.API_CLIENT_ID}/user_impersonation"] } ) return swagger_ui_html @core_swagger_router.get('/docs/oauth2-redirect', include_in_schema=False) async def swagger_ui_redirect():
64
64
36
24
39
marrobi/AzureTRE
api_app/api/routes/api.py
Python
swagger_ui_redirect
swagger_ui_redirect
80
82
80
81
1924561a98bce45a111ad44e720544c1cbfd7ace
bigcode/the-stack
train
be0e6cec11c685a1dbfb7d69
train
function
def get_scope(workspace) -> str: # Cope with the fact that scope id can have api:// at the front. return f"api://{workspace.properties['scope_id'].lstrip('api://')}/user_impersonation"
def get_scope(workspace) -> str: # Cope with the fact that scope id can have api:// at the front.
return f"api://{workspace.properties['scope_id'].lstrip('api://')}/user_impersonation"
(workspaces.workspace_services_workspace_router, tags=["workspace services"]) workspace_router.include_router(workspaces.user_resources_workspace_router, tags=["user resources"]) workspace_swagger_router = APIRouter() def get_scope(workspace) -> str: # Cope with the fact that scope id can have api:// at the front....
64
64
52
27
37
marrobi/AzureTRE
api_app/api/routes/api.py
Python
get_scope
get_scope
96
98
96
97
ae6a75fe1de493dcf805d9ea16550c7e8ea47631
bigcode/the-stack
train
d72ebe26c169399f53ec2bb6
train
function
@workspace_swagger_router.get("/workspaces/{workspace_id}/docs", include_in_schema=False, name="workspace_swagger") async def get_workspace_swagger(workspace_id, request: Request, workspace_repo=Depends(get_repository(WorkspaceRepository))): workspace = workspace_repo.get_workspace_by_id(workspace_id) scope = ...
@workspace_swagger_router.get("/workspaces/{workspace_id}/docs", include_in_schema=False, name="workspace_swagger") async def get_workspace_swagger(workspace_id, request: Request, workspace_repo=Depends(get_repository(WorkspaceRepository))):
workspace = workspace_repo.get_workspace_by_id(workspace_id) scope = get_scope(workspace) swagger_ui_html = get_swagger_ui_html( openapi_url="openapi.json", title=request.app.title + " - Swagger UI", oauth2_redirect_url="/api/docs/oauth2-redirect", init_oauth={ "u...
workspace_id return openapi_definitions[workspace_id] @workspace_swagger_router.get("/workspaces/{workspace_id}/docs", include_in_schema=False, name="workspace_swagger") async def get_workspace_swagger(workspace_id, request: Request, workspace_repo=Depends(get_repository(WorkspaceRepository))):
64
64
171
51
13
marrobi/AzureTRE
api_app/api/routes/api.py
Python
get_workspace_swagger
get_workspace_swagger
131
147
131
133
29cd537083722ffb0011b47bc609391bc061f624
bigcode/the-stack
train
fc91e5c65242cd1d72e483fa
train
function
@workspace_swagger_router.get("/workspaces/{workspace_id}/openapi.json", include_in_schema=False, name="openapi_definitions") async def get_openapi_json(workspace_id: str, request: Request, workspace_repo=Depends(get_repository(WorkspaceRepository))): global openapi_definitions if openapi_definitions[workspace...
@workspace_swagger_router.get("/workspaces/{workspace_id}/openapi.json", include_in_schema=False, name="openapi_definitions") async def get_openapi_json(workspace_id: str, request: Request, workspace_repo=Depends(get_repository(WorkspaceRepository))):
global openapi_definitions if openapi_definitions[workspace_id] is None: openapi_definitions[workspace_id] = get_openapi( title=f"{config.PROJECT_NAME} - Workspace {workspace_id}", description=config.API_DESCRIPTION, version=config.VERSION, routes=worksp...
api:// at the front. return f"api://{workspace.properties['scope_id'].lstrip('api://')}/user_impersonation" @workspace_swagger_router.get("/workspaces/{workspace_id}/openapi.json", include_in_schema=False, name="openapi_definitions") async def get_openapi_json(workspace_id: str, request: Request, workspace_repo=De...
87
87
290
56
31
marrobi/AzureTRE
api_app/api/routes/api.py
Python
get_openapi_json
get_openapi_json
101
128
101
102
3dc0daf9064e99b8962248d076a4b28faf7cfbaa
bigcode/the-stack
train
566097965301ffd5ef68c0b2
train
function
@core_swagger_router.get("/openapi.json", include_in_schema=False, name="core_openapi") async def core_openapi(request: Request): global openapi_definitions if openapi_definitions["core"] is None: openapi_definitions["core"] = get_openapi( title=f"{config.PROJECT_NAME}", descrip...
@core_swagger_router.get("/openapi.json", include_in_schema=False, name="core_openapi") async def core_openapi(request: Request):
global openapi_definitions if openapi_definitions["core"] is None: openapi_definitions["core"] = get_openapi( title=f"{config.PROJECT_NAME}", description=config.API_DESCRIPTION, version=config.VERSION, routes=core_router.routes, tags=core_tags...
igrations"]) core_swagger_router = APIRouter() openapi_definitions: DefaultDict[str, Optional[Dict[str, Any]]] = defaultdict(lambda: None) @core_swagger_router.get("/openapi.json", include_in_schema=False, name="core_openapi") async def core_openapi(request: Request):
64
64
108
31
33
marrobi/AzureTRE
api_app/api/routes/api.py
Python
core_openapi
core_openapi
48
61
48
49
2b446b497821a05d359c84b53b14c384ba6c901d
bigcode/the-stack
train
f925345c9144fe63cfb6c084
train
function
def _get_properties_schema(input_schema): properties_schema = input_schema.get('properties', None) if properties_schema is None: raise CLIError('unable to get properties from input schema') return properties_schema
def _get_properties_schema(input_schema):
properties_schema = input_schema.get('properties', None) if properties_schema is None: raise CLIError('unable to get properties from input schema') return properties_schema
if nms]))) from e break else: raise CLIError('--parameters missing required values: {}' .format(' | '.join([', '.join(nms) for nms in property_names_list if nms]))) return best_match def _get_properties_schema(input_schema):
64
64
45
8
55
microsoft/TeamCloud
client/tc/azext_tc/_input_utils.py
Python
_get_properties_schema
_get_properties_schema
85
91
85
85
971c4e936aad92d41364b72ee5737c36c9039522
bigcode/the-stack
train
cb34c514b5f6a1b44617b854
train
function
def _get_property_enums(property_schema): property_enums = property_schema.get('enum', None) property_enum_names = property_schema.get('enumNames', None) if property_enums is not None and property_enum_names is not None: allowed_values = [{ 'name': property_enum_names[index], ...
def _get_property_enums(property_schema):
property_enums = property_schema.get('enum', None) property_enum_names = property_schema.get('enumNames', None) if property_enums is not None and property_enum_names is not None: allowed_values = [{ 'name': property_enum_names[index], 'desc': item } for index, item i...
for t in property_types if t.lower() != 'null'), None) if property_type is None: raise CLIError("unable to resolve the type for input paramater '{}'".format(property_name)) property_type = property_type.lower() return property_type def _get_property_enums(property_schema):
64
64
104
9
54
microsoft/TeamCloud
client/tc/azext_tc/_input_utils.py
Python
_get_property_enums
_get_property_enums
126
138
126
126
9c89b880b2bc0a77ec5fe55247c1fd91b2649712
bigcode/the-stack
train
30ded31a898eff86e7011710
train
function
def _prompt_for_parameters(missing_parameters, ui_schema=None, fail_on_no_tty=True): # pylint: disable=too-many-branches prompt_list = missing_parameters.keys() if isinstance(missing_parameters, OrderedDict) \ else sorted(missing_parameters) result = OrderedDict() no_tty = False for property_n...
def _prompt_for_parameters(missing_parameters, ui_schema=None, fail_on_no_tty=True): # pylint: disable=too-many-branches
prompt_list = missing_parameters.keys() if isinstance(missing_parameters, OrderedDict) \ else sorted(missing_parameters) result = OrderedDict() no_tty = False for property_name in prompt_list: property_schema = missing_parameters[property_name] ui = ui_schema.get(property_name, ...
-schema/reference/object.html#additional-properties additional_properties = input_schema.get('additionalProperties', False) parameters = {} for params in parameter_lists or []: for item in params: if not _try_parse_key_value_object(properties_schema, parameters, item, additional_propert...
256
256
867
31
224
microsoft/TeamCloud
client/tc/azext_tc/_input_utils.py
Python
_prompt_for_parameters
_prompt_for_parameters
233
337
233
234
9e19acd83d1b407f47ff67293c67a4321ce08fbc
bigcode/the-stack
train
ba9393cc07eb30c741107a0c
train
function
def _get_best_match_one_of(input_schema, parameter_lists): def _get_parameter_keys(parameters_list): parameter_keys = [] for params in parameters_list or []: for item in params: try: key, _ = item.split('=', 1) parameter_keys.appen...
def _get_best_match_one_of(input_schema, parameter_lists):
def _get_parameter_keys(parameters_list): parameter_keys = [] for params in parameters_list or []: for item in params: try: key, _ = item.split('=', 1) parameter_keys.append(key) except ValueError: ...
-locals, too-many-statements from collections import OrderedDict from knack.log import get_logger # from knack.prompting import prompt_pass from knack.prompting import (prompt, prompt_t_f, prompt_choice_list, prompt_int, NoTTYException) from knack.util import CLIError from azure.cli.core....
144
144
482
13
130
microsoft/TeamCloud
client/tc/azext_tc/_input_utils.py
Python
_get_best_match_one_of
_get_best_match_one_of
24
82
24
25
6d1a6eba52c206e3b060e0fa7cf59f7009d6b621
bigcode/the-stack
train
14cb8a7785e1c8ea25eb94d4
train
function
def _get_property_schema(properties_schema, property_name): property_schema = properties_schema.get(property_name, None) if property_schema is None: return None, None # raise CLIError('unable to get properties from input schema') property_type = _get_property_type(property_schema, property...
def _get_property_schema(properties_schema, property_name):
property_schema = properties_schema.get(property_name, None) if property_schema is None: return None, None # raise CLIError('unable to get properties from input schema') property_type = _get_property_type(property_schema, property_name) return property_schema, property_type
ms]))) return best_match def _get_properties_schema(input_schema): properties_schema = input_schema.get('properties', None) if properties_schema is None: raise CLIError('unable to get properties from input schema') return properties_schema def _get_property_schema(properties_schema, propert...
64
64
72
11
52
microsoft/TeamCloud
client/tc/azext_tc/_input_utils.py
Python
_get_property_schema
_get_property_schema
94
103
94
94
986619c460f400c6be9d7cf01f5b92b8a7272e2d
bigcode/the-stack
train
3521be95e5a08064d96de1cd
train
function
def _get_missing_parameters(parameters, input_schema, prompt_fn, ui_schema=None, no_prompt=False): missing = _find_missing_parameters(parameters, input_schema) if missing: if no_prompt is True: logger.warning("Missing input parameters: %s ", ', '.join(sorted(missing.keys()))) else: ...
def _get_missing_parameters(parameters, input_schema, prompt_fn, ui_schema=None, no_prompt=False):
missing = _find_missing_parameters(parameters, input_schema) if missing: if no_prompt is True: logger.warning("Missing input parameters: %s ", ', '.join(sorted(missing.keys()))) else: try: prompt_parameters = prompt_fn(missing, ui_schema) f...
no_tty = True break if no_tty and fail_on_no_tty: raise NoTTYException return result # pylint: disable=redefined-outer-name def _get_missing_parameters(parameters, input_schema, prompt_fn, ui_schema=None, no_prompt=False):
64
64
138
21
42
microsoft/TeamCloud
client/tc/azext_tc/_input_utils.py
Python
_get_missing_parameters
_get_missing_parameters
341
354
341
341
840f8d8ca81e56a2c2449d5432fe0a878c005b46
bigcode/the-stack
train
4b961ea50afb71d6ea40e24d
train
function
def _find_missing_parameters(parameters, input_schema): if input_schema is None: return {} properties_schema = _get_properties_schema(input_schema) if properties_schema is None: return {} required_properties = input_schema.get('required', None) missing = OrderedDict() for prop...
def _find_missing_parameters(parameters, input_schema):
if input_schema is None: return {} properties_schema = _get_properties_schema(input_schema) if properties_schema is None: return {} required_properties = input_schema.get('required', None) missing = OrderedDict() for property_name in properties_schema: property_schema ...
_try_parse_key_value_object(properties_schema, parameters, item, additional_properties): raise CLIError('Unable to parse parameter: {}'.format(item)) _try_set_defaults(properties_schema, parameters) return parameters # pylint: disable=redefined-outer-name def _find_missing_parameters(parame...
64
64
128
10
53
microsoft/TeamCloud
client/tc/azext_tc/_input_utils.py
Python
_find_missing_parameters
_find_missing_parameters
212
230
212
212
2858adfa9702405b2f682cfdbab38443a62b0220
bigcode/the-stack
train
4b1e70bea6357721a72221b7
train
function
def _get_property_type(property_schema, property_name=None): property_name = property_schema.get('title', '') if property_name is None else property_name property_types = property_schema.get('type', None) if property_types is None: raise CLIError("unable to resolve the type for input paramater '{}'...
def _get_property_type(property_schema, property_name=None):
property_name = property_schema.get('title', '') if property_name is None else property_name property_types = property_schema.get('type', None) if property_types is None: raise CLIError("unable to resolve the type for input paramater '{}'".format(property_name)) # The type keyword may either b...
, None) if property_schema is None: return None, None # raise CLIError('unable to get properties from input schema') property_type = _get_property_type(property_schema, property_name) return property_schema, property_type def _get_property_type(property_schema, property_name=None):
64
64
180
12
51
microsoft/TeamCloud
client/tc/azext_tc/_input_utils.py
Python
_get_property_type
_get_property_type
106
123
106
106
2c2847b76640bd8b5a777d74a688d57dc092d8d2
bigcode/the-stack
train
e8713cf35cab402d370e1f0e
train
function
def _process_parameters(input_schema, parameter_lists): # pylint: disable=too-many-branches # def _try_parse_json_object(value): # try: # parsed = _remove_comments_from_json(value, False) # return parsed.get('parameters', parsed) # except Exception: # pylint: disable=broad...
def _process_parameters(input_schema, parameter_lists): # pylint: disable=too-many-branches # def _try_parse_json_object(value): # try: # parsed = _remove_comments_from_json(value, False) # return parsed.get('parameters', parsed) # except Exception: # pylint: disable=broad...
def _try_parse_key_value_object(properties_schema, parameters, value, addtl_properties=False): # support situation where empty JSON "{}" is provided if value == '{}' and not parameters: return True try: key, value = value.split('=', 1) except ValueError: ...
) property_enum_names = property_schema.get('enumNames', None) if property_enums is not None and property_enum_names is not None: allowed_values = [{ 'name': property_enum_names[index], 'desc': item } for index, item in enumerate(property_enums)] else: allowe...
166
166
556
83
82
microsoft/TeamCloud
client/tc/azext_tc/_input_utils.py
Python
_process_parameters
_process_parameters
141
208
141
149
0f7dc9907dea0524b6d763ee94128f43a5ff6842
bigcode/the-stack
train
71fecd51543f68fd37948e74
train
class
class ElementEntity(object): """ ElementEntity class holds elements for one block. """ def __init__(self): self.dimension_ = -1 self.tag_ = -1 self.element_type_ = -1 self.number_of_elements_ = -1 self.elements_ = {} def set_dimension(self, dimension: int): ...
class ElementEntity(object):
""" ElementEntity class holds elements for one block. """ def __init__(self): self.dimension_ = -1 self.tag_ = -1 self.element_type_ = -1 self.number_of_elements_ = -1 self.elements_ = {} def set_dimension(self, dimension: int): """Set the dimension of eleme...
from typing import List from io import StringIO from .element import Element class ElementEntity(object):
22
138
461
5
16
ahojukka5/gmshparser
gmshparser/element_entity.py
Python
ElementEntity
ElementEntity
6
67
6
7
bd92233ff4e4d3a867a9fae8e49984eb00e0bf28
bigcode/the-stack
train
97d1161e94d121535ee4171c
train
function
@pytest.mark.parametrize('spider_args,start_request_response,initial_url,results_pattern,expected', TEST_CASES) def test_urls(spider_args, start_request_response, initial_url, results_pattern, expected): response_mock = MagicMock() response_mock.request.url = initial_url response_mo...
@pytest.mark.parametrize('spider_args,start_request_response,initial_url,results_pattern,expected', TEST_CASES) def test_urls(spider_args, start_request_response, initial_url, results_pattern, expected):
response_mock = MagicMock() response_mock.request.url = initial_url response_mock.status = 200 response_mock.text = start_request_response test_spider = type('TestSpider', (IndexSpider,), spider_args) spider = spider_with_crawler(spider_class=test_spider) requests = [x for x in spider.par...
pageNumber=(\d+)&step=10', [str(x) for x in range(0, 10)]) ] @pytest.mark.parametrize('spider_args,start_request_response,initial_url,results_pattern,expected', TEST_CASES) def test_urls(spider_args, start_request_response, initial_url, results_pattern, expected):
70
70
234
43
27
sgaseretto/kingfisher-collect
tests/test_index_spider.py
Python
test_urls
test_urls
59
84
59
61
8aab5adc020c2d2225afe80334a3d3b3f94c60f8
bigcode/the-stack
train
1694aebde7a20b25618b820c
train
class
@override_settings(MEDIA_ROOT=TEST_MEDIA_ROOT) class MathematicalObjectNameListTests(APITestCase): def test_add_name(self): utils.log_as(self, utils.UserType.STAFF) mathematical_object = utils.create_mathematical_object(self) name = 'test_add_name' data = { 'name': nam...
@override_settings(MEDIA_ROOT=TEST_MEDIA_ROOT) class MathematicalObjectNameListTests(APITestCase):
def test_add_name(self): utils.log_as(self, utils.UserType.STAFF) mathematical_object = utils.create_mathematical_object(self) name = 'test_add_name' data = { 'name': name } response = self.client.post(reverse('api:mathematical_object_names', kwargs={'o...
from rest_framework import status from rest_framework.test import APITestCase from django.test import override_settings from django.urls import reverse from oems.settings import TEST_MEDIA_ROOT from api.models import Name from api.tests import utils @override_settings(MEDIA_ROOT=TEST_MEDIA_ROOT) class MathematicalObjec...
70
172
575
21
48
Gawaboumga/OEMS
api/tests/mathematical_object_name_list.py
Python
MathematicalObjectNameListTests
MathematicalObjectNameListTests
10
69
10
12
d82388fdffb7ac5986a83491b9402e5bd9a086f7
bigcode/the-stack
train
16793769e4e2139177152158
train
class
class TestGateSetConstructionMethods(BaseTestCase): def setUp(self): super(TestGateSetConstructionMethods, self).setUp() #OK for these tests, since we test user interface? #Set Model objects to "strict" mode for testing pygsti.models.ExplicitOpModel._strict = False def test_b...
class TestGateSetConstructionMethods(BaseTestCase):
def setUp(self): super(TestGateSetConstructionMethods, self).setUp() #OK for these tests, since we test user interface? #Set Model objects to "strict" mode for testing pygsti.models.ExplicitOpModel._strict = False def test_build_gatesets(self): SQ2 = 1/np.sqrt(2) ...
import unittest import numpy as np import pygsti from pygsti.models import modelconstruction from ..testutils import BaseTestCase class TestGateSetConstructionMethods(BaseTestCase):
39
228
760
10
28
colibri-coruscans/pyGSTi
test/test_packages/construction/testGateSetConstruction.py
Python
TestGateSetConstructionMethods
TestGateSetConstructionMethods
10
65
10
11
8a9df12eab3db8843f724a17626522004db09a14
bigcode/the-stack
train
227104ddef490c2e5a4468c8
train
function
def predictors(cd, cf_parser, outfmt): src_dirs = dict() packages_in_binx = os.listdir('{}/binx/'.format(cd)) preds, dirs = zip(*cf_parser.items('bin_directories')) missing_option_keys = set(packages_in_binx) - set(preds) if missing_option_keys: logging.error( 'One or more key...
def predictors(cd, cf_parser, outfmt):
src_dirs = dict() packages_in_binx = os.listdir('{}/binx/'.format(cd)) preds, dirs = zip(*cf_parser.items('bin_directories')) missing_option_keys = set(packages_in_binx) - set(preds) if missing_option_keys: logging.error( 'One or more keys necessary for output format <%s> are ...
import os import logging def predictors(cd, cf_parser, outfmt):
16
70
234
10
5
santosh653/interproscan
core/jms-implementation/support-mini-x86-32/bin/mobidb/2.0/mdblib/setdirs.py
Python
predictors
predictors
5
31
5
5
b890884e09275a787b7c637ac93e032594813af3
bigcode/the-stack
train
ff729ef3512e591af35fb81e
train
class
class MemoryReader(Reader): def __init__(self): super(MemoryReader, self).__init__() def get_padded_bytes(self, size): result = "\x00" * size ranges_left = [MemoryRange(self.address, self.address + size)] segment_count = idaapi.get_segm_qty() valid_memory_ranges = [] ...
class MemoryReader(Reader):
def __init__(self): super(MemoryReader, self).__init__() def get_padded_bytes(self, size): result = "\x00" * size ranges_left = [MemoryRange(self.address, self.address + size)] segment_count = idaapi.get_segm_qty() valid_memory_ranges = [] for i in range(segment...
from librgb.reader import Reader # Avoid complaints from __init__.py for CLI try: import idaapi import idc except ImportError: pass class MemoryRange(object): def __init__(self, start, end): self.start = start self.end = end def length(self): return self.end - self.start ...
138
151
505
6
132
rr-/ida-images
librgb/memory_reader.py
Python
MemoryReader
MemoryReader
25
101
25
25
1d2b7f40a249f5a695b61e9c977f94abd68faf68
bigcode/the-stack
train
77d994ba99f31fd30550e135
train
class
class MemoryRange(object): def __init__(self, start, end): self.start = start self.end = end def length(self): return self.end - self.start def __str__(self): return "start: %08x end: %08x" % (self.start, self.end)
class MemoryRange(object):
def __init__(self, start, end): self.start = start self.end = end def length(self): return self.end - self.start def __str__(self): return "start: %08x end: %08x" % (self.start, self.end)
from librgb.reader import Reader # Avoid complaints from __init__.py for CLI try: import idaapi import idc except ImportError: pass class MemoryRange(object):
42
64
70
5
36
rr-/ida-images
librgb/memory_reader.py
Python
MemoryRange
MemoryRange
11
20
11
11
9673d1f7aab304f93134fa8debf129134a288781
bigcode/the-stack
train
8f789eb3b0b1d680e9dbd7db
train
class
class Action: def __init__(self): self.connection = Connection() self.banknotes = BankNotes() self.cashbank = CashBank() self.address = Address() self.people = People() def create(self): self.banknotes.twenty = 20 self.banknotes.fifty = 50 self.b...
class Action:
def __init__(self): self.connection = Connection() self.banknotes = BankNotes() self.cashbank = CashBank() self.address = Address() self.people = People() def create(self): self.banknotes.twenty = 20 self.banknotes.fifty = 50 self.banknotes.hundre...
from MongoDB.POO.app.services.connection import Connection from MongoDB.POO.app.orm.Cash_bank.models import CashBank from MongoDB.POO.app.orm.Bank_notes.models import BankNotes from MongoDB.POO.app.orm.People.models import People from MongoDB.POO.app.orm.Addresses.models import Address class Action:
69
74
249
3
65
Renanrbsc/Non_Relational_Databases
MongoDB/POO/app/services/actions.py
Python
Action
Action
8
46
8
9
a4b5801342e49859f6d469804f85226e44f96187
bigcode/the-stack
train
177b617855db6037ba032401
train
class
class CanvasBackend(_Window, BaseCanvasBackend): """ Pyglet backend for Canvas abstract class.""" def __init__(self, **kwargs): BaseCanvasBackend.__init__(self, capability, SharedContext) title, size, position, show, vsync, resize, dec, fs, parent, context, \ vispy_canvas = self._p...
class CanvasBackend(_Window, BaseCanvasBackend):
""" Pyglet backend for Canvas abstract class.""" def __init__(self, **kwargs): BaseCanvasBackend.__init__(self, capability, SharedContext) title, size, position, show, vsync, resize, dec, fs, parent, context, \ vispy_canvas = self._process_backend_kwargs(kwargs) self._vispy_...
_config.accum_alpha_size = 0 pyglet_config.depth_size = config['depth_size'] pyglet_config.stencil_size = config['stencil_size'] pyglet_config.double_buffer = config['double_buffer'] pyglet_config.stereo = config['stereo'] pyglet_config.samples = config['samples'] return pyglet_config class S...
255
256
2,045
10
245
shjoshi/vispy
vispy/app/backends/_pyglet.py
Python
CanvasBackend
CanvasBackend
167
421
167
168
0e6e6839785838cb2cd0d7a42d89413d2acdbaba
bigcode/the-stack
train
c1ce5b0f6cd83c38258c43f9
train
class
class SharedContext(BaseSharedContext): _backend = 'pyglet'
class SharedContext(BaseSharedContext):
_backend = 'pyglet'
depth_size'] pyglet_config.stencil_size = config['stencil_size'] pyglet_config.double_buffer = config['double_buffer'] pyglet_config.stereo = config['stereo'] pyglet_config.samples = config['samples'] return pyglet_config class SharedContext(BaseSharedContext):
64
64
16
7
56
shjoshi/vispy
vispy/app/backends/_pyglet.py
Python
SharedContext
SharedContext
133
134
133
133
3f44822a51b818ec4807d063b805b21c2b4187aa
bigcode/the-stack
train
d44c1107b021ae6206788f8d
train
class
class ApplicationBackend(BaseApplicationBackend): def __init__(self): BaseApplicationBackend.__init__(self) def _vispy_get_backend_name(self): return 'Pyglet' def _vispy_process_events(self): # pyglet.app.platform_event_loop.step(0.0) pyglet.clock.tick() for window...
class ApplicationBackend(BaseApplicationBackend):
def __init__(self): BaseApplicationBackend.__init__(self) def _vispy_get_backend_name(self): return 'Pyglet' def _vispy_process_events(self): # pyglet.app.platform_event_loop.step(0.0) pyglet.clock.tick() for window in pyglet.app.windows: window.switch_t...
_buffer = config['double_buffer'] pyglet_config.stereo = config['stereo'] pyglet_config.samples = config['samples'] return pyglet_config class SharedContext(BaseSharedContext): _backend = 'pyglet' # ------------------------------------------------------------- application --- class ApplicationBacken...
63
64
143
7
56
shjoshi/vispy
vispy/app/backends/_pyglet.py
Python
ApplicationBackend
ApplicationBackend
139
162
139
140
94bc657bbd88c4196aa26a39eeaff3d4e065002e
bigcode/the-stack
train