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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
760cfda56830be3c0b408e97 | train | class | class InstrumentsServiceStub(object):
"""Сервис предназначен для получения:</br>**1**. информации об инструментах;</br>**2**.
расписания торговых сессий;</br>**3**. календаря выплат купонов по облигациям;</br>**4**.
размера гарантийного обеспечения по фьючерсам;</br>**5**. дивидендов по ценной бумаге.
"... | class InstrumentsServiceStub(object):
| """Сервис предназначен для получения:</br>**1**. информации об инструментах;</br>**2**.
расписания торговых сессий;</br>**3**. календаря выплат купонов по облигациям;</br>**4**.
размера гарантийного обеспечения по фьючерсам;</br>**5**. дивидендов по ценной бумаге.
"""
def __init__(self, channel):
... | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from tinkoff.invest.grpc import instruments_pb2 as tinkoff_dot_invest_dot_grpc_dot_instruments__pb2
class InstrumentsServiceStub(object):
| 61 | 256 | 1,380 | 6 | 54 | kordimsan/invest-python | tinkoff/invest/grpc/instruments_pb2_grpc.py | Python | InstrumentsServiceStub | InstrumentsServiceStub | 8 | 94 | 8 | 8 | 6cb92df340382fd4bc59d488db25812127f9504c | bigcode/the-stack | train |
0dca04bd6ffe3c3c10afcff3 | train | class | class InstrumentsService(object):
"""Сервис предназначен для получения:</br>**1**. информации об инструментах;</br>**2**.
расписания торговых сессий;</br>**3**. календаря выплат купонов по облигациям;</br>**4**.
размера гарантийного обеспечения по фьючерсам;</br>**5**. дивидендов по ценной бумаге.
"""
... | class InstrumentsService(object):
| """Сервис предназначен для получения:</br>**1**. информации об инструментах;</br>**2**.
расписания торговых сессий;</br>**3**. календаря выплат купонов по облигациям;</br>**4**.
размера гарантийного обеспечения по фьючерсам;</br>**5**. дивидендов по ценной бумаге.
"""
@staticmethod
def TradingS... | struments__pb2.GetFuturesMarginRequest.FromString,
response_serializer=tinkoff_dot_invest_dot_grpc_dot_instruments__pb2.GetFuturesMarginResponse.SerializeToString,
),
'GetInstrumentBy': grpc.unary_unary_rpc_method_handler(
servicer.GetInstrumentBy,
... | 256 | 256 | 2,278 | 5 | 251 | kordimsan/invest-python | tinkoff/invest/grpc/instruments_pb2_grpc.py | Python | InstrumentsService | InstrumentsService | 293 | 552 | 293 | 293 | 03474423ca223e02c3911ea297b79f9f92707531 | bigcode/the-stack | train |
47505f4e57ff9b98bdd1186a | train | class | class InstrumentsServiceServicer(object):
"""Сервис предназначен для получения:</br>**1**. информации об инструментах;</br>**2**.
расписания торговых сессий;</br>**3**. календаря выплат купонов по облигациям;</br>**4**.
размера гарантийного обеспечения по фьючерсам;</br>**5**. дивидендов по ценной бумаге.
... | class InstrumentsServiceServicer(object):
| """Сервис предназначен для получения:</br>**1**. информации об инструментах;</br>**2**.
расписания торговых сессий;</br>**3**. календаря выплат купонов по облигациям;</br>**4**.
размера гарантийного обеспечения по фьючерсам;</br>**5**. дивидендов по ценной бумаге.
"""
def TradingSchedules(self, req... | (
'/tinkoff.public.invest.api.contract.v1.InstrumentsService/GetFuturesMargin',
request_serializer=tinkoff_dot_invest_dot_grpc_dot_instruments__pb2.GetFuturesMarginRequest.SerializeToString,
response_deserializer=tinkoff_dot_invest_dot_grpc_dot_instruments__pb2.GetFutures... | 256 | 256 | 956 | 7 | 249 | kordimsan/invest-python | tinkoff/invest/grpc/instruments_pb2_grpc.py | Python | InstrumentsServiceServicer | InstrumentsServiceServicer | 97 | 206 | 97 | 97 | 3450a497749dbce04d62242be1d74112e087cfc1 | bigcode/the-stack | train |
a226056942d952f75a141fe1 | train | function | def add_InstrumentsServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'TradingSchedules': grpc.unary_unary_rpc_method_handler(
servicer.TradingSchedules,
request_deserializer=tinkoff_dot_invest_dot_grpc_dot_instruments__pb2.TradingSchedulesReques... | def add_InstrumentsServiceServicer_to_server(servicer, server):
| rpc_method_handlers = {
'TradingSchedules': grpc.unary_unary_rpc_method_handler(
servicer.TradingSchedules,
request_deserializer=tinkoff_dot_invest_dot_grpc_dot_instruments__pb2.TradingSchedulesRequest.FromString,
response_serializer=tinkoff_do... | AccruedInterests(self, request, context):
"""Метод получения накопленного купонного дохода по облигации.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def GetFuturesMarg... | 255 | 256 | 1,179 | 14 | 242 | kordimsan/invest-python | tinkoff/invest/grpc/instruments_pb2_grpc.py | Python | add_InstrumentsServiceServicer_to_server | add_InstrumentsServiceServicer_to_server | 209 | 289 | 209 | 209 | 17159c21f134361af260dac62f50d9afde5ae0f6 | bigcode/the-stack | train |
a52b762b792460861cd9e303 | train | function | def TFGenModelData(gen_pb_model=True):
os.environ["CUDA_VISIBLE_DEVICES"] = ''
with tf.Session(graph=tf.Graph()) as sess:
'''
STEP 1: plz input the tensor shapes
shapes must be 4D, and the first dim means batch_size
'''
shape_x = (7, 2, 3, 4)
shape_y = (7, 2, 3, ... | def TFGenModelData(gen_pb_model=True):
| os.environ["CUDA_VISIBLE_DEVICES"] = ''
with tf.Session(graph=tf.Graph()) as sess:
'''
STEP 1: plz input the tensor shapes
shapes must be 4D, and the first dim means batch_size
'''
shape_x = (7, 2, 3, 4)
shape_y = (7, 2, 3, 4)
coor_x = tf.placeholder(tf.f... | , SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#... | 153 | 154 | 515 | 10 | 143 | huaweiatlasTest/AtkOps | get_tf_model_and_data.py | Python | TFGenModelData | TFGenModelData | 43 | 98 | 43 | 43 | ddb95e34e6cca2588f027cf2f43940309bc54603 | bigcode/the-stack | train |
855146bb41c9e258ace1f5c3 | train | function | def data_send():
counter = 0
while True:
LIST_DIR = os.listdir('./device-video')
SORTED_DIR = [ int(x.split('.')[0]) for x in LIST_DIR]
SORTED_DIR.sort()
SORTED_DIR = [ str(x) + '.h264' for x in SORTED_DIR]
LENGTH = len(LIST_DIR)
if LENGTH > 1 and LENGTH > coun... | def data_send():
| counter = 0
while True:
LIST_DIR = os.listdir('./device-video')
SORTED_DIR = [ int(x.split('.')[0]) for x in LIST_DIR]
SORTED_DIR.sort()
SORTED_DIR = [ str(x) + '.h264' for x in SORTED_DIR]
LENGTH = len(LIST_DIR)
if LENGTH > 1 and LENGTH > counter:
... | 264')
camera.wait_recording(2)
counter = 1
while True:
counter += 1
camera.split_recording('./device-video/%d.h264' % counter)
camera.wait_recording(2)
camera.stop_recording()
#### DEVICE ####
def data_send():
| 64 | 64 | 150 | 4 | 59 | Haabibi/Realtime_Action_Recognition | realtime-recognition/rpc_video_h264_streaming.py | Python | data_send | data_send | 32 | 48 | 32 | 32 | 671d502dd6288bb16deb2fef53b40d725cc6b22d | bigcode/the-stack | train |
7e6c6c07bec528acddf7b2fa | train | function | def receive_and_save(rgb_net, redis):
counter = 1
frames_to_run = []
while True:
initial_time = time.time()
if redis.llen('Frame') > 0:
start_redis = time.time()
incoming_video = redis.lpop('Frame')
stop_redis = time.time()
print("TYPE OF FRAM... | def receive_and_save(rgb_net, redis):
| counter = 1
frames_to_run = []
while True:
initial_time = time.time()
if redis.llen('Frame') > 0:
start_redis = time.time()
incoming_video = redis.lpop('Frame')
stop_redis = time.time()
print("TYPE OF FRAME: ", type(incoming_video), "Popping T... | = os.path.join('/home/pi/venv/video', item)
read_file = open(PATH, 'rb')
encoding = read_file.read()
if encoding != b'':
send('Frame', encoding)
counter += 1
#### HUB ####
def receive_and_save(rgb_net, redis):
| 64 | 64 | 213 | 9 | 54 | Haabibi/Realtime_Action_Recognition | realtime-recognition/rpc_video_h264_streaming.py | Python | receive_and_save | receive_and_save | 50 | 71 | 50 | 50 | e06478e504e38470845374eea36b331b7f95c0b8 | bigcode/the-stack | train |
6f5bf64fa2bd9ee811886e9f | train | function | def read_file_and_run():
counter = 0
while True:
LIST_DIR = sorted(os.listdir('./video'))
SORTED_DIR = [ int(x.split('.')[0]) for x in LIST_DIR]
SORTED_DIR.sort()
SORTED_DIR = [ str(x) + '.h264' for x in SORTED_DIR ]
LENGTH = len(LIST_DIR)
if LENGTH > 1 and LENGTH... | def read_file_and_run():
| counter = 0
while True:
LIST_DIR = sorted(os.listdir('./video'))
SORTED_DIR = [ int(x.split('.')[0]) for x in LIST_DIR]
SORTED_DIR.sort()
SORTED_DIR = [ str(x) + '.h264' for x in SORTED_DIR ]
LENGTH = len(LIST_DIR)
if LENGTH > 1 and LENGTH > counter:
i... | time.time()
f = open('./video/%d.h264'%counter, 'wb+')
opened = time.time()
f.write(video)
write_file = time.time()
#f.write(video.encode('utf-8'))
print("[Pickle Loading Time: ]", end_load-start_load)
print("[Video Open Time: ]", open... | 107 | 107 | 359 | 6 | 100 | Haabibi/Realtime_Action_Recognition | realtime-recognition/rpc_video_h264_streaming.py | Python | read_file_and_run | read_file_and_run | 74 | 108 | 74 | 74 | 3e662a0461958d56935146dd6767f532875140e8 | bigcode/the-stack | train |
0baf64c72a42ed45bf2166a6 | train | function | def streaming():
while True:
with picamera.PiCamera() as camera:
camera.resolution = (224, 224)
camera.framerate = 40
camera.start_recording('./device-video/1.h264')
camera.wait_recording(2)
counter = 1
while True:
coun... | def streaming():
| while True:
with picamera.PiCamera() as camera:
camera.resolution = (224, 224)
camera.framerate = 40
camera.start_recording('./device-video/1.h264')
camera.wait_recording(2)
counter = 1
while True:
counter += 1
... | Event
import cv2
import numpy as np
from redis import Redis
import pickle
import torch
from models import TSN
from baseline_rpc_rgb import make_ucf, make_infer, make_hmdb
from sklearn.metrics import confusion_matrix
import os
#### DEVIVCE ####
def streaming():
| 64 | 64 | 105 | 3 | 60 | Haabibi/Realtime_Action_Recognition | realtime-recognition/rpc_video_h264_streaming.py | Python | streaming | streaming | 17 | 29 | 17 | 17 | 6f4599dd1ad36c3f048411d329bd24e5a34e17cf | bigcode/the-stack | train |
66f3a885fe2b7b0efc861783 | train | class | class Pet(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, id: int=None, category: Category=None, name: str=None, photo_urls: List[str]=None, tags: List[Tag]=None, status: str=None): # noqa: E501
"""Pet... | class Pet(Model):
| """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, id: int=None, category: Category=None, name: str=None, photo_urls: List[str]=None, tags: List[Tag]=None, status: str=None): # noqa: E501
"""Pet - a model defined... | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class Pet(Model):
| 61 | 256 | 1,212 | 4 | 56 | Nirostar/swagger-codegen | samples/server/petstore/flaskConnexion/swagger_server/models/pet.py | Python | Pet | Pet | 12 | 206 | 12 | 12 | 7edeb7a4a71c9cb7396dab2c890dbfae4242d397 | bigcode/the-stack | train |
75d45ba5b2a2f1df8927ede3 | train | class | class MARTE_CONFIG(Device):
"""MARTe configuration"""
parts=[{'path':':COMMENT', 'type':'text'},
{'path':':CONFIG', 'type':'numeric', 'value':0},
{'path':':DEC_GAIN', 'type':'numeric', 'value':0},
{'path':':COMP_RS_GAIN', 'type':'numeric', 'value':0},
{'path':':KP', 'type':'numeric', 'va... | class MARTE_CONFIG(Device):
| """MARTe configuration"""
parts=[{'path':':COMMENT', 'type':'text'},
{'path':':CONFIG', 'type':'numeric', 'value':0},
{'path':':DEC_GAIN', 'type':'numeric', 'value':0},
{'path':':COMP_RS_GAIN', 'type':'numeric', 'value':0},
{'path':':KP', 'type':'numeric', 'value':0},
{'path':':KI'... | OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# -*- coding: iso-8859-1 -*-
from MDSpl... | 87 | 87 | 293 | 6 | 80 | consorzio-rfx/mdsplus | pydevices/RfxDevices/MARTE_CONFIG.py | Python | MARTE_CONFIG | MARTE_CONFIG | 29 | 45 | 29 | 29 | 238009fa23c2826f4deaa80ac39a551c960c508c | bigcode/the-stack | train |
52e77e7265921d75f56310b1 | train | class | class SearchInstitutions(BaseSearchView):
"""
*Read-Only*
Institutions that have been found by the given Elasticsearch query.
<!-- Copied spiel from InstitutionDetail -->
##Attributes
OSF Institutions have the "institutions" `type`.
name type description
... | class SearchInstitutions(BaseSearchView):
| """
*Read-Only*
Institutions that have been found by the given Elasticsearch query.
<!-- Copied spiel from InstitutionDetail -->
##Attributes
OSF Institutions have the "institutions" `type`.
name type description
======================================... | -- page number of results to view, default 1
# This Request/Response
"""
model_class = OSFUser
serializer_class = UserSerializer
doc_type = 'user'
view_category = 'search'
view_name = 'search-user'
class SearchInstitutions(BaseSearchView):
| 66 | 66 | 220 | 8 | 58 | shun-nakazawa/RDM-osf.io | api/search/views.py | Python | SearchInstitutions | SearchInstitutions | 586 | 626 | 586 | 586 | a8c74cb0fb550a8d41feb1152caae20f88aef576 | bigcode/the-stack | train |
51e315118684aaf6f03959da | train | class | class SearchRegistrations(BaseSearchView):
"""
*Read-Only*
Registrations that have been found by the given Elasticsearch query.
<!--- Copied spiel from RegistrationDetail -->
Node Registrations.
Registrations are read-only snapshots of a project. This view is a list of all current registrati... | class SearchRegistrations(BaseSearchView):
| """
*Read-Only*
Registrations that have been found by the given Elasticsearch query.
<!--- Copied spiel from RegistrationDetail -->
Node Registrations.
Registrations are read-only snapshots of a project. This view is a list of all current registrations for which a user
has access. A wit... | in the
`/parent/links/related/href` key. Otherwise, it will be null.
###Registrations
List of registrations of the current node.
###Root
Returns the top-level node associated with the current node. If the current node is the top-level node, the root is
the current node.
##Links
... | 239 | 239 | 799 | 8 | 231 | shun-nakazawa/RDM-osf.io | api/search/views.py | Python | SearchRegistrations | SearchRegistrations | 433 | 519 | 433 | 433 | 402d6a310ac1da0b5248a4af6822f9841116f0a3 | bigcode/the-stack | train |
2cef3fed8f46f4c8a93a5f7d | train | class | class Search(BaseSearchView):
"""
*Read-Only*
Objects (including projects, components, registrations, users, files, and institutions) that have been found by the given
Elasticsearch query. Each object is serialized with the appropriate serializer for its type (files are serialized as
files, users a... | class Search(BaseSearchView):
| """
*Read-Only*
Objects (including projects, components, registrations, users, files, and institutions) that have been found by the given
Elasticsearch query. Each object is serialized with the appropriate serializer for its type (files are serialized as
files, users are serialized as users, etc.) ... | ['PAGE_SIZE'])), MAX_PAGE_SIZE)
start = (page - 1) * page_size
try:
results = search.search(build_query(query, start=start, size=page_size), doc_type=self.doc_type, raw=True)
except MalformedQueryError as e:
raise ValidationError(e.message)
return results
class Se... | 77 | 77 | 257 | 6 | 70 | shun-nakazawa/RDM-osf.io | api/search/views.py | Python | Search | Search | 53 | 86 | 53 | 53 | 17744548fe82688e98002eda2b86f6d27496ae89 | bigcode/the-stack | train |
2a10712ab3e71d8cc35eb777 | train | class | class BaseSearchView(JSONAPIBaseView, generics.ListAPIView):
required_read_scopes = [CoreScopes.SEARCH]
required_write_scopes = [CoreScopes.NULL]
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
pagination_class = SearchPagination... | class BaseSearchView(JSONAPIBaseView, generics.ListAPIView):
| required_read_scopes = [CoreScopes.SEARCH]
required_write_scopes = [CoreScopes.NULL]
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
pagination_class = SearchPagination
def __init__(self):
super(BaseSearchView, self).... | from framework.auth.oauth_scopes import CoreScopes
from osf.models import Institution, BaseFileNode, AbstractNode, OSFUser
from website.search import search
from website.search.exceptions import MalformedQueryError
from website.search.util import build_query
class BaseSearchView(JSONAPIBaseView, generics.ListAPIView):... | 66 | 66 | 222 | 14 | 51 | shun-nakazawa/RDM-osf.io | api/search/views.py | Python | BaseSearchView | BaseSearchView | 25 | 50 | 25 | 26 | 35456a6ad3f61bb4dbc5a316044490877cee8d0d | bigcode/the-stack | train |
499b86165bf4fe60b6a86a1d | train | class | class SearchComponents(BaseSearchView):
"""
*Read-Only*
Components that have been found by the given Elasticsearch query.
<!--- Copied piel from NodeDetail -->
On the front end, nodes are considered 'projects' or 'components'. The difference between a project and a component
is that a project... | class SearchComponents(BaseSearchView):
| """
*Read-Only*
Components that have been found by the given Elasticsearch query.
<!--- Copied piel from NodeDetail -->
On the front end, nodes are considered 'projects' or 'components'. The difference between a project and a component
is that a project is the top-level node, and components a... | *Read-Only*
Objects (including projects, components, registrations, users, files, and institutions) that have been found by the given
Elasticsearch query. Each object is serialized with the appropriate serializer for its type (files are serialized as
files, users are serialized as users, etc.) and retu... | 256 | 256 | 969 | 7 | 249 | shun-nakazawa/RDM-osf.io | api/search/views.py | Python | SearchComponents | SearchComponents | 89 | 201 | 89 | 89 | 0baaf7a0594f2d341c4dba9d83aed3150d733b94 | bigcode/the-stack | train |
a41c7281cfdbbd6757ef0e55 | train | class | class SearchFiles(BaseSearchView):
"""
*Read-Only*
Files that have been found by the given Elasticsearch query.
<!-- Copied attributes from FileDetail -->
####File Entity
name type description
========================================================================... | class SearchFiles(BaseSearchView):
| """
*Read-Only*
Files that have been found by the given Elasticsearch query.
<!-- Copied attributes from FileDetail -->
####File Entity
name type description
=========================================================================
guid string ... | this node is a child node of another node, the parent's canonical endpoint will be available in the
`/parent/links/related/href` key. Otherwise, it will be null.
###Registrations
List of registrations of the current node.
###Root
Returns the top-level node associated with the current node. If... | 256 | 256 | 1,173 | 7 | 249 | shun-nakazawa/RDM-osf.io | api/search/views.py | Python | SearchFiles | SearchFiles | 204 | 314 | 204 | 204 | 8310ad6c4e0f5cd2895b3dd77b9c1451a03d9d99 | bigcode/the-stack | train |
33b774b556310a974e135df1 | train | class | class SearchUsers(BaseSearchView):
"""
*Read-Only*
Users that have been found by the given Elasticsearch query.
<!-- Copied spiel from UserDetail -->
The User Detail endpoint retrieves information about the user whose id is the final part of the path. If `me`
is given as the id, the record o... | class SearchUsers(BaseSearchView):
| """
*Read-Only*
Users that have been found by the given Elasticsearch query.
<!-- Copied spiel from UserDetail -->
The User Detail endpoint retrieves information about the user whose id is the final part of the path. If `me`
is given as the id, the record of the currently logged-in user will... | . A registration has many of the same properties as a node.
##Links
See the [JSON-API spec regarding pagination](http://jsonapi.org/format/1.0/#fetching-pagination).
## Query Params
+ `q=<Str>` -- Query to search registrations for, searches across a registration's title, description, tags, and cont... | 150 | 150 | 502 | 7 | 143 | shun-nakazawa/RDM-osf.io | api/search/views.py | Python | SearchUsers | SearchUsers | 522 | 583 | 522 | 522 | 6fbae29648d6f3357c176a5e9ea9b304ae388c94 | bigcode/the-stack | train |
0c4917bc8e3be7b0e3550a8f | train | class | class SearchProjects(BaseSearchView):
"""
*Read-Only*
Projects that have been found by the given Elasticsearch query.
<!--- Copied spiel from NodeDetail -->
On the front end, nodes are considered 'projects' or 'components'. The difference between a project and a component
is that a project is... | class SearchProjects(BaseSearchView):
| """
*Read-Only*
Projects that have been found by the given Elasticsearch query.
<!--- Copied spiel from NodeDetail -->
On the front end, nodes are considered 'projects' or 'components'. The difference between a project and a component
is that a project is the top-level node, and components ar... | The `files` endpoint lists all of the subfiles and folders of the current folder. Will be null for files.
###Versions (*files*)
The `versions` endpoint provides version history for files. Will be null for folders.
##Links
info: the canonical api endpoint for the folder's contents or ... | 256 | 256 | 968 | 7 | 249 | shun-nakazawa/RDM-osf.io | api/search/views.py | Python | SearchProjects | SearchProjects | 317 | 430 | 317 | 317 | 2f22ee7ebbe079a98fd91e0a1f776bf2aad4c703 | bigcode/the-stack | train |
186d09987522397598e2415a | train | class | class ComplementOperator(BaseRSEOperator):
"""
Representation of the complement operator
"""
def __init__(self):
"""
Create a ComplementOperator representation
"""
self.left_term = None
self.right_term = None
def set_left_term(self, left_term):
"""
... | class ComplementOperator(BaseRSEOperator):
| """
Representation of the complement operator
"""
def __init__(self):
"""
Create a ComplementOperator representation
"""
self.left_term = None
self.right_term = None
def set_left_term(self, left_term):
"""
Inherited from :py:func:`BaseRSEOpe... | :param left_term: Left term
"""
pass
@abc.abstractmethod
def set_right_term(self, right_term):
"""
Set the right site of the term
:param left_term: Left term
"""
pass
class ComplementOperator(BaseRSEOperator):
| 65 | 65 | 218 | 8 | 56 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | ComplementOperator | ComplementOperator | 376 | 407 | 376 | 376 | 99e670562aa12c230b7d37feedee19d85715d620 | bigcode/the-stack | train |
bafb61614e37abead519fa51 | train | class | @add_metaclass(abc.ABCMeta)
class BaseExpressionElement:
@abc.abstractmethod
def resolve_elements(self, session):
"""
Resolve the ExpressionElement and return a set of RSE ids
:param session: Database session in use
:returns: (Set of RSE ids, Dictionary of RSE dicts)
... | @add_metaclass(abc.ABCMeta)
class BaseExpressionElement:
@abc.abstractmethod
| def resolve_elements(self, session):
"""
Resolve the ExpressionElement and return a set of RSE ids
:param session: Database session in use
:returns: (Set of RSE ids, Dictionary of RSE dicts)
:rtype: (Set of Strings, Dictionary of RSE dicts organized by rse_i... | 1
if (open_parantheses == 0):
return expression[1:i]
i = i + 1
raise SystemError('This point in the code should not be reachable')
@add_metaclass(abc.ABCMeta)
class BaseExpressionElement:
@abc.abstractmethod
| 64 | 64 | 102 | 21 | 43 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | BaseExpressionElement | BaseExpressionElement | 225 | 236 | 225 | 227 | f977e25ecce457d9ce3b60dbc924197c8379900c | bigcode/the-stack | train |
d608b71929478c3a75921a4d | train | class | class RSEAttributeLargerCheck(BaseExpressionElement):
"""
Representation of an RSE Attribute with Larger (>) Check
"""
def __init__(self, key, value=True):
"""
Creates an RSEAttribute representation
:param key: Key of the RSE Attribute.
:param value: V... | class RSEAttributeLargerCheck(BaseExpressionElement):
| """
Representation of an RSE Attribute with Larger (>) Check
"""
def __init__(self, key, value=True):
"""
Creates an RSEAttribute representation
:param key: Key of the RSE Attribute.
:param value: Value of the RSE Attribute.
"""
self.ke... | =self.key, rse_id=rse['id'], session=session)[0]) < float(self.value):
rse_dict[rse['id']] = rse
output.append(rse['id'])
except ValueError:
continue
return (set(output), rse_dict)
class RSEAttributeLargerCheck(BaseExpressionElement):
| 71 | 71 | 238 | 11 | 60 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | RSEAttributeLargerCheck | RSEAttributeLargerCheck | 320 | 352 | 320 | 320 | b9db48ae54f4023b96c90be42a59d0e708cd4b53 | bigcode/the-stack | train |
5427be1dc93e0f447b07519c | train | class | @add_metaclass(abc.ABCMeta)
class BaseRSEOperator(BaseExpressionElement):
@abc.abstractmethod
def set_left_term(self, left_term):
"""
Set the left site of the term
:param left_term: Left term
"""
pass
@abc.abstractmethod
def set_right_term(self, right_term):
... | @add_metaclass(abc.ABCMeta)
class BaseRSEOperator(BaseExpressionElement):
@abc.abstractmethod
| def set_left_term(self, left_term):
"""
Set the left site of the term
:param left_term: Left term
"""
pass
@abc.abstractmethod
def set_right_term(self, right_term):
"""
Set the right site of the term
:param left_term: Left term
"""... | rse_dict[rse['id']] = rse
output.append(rse['id'])
except ValueError:
continue
return (set(output), rse_dict)
@add_metaclass(abc.ABCMeta)
class BaseRSEOperator(BaseExpressionElement):
@abc.abstractmethod
| 64 | 64 | 103 | 25 | 39 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | BaseRSEOperator | BaseRSEOperator | 355 | 373 | 355 | 357 | 6cd7d6e07c1ed31cf22d8703d7e92721ba115799 | bigcode/the-stack | train |
d7b939be159a0a38b63dc5d7 | train | function | @transactional_session
def parse_expression(expression, filter=None, session=None):
"""
Parse a RSE expression and return the list of RSE dictionaries.
:param expression: RSE expression, e.g: 'CERN|BNL'.
:param filter: Availability filter (dictionary) used for the RSEs. e.g.: {'availability_w... | @transactional_session
def parse_expression(expression, filter=None, session=None):
| """
Parse a RSE expression and return the list of RSE dictionaries.
:param expression: RSE expression, e.g: 'CERN|BNL'.
:param filter: Availability filter (dictionary) used for the RSEs. e.g.: {'availability_write': True}
:param session: Database session in use.
:returns: ... | 0-9_-]+)'
PRIMITIVE = r'(\(*(%s|%s|%s)\)*)' % (RSE_ATTRIBUTE, DEFAULT_RSE_ATTRIBUTE, r'\*')
UNION = r'(\|%s)' % (PRIMITIVE)
INTERSECTION = r'(\&%s)' % (PRIMITIVE)
COMPLEMENT = r'(\\%s)' % (PRIMITIVE)
PATTERN = r'^%s(%s|%s|%s)*' % (PRIMITIVE, UNION, INTERSECTION, COMPLEMENT)
REGION = make_region().configure('dogpile.... | 188 | 188 | 629 | 16 | 172 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | parse_expression | parse_expression | 57 | 124 | 57 | 58 | 51e4e74132bbb9832ba1ee40d3c6eb207d271f43 | bigcode/the-stack | train |
6e35b653b8d3180b9d8d3d64 | train | function | def __resolve_primitive_expression(expression):
"""
Resolve a primitive expression and return a RSEAttribute object
:param expression: String of the expresssion
:returns: Tuple of RSEAttribute, primitive expression
"""
primitiveexpression = re.match(PRIMITIVE, expression).group()... | def __resolve_primitive_expression(expression):
| """
Resolve a primitive expression and return a RSEAttribute object
:param expression: String of the expresssion
:returns: Tuple of RSEAttribute, primitive expression
"""
primitiveexpression = re.match(PRIMITIVE, expression).group()
if ('=' in primitiveexpression):
ke... |
else:
right_term, primitiveexpression = __resolve_primitive_expression(expression)
expression = expression[len(primitiveexpression):]
operator.set_left_term(left_term)
operator.set_right_term(right_term)
left_term = operator
... | 66 | 66 | 220 | 8 | 57 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | __resolve_primitive_expression | __resolve_primitive_expression | 182 | 202 | 182 | 182 | f508272b0528f648aeb62f665cc87ecb915dc649 | bigcode/the-stack | train |
220957adbabf40dfdddef41d | train | class | class RSEAttributeSmallerCheck(BaseExpressionElement):
"""
Representation of an RSE Attribute with Smaller (<) Check
"""
def __init__(self, key, value=True):
"""
Creates an RSEAttribute representation
:param key: Key of the RSE Attribute.
:param value: ... | class RSEAttributeSmallerCheck(BaseExpressionElement):
| """
Representation of an RSE Attribute with Smaller (<) Check
"""
def __init__(self, key, value=True):
"""
Creates an RSEAttribute representation
:param key: Key of the RSE Attribute.
:param value: Value of the RSE Attribute.
"""
self.k... | session=session)
if not output:
return (set(), {})
rse_dict = {}
for rse in output:
rse_dict[rse['id']] = rse
return (set([rse['id'] for rse in output]), rse_dict)
class RSEAttributeSmallerCheck(BaseExpressionElement):
| 71 | 71 | 238 | 11 | 60 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | RSEAttributeSmallerCheck | RSEAttributeSmallerCheck | 285 | 317 | 285 | 285 | 7af1c90069fd1441c0b3874934089654811b81a6 | bigcode/the-stack | train |
8704c458c4dcc2ade0f2ae24 | train | function | def __extract_term(expression):
"""
Extract a term from an expression with parantheses
:param expression: The expression starting with a '('
:return: The extracted term string
"""
open_parantheses = 0
i = 0
for char in expression:
if (char == '('):
open_p... | def __extract_term(expression):
| """
Extract a term from an expression with parantheses
:param expression: The expression starting with a '('
:return: The extracted term string
"""
open_parantheses = 0
i = 0
for char in expression:
if (char == '('):
open_parantheses += 1
elif (ch... | (RSEAttributeLargerCheck(keyvalue[0], keyvalue[1]), primitiveexpression)
elif ('*' in primitiveexpression):
return (RSEAll(), primitiveexpression)
else:
return (RSEAttributeEqualCheck(key=primitiveexpression), primitiveexpression)
def __extract_term(expression):
| 64 | 64 | 139 | 6 | 58 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | __extract_term | __extract_term | 205 | 222 | 205 | 205 | be6c05b6c8898bee3f16fde8b65693460682ffcc | bigcode/the-stack | train |
eddd6e6f406e3f2f82c047e2 | train | class | class RSEAttributeEqualCheck(BaseExpressionElement):
"""
Representation of an RSE Attribute with Equal Check
"""
def __init__(self, key, value=True):
"""
Creates an RSEAttribute representation
:param key: Key of the RSE Attribute.
:param value: Value o... | class RSEAttributeEqualCheck(BaseExpressionElement):
| """
Representation of an RSE Attribute with Equal Check
"""
def __init__(self, key, value=True):
"""
Creates an RSEAttribute representation
:param key: Key of the RSE Attribute.
:param value: Value of the RSE Attribute.
"""
self.key = k... | output:
return (set(), {})
rse_dict = {}
for rse in output:
rse_dict[rse['id']] = rse
return (set([rse['id'] for rse in output]), rse_dict)
class RSEAttributeEqualCheck(BaseExpressionElement):
| 64 | 64 | 187 | 10 | 54 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | RSEAttributeEqualCheck | RSEAttributeEqualCheck | 257 | 282 | 257 | 257 | d744052a70daab88d36598c43f7ffca828db0eef | bigcode/the-stack | train |
8a3e0d534d417d4d445497dc | train | class | class UnionOperator(BaseRSEOperator):
"""
Representation of the or operator
"""
def __init__(self):
"""
Create a UnionOperator representation
"""
self.left_term = None
self.right_term = None
def set_left_term(self, left_term):
"""
Inherited ... | class UnionOperator(BaseRSEOperator):
| """
Representation of the or operator
"""
def __init__(self):
"""
Create a UnionOperator representation
"""
self.left_term = None
self.right_term = None
def set_left_term(self, left_term):
"""
Inherited from :py:func:`BaseRSEOperator.set_lef... | .left_term.resolve_elements(session=session)
right_term_tuple = self.right_term.resolve_elements(session=session)
return (left_term_tuple[0] - right_term_tuple[0], dict(list(left_term_tuple[1].items()) + list(right_term_tuple[1].items())))
class UnionOperator(BaseRSEOperator):
| 64 | 65 | 218 | 8 | 56 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | UnionOperator | UnionOperator | 410 | 441 | 410 | 410 | 36b741e0ffb81acc48cbc35fc114d812ad82a2c4 | bigcode/the-stack | train |
c38a71b7995d4ef3754c0f6d | train | class | class RSEAll(BaseExpressionElement):
"""
Representation of all RSEs
"""
def resolve_elements(self, session):
"""
Inherited from :py:func:`BaseExpressionElement.resolve_elements`
"""
output = list_rses(session=session)
if not output:
return (set(), {})... | class RSEAll(BaseExpressionElement):
| """
Representation of all RSEs
"""
def resolve_elements(self, session):
"""
Inherited from :py:func:`BaseExpressionElement.resolve_elements`
"""
output = list_rses(session=session)
if not output:
return (set(), {})
rse_dict = {}
for rs... | :param session: Database session in use
:returns: (Set of RSE ids, Dictionary of RSE dicts)
:rtype: (Set of Strings, Dictionary of RSE dicts organized by rse_id)
"""
pass
class RSEAll(BaseExpressionElement):
| 64 | 64 | 113 | 8 | 55 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | RSEAll | RSEAll | 239 | 254 | 239 | 239 | 9d287f95e46142025c3789fbcaecb812c75ae1bc | bigcode/the-stack | train |
59ed76d12e029fad6ae303cc | train | class | class IntersectOperator(BaseRSEOperator):
"""
Representation of the intersect operator
"""
def __init__(self):
"""
Create a IntersectOperator representation
"""
self.left_term = None
self.right_term = None
def set_left_term(self, left_term):
"""
... | class IntersectOperator(BaseRSEOperator):
| """
Representation of the intersect operator
"""
def __init__(self):
"""
Create a IntersectOperator representation
"""
self.left_term = None
self.right_term = None
def set_left_term(self, left_term):
"""
Inherited from :py:func:`BaseRSEOpera... | .left_term.resolve_elements(session=session)
right_term_tuple = self.right_term.resolve_elements(session=session)
return (left_term_tuple[0] | right_term_tuple[0], dict(list(left_term_tuple[1].items()) + list(right_term_tuple[1].items())))
class IntersectOperator(BaseRSEOperator):
| 65 | 66 | 220 | 9 | 56 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | IntersectOperator | IntersectOperator | 444 | 475 | 444 | 444 | 5fb41442411088d7cdf034d7031ed599da05f10e | bigcode/the-stack | train |
d46768ae05df86515bb15ca2 | train | function | def __resolve_term_expression(expression):
"""
Resolves a Term Expression and returns an object of type BaseExpressionElement
:param subexpression: String of the term expression.
:returns: Tuple of BaseExpressionElement, term Expression string
"""
left_term = None
operator = ... | def __resolve_term_expression(expression):
| """
Resolves a Term Expression and returns an object of type BaseExpressionElement
:param subexpression: String of the term expression.
:returns: Tuple of BaseExpressionElement, term Expression string
"""
left_term = None
operator = None
original_expression = expression
... | SE Expression resulted in an empty set.')
# Filter
final_result = []
if filter:
for rse in vo_result:
if filter.get('availability_write', False):
if rse.get('availability') & 2:
final_result.append(rse)
if not final_result:
raise R... | 112 | 112 | 374 | 7 | 104 | dynamic-entropy/rucio | lib/rucio/core/rse_expression_parser.py | Python | __resolve_term_expression | __resolve_term_expression | 127 | 179 | 127 | 127 | 98d5e3af8945007cfb1e36a74d3a413c579cdff2 | bigcode/the-stack | train |
40e7d99ef3b1cf5eab2aeacf | train | class | class SweetPeasAndSaffronLister(SitemapLister):
""" """
start_url = "https://sweetpeasandsaffron.com/post-sitemap.xml"
| class SweetPeasAndSaffronLister(SitemapLister):
| """ """
start_url = "https://sweetpeasandsaffron.com/post-sitemap.xml"
| from recipes.site_listers.base import SitemapLister
class SweetPeasAndSaffronLister(SitemapLister):
| 23 | 64 | 34 | 13 | 9 | cfeenstra67/recipes | recipes/site_listers/sweetpeasandsaffron.py | Python | SweetPeasAndSaffronLister | SweetPeasAndSaffronLister | 4 | 7 | 4 | 4 | e7d58fe5b394787ecc7c53d1c3781a0ee37852a6 | bigcode/the-stack | train |
2945c91d7f891ad48de046ab | train | function | def main():
# Collect materials
logging.info("Collecting all material prices")
materials = collect_material_prices()
for i, material in enumerate(materials):
logging.debug(material)
# Calculate best price
logging.info("Calculating best price")
material_all_prices = [[material.get_fi... | def main():
# Collect materials
| logging.info("Collecting all material prices")
materials = collect_material_prices()
for i, material in enumerate(materials):
logging.debug(material)
# Calculate best price
logging.info("Calculating best price")
material_all_prices = [[material.get_fine_prices(), material.get_masterwork... | import csv
import logging
import config
import recipes
from api import Commerce
from material import CraftingMaterial, Seed
RARITIES = ['fine', 'masterwork', 'rare', 'exotic']
def main():
# Collect materials
| 51 | 142 | 475 | 8 | 43 | JSpeleers/GW2-AscendedFoodsCalculator | calculator.py | Python | main | main | 12 | 55 | 12 | 13 | 1b091f3c3fbd1ef8d2db72c7234563e749df562f | bigcode/the-stack | train |
1edd6cba7272eda615167bd8 | train | function | def collect_material_prices():
"""
Read the materials.csv list; for each material collect the current price and return a list of CraftingMaterial
objects
:return: list of CraftingMaterials
"""
# with timebudget("Collecting material prices"):
commerce = Commerce()
materials = []
with ... | def collect_material_prices():
| """
Read the materials.csv list; for each material collect the current price and return a list of CraftingMaterial
objects
:return: list of CraftingMaterials
"""
# with timebudget("Collecting material prices"):
commerce = Commerce()
materials = []
with open('resources/materials.csv',... | profitable Pouch is thus {most_profitable_seed.pouch_name}'
f' ({config.format_coins(most_profit_seed)})')
else:
logging.info(f'By Ogden\'s hammer, what savings. Sadly, there is no money to be made here.')
def collect_material_prices():
| 63 | 64 | 192 | 5 | 58 | JSpeleers/GW2-AscendedFoodsCalculator | calculator.py | Python | collect_material_prices | collect_material_prices | 58 | 76 | 58 | 58 | 3d66cba24bb69d1a771ff66c6eec8ca85ab1da5e | bigcode/the-stack | train |
ec78fc8d7e642756d9d06d86 | train | function | def log_cheapest_materials(index, materials, cheapest_nourishments):
logging.info(
f'Cheapest {RARITIES[index]}:\t{materials[cheapest_nourishments[index][2]].name}'
f' for {config.format_coins(cheapest_nourishments[index][3])} each')
| def log_cheapest_materials(index, materials, cheapest_nourishments):
| logging.info(
f'Cheapest {RARITIES[index]}:\t{materials[cheapest_nourishments[index][2]].name}'
f' for {config.format_coins(cheapest_nourishments[index][3])} each')
| in enumerate(seeds):
seed.seed_price = seed_prices[i * 2]['sells']['unit_price']
seed.harvest_price = seed_prices[i * 2 + 1]['sells']['unit_price']
return seeds
def log_cheapest_materials(index, materials, cheapest_nourishments):
| 64 | 64 | 67 | 15 | 48 | JSpeleers/GW2-AscendedFoodsCalculator | calculator.py | Python | log_cheapest_materials | log_cheapest_materials | 119 | 122 | 119 | 119 | 4085638745892f839030b7614c85a5a30ee984dc | bigcode/the-stack | train |
4608880a302dffcf99a7c631 | train | function | def find_cheapest_nourishments(material_all_prices):
"""
For each rarity, return the cheapest consumable to salvage in order to gain nourishments :param
material_all_prices: 2D list where each inner list represents the price of a consumable to be salvaged in order to
get a single nourishment
:return... | def find_cheapest_nourishments(material_all_prices):
| """
For each rarity, return the cheapest consumable to salvage in order to gain nourishments :param
material_all_prices: 2D list where each inner list represents the price of a consumable to be salvaged in order to
get a single nourishment
:return: 2D list where each inner list represents the cheape... | row[5]))
prices = commerce.get_prices()
for i, material in enumerate(materials):
material.order_price = prices[i]['buys']['unit_price']
material.instant_price = prices[i]['sells']['unit_price']
return materials
def find_cheapest_nourishments(material_all_prices):
| 64 | 64 | 213 | 11 | 52 | JSpeleers/GW2-AscendedFoodsCalculator | calculator.py | Python | find_cheapest_nourishments | find_cheapest_nourishments | 79 | 96 | 79 | 79 | 4c79b4137886edb9bfe4eb971c3d9081afd5888d | bigcode/the-stack | train |
d49f2bef148cf495b4794898 | train | function | def collect_seed_prices():
"""
Read the seeds.csv list; for each material collect the current price and return a list of Seed objects
:return: list of Seeds
"""
seeds = []
commerce = Commerce()
with open('resources/seeds.csv', 'r') as seed_list:
next(seed_list) # Skip first line
... | def collect_seed_prices():
| """
Read the seeds.csv list; for each material collect the current price and return a list of Seed objects
:return: list of Seeds
"""
seeds = []
commerce = Commerce()
with open('resources/seeds.csv', 'r') as seed_list:
next(seed_list) # Skip first line
for row in csv.reader(... | [0]:
cheapest[j][1] = prices[0]
cheapest[j][0] = i
if cheapest[j][3] > prices[1]:
cheapest[j][3] = prices[1]
cheapest[j][2] = i
return cheapest
def collect_seed_prices():
| 64 | 64 | 195 | 5 | 58 | JSpeleers/GW2-AscendedFoodsCalculator | calculator.py | Python | collect_seed_prices | collect_seed_prices | 99 | 116 | 99 | 99 | d3efc675091c52141515a53ba74d3b8d5a0d1c37 | bigcode/the-stack | train |
8486231b56839efe795e88fe | train | function | def cpg_1():
tst = gdaltest.GDALTest('CPG', 'fakecpgSIRC.hdr', 1, 0)
return tst.testOpen()
| def cpg_1():
| tst = gdaltest.GDALTest('CPG', 'fakecpgSIRC.hdr', 1, 0)
return tst.testOpen()
| , TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###############################################################################
import sys
sys.path.append('../pymod')
import gdaltest
######################################################... | 64 | 64 | 40 | 6 | 57 | rcoup/gdal | autotest/gdrivers/cpg.py | Python | cpg_1 | cpg_1 | 41 | 44 | 41 | 42 | ee733a4429dfd1facfa6e01bf3e0c86ebd84f5f3 | bigcode/the-stack | train |
c486b71730223dce5f628095 | train | class | class a_W2(object):
__slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
| class a_W2(object):
| __slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
| self.__hidden = 5
class _W2(object):
__slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
class a_W1(object):
def __init__(self):
self.__hidden = 5
class a_W2(object):
| 64 | 64 | 29 | 6 | 57 | Mortal/Nuitka | tests/basics/Slots.py | Python | a_W2 | a_W2 | 40 | 43 | 40 | 40 | 99020fecc2563a8aec7132ae8052753b9b75492d | bigcode/the-stack | train |
af166ebee5d5d297e49fc253 | train | class | class W2_(object):
__slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
| class W2_(object):
| __slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
| self.__hidden = 5
class a_W2(object):
__slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
class W1_(object):
def __init__(self):
self.__hidden = 5
class W2_(object):
| 64 | 64 | 29 | 6 | 57 | Mortal/Nuitka | tests/basics/Slots.py | Python | W2_ | W2_ | 49 | 52 | 49 | 49 | ac1e94af277de8b230cd29260dd7cde7fcce45ad | bigcode/the-stack | train |
7b4046efd24718a1e20c0827 | train | class | class W1(object):
def __init__(self):
self.__hidden = 5
| class W1(object):
| def __init__(self):
self.__hidden = 5
| agreed to in 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.
#
class W1(object):
| 64 | 64 | 20 | 5 | 59 | Mortal/Nuitka | tests/basics/Slots.py | Python | W1 | W1 | 18 | 20 | 18 | 18 | caa1892b7a5a18d4a513a78f26097b0a66950a3c | bigcode/the-stack | train |
3ed740fdf4127c2be407fe28 | train | class | class W1_(object):
def __init__(self):
self.__hidden = 5
| class W1_(object):
| def __init__(self):
self.__hidden = 5
| self.__hidden = 5
class a_W1(object):
def __init__(self):
self.__hidden = 5
class a_W2(object):
__slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
class W1_(object):
| 64 | 64 | 21 | 6 | 57 | Mortal/Nuitka | tests/basics/Slots.py | Python | W1_ | W1_ | 45 | 47 | 45 | 45 | 70b5dbcdab180e84907b36e57941d49631338b7d | bigcode/the-stack | train |
e380c010f57b6752cf39ee98 | train | class | class a_W1(object):
def __init__(self):
self.__hidden = 5
| class a_W1(object):
| def __init__(self):
self.__hidden = 5
| self.__hidden = 5
class _W1(object):
def __init__(self):
self.__hidden = 5
class _W2(object):
__slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
class a_W1(object):
| 64 | 64 | 21 | 6 | 57 | Mortal/Nuitka | tests/basics/Slots.py | Python | a_W1 | a_W1 | 36 | 38 | 36 | 36 | 47ae68555b17113c401e45fd3d2792184e8b9b8a | bigcode/the-stack | train |
37b005fcd86f00b83bcb7a71 | train | class | class _W2(object):
__slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
| class _W2(object):
| __slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
| ):
self.__hidden = 5
class W2(object):
__slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
class _W1(object):
def __init__(self):
self.__hidden = 5
class _W2(object):
| 64 | 64 | 29 | 6 | 57 | Mortal/Nuitka | tests/basics/Slots.py | Python | _W2 | _W2 | 31 | 34 | 31 | 31 | bb52aaca8c705a38881b358bf6b8ab537aa84f5b | bigcode/the-stack | train |
0ed55c29da8c9509a807b9c8 | train | class | class W2(object):
__slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
| class W2(object):
| __slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
| " 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.
#
class W1(object):
def __init__(self):
self.__hidden = 5
class W2(object):
| 64 | 64 | 28 | 5 | 58 | Mortal/Nuitka | tests/basics/Slots.py | Python | W2 | W2 | 22 | 25 | 22 | 22 | 782de8556d3ae8080582b69b6bddde5e1feb1e8c | bigcode/the-stack | train |
150bba61ed5ae299d770626d | train | class | class _W1(object):
def __init__(self):
self.__hidden = 5
| class _W1(object):
| def __init__(self):
self.__hidden = 5
| and
# limitations under the License.
#
class W1(object):
def __init__(self):
self.__hidden = 5
class W2(object):
__slots__=["__hidden"]
def __init__(self):
self.__hidden = 5
class _W1(object):
| 64 | 64 | 21 | 6 | 57 | Mortal/Nuitka | tests/basics/Slots.py | Python | _W1 | _W1 | 27 | 29 | 27 | 27 | dc1b79a56a73766ee2576064b339eafe3458f5a4 | bigcode/the-stack | train |
84b26c45ae84d0a6eeb7e7e2 | train | class | class Migration(migrations.Migration):
dependencies = [
('orders', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='order',
name='total',
field=models.DecimalField(decimal_places=2, default=0.0, max_digits=100),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('orders', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='order',
name='total',
field=models.DecimalField(decimal_places=2, default=0.0, max_digits=100),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-03 01:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 54 | 64 | 67 | 7 | 46 | khalildh/ecommerce-django | ecommerce/src/orders/migrations/0002_auto_20171203_0132.py | Python | Migration | Migration | 8 | 20 | 8 | 9 | 3bc162168288eca74d676c5e85e12874b8059a44 | bigcode/the-stack | train |
0b05577637e09ac3f869faca | train | function | def run_service(service_cls):
def _signal_handler(_signum, _frame):
"""
Handler on signal
"""
LOGGER.info('stop service')
eventlet.spawn(runner.stop)
params = get_args()
runner = ServiceRunner(config={})
service_cls.prepare(params)
runner.add_service(service_... | def run_service(service_cls):
| def _signal_handler(_signum, _frame):
"""
Handler on signal
"""
LOGGER.info('stop service')
eventlet.spawn(runner.stop)
params = get_args()
runner = ServiceRunner(config={})
service_cls.prepare(params)
runner.add_service(service_cls)
signal.signal(signal.... | Consul',
help='Service registry type')
parser.add_argument(
'--address', dest='address', action='store',
default='0.0.0.0:8055',
help='The address and port which for service')
return parser.parse_args()
def run_service(service_cls):
| 64 | 64 | 129 | 6 | 58 | LuyaoHuang/python-MSA-infrastructure | nameko_base/run.py | Python | run_service | run_service | 25 | 46 | 25 | 25 | bd7fec678528789d33de5540361d205376196d51 | bigcode/the-stack | train |
892056ed713ef3ab252c0d3a | train | function | def get_args():
parser = argparse.ArgumentParser(description='This is a service example')
parser.add_argument(
'--service-id', dest='service_id', action='store',
help='Id of service')
parser.add_argument(
'--registry', dest='registry', action='store',
default='Consul',
... | def get_args():
| parser = argparse.ArgumentParser(description='This is a service example')
parser.add_argument(
'--service-id', dest='service_id', action='store',
help='Id of service')
parser.add_argument(
'--registry', dest='registry', action='store',
default='Consul',
help='Service ... | import argparse
import signal
import eventlet
from nameko.runners import ServiceRunner
from logging import getLogger
LOGGER = getLogger(__name__)
def get_args():
| 35 | 64 | 122 | 4 | 31 | LuyaoHuang/python-MSA-infrastructure | nameko_base/run.py | Python | get_args | get_args | 10 | 23 | 10 | 10 | 696590d96a31255b4d414d83ed91b81f33922371 | bigcode/the-stack | train |
02f79010b9d826e228090b59 | train | class | class JQCheckBox(QCheckBox):
def __init__(self, text: Optional[str] = None, enabled=True, Checked=True):
super().__init__()
if text:
self.setText(text)
self.setEnabled(enabled)
if Checked:
self.setCheckState(Qt.Checked)
else:
self.setCheck... | class JQCheckBox(QCheckBox):
| def __init__(self, text: Optional[str] = None, enabled=True, Checked=True):
super().__init__()
if text:
self.setText(text)
self.setEnabled(enabled)
if Checked:
self.setCheckState(Qt.Checked)
else:
self.setCheckState(Qt.Unchecked)
@pro... | return {self.__TYPE__: self.currentText()}
def Deserialize(self, text: str):
for i in range(self.count()):
if text == self.itemText(i):
self.setCurrentIndex(i)
return
logger.error("invalid option")
class JQCheckBox(QCheckBox):
| 64 | 64 | 113 | 9 | 55 | ironWolf1990/python-jils | jigls/jeditor/widgets/custom.py | Python | JQCheckBox | JQCheckBox | 147 | 167 | 147 | 147 | d4d1498704f6b7a1eb98f8c65ac7e5a94e1f7c28 | bigcode/the-stack | train |
f88e357e944a4c5d42dbf757 | train | class | class PropertiesSection(QTreeWidget):
def __init__(self, parent: Optional[QWidget] = None, columnCount: int = 2) -> None:
super().__init__(parent=parent)
self.setHeaderHidden(True)
self.setColumnCount(columnCount)
self.setAlternatingRowColors(True)
self.header().setSectionRe... | class PropertiesSection(QTreeWidget):
| def __init__(self, parent: Optional[QWidget] = None, columnCount: int = 2) -> None:
super().__init__(parent=parent)
self.setHeaderHidden(True)
self.setColumnCount(columnCount)
self.setAlternatingRowColors(True)
self.header().setSectionResizeMode(QtWidgets.QHeaderView.ResizeT... | Add)
self.layout().addWidget(buttonRemove)
buttonAdd.clicked.connect(self.AddChild)
buttonRemove.clicked.connect(self.RemoveChild)
def AddChild(self):
self.sectionTree._AddChild()
def RemoveChild(self):
self.sectionTree._RemoveChild()
class PropertiesSection(QTreeWidge... | 64 | 64 | 108 | 7 | 57 | ironWolf1990/python-jils | jigls/jeditor/widgets/custom.py | Python | PropertiesSection | PropertiesSection | 274 | 285 | 274 | 274 | 8de0978608b557fe81d218a4aa1107b1bbe623b4 | bigcode/the-stack | train |
b7ddec8b80f742ebb12414cf | train | class | class JQTextEdit(QTextEdit):
__TYPE__ = "JQTextEdit"
def __init__(
self,
text: Optional[str] = None,
placeholder: Optional[str] = None,
readOnly: bool = True,
maxCharacter: Optional[int] = None,
):
super().__init__()
self.maxCharacter: Optional[int]... | class JQTextEdit(QTextEdit):
| __TYPE__ = "JQTextEdit"
def __init__(
self,
text: Optional[str] = None,
placeholder: Optional[str] = None,
readOnly: bool = True,
maxCharacter: Optional[int] = None,
):
super().__init__()
self.maxCharacter: Optional[int] = maxCharacter
if te... | (validator)
@property
def widgetType(self):
return self.__TYPE__
def Serialize(self) -> Dict[str, str]:
return {self.__TYPE__: self.text()}
def Deserialize(self, text: str):
self.setText(text)
class JQTextEdit(QTextEdit):
| 65 | 65 | 218 | 9 | 56 | ironWolf1990/python-jils | jigls/jeditor/widgets/custom.py | Python | JQTextEdit | JQTextEdit | 83 | 119 | 83 | 84 | fce6b8e4c7fca05035e255f0441b9b49df3dee44 | bigcode/the-stack | train |
aeb6c16e94beea797bfd2a80 | train | class | class JQComboBox(QComboBox):
__TYPE__ = "JQComboBox"
def __init__(self, options: List[str] = [""]) -> None:
super().__init__()
for op in options:
self.addItem(op)
@property
def widgetType(self):
return self.__TYPE__
def Serialize(self) -> Dict[str, str]:
... | class JQComboBox(QComboBox):
| __TYPE__ = "JQComboBox"
def __init__(self, options: List[str] = [""]) -> None:
super().__init__()
for op in options:
self.addItem(op)
@property
def widgetType(self):
return self.__TYPE__
def Serialize(self) -> Dict[str, str]:
return {self.__TYPE__: sel... | Character:
self.setText(self.toPlainText()[: self.maxCharacter])
def Serialize(self) -> Dict[str, str]:
return {self.__TYPE__: self.toPlainText()}
def Deserialize(self, text: str):
self.setText(text)
class JQComboBox(QComboBox):
| 64 | 64 | 137 | 9 | 55 | ironWolf1990/python-jils | jigls/jeditor/widgets/custom.py | Python | JQComboBox | JQComboBox | 122 | 144 | 122 | 123 | 6015d96ab7c1711af01240efb616fed03596e054 | bigcode/the-stack | train |
8a797daac7e2637c84864be0 | train | class | class DelegateTreeOperations(QWidget):
def __init__(self, sectionTree: PropertyTree):
super().__init__(parent=None)
self.sectionTree = sectionTree
self.initUI()
# ? should be reimplemented based on use case
def initUI(self):
self.setLayout(QHBoxLayout())
self.layou... | class DelegateTreeOperations(QWidget):
| def __init__(self, sectionTree: PropertyTree):
super().__init__(parent=None)
self.sectionTree = sectionTree
self.initUI()
# ? should be reimplemented based on use case
def initUI(self):
self.setLayout(QHBoxLayout())
self.layout().setSpacing(0)
self.layout()... | 0, label)
self.rootTree.setItemWidget(entry, 1, line)
@property
def widgetType(self):
return self.__TYPE__
def _RemoveChild(self):
for item in self.rootTree.selectedItems():
self.removeChild(item)
def Serialize(self):
raise NotImplementedError()
def De... | 85 | 85 | 285 | 6 | 79 | ironWolf1990/python-jils | jigls/jeditor/widgets/custom.py | Python | DelegateTreeOperations | DelegateTreeOperations | 233 | 271 | 233 | 233 | 8d8fbc51ac8680f19a995f216b52eb586ba3a27d | bigcode/the-stack | train |
fcba985de356e9ef3195d0e0 | train | class | class JQLineEdit(QLineEdit):
__TYPE__ = "JQLineEdit"
def __init__(
self,
text: Optional[str] = None,
placeholder: Optional[str] = None,
validator: Optional[QValidator] = None,
width: Optional[int] = None,
readOnly: bool = True,
):
super().__init__()
... | class JQLineEdit(QLineEdit):
| __TYPE__ = "JQLineEdit"
def __init__(
self,
text: Optional[str] = None,
placeholder: Optional[str] = None,
validator: Optional[QValidator] = None,
width: Optional[int] = None,
readOnly: bool = True,
):
super().__init__()
if text:
s... | Width)
@property
def widgetType(self):
return self.__TYPE__
def Serialize(self) -> Dict[str, str]:
return {self.__TYPE__: self.text()}
def Deserialize(self, text: str):
self.setText(text)
class JQLineEdit(QLineEdit):
| 64 | 64 | 186 | 9 | 55 | ironWolf1990/python-jils | jigls/jeditor/widgets/custom.py | Python | JQLineEdit | JQLineEdit | 49 | 80 | 49 | 50 | 7c8991a46394164226a0316426bc52e58b81380c | bigcode/the-stack | train |
84fed11b8f6eb366ff69572a | train | class | class JQCheckBoxWidget(QWidget):
def __init__(
self, parent: Optional[QWidget] = None, text: Optional[str] = None, enabled=True, Checked=True
) -> None:
super().__init__(parent=parent)
self.setLayout(QHBoxLayout())
self.layout().setAlignment(Qt.AlignCenter)
self.layout()... | class JQCheckBoxWidget(QWidget):
| def __init__(
self, parent: Optional[QWidget] = None, text: Optional[str] = None, enabled=True, Checked=True
) -> None:
super().__init__(parent=parent)
self.setLayout(QHBoxLayout())
self.layout().setAlignment(Qt.AlignCenter)
self.layout().setContentsMargins(0, 0, 0, 0)
... | .setCheckState(Qt.Checked)
else:
self.setCheckState(Qt.Unchecked)
@property
def widgetType(self):
return self.__TYPE__
def Serialize(self):
raise NotImplementedError()
def Deserialize(self):
raise NotImplementedError()
class JQCheckBoxWidget(QWidget):
| 64 | 64 | 150 | 8 | 56 | ironWolf1990/python-jils | jigls/jeditor/widgets/custom.py | Python | JQCheckBoxWidget | JQCheckBoxWidget | 170 | 189 | 170 | 170 | 406dfb05b927dd7e73660c2fb76e7db8796bb4cc | bigcode/the-stack | train |
2ba945cf9db447b9036e8c28 | train | class | class PropertyTree(QTreeWidgetItem):
__TYPE__ = "JQPropertyTree"
def __init__(self, parent: QTreeWidget):
super().__init__(parent)
self.rootTree: QTreeWidget = parent
self.setExpanded(True)
# ? should be reimplemented based on use case
def _AddChild(self):
entry = QTre... | class PropertyTree(QTreeWidgetItem):
| __TYPE__ = "JQPropertyTree"
def __init__(self, parent: QTreeWidget):
super().__init__(parent)
self.rootTree: QTreeWidget = parent
self.setExpanded(True)
# ? should be reimplemented based on use case
def _AddChild(self):
entry = QTreeWidgetItem()
self.addChild(en... | , 0)
self.layout().addWidget(JQCheckBox(text=text, enabled=enabled, Checked=Checked))
@property
def widgetType(self):
return self.__TYPE__
def Serialize(self):
raise NotImplementedError()
def Deserialize(self):
raise NotImplementedError()
class PropertyTree(QTreeWidget... | 71 | 71 | 238 | 8 | 63 | ironWolf1990/python-jils | jigls/jeditor/widgets/custom.py | Python | PropertyTree | PropertyTree | 192 | 230 | 192 | 193 | f28983caf4ae99c13a4eebea3e5fd5b453b3a3e3 | bigcode/the-stack | train |
75ef6f00adecd5a388fa63d5 | train | class | class JQLabel(QLabel):
__TYPE__ = "JQLabel"
def __init__(self, text: str, maxWidth: int = 140):
super().__init__(text=text)
self.setFixedWidth(maxWidth)
@property
def widgetType(self):
return self.__TYPE__
def Serialize(self) -> Dict[str, str]:
return {self.__TYPE... | class JQLabel(QLabel):
| __TYPE__ = "JQLabel"
def __init__(self, text: str, maxWidth: int = 140):
super().__init__(text=text)
self.setFixedWidth(maxWidth)
@property
def widgetType(self):
return self.__TYPE__
def Serialize(self) -> Dict[str, str]:
return {self.__TYPE__: self.text()}
de... | Dialog,
QHBoxLayout,
QLabel,
QLineEdit,
QTextEdit,
QToolButton,
QTreeWidget,
QTreeWidgetItem,
QVBoxLayout,
QWidget,
)
logger = logging.getLogger(__name__)
from typing import Optional
class JQLabel(QLabel):
| 64 | 64 | 105 | 7 | 56 | ironWolf1990/python-jils | jigls/jeditor/widgets/custom.py | Python | JQLabel | JQLabel | 30 | 46 | 30 | 31 | fc686f572b129c6c759dc1572ff6f8ab819d3ece | bigcode/the-stack | train |
63d3ed5446fa598660c08c16 | train | function | def worker(i):
time.sleep(random.randint(2, 10))
| def worker(i):
| time.sleep(random.randint(2, 10))
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import random
import time
def worker(i):
| 27 | 64 | 15 | 4 | 22 | thierrydecker/learning-python | samples/threads_count.py | Python | worker | worker | 9 | 10 | 9 | 9 | de68c200d7b1ac8d3845ec11c6c029ad675ed5ed | bigcode/the-stack | train |
fa4588401f292fdd32986689 | train | function | def main():
for i in range(5000):
t = threading.Thread(target=worker, args=(i,))
t.start()
count = threading.active_count()
while count > 1:
count = threading.active_count()
print("{} active threads".format(count))
time.sleep(0.5)
| def main():
| for i in range(5000):
t = threading.Thread(target=worker, args=(i,))
t.start()
count = threading.active_count()
while count > 1:
count = threading.active_count()
print("{} active threads".format(count))
time.sleep(0.5)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import random
import time
def worker(i):
time.sleep(random.randint(2, 10))
def main():
| 41 | 64 | 67 | 3 | 38 | thierrydecker/learning-python | samples/threads_count.py | Python | main | main | 13 | 21 | 13 | 13 | a9431ba9e871f4093bdd674638cf4a5d01439583 | bigcode/the-stack | train |
3a70531595ca2265753eadf5 | train | class | class PyBinaryornot(PythonPackage):
"""Ultra-lightweight pure Python package to check if a file is binary or text.
"""
homepage = "https://binaryornot.readthedocs.io"
url = "https://github.com/audreyr/binaryornot/archive/0.4.0.tar.gz"
version('0.4.4', sha256='8cca04876a5e9d01f0dda79390e99089d... | class PyBinaryornot(PythonPackage):
| """Ultra-lightweight pure Python package to check if a file is binary or text.
"""
homepage = "https://binaryornot.readthedocs.io"
url = "https://github.com/audreyr/binaryornot/archive/0.4.0.tar.gz"
version('0.4.4', sha256='8cca04876a5e9d01f0dda79390e99089da87f3c1948ab2720661ba379d1b23f2')
... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyBinaryornot(PythonPackage):
| 63 | 64 | 142 | 9 | 54 | kkauder/spack | var/spack/repos/builtin/packages/py-binaryornot/package.py | Python | PyBinaryornot | PyBinaryornot | 9 | 19 | 9 | 9 | ebe77f8196b984fdfe2d86f7087bea9613880864 | bigcode/the-stack | train |
d94f7b1396a8a6259498fc46 | train | class | class GAT(nn.Module):
def __init__(self, n_features, n_classes, k=8, f=8):
super(GAT, self).__init__()
self.initial_layer = AttentionLayer(n_in_features=n_features, n_out_features_per_head=f, n_heads=k)
self.activation_layer = AttentionLayer(n_in_features=k * f, n_out_features_per_head=n_cla... | class GAT(nn.Module):
| def __init__(self, n_features, n_classes, k=8, f=8):
super(GAT, self).__init__()
self.initial_layer = AttentionLayer(n_in_features=n_features, n_out_features_per_head=f, n_heads=k)
self.activation_layer = AttentionLayer(n_in_features=k * f, n_out_features_per_head=n_classes, n_heads=k)
... | import torch
import torch.nn as nn
import torch.nn.functional as F
class GAT(nn.Module):
| 22 | 64 | 198 | 6 | 15 | linklab/link_rl | temp/GAT/model.py | Python | GAT | GAT | 6 | 21 | 6 | 6 | bc3536810c00405d9b7890fe18099edfe1c7195b | bigcode/the-stack | train |
41f32785cc0d620445dc7c9e | train | class | class AttentionCoefficient(nn.Module):
def __init__(self, n_features):
super(AttentionCoefficient, self).__init__()
self.a1 = nn.Linear(n_features, 1, bias=False)
self.a2 = nn.Linear(n_features, 1, bias=False)
def forward(self, features, neighbors):
x = self.a1(features) + self.... | class AttentionCoefficient(nn.Module):
| def __init__(self, n_features):
super(AttentionCoefficient, self).__init__()
self.a1 = nn.Linear(n_features, 1, bias=False)
self.a2 = nn.Linear(n_features, 1, bias=False)
def forward(self, features, neighbors):
x = self.a1(features) + self.a2(neighbors) # [BATCH * H * 1 * 1] + ... | (x, -2) # [BATCH * HEAD * OF_PER_HEAD]
x = x.view(-1, 1, self.n_heads, self.n_out_features_per_head) # [BATCH * 1 * HEAD * OF_PER_HEAD]
return x
class AttentionCoefficient(nn.Module):
| 64 | 64 | 146 | 6 | 57 | linklab/link_rl | temp/GAT/model.py | Python | AttentionCoefficient | AttentionCoefficient | 85 | 95 | 85 | 85 | 94f38d6f175f0ade0d3647766127253417c2bf67 | bigcode/the-stack | train |
85fbe643cfee9eaad9bdb5f0 | train | class | class MultiHeadAttention(nn.Module):
def __init__(self, n_heads, n_in_features, n_out_features_per_head):
super(MultiHeadAttention, self).__init__()
self.n_heads = n_heads
self.n_in_features = n_in_features
self.n_out_features_per_head = n_out_features_per_head
self.w = nn.Li... | class MultiHeadAttention(nn.Module):
| def __init__(self, n_heads, n_in_features, n_out_features_per_head):
super(MultiHeadAttention, self).__init__()
self.n_heads = n_heads
self.n_in_features = n_in_features
self.n_out_features_per_head = n_out_features_per_head
self.w = nn.Linear(n_in_features, n_out_features_pe... | (AttentionLayer, self).__init__()
self.multi_head_attention = MultiHeadAttention(n_heads, n_in_features, n_out_features_per_head)
self.n_out_features_per_head = n_out_features_per_head
self.n_heads = n_heads
def forward(self, graph, node_features):
x = None
for i in range(le... | 167 | 167 | 557 | 7 | 159 | linklab/link_rl | temp/GAT/model.py | Python | MultiHeadAttention | MultiHeadAttention | 47 | 82 | 47 | 47 | 183e585158b898cd99f3fe98c1874081be9cc4a8 | bigcode/the-stack | train |
830eeccb28ceca52e301dfd3 | train | class | class AttentionLayer(nn.Module):
def __init__(self, n_in_features, n_out_features_per_head, n_heads):
super(AttentionLayer, self).__init__()
self.multi_head_attention = MultiHeadAttention(n_heads, n_in_features, n_out_features_per_head)
self.n_out_features_per_head = n_out_features_per_head
... | class AttentionLayer(nn.Module):
| def __init__(self, n_in_features, n_out_features_per_head, n_heads):
super(AttentionLayer, self).__init__()
self.multi_head_attention = MultiHeadAttention(n_heads, n_in_features, n_out_features_per_head)
self.n_out_features_per_head = n_out_features_per_head
self.n_heads = n_heads
... | .k * self.f)
x = self.activation_layer(graph, x)
x = torch.mean(x, -2)
x = x.softmax(-1) # TODO: needs to be fixed to mask softmax for the unconnected neighbors.
return x.squeeze(0)
class AttentionLayer(nn.Module):
| 64 | 64 | 188 | 6 | 58 | linklab/link_rl | temp/GAT/model.py | Python | AttentionLayer | AttentionLayer | 24 | 44 | 24 | 24 | beec82821e9a17e6bc8edd6f70589668c9fcc17f | bigcode/the-stack | train |
6476e22dfd39ab2dce3bcdd6 | train | class | class SendIndexFile():
"""
发送更新索引文件
"""
def __init__(self, connect, address):
if DEBUG and VERSION_CONTROL_DEBUG:
print('Accept new connection from {0}'.format(address))
self.connect = connect
self.address = address
def sendFile(self):
"""
发送更新索引文... | class SendIndexFile():
| """
发送更新索引文件
"""
def __init__(self, connect, address):
if DEBUG and VERSION_CONTROL_DEBUG:
print('Accept new connection from {0}'.format(address))
self.connect = connect
self.address = address
def sendFile(self):
"""
发送更新索引文件
:return:
... | # -*- coding:utf-8 -*-
from src.Server.Conf.config import *
class SendIndexFile():
| 20 | 68 | 228 | 5 | 15 | Sniper970119/MemoryAssistInPython | src/Server/MessageTransferSystem/VersionControlSystem/Tools/sendInexFile.py | Python | SendIndexFile | SendIndexFile | 5 | 34 | 5 | 5 | 5c96f09cbab1a0fc2c369fb64c02b8e660f2b71d | bigcode/the-stack | train |
d3015fc51f2318a2cea74dba | train | function | def wamole(moles):
lp = lpfk()
# starting pattern
for k in sample(range(32), moles):
lp.keys[k] = 1
lp.update_lights()
while True:
cmd = lp.get()
if not len(cmd):
continue
if cmd == lp.RETRANSMIT:
print ('got error, resending')
... | def wamole(moles):
| lp = lpfk()
# starting pattern
for k in sample(range(32), moles):
lp.keys[k] = 1
lp.update_lights()
while True:
cmd = lp.get()
if not len(cmd):
continue
if cmd == lp.RETRANSMIT:
print ('got error, resending')
update_lights()
... | #!/usr/bin/env python
from lpfk import lpfk
from random import sample
def wamole(moles):
| 26 | 64 | 212 | 6 | 19 | dmd/IBM-LPFK | wamole.py | Python | wamole | wamole | 6 | 41 | 6 | 6 | 2d85ee2e40199323a0bba53de89e7a83e1872891 | bigcode/the-stack | train |
90b058ff402cf59e2cf20ba3 | train | function | def get_eigenvector_weights(data):
def _eigenvector_centrality(data):
graph = to_networkx(data)
x = nx.eigenvector_centrality_numpy(graph)
x = [x[i] for i in range(data.num_nodes)]
return torch.tensor(x, dtype=torch.float32).to(data.edge_index.device)
evc = _eigenvector_centrali... | def get_eigenvector_weights(data):
| def _eigenvector_centrality(data):
graph = to_networkx(data)
x = nx.eigenvector_centrality_numpy(graph)
x = [x[i] for i in range(data.num_nodes)]
return torch.tensor(x, dtype=torch.float32).to(data.edge_index.device)
evc = _eigenvector_centrality(data)
scaled_evc = evc.where... |
weights = weights.where(weights < threshold, torch.ones_like(weights) * threshold) # clip
drop_mask = torch.bernoulli(weights).to(torch.bool)
x = x.clone()
x[:, drop_mask] = 0.
return x
def get_eigenvector_weights(data):
| 64 | 64 | 166 | 8 | 55 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | get_eigenvector_weights | get_eigenvector_weights | 134 | 149 | 134 | 134 | 9ae65e4374787aed7d36222e558863902f7aee80 | bigcode/the-stack | train |
0aac7bd9892ffc754eb3c047 | train | function | def drop_node(edge_index: torch.Tensor, edge_weight: Optional[torch.Tensor] = None, keep_prob: float = 0.5) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
num_nodes = edge_index.max().item() + 1
probs = torch.tensor([keep_prob for _ in range(num_nodes)])
dist = Bernoulli(probs)
subset = dist.sample().... | def drop_node(edge_index: torch.Tensor, edge_weight: Optional[torch.Tensor] = None, keep_prob: float = 0.5) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
| num_nodes = edge_index.max().item() + 1
probs = torch.tensor([keep_prob for _ in range(num_nodes)])
dist = Bernoulli(probs)
subset = dist.sample().to(torch.bool).to(edge_index.device)
edge_index, edge_weight = subgraph(subset, edge_index, edge_weight)
return edge_index, edge_weight
| edge_index = sort_edge_index(edge_index)[0]
return coalesce_edge_index(edge_index)[0]
def drop_node(edge_index: torch.Tensor, edge_weight: Optional[torch.Tensor] = None, keep_prob: float = 0.5) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
| 64 | 64 | 120 | 41 | 23 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | drop_node | drop_node | 310 | 318 | 310 | 310 | b001f199bfe9567a429c8caece735608c5bf664d | bigcode/the-stack | train |
80a81465bd42e83cd41c749a | train | function | def multiinstance_mixup(x1: torch.Tensor, x2: torch.Tensor,
alpha: float, shuffle=False) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Randomly mixup node embeddings or features with nodes from other views.
Args:
x1: The latent embedding or node feature from one view.
x2... | def multiinstance_mixup(x1: torch.Tensor, x2: torch.Tensor,
alpha: float, shuffle=False) -> Tuple[torch.Tensor, torch.Tensor]:
| """
Randomly mixup node embeddings or features with nodes from other views.
Args:
x1: The latent embedding or node feature from one view.
x2: The latent embedding or node feature from the other view.
alpha: The mixup coefficient `\lambda` follows `Beta(\alpha, \alpha)`.
shuf... | Uniform(alpha, 1.).sample([1]).to(device)
x = (1 - lambda_) * x + lambda_ * x[mixup_idx]
return x
def multiinstance_mixup(x1: torch.Tensor, x2: torch.Tensor,
alpha: float, shuffle=False) -> Tuple[torch.Tensor, torch.Tensor]:
| 71 | 71 | 238 | 34 | 36 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | multiinstance_mixup | multiinstance_mixup | 64 | 86 | 64 | 65 | 58f2f7cbe8f815067d19a3230598e308e0a9a704 | bigcode/the-stack | train |
b585cb38ddb05b81d811fa62 | train | function | def permute(x: torch.Tensor) -> torch.Tensor:
"""
Randomly permute node embeddings or features.
Args:
x: The latent embedding or node feature.
Returns:
torch.Tensor: Embeddings or features resulting from permutation.
"""
return x[torch.randperm(x.size(0))]
| def permute(x: torch.Tensor) -> torch.Tensor:
| """
Randomly permute node embeddings or features.
Args:
x: The latent embedding or node feature.
Returns:
torch.Tensor: Embeddings or features resulting from permutation.
"""
return x[torch.randperm(x.size(0))]
| , to_networkx, to_undirected, degree, to_scipy_sparse_matrix, \
from_scipy_sparse_matrix, sort_edge_index, add_self_loops, subgraph
from torch.distributions.bernoulli import Bernoulli
def permute(x: torch.Tensor) -> torch.Tensor:
| 64 | 64 | 66 | 12 | 51 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | permute | permute | 16 | 26 | 16 | 16 | b5727fbbb0a6263cab920fe1b98ecbef0f98c83a | bigcode/the-stack | train |
2ba4706e40431781dbb93528 | train | function | def dropout_feature(x: torch.FloatTensor, drop_prob: float) -> torch.FloatTensor:
return F.dropout(x, p=1. - drop_prob)
| def dropout_feature(x: torch.FloatTensor, drop_prob: float) -> torch.FloatTensor:
| return F.dropout(x, p=1. - drop_prob)
| dtype=torch.float32).uniform_(0, 1) < drop_prob
drop_mask = drop_mask.to(device)
x = x.clone()
x[:, drop_mask] = 0
return x
def dropout_feature(x: torch.FloatTensor, drop_prob: float) -> torch.FloatTensor:
| 64 | 64 | 33 | 19 | 44 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | dropout_feature | dropout_feature | 99 | 100 | 99 | 99 | f76ad6dd235b840455b160ded2619874a02f019b | bigcode/the-stack | train |
87e574bf6e3d344fad5a0441 | train | function | def get_subgraph(x, edge_index, idx):
adj = to_scipy_sparse_matrix(edge_index).tocsr()
x_sampled = x[idx]
edge_index_sampled = from_scipy_sparse_matrix(adj[idx, :][:, idx])
return x_sampled, edge_index_sampled
| def get_subgraph(x, edge_index, idx):
| adj = to_scipy_sparse_matrix(edge_index).tocsr()
x_sampled = x[idx]
edge_index_sampled = from_scipy_sparse_matrix(adj[idx, :][:, idx])
return x_sampled, edge_index_sampled
| x, edge_index):
edge_index = drop_edge_by_weight(edge_index, self.edge_weights, self.pe, self.threshold)
x = drop_feature_by_weight(x, self.feature_weights, self.pf, self.threshold)
return x, edge_index
def get_subgraph(x, edge_index, idx):
| 64 | 64 | 66 | 11 | 52 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | get_subgraph | get_subgraph | 215 | 219 | 215 | 215 | 69937f5574d0a24b18f66413bc2286c0da327ce1 | bigcode/the-stack | train |
9946eedb00f3d0540b446159 | train | function | def add_edge(edge_index: torch.Tensor, ratio: float) -> torch.Tensor:
num_edges = edge_index.size()[1]
num_nodes = edge_index.max().item() + 1
num_add = int(num_edges * ratio)
new_edge_index = torch.randint(0, num_nodes - 1, size=(2, num_add)).to(edge_index.device)
edge_index = torch.cat([edge_inde... | def add_edge(edge_index: torch.Tensor, ratio: float) -> torch.Tensor:
| num_edges = edge_index.size()[1]
num_nodes = edge_index.max().item() + 1
num_add = int(num_edges * ratio)
new_edge_index = torch.randint(0, num_nodes - 1, size=(2, num_add)).to(edge_index.device)
edge_index = torch.cat([edge_index, new_edge_index], dim=1)
edge_index = sort_edge_index(edge_inde... | edge_weights = edge_weights if edge_weights is not None else torch.ones((num_edges,), dtype=torch.float32, device=edge_index.device)
return coalesce(edge_index, edge_weights, m=num_nodes, n=num_nodes)
def add_edge(edge_index: torch.Tensor, ratio: float) -> torch.Tensor:
| 64 | 64 | 120 | 17 | 47 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | add_edge | add_edge | 297 | 307 | 297 | 297 | 2e36530a19c2949461e18742d7fbca0c69f5eca1 | bigcode/the-stack | train |
a806460f2af43052e6c4c49c | train | function | def drop_feature_by_weight(x, weights, drop_prob: float, threshold: float = 0.7):
weights = weights / weights.mean() * drop_prob
weights = weights.where(weights < threshold, torch.ones_like(weights) * threshold) # clip
drop_mask = torch.bernoulli(weights).to(torch.bool)
x = x.clone()
x[:, drop_mask... | def drop_feature_by_weight(x, weights, drop_prob: float, threshold: float = 0.7):
| weights = weights / weights.mean() * drop_prob
weights = weights.where(weights < threshold, torch.ones_like(weights) * threshold) # clip
drop_mask = torch.bernoulli(weights).to(torch.bool)
x = x.clone()
x[:, drop_mask] = 0.
return x
| = x.to(torch.bool).to(torch.float32)
else:
x = x.abs()
w = x.t() @ centrality
w = w.log()
return normalize(w)
def drop_feature_by_weight(x, weights, drop_prob: float, threshold: float = 0.7):
| 64 | 64 | 90 | 23 | 41 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | drop_feature_by_weight | drop_feature_by_weight | 125 | 131 | 125 | 125 | 8e024e3a70be44c76d814c5ccfafca4eb063d2d4 | bigcode/the-stack | train |
637078289f427aa49f85990e | train | function | def drop_edge_by_weight(edge_index, weights, drop_prob: float, threshold: float = 0.7):
weights = weights / weights.mean() * drop_prob
weights = weights.where(weights < threshold, torch.ones_like(weights) * threshold)
drop_mask = torch.bernoulli(1. - weights).to(torch.bool)
return edge_index[:, drop_ma... | def drop_edge_by_weight(edge_index, weights, drop_prob: float, threshold: float = 0.7):
| weights = weights / weights.mean() * drop_prob
weights = weights.where(weights < threshold, torch.ones_like(weights) * threshold)
drop_mask = torch.bernoulli(1. - weights).to(torch.bool)
return edge_index[:, drop_mask]
| elif aggr == 'mean':
s = (s_col + s_row) * 0.5
else:
s = s_col
return normalize(s), pv
def drop_edge_by_weight(edge_index, weights, drop_prob: float, threshold: float = 0.7):
| 64 | 64 | 79 | 24 | 39 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | drop_edge_by_weight | drop_edge_by_weight | 192 | 197 | 192 | 192 | 01e01956703d7c4b243261341e6e2f39d36a6a37 | bigcode/the-stack | train |
c10ed3e94730e676ae8168f9 | train | function | def get_pagerank_weights(data, aggr: str = 'sink', k: int = 10):
def _compute_pagerank(edge_index, damp: float = 0.85, k: int = 10):
num_nodes = edge_index.max().item() + 1
deg_out = degree(edge_index[0])
x = torch.ones((num_nodes,)).to(edge_index.device).to(torch.float32)
for i in ... | def get_pagerank_weights(data, aggr: str = 'sink', k: int = 10):
| def _compute_pagerank(edge_index, damp: float = 0.85, k: int = 10):
num_nodes = edge_index.max().item() + 1
deg_out = degree(edge_index[0])
x = torch.ones((num_nodes,)).to(edge_index.device).to(torch.float32)
for i in range(k):
edge_msg = x[edge_index[0]] / deg_out[edge_... | get_degree_weights(data):
edge_index_ = to_undirected(data.edge_index)
deg = degree(edge_index_[1])
deg_col = deg[data.edge_index[1]].to(torch.float32)
scaled_deg_col = torch.log(deg_col)
return normalize(scaled_deg_col), deg
def get_pagerank_weights(data, aggr: str = 'sink', k: int = 10):
| 87 | 87 | 292 | 23 | 63 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | get_pagerank_weights | get_pagerank_weights | 161 | 189 | 161 | 161 | 6272e1130204344c64b9b35fadcec7e2a4048742 | bigcode/the-stack | train |
09b09d26bc5b5ddc07ee4ba2 | train | function | def get_sparse_adj(edge_index: torch.LongTensor, edge_weight: torch.FloatTensor = None,
add_self_loop: bool = True) -> torch.sparse.Tensor:
num_nodes = edge_index.max().item() + 1
num_edges = edge_index.size(1)
if edge_weight is None:
edge_weight = torch.ones((num_edges,), dtype=... | def get_sparse_adj(edge_index: torch.LongTensor, edge_weight: torch.FloatTensor = None,
add_self_loop: bool = True) -> torch.sparse.Tensor:
| num_nodes = edge_index.max().item() + 1
num_edges = edge_index.size(1)
if edge_weight is None:
edge_weight = torch.ones((num_edges,), dtype=torch.float32, device=edge_index.device)
if add_self_loop:
edge_index, edge_weight = add_self_loops(
edge_index, edge_weight, fill_val... | _weight = GDC().transition_matrix(
edge_index, edge_weight, N, normalization='sym')
return edge_index, edge_weight
def get_sparse_adj(edge_index: torch.LongTensor, edge_weight: torch.FloatTensor = None,
add_self_loop: bool = True) -> torch.sparse.Tensor:
| 64 | 64 | 202 | 35 | 28 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | get_sparse_adj | get_sparse_adj | 249 | 267 | 249 | 250 | d811655363f45e128f63d013188aa23a8c0cd3dc | bigcode/the-stack | train |
f0d7f54b6b62d50628c73833 | train | function | def random_walk_subgraph(edge_index: torch.LongTensor, edge_weight: Optional[torch.FloatTensor] = None, batch_size: int = 1000, length: int = 10):
num_nodes = edge_index.max().item() + 1
row, col = edge_index
adj = SparseTensor(row=row, col=col, sparse_sizes=(num_nodes, num_nodes))
start = torch.randi... | def random_walk_subgraph(edge_index: torch.LongTensor, edge_weight: Optional[torch.FloatTensor] = None, batch_size: int = 1000, length: int = 10):
| num_nodes = edge_index.max().item() + 1
row, col = edge_index
adj = SparseTensor(row=row, col=col, sparse_sizes=(num_nodes, num_nodes))
start = torch.randint(0, num_nodes, size=(batch_size, ), dtype=torch.long).to(edge_index.device)
node_idx = adj.random_walk(start.flatten(), length).view(-1)
... | _index, edge_weight = subgraph(subset, edge_index, edge_weight)
return edge_index, edge_weight
def random_walk_subgraph(edge_index: torch.LongTensor, edge_weight: Optional[torch.FloatTensor] = None, batch_size: int = 1000, length: int = 10):
| 64 | 64 | 151 | 40 | 23 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | random_walk_subgraph | random_walk_subgraph | 321 | 332 | 321 | 321 | 65b11aa4b4d5182a319540aff70a8715071a05b8 | bigcode/the-stack | train |
e57e67ba2e2b68e731f50256 | train | function | def get_feature_weights(x, centrality, sparse=True):
if sparse:
x = x.to(torch.bool).to(torch.float32)
else:
x = x.abs()
w = x.t() @ centrality
w = w.log()
return normalize(w)
| def get_feature_weights(x, centrality, sparse=True):
| if sparse:
x = x.to(torch.bool).to(torch.float32)
else:
x = x.abs()
w = x.t() @ centrality
w = w.log()
return normalize(w)
| self.pf = pf
def __call__(self, x, edge_index):
edge_index = dropout_adj(edge_index, p=self.pe)[0]
x = drop_feature(x, self.pf)
return x, edge_index
def get_feature_weights(x, centrality, sparse=True):
| 64 | 64 | 59 | 12 | 51 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | get_feature_weights | get_feature_weights | 114 | 122 | 114 | 114 | 94c9fd27efe1449ac8f8b2ca822451a987c38e49 | bigcode/the-stack | train |
abb6e85db725b909006544e1 | train | class | class AdaptivelyAugmentTopologyAttributes(object):
def __init__(self, edge_weights, feature_weights, pe=0.5, pf=0.5, threshold=0.7):
self.edge_weights = edge_weights
self.feature_weights = feature_weights
self.pe = pe
self.pf = pf
self.threshold = threshold
def __call__(... | class AdaptivelyAugmentTopologyAttributes(object):
| def __init__(self, edge_weights, feature_weights, pe=0.5, pf=0.5, threshold=0.7):
self.edge_weights = edge_weights
self.feature_weights = feature_weights
self.pe = pe
self.pf = pf
self.threshold = threshold
def __call__(self, x, edge_index):
edge_index = drop_edg... | weights = weights / weights.mean() * drop_prob
weights = weights.where(weights < threshold, torch.ones_like(weights) * threshold)
drop_mask = torch.bernoulli(1. - weights).to(torch.bool)
return edge_index[:, drop_mask]
class AdaptivelyAugmentTopologyAttributes(object):
| 64 | 64 | 135 | 9 | 55 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | AdaptivelyAugmentTopologyAttributes | AdaptivelyAugmentTopologyAttributes | 200 | 212 | 200 | 200 | 0023606469b9c881f6f00f8e155c400f1456e502 | bigcode/the-stack | train |
755e8fe9e3710bae47e714f8 | train | function | def get_degree_weights(data):
edge_index_ = to_undirected(data.edge_index)
deg = degree(edge_index_[1])
deg_col = deg[data.edge_index[1]].to(torch.float32)
scaled_deg_col = torch.log(deg_col)
return normalize(scaled_deg_col), deg
| def get_degree_weights(data):
| edge_index_ = to_undirected(data.edge_index)
deg = degree(edge_index_[1])
deg_col = deg[data.edge_index[1]].to(torch.float32)
scaled_deg_col = torch.log(deg_col)
return normalize(scaled_deg_col), deg
| vc = scaled_evc + 1e-8
s = scaled_evc.log()
edge_index = data.edge_index
s_row, s_col = s[edge_index[0]], s[edge_index[1]]
return normalize(s_col), evc
def get_degree_weights(data):
| 64 | 64 | 65 | 6 | 57 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | get_degree_weights | get_degree_weights | 152 | 158 | 152 | 152 | 0e5e2d52a175878bb2a66b5d12314fd3d359cd0b | bigcode/the-stack | train |
0f4ee66c06af0971070d19e3 | train | function | def get_mixup_idx(x: torch.Tensor) -> torch.Tensor:
"""
Generate node IDs randomly for mixup; avoid mixup the same node.
Args:
x: The latent embedding or node feature.
Returns:
torch.Tensor: Random node IDs.
"""
mixup_idx = torch.randint(x.size(0) - 1, [x.size(0)])
mixup_se... | def get_mixup_idx(x: torch.Tensor) -> torch.Tensor:
| """
Generate node IDs randomly for mixup; avoid mixup the same node.
Args:
x: The latent embedding or node feature.
Returns:
torch.Tensor: Random node IDs.
"""
mixup_idx = torch.randint(x.size(0) - 1, [x.size(0)])
mixup_self_mask = mixup_idx - torch.arange(x.size(0))
mi... | permute node embeddings or features.
Args:
x: The latent embedding or node feature.
Returns:
torch.Tensor: Embeddings or features resulting from permutation.
"""
return x[torch.randperm(x.size(0))]
def get_mixup_idx(x: torch.Tensor) -> torch.Tensor:
| 63 | 64 | 140 | 14 | 50 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | get_mixup_idx | get_mixup_idx | 29 | 43 | 29 | 29 | 3909dbc75f9a81767dfd7dda5a4ec8832770389d | bigcode/the-stack | train |
c2f397c2e3fa6f5c748d2d8c | train | function | def drop_feature(x: torch.Tensor, drop_prob: float) -> torch.Tensor:
device = x.device
drop_mask = torch.empty((x.size(1),), dtype=torch.float32).uniform_(0, 1) < drop_prob
drop_mask = drop_mask.to(device)
x = x.clone()
x[:, drop_mask] = 0
return x
| def drop_feature(x: torch.Tensor, drop_prob: float) -> torch.Tensor:
| device = x.device
drop_mask = torch.empty((x.size(1),), dtype=torch.float32).uniform_(0, 1) < drop_prob
drop_mask = drop_mask.to(device)
x = x.clone()
x[:, drop_mask] = 0
return x
| ) - torch.arange(x1.size(0)) - 1
x_spurious = (1 - lambda_) * x1 + lambda_ * x2[mixup_idx]
return x_spurious, lambda_
def drop_feature(x: torch.Tensor, drop_prob: float) -> torch.Tensor:
| 63 | 64 | 81 | 17 | 46 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | drop_feature | drop_feature | 89 | 96 | 89 | 89 | 02ee28d2cf8d20c10c26e6a9b0f16b6125c97cd3 | bigcode/the-stack | train |
d199e698aad5bf33223dad08 | train | function | def mixup(x: torch.Tensor, alpha: float) -> torch.Tensor:
"""
Randomly mixup node embeddings or features with other nodes'.
Args:
x: The latent embedding or node feature.
alpha: The hyperparameter controlling the mixup coefficient.
Returns:
torch.Tensor: Embeddings or features ... | def mixup(x: torch.Tensor, alpha: float) -> torch.Tensor:
| """
Randomly mixup node embeddings or features with other nodes'.
Args:
x: The latent embedding or node feature.
alpha: The hyperparameter controlling the mixup coefficient.
Returns:
torch.Tensor: Embeddings or features resulting from mixup.
"""
device = x.device
mi... | (x.size(0))
mixup_self_mask = (mixup_self_mask == 0)
mixup_idx += torch.ones(x.size(0), dtype=torch.int) * mixup_self_mask
return mixup_idx
def mixup(x: torch.Tensor, alpha: float) -> torch.Tensor:
| 64 | 64 | 135 | 16 | 47 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | mixup | mixup | 46 | 61 | 46 | 46 | 9504d7b548a0f502bac0cb1015a1c23edf579c82 | bigcode/the-stack | train |
e0ec11e302be3ac439ceb2bb | train | function | def sample_nodes(x, edge_index, sample_size):
idx = torch.randperm(x.size(0))[:sample_size]
return get_subgraph(x, edge_index, idx), idx
| def sample_nodes(x, edge_index, sample_size):
| idx = torch.randperm(x.size(0))[:sample_size]
return get_subgraph(x, edge_index, idx), idx
| = to_scipy_sparse_matrix(edge_index).tocsr()
x_sampled = x[idx]
edge_index_sampled = from_scipy_sparse_matrix(adj[idx, :][:, idx])
return x_sampled, edge_index_sampled
def sample_nodes(x, edge_index, sample_size):
| 64 | 64 | 40 | 11 | 52 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | sample_nodes | sample_nodes | 222 | 224 | 222 | 222 | 7658fdfa7bc1010e0894396beea37b68f580afef | bigcode/the-stack | train |
752afd8589119416727b5c92 | train | function | def coalesce_edge_index(edge_index: torch.Tensor, edge_weights: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.FloatTensor]:
num_edges = edge_index.size()[1]
num_nodes = edge_index.max().item() + 1
edge_weights = edge_weights if edge_weights is not None else torch.ones((num_edges,), dtype=torch... | def coalesce_edge_index(edge_index: torch.Tensor, edge_weights: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.FloatTensor]:
| num_edges = edge_index.size()[1]
num_nodes = edge_index.max().item() + 1
edge_weights = edge_weights if edge_weights is not None else torch.ones((num_edges,), dtype=torch.float32, device=edge_index.device)
return coalesce(edge_index, edge_weights, m=num_nodes, n=num_nodes)
| alpha * adj
adj_t = z.t()
return GDC().sparsify_dense(adj_t, method='threshold', eps=sp_eps)
def coalesce_edge_index(edge_index: torch.Tensor, edge_weights: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.FloatTensor]:
| 64 | 64 | 103 | 32 | 32 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | coalesce_edge_index | coalesce_edge_index | 289 | 294 | 289 | 289 | 6d5eb409d5da021e765f23fd7582748ea5e9da72 | bigcode/the-stack | train |
6f24db6b2f01d1b1ccdeb08f | train | class | class AugmentTopologyAttributes(object):
def __init__(self, pe=0.5, pf=0.5):
self.pe = pe
self.pf = pf
def __call__(self, x, edge_index):
edge_index = dropout_adj(edge_index, p=self.pe)[0]
x = drop_feature(x, self.pf)
return x, edge_index
| class AugmentTopologyAttributes(object):
| def __init__(self, pe=0.5, pf=0.5):
self.pe = pe
self.pf = pf
def __call__(self, x, edge_index):
edge_index = dropout_adj(edge_index, p=self.pe)[0]
x = drop_feature(x, self.pf)
return x, edge_index
| _mask.to(device)
x = x.clone()
x[:, drop_mask] = 0
return x
def dropout_feature(x: torch.FloatTensor, drop_prob: float) -> torch.FloatTensor:
return F.dropout(x, p=1. - drop_prob)
class AugmentTopologyAttributes(object):
| 64 | 64 | 84 | 7 | 57 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | AugmentTopologyAttributes | AugmentTopologyAttributes | 103 | 111 | 103 | 103 | 2792fb02111f7eb37711217f5b6463a47ec36227 | bigcode/the-stack | train |
915903491540429d0d2858cc | train | function | def compute_markov_diffusion(
edge_index: torch.LongTensor, edge_weight: torch.FloatTensor = None,
alpha: float = 0.1, degree: int = 10,
sp_eps: float = 1e-3, add_self_loop: bool = True):
adj = get_sparse_adj(edge_index, edge_weight, add_self_loop)
z = adj.to_dense()
t = adj.to_dens... | def compute_markov_diffusion(
edge_index: torch.LongTensor, edge_weight: torch.FloatTensor = None,
alpha: float = 0.1, degree: int = 10,
sp_eps: float = 1e-3, add_self_loop: bool = True):
| adj = get_sparse_adj(edge_index, edge_weight, add_self_loop)
z = adj.to_dense()
t = adj.to_dense()
for _ in range(degree):
t = (1.0 - alpha) * torch.spmm(adj, t)
z += t
z /= degree
z = z + alpha * adj
adj_t = z.t()
return GDC().sparsify_dense(adj_t, method='threshold',... | _t.t()
def compute_markov_diffusion(
edge_index: torch.LongTensor, edge_weight: torch.FloatTensor = None,
alpha: float = 0.1, degree: int = 10,
sp_eps: float = 1e-3, add_self_loop: bool = True):
| 64 | 64 | 164 | 61 | 3 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | compute_markov_diffusion | compute_markov_diffusion | 270 | 286 | 270 | 273 | 2d2a70c858d498e397b589b64e7671b6b82071bc | bigcode/the-stack | train |
d73e5616699cabaf01972787 | train | function | def compute_ppr(edge_index, edge_weight=None, alpha=0.2, eps=0.1, ignore_edge_attr=True, add_self_loop=True):
N = edge_index.max().item() + 1
if ignore_edge_attr or edge_weight is None:
edge_weight = torch.ones(
edge_index.size(1), device=edge_index.device)
if add_self_loop:
edge... | def compute_ppr(edge_index, edge_weight=None, alpha=0.2, eps=0.1, ignore_edge_attr=True, add_self_loop=True):
| N = edge_index.max().item() + 1
if ignore_edge_attr or edge_weight is None:
edge_weight = torch.ones(
edge_index.size(1), device=edge_index.device)
if add_self_loop:
edge_index, edge_weight = add_self_loops(
edge_index, edge_weight, fill_value=1, num_nodes=N)
... | return x_sampled, edge_index_sampled
def sample_nodes(x, edge_index, sample_size):
idx = torch.randperm(x.size(0))[:sample_size]
return get_subgraph(x, edge_index, idx), idx
def compute_ppr(edge_index, edge_weight=None, alpha=0.2, eps=0.1, ignore_edge_attr=True, add_self_loop=True):
| 84 | 84 | 282 | 33 | 50 | lem0nle/PyGCL | GCL/augmentors/functional.py | Python | compute_ppr | compute_ppr | 227 | 246 | 227 | 227 | 18dd16cf8527e8668833e4b657611960e5d9b295 | bigcode/the-stack | train |
d936e3b4c40e8c3e241fa10c | train | function | def _get_api_version_tuple(resource_type, sdk_profile, post_process=lambda x: x):
"""Return a _ApiVersion instance where key are operation group and value are api version."""
return _ApiVersions(client_type=get_client_class(resource_type),
sdk_profile=sdk_profile,
... | def _get_api_version_tuple(resource_type, sdk_profile, post_process=lambda x: x):
| """Return a _ApiVersion instance where key are operation group and value are api version."""
return _ApiVersions(client_type=get_client_class(resource_type),
sdk_profile=sdk_profile,
post_process=post_process)
| def __getattr__(self, item):
try:
self._resolve()
return self._operations_groups_value[item]
except KeyError:
raise AttributeError('Attribute {} does not exist.'.format(item))
def _get_api_version_tuple(resource_type, sdk_profile, post_process=lambda x: x):
| 64 | 64 | 65 | 19 | 45 | mdewan/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | Python | _get_api_version_tuple | _get_api_version_tuple | 247 | 251 | 247 | 247 | 1cf9637d3e788edff725d85238778493d39cf079 | bigcode/the-stack | train |
cec89cfb1f5b20f3d2bcb31b | train | function | def _cross_api_format_less_than(api_version, other):
"""LT strategy that supports if types are different.
For now, let's assume that any Semver is higher than any DateAPI
This fits KeyVault, if later we have a counter-example we'll update
"""
api_version = _parse_api_version(api_version)
other ... | def _cross_api_format_less_than(api_version, other):
| """LT strategy that supports if types are different.
For now, let's assume that any Semver is higher than any DateAPI
This fits KeyVault, if later we have a counter-example we'll update
"""
api_version = _parse_api_version(api_version)
other = _parse_api_version(other)
if type(api_version)... | parse it as a date, and if not working
as semver, and if still not working raise.
"""
try:
return _DateAPIFormat(api_version)
except ValueError:
return _SemVerAPIFormat(api_version)
def _cross_api_format_less_than(api_version, other):
| 64 | 64 | 116 | 12 | 52 | mdewan/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | Python | _cross_api_format_less_than | _cross_api_format_less_than | 358 | 369 | 358 | 358 | 2a23dfb13938e5d49b653a1702c3f683501c964a | bigcode/the-stack | train |
8f7bb791b05ea183138cc49d | train | function | def get_client_class(resource_type):
return _get_attr(resource_type.import_prefix, '#' + resource_type.client_name)
| def get_client_class(resource_type):
| return _get_attr(resource_type.import_prefix, '#' + resource_type.client_name)
| if attr_path:
# Only load attributes if needed
for part in attr_path.split('.'):
op = getattr(op, part)
return op
except (ImportError, AttributeError) as ex:
if checked:
return None
raise ex
def get_client_class(resource_type):
| 64 | 64 | 24 | 7 | 56 | mdewan/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | Python | get_client_class | get_client_class | 427 | 428 | 427 | 427 | 44c90250bb08ab63268ac1ef7884807e6f6cda59 | bigcode/the-stack | train |
200e8b42dc26c7f1fcdff2ef | train | class | class _ApiVersions(object): # pylint: disable=too-few-public-methods
def __init__(self, client_type, sdk_profile, post_process):
self._client_type = client_type
self._sdk_profile = sdk_profile
self._post_process = post_process
self._operations_groups_value = None
self._resol... | class _ApiVersions(object): # pylint: disable=too-few-public-methods
| def __init__(self, client_type, sdk_profile, post_process):
self._client_type = client_type
self._sdk_profile = sdk_profile
self._post_process = post_process
self._operations_groups_value = None
self._resolved = False
def _resolve(self):
if self._resolved:
... | 'classic_administrators': '2015-06-01'
}),
ResourceType.DATA_KEYVAULT: '2016-10-01',
ResourceType.DATA_STORAGE: '2015-04-05'
}
}
class _ApiVersions(object): # pylint: disable=too-few-public-methods
| 69 | 69 | 232 | 19 | 50 | mdewan/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | Python | _ApiVersions | _ApiVersions | 215 | 244 | 215 | 215 | d27fac064ac5c563abfdeada0dfafbb9eabba2bb | bigcode/the-stack | train |
ac3d57220ebf9eb3ad7b1657 | train | class | @total_ordering # pylint: disable=too-few-public-methods
class _DateAPIFormat(object):
""" Class to support comparisons for API versions in
YYYY-MM-DD, YYYY-MM-DD-preview, YYYY-MM-DD-profile, YYYY-MM-DD-profile-preview
or any string that starts with YYYY-MM-DD format. A special case is made for 'la... | @total_ordering # pylint: disable=too-few-public-methods
class _DateAPIFormat(object):
| """ Class to support comparisons for API versions in
YYYY-MM-DD, YYYY-MM-DD-preview, YYYY-MM-DD-profile, YYYY-MM-DD-profile-preview
or any string that starts with YYYY-MM-DD format. A special case is made for 'latest'.
"""
def __init__(self, api_version_str):
try:
self.l... | , TypeError):
raise ValueError('The API version {} is not in a '
'semver format'.format(api_version_str))
def __eq__(self, other):
return (self.major, self.minor, self.patch) == (other.major, other.minor, other.patch)
def __lt__(self, other):
return (se... | 121 | 121 | 404 | 24 | 97 | mdewan/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | Python | _DateAPIFormat | _DateAPIFormat | 299 | 345 | 299 | 300 | 431b97c99b07a0dc9b9c2148bc4c7b73cf263d02 | bigcode/the-stack | train |
18c852f2e099903f993c6391 | train | function | def _validate_api_version(api_version_str, min_api=None, max_api=None):
"""Validate if api_version is inside the interval min_api/max_api.
"""
if min_api and _cross_api_format_less_than(api_version_str, min_api):
return False
if max_api and _cross_api_format_less_than(max_api, api_version_str):
... | def _validate_api_version(api_version_str, min_api=None, max_api=None):
| """Validate if api_version is inside the interval min_api/max_api.
"""
if min_api and _cross_api_format_less_than(api_version_str, min_api):
return False
if max_api and _cross_api_format_less_than(max_api, api_version_str):
return False
return True
| other = _parse_api_version(other)
if type(api_version) is type(other):
return api_version < other
return isinstance(api_version, _DateAPIFormat) and isinstance(other, _SemVerAPIFormat)
def _validate_api_version(api_version_str, min_api=None, max_api=None):
| 64 | 64 | 82 | 17 | 47 | mdewan/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | Python | _validate_api_version | _validate_api_version | 372 | 379 | 372 | 372 | ebcd410dd835d370d7f90de8dab55d4b274c417e | bigcode/the-stack | train |
7f4456aa524b18d63c43fe70 | train | class | class CustomResourceType(object): # pylint: disable=too-few-public-methods
def __init__(self, import_prefix, client_name):
self.import_prefix = import_prefix
self.client_name = client_name
| class CustomResourceType(object): # pylint: disable=too-few-public-methods
| def __init__(self, import_prefix, client_name):
self.import_prefix = import_prefix
self.client_name = client_name
|
def __str__(self):
return "Unable to get API version for type '{}' in profile '{}'".format(
self.type_name, self.api_profile)
# Sentinel value for profile
PROFILE_TYPE = object()
class CustomResourceType(object): # pylint: disable=too-few-public-methods
| 64 | 64 | 48 | 19 | 45 | mdewan/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | Python | CustomResourceType | CustomResourceType | 27 | 30 | 27 | 27 | 26a282c8b15616dccf2948453a20c1b2c4b6b8d7 | bigcode/the-stack | train |
ea7c7fc88e14aa8e1a7ea472 | train | class | class SDKProfile(object): # pylint: disable=too-few-public-methods
def __init__(self, default_api_version, profile=None):
"""Constructor.
:param str default_api_version: Default API version if not overridden by a profile. Nullable.
:param profile: A dict operation group name to API versio... | class SDKProfile(object): # pylint: disable=too-few-public-methods
| def __init__(self, default_api_version, profile=None):
"""Constructor.
:param str default_api_version: Default API version if not overridden by a profile. Nullable.
:param profile: A dict operation group name to API version.
:type profile: dict[str, str]
"""
self.pro... | type import_prefix: str.
:param client_name: Name the client for this resource type.
:type client_name: str.
"""
self.import_prefix = import_prefix
self.client_name = client_name
class SDKProfile(object): # pylint: disable=too-few-public-methods
| 64 | 64 | 123 | 18 | 45 | mdewan/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | Python | SDKProfile | SDKProfile | 107 | 121 | 107 | 108 | 627d4092465aeb62cecc18752f620012ff8ca778 | bigcode/the-stack | train |
3a0e6d9ace3d8b5b47b9fe2b | train | function | def get_versioned_sdk(api_profile, resource_type, *attr_args, **kwargs):
checked = kwargs.get('checked', True)
sub_mod_prefix = kwargs.get('mod', None)
operation_group = kwargs.get('operation_group', None)
sdk_path = get_versioned_sdk_path(api_profile, resource_type, operation_group)
if not attr_arg... | def get_versioned_sdk(api_profile, resource_type, *attr_args, **kwargs):
| checked = kwargs.get('checked', True)
sub_mod_prefix = kwargs.get('mod', None)
operation_group = kwargs.get('operation_group', None)
sdk_path = get_versioned_sdk_path(api_profile, resource_type, operation_group)
if not attr_args:
# No attributes to load. Return the versioned sdk
retu... | _group is required for resource type '{}'".format(resource_type))
api_version = getattr(api_version, operation_group)
return '{}.v{}'.format(resource_type.import_prefix, api_version.replace('-', '_').replace('.', '_'))
def get_versioned_sdk(api_profile, resource_type, *attr_args, **kwargs):
| 63 | 64 | 180 | 18 | 45 | mdewan/azure-cli | src/azure-cli-core/azure/cli/core/profiles/_shared.py | Python | get_versioned_sdk | get_versioned_sdk | 448 | 462 | 448 | 448 | b352b2248d75e61fb8e338b0c03d0131c5f18655 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.