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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
489bb6352c5b38b52c94f05a | train | class | class BomImportUpload(generics.CreateAPIView):
"""
API endpoint for uploading a complete Bill of Materials.
It is assumed that the BOM has been extracted from a file using the BomExtract endpoint.
"""
queryset = Part.objects.all()
serializer_class = part_serializers.BomImportUploadSerializer
... | class BomImportUpload(generics.CreateAPIView):
| """
API endpoint for uploading a complete Bill of Materials.
It is assumed that the BOM has been extracted from a file using the BomExtract endpoint.
"""
queryset = Part.objects.all()
serializer_class = part_serializers.BomImportUploadSerializer
def create(self, request, *args, **kwargs):... | _item.purchase_price_avg = convert_price(bom_item.purchase_price_avg, purchase_price_currency)
return queryset
filter_backends = [
DjangoFilterBackend,
filters.SearchFilter,
filters.OrderingFilter,
]
filter_fields = [
]
class BomImportUpload(generics.CreateAPIView):
| 63 | 64 | 148 | 10 | 53 | rkalman/InvenTree | InvenTree/part/api.py | Python | BomImportUpload | BomImportUpload | 1,809 | 1,831 | 1,809 | 1,809 | 6cbb15c1b65658428ece7881c608c8c4e1a6db48 | bigcode/the-stack | train |
671e3985ea9f1ac5a652f481 | train | class | class CategoryMetadata(generics.RetrieveUpdateAPIView):
"""API endpoint for viewing / updating PartCategory metadata"""
def get_serializer(self, *args, **kwargs):
return MetadataSerializer(PartCategory, *args, **kwargs)
queryset = PartCategory.objects.all()
| class CategoryMetadata(generics.RetrieveUpdateAPIView):
| """API endpoint for viewing / updating PartCategory metadata"""
def get_serializer(self, *args, **kwargs):
return MetadataSerializer(PartCategory, *args, **kwargs)
queryset = PartCategory.objects.all()
| starred' in request.data:
starred = str2bool(request.data.get('starred', False))
self.get_object().set_starred(request.user, starred)
response = super().update(request, *args, **kwargs)
return response
class CategoryMetadata(generics.RetrieveUpdateAPIView):
| 64 | 64 | 57 | 11 | 52 | rkalman/InvenTree | InvenTree/part/api.py | Python | CategoryMetadata | CategoryMetadata | 204 | 210 | 204 | 204 | 49e02c825aaa21d5400f46291752d6f876d21070 | bigcode/the-stack | train |
63dade1ac130d44a97f38421 | train | class | class PartParameterDetail(generics.RetrieveUpdateDestroyAPIView):
"""
API endpoint for detail view of a single PartParameter object
"""
queryset = PartParameter.objects.all()
serializer_class = part_serializers.PartParameterSerializer
| class PartParameterDetail(generics.RetrieveUpdateDestroyAPIView):
| """
API endpoint for detail view of a single PartParameter object
"""
queryset = PartParameter.objects.all()
serializer_class = part_serializers.PartParameterSerializer
|
"""
queryset = PartParameter.objects.all()
serializer_class = part_serializers.PartParameterSerializer
filter_backends = [
DjangoFilterBackend
]
filter_fields = [
'part',
'template',
]
class PartParameterDetail(generics.RetrieveUpdateDestroyAPIView):
| 63 | 64 | 49 | 13 | 50 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartParameterDetail | PartParameterDetail | 1,526 | 1,532 | 1,526 | 1,526 | 80ebd8d50bfd2bdf5e615220742a642368a96779 | bigcode/the-stack | train |
3e81e55ae36d46ee9eab409d | train | class | class PartThumbs(generics.ListAPIView):
"""
API endpoint for retrieving information on available Part thumbnails
"""
queryset = Part.objects.all()
serializer_class = part_serializers.PartThumbSerializer
def get_queryset(self):
queryset = super().get_queryset()
# Get all Parts... | class PartThumbs(generics.ListAPIView):
| """
API endpoint for retrieving information on available Part thumbnails
"""
queryset = Part.objects.all()
serializer_class = part_serializers.PartThumbSerializer
def get_queryset(self):
queryset = super().get_queryset()
# Get all Parts which have an associated image
... | params.get('required', None)
if required is not None:
queryset = queryset.filter(required=str2bool(required))
return queryset
filter_backends = [
DjangoFilterBackend,
filters.OrderingFilter,
filters.SearchFilter,
]
class PartThumbs(generics.ListAPIView):
| 63 | 64 | 210 | 10 | 53 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartThumbs | PartThumbs | 404 | 447 | 404 | 404 | 2aa62c9eacf918d820c1682980669989af0c4a59 | bigcode/the-stack | train |
27d35d6cd38ef85642ec7628 | train | class | class BomImportSubmit(generics.CreateAPIView):
"""
API endpoint for submitting BOM data from a BOM file
"""
queryset = BomItem.objects.none()
serializer_class = part_serializers.BomImportSubmitSerializer
| class BomImportSubmit(generics.CreateAPIView):
| """
API endpoint for submitting BOM data from a BOM file
"""
queryset = BomItem.objects.none()
serializer_class = part_serializers.BomImportSubmitSerializer
| .HTTP_201_CREATED, headers=headers)
class BomImportExtract(generics.CreateAPIView):
"""
API endpoint for extracting BOM data from a BOM file.
"""
queryset = Part.objects.none()
serializer_class = part_serializers.BomImportExtractSerializer
class BomImportSubmit(generics.CreateAPIView):
| 64 | 64 | 47 | 10 | 53 | rkalman/InvenTree | InvenTree/part/api.py | Python | BomImportSubmit | BomImportSubmit | 1,843 | 1,849 | 1,843 | 1,843 | ddd0c71dd279dd2088a919b222e92db8ef447295 | bigcode/the-stack | train |
58884fbc452515a49d9018a0 | train | class | class BomList(generics.ListCreateAPIView):
"""
API endpoint for accessing a list of BomItem objects.
- GET: Return list of BomItem objects
- POST: Create a new BomItem object
"""
serializer_class = part_serializers.BomItemSerializer
queryset = BomItem.objects.all()
filterset_class = Bo... | class BomList(generics.ListCreateAPIView):
| """
API endpoint for accessing a list of BomItem objects.
- GET: Return list of BomItem objects
- POST: Create a new BomItem object
"""
serializer_class = part_serializers.BomItemSerializer
queryset = BomItem.objects.all()
filterset_class = BomFilter
def list(self, request, *args,... | ='part__active')
part_trackable = rest_filters.BooleanFilter(label='Master part is trackable', field_name='part__trackable')
# Filters for linked 'sub_part'
sub_part_trackable = rest_filters.BooleanFilter(label='Sub part is trackable', field_name='sub_part__trackable')
sub_part_assembly = rest_filters.... | 256 | 256 | 1,523 | 10 | 245 | rkalman/InvenTree | InvenTree/part/api.py | Python | BomList | BomList | 1,578 | 1,806 | 1,578 | 1,578 | 3370688c5a2747dfa72e5cc9dfe1ea2ea005f4cd | bigcode/the-stack | train |
90e35f514775d3e1c980a1b2 | train | class | class BomFilter(rest_filters.FilterSet):
"""
Custom filters for the BOM list
"""
# Boolean filters for BOM item
optional = rest_filters.BooleanFilter(label='BOM line is optional')
inherited = rest_filters.BooleanFilter(label='BOM line is inherited')
allow_variants = rest_filters.BooleanFilt... | class BomFilter(rest_filters.FilterSet):
| """
Custom filters for the BOM list
"""
# Boolean filters for BOM item
optional = rest_filters.BooleanFilter(label='BOM line is optional')
inherited = rest_filters.BooleanFilter(label='BOM line is inherited')
allow_variants = rest_filters.BooleanFilter(label='Variants are allowed')
# F... | = PartParameter.objects.all()
serializer_class = part_serializers.PartParameterSerializer
filter_backends = [
DjangoFilterBackend
]
filter_fields = [
'part',
'template',
]
class PartParameterDetail(generics.RetrieveUpdateDestroyAPIView):
"""
API endpoint for deta... | 103 | 103 | 344 | 8 | 94 | rkalman/InvenTree | InvenTree/part/api.py | Python | BomFilter | BomFilter | 1,535 | 1,575 | 1,535 | 1,535 | a422d5029cada0b003ca95a3ede080f340294257 | bigcode/the-stack | train |
2295ad1cb7cb2466c81754e2 | train | class | class BomItemSubstituteDetail(generics.RetrieveUpdateDestroyAPIView):
"""
API endpoint for detail view of a single BomItemSubstitute object
"""
queryset = BomItemSubstitute.objects.all()
serializer_class = part_serializers.BomItemSubstituteSerializer
| class BomItemSubstituteDetail(generics.RetrieveUpdateDestroyAPIView):
| """
API endpoint for detail view of a single BomItemSubstitute object
"""
queryset = BomItemSubstitute.objects.all()
serializer_class = part_serializers.BomItemSubstituteSerializer
| = BomItemSubstitute.objects.all()
filter_backends = [
DjangoFilterBackend,
filters.SearchFilter,
filters.OrderingFilter,
]
filter_fields = [
'part',
'bom_item',
]
class BomItemSubstituteDetail(generics.RetrieveUpdateDestroyAPIView):
| 63 | 64 | 58 | 15 | 48 | rkalman/InvenTree | InvenTree/part/api.py | Python | BomItemSubstituteDetail | BomItemSubstituteDetail | 1,917 | 1,923 | 1,917 | 1,917 | 9952d89486987e2342bb477280f8adbcffb53682 | bigcode/the-stack | train |
4582cd15929229ca0a98463c | train | class | class BomDetail(generics.RetrieveUpdateDestroyAPIView):
""" API endpoint for detail view of a single BomItem object """
queryset = BomItem.objects.all()
serializer_class = part_serializers.BomItemSerializer
def get_queryset(self, *args, **kwargs):
queryset = super().get_queryset(*args, **kwar... | class BomDetail(generics.RetrieveUpdateDestroyAPIView):
| """ API endpoint for detail view of a single BomItem object """
queryset = BomItem.objects.all()
serializer_class = part_serializers.BomItemSerializer
def get_queryset(self, *args, **kwargs):
queryset = super().get_queryset(*args, **kwargs)
queryset = self.get_serializer_class().setu... | omImportExtractSerializer
class BomImportSubmit(generics.CreateAPIView):
"""
API endpoint for submitting BOM data from a BOM file
"""
queryset = BomItem.objects.none()
serializer_class = part_serializers.BomImportSubmitSerializer
class BomDetail(generics.RetrieveUpdateDestroyAPIView):
| 64 | 64 | 104 | 12 | 51 | rkalman/InvenTree | InvenTree/part/api.py | Python | BomDetail | BomDetail | 1,852 | 1,865 | 1,852 | 1,852 | 480a85993d695e1a4e1f05605b2c55ff0660bfc1 | bigcode/the-stack | train |
22410cd05e7b83f0a94e2d21 | train | class | class BomItemSubstituteList(generics.ListCreateAPIView):
"""
API endpoint for accessing a list of BomItemSubstitute objects
"""
serializer_class = part_serializers.BomItemSubstituteSerializer
queryset = BomItemSubstitute.objects.all()
filter_backends = [
DjangoFilterBackend,
fi... | class BomItemSubstituteList(generics.ListCreateAPIView):
| """
API endpoint for accessing a list of BomItemSubstitute objects
"""
serializer_class = part_serializers.BomItemSubstituteSerializer
queryset = BomItemSubstitute.objects.all()
filter_backends = [
DjangoFilterBackend,
filters.SearchFilter,
filters.OrderingFilter,
]... | = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
if type(instance) == BomItem:
instance.validate_hash(valid)
return Response(serializer.data)
class BomItemSubstituteList(generics.L... | 64 | 64 | 95 | 13 | 51 | rkalman/InvenTree | InvenTree/part/api.py | Python | BomItemSubstituteList | BomItemSubstituteList | 1,897 | 1,914 | 1,897 | 1,897 | bde420ce3218088930e4e565638026ef9aa32507 | bigcode/the-stack | train |
d46c80999d9477eb417287c5 | train | class | class PartInternalPriceDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Detail endpoint for PartInternalPriceBreak model
"""
queryset = PartInternalPriceBreak.objects.all()
serializer_class = part_serializers.PartInternalPriceSerializer
| class PartInternalPriceDetail(generics.RetrieveUpdateDestroyAPIView):
| """
Detail endpoint for PartInternalPriceBreak model
"""
queryset = PartInternalPriceBreak.objects.all()
serializer_class = part_serializers.PartInternalPriceSerializer
|
"""
queryset = PartSellPriceBreak.objects.all()
serializer_class = part_serializers.PartSalePriceSerializer
filter_backends = [
DjangoFilterBackend
]
filter_fields = [
'part',
]
class PartInternalPriceDetail(generics.RetrieveUpdateDestroyAPIView):
| 63 | 64 | 50 | 14 | 49 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartInternalPriceDetail | PartInternalPriceDetail | 298 | 304 | 298 | 298 | 86094d425e24185a837bfa770f6cffd518bde6c7 | bigcode/the-stack | train |
fa4df5aebe96ba674617f2cc | train | class | class PartScheduling(generics.RetrieveAPIView):
"""
API endpoint for delivering "scheduling" information about a given part via the API.
Returns a chronologically ordered list about future "scheduled" events,
concerning stock levels for the part:
- Purchase Orders (incoming stock)
- Sales Orde... | class PartScheduling(generics.RetrieveAPIView):
| """
API endpoint for delivering "scheduling" information about a given part via the API.
Returns a chronologically ordered list about future "scheduled" events,
concerning stock levels for the part:
- Purchase Orders (incoming stock)
- Sales Orders (outgoing stock)
- Build Orders (incoming... | = part_serializers.PartThumbSerializer
def get_queryset(self):
queryset = super().get_queryset()
# Get all Parts which have an associated image
queryset = queryset.exclude(image='')
return queryset
def list(self, request, *args, **kwargs):
"""
Serialize the ... | 240 | 241 | 804 | 10 | 230 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartScheduling | PartScheduling | 461 | 594 | 461 | 461 | 3341f889c0b5cfc97ccce911ddb5aa2ba6efd05b | bigcode/the-stack | train |
401f56bceeaa53a0e2b751c7 | train | class | class PartList(APIDownloadMixin, generics.ListCreateAPIView):
"""
API endpoint for accessing a list of Part objects
- GET: Return list of objects
- POST: Create a new Part object
The Part object list can be filtered by:
- category: Filter by PartCategory reference
- cascade: If tru... | class PartList(APIDownloadMixin, generics.ListCreateAPIView):
| """
API endpoint for accessing a list of Part objects
- GET: Return list of objects
- POST: Create a new Part object
The Part object list can be filtered by:
- category: Filter by PartCategory reference
- cascade: If true, include parts from sub-categories
- starred: Is the... |
# has_stock filter
has_stock = rest_filters.BooleanFilter(label='Has stock', method='filter_has_stock')
def filter_has_stock(self, queryset, name, value):
value = str2bool(value)
if value:
queryset = queryset.filter(Q(in_stock__gt=0))
else:
queryset = que... | 256 | 256 | 3,529 | 14 | 242 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartList | PartList | 868 | 1,402 | 868 | 868 | a8b2f9bea7e6d6ca04609ba284eefe9a54a2c5fb | bigcode/the-stack | train |
2eff5118705243bf8265d8cd | train | class | class PartValidateBOM(generics.RetrieveUpdateAPIView):
"""
API endpoint for 'validating' the BOM for a given Part
"""
class BOMValidateSerializer(serializers.ModelSerializer):
class Meta:
model = Part
fields = [
'checksum',
'valid',
... | class PartValidateBOM(generics.RetrieveUpdateAPIView):
| """
API endpoint for 'validating' the BOM for a given Part
"""
class BOMValidateSerializer(serializers.ModelSerializer):
class Meta:
model = Part
fields = [
'checksum',
'valid',
]
checksum = serializers.CharField(
... | part_serializers.PartCopyBOMSerializer
def get_serializer_context(self):
ctx = super().get_serializer_context()
try:
ctx['part'] = Part.objects.get(pk=self.kwargs.get('pk', None))
except:
pass
return ctx
class PartValidateBOM(generics.RetrieveUpdateAPIVie... | 70 | 70 | 236 | 13 | 56 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartValidateBOM | PartValidateBOM | 655 | 702 | 655 | 655 | 62b1d19b730420a4b142fb5d979454c58e80ffaa | bigcode/the-stack | train |
858e2364ea41d366e6d17e31 | train | class | class BomImportExtract(generics.CreateAPIView):
"""
API endpoint for extracting BOM data from a BOM file.
"""
queryset = Part.objects.none()
serializer_class = part_serializers.BomImportExtractSerializer
| class BomImportExtract(generics.CreateAPIView):
| """
API endpoint for extracting BOM data from a BOM file.
"""
queryset = Part.objects.none()
serializer_class = part_serializers.BomImportExtractSerializer
| self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
data = serializer.extract_data()
return Response(data, status=status.HTTP_201_CREATED, headers=headers)
class Bo... | 64 | 64 | 46 | 10 | 54 | rkalman/InvenTree | InvenTree/part/api.py | Python | BomImportExtract | BomImportExtract | 1,834 | 1,840 | 1,834 | 1,834 | c8fe49f15b7f80d885d3e20683cfc62550a9d52c | bigcode/the-stack | train |
bd2e0132deb8fbbe343acac0 | train | class | class PartMetadata(generics.RetrieveUpdateAPIView):
"""
API endpoint for viewing / updating Part metadata
"""
def get_serializer(self, *args, **kwargs):
return MetadataSerializer(Part, *args, **kwargs)
queryset = Part.objects.all()
| class PartMetadata(generics.RetrieveUpdateAPIView):
| """
API endpoint for viewing / updating Part metadata
"""
def get_serializer(self, *args, **kwargs):
return MetadataSerializer(Part, *args, **kwargs)
queryset = Part.objects.all()
| .quantity,
_('Stock required for Build Order'),
str(allocation.build),
allocation.build.get_absolute_url(),
)
# Sort by incrementing date values
schedule = sorted(schedule, key=lambda entry: entry['date'])
return Response(schedule)
cl... | 64 | 64 | 57 | 11 | 53 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartMetadata | PartMetadata | 597 | 605 | 597 | 597 | 8e6d317b86aa9385046b6ff6cb78d8d4b82869a6 | bigcode/the-stack | train |
26a4784c467f9dba89ef4c4b | train | class | class PartDetail(generics.RetrieveUpdateDestroyAPIView):
""" API endpoint for detail view of a single Part object """
queryset = Part.objects.all()
serializer_class = part_serializers.PartSerializer
starred_parts = None
def get_queryset(self, *args, **kwargs):
queryset = super().get_query... | class PartDetail(generics.RetrieveUpdateDestroyAPIView):
| """ API endpoint for detail view of a single Part object """
queryset = Part.objects.all()
serializer_class = part_serializers.PartSerializer
starred_parts = None
def get_queryset(self, *args, **kwargs):
queryset = super().get_queryset(*args, **kwargs)
queryset = part_serializers... | ('Valid'),
help_text=_('Validate entire Bill of Materials'),
)
def validate_valid(self, valid):
if not valid:
raise ValidationError(_('This option must be selected'))
queryset = Part.objects.all()
serializer_class = BOMValidateSerializer
def update... | 145 | 145 | 484 | 12 | 133 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartDetail | PartDetail | 705 | 766 | 705 | 705 | 9c5f55efd833ab44096fc5e9a5ef1cfddaa800ca | bigcode/the-stack | train |
a2221bf93e1a6dca2ab23517 | train | class | class PartRelatedList(generics.ListCreateAPIView):
"""
API endpoint for accessing a list of PartRelated objects
"""
queryset = PartRelated.objects.all()
serializer_class = part_serializers.PartRelationSerializer
def filter_queryset(self, queryset):
queryset = super().filter_queryset(q... | class PartRelatedList(generics.ListCreateAPIView):
| """
API endpoint for accessing a list of PartRelated objects
"""
queryset = PartRelated.objects.all()
serializer_class = part_serializers.PartRelationSerializer
def filter_queryset(self, queryset):
queryset = super().filter_queryset(queryset)
params = self.request.query_param... | # Default ordering
ordering = 'name'
search_fields = [
'name',
'description',
'IPN',
'revision',
'keywords',
'category__name',
'manufacturer_parts__MPN',
]
class PartRelatedList(generics.ListCreateAPIView):
| 63 | 64 | 162 | 11 | 52 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartRelatedList | PartRelatedList | 1,405 | 1,431 | 1,405 | 1,405 | 5c075bb30df39dbaa5c6259d03d0ba89f2c4995a | bigcode/the-stack | train |
334b0f43f4b355cb2f8f5f12 | train | class | class PartThumbsUpdate(generics.RetrieveUpdateAPIView):
""" API endpoint for updating Part thumbnails"""
queryset = Part.objects.all()
serializer_class = part_serializers.PartThumbSerializerUpdate
filter_backends = [
DjangoFilterBackend
]
| class PartThumbsUpdate(generics.RetrieveUpdateAPIView):
| """ API endpoint for updating Part thumbnails"""
queryset = Part.objects.all()
serializer_class = part_serializers.PartThumbSerializerUpdate
filter_backends = [
DjangoFilterBackend
]
| Response(data)
filter_backends = [
filters.SearchFilter,
]
search_fields = [
'name',
'description',
'IPN',
'revision',
'keywords',
'category__name',
]
class PartThumbsUpdate(generics.RetrieveUpdateAPIView):
| 63 | 64 | 54 | 13 | 50 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartThumbsUpdate | PartThumbsUpdate | 450 | 458 | 450 | 450 | d79e78ddb90c0eed89a53d7c5f87a795cb24c97a | bigcode/the-stack | train |
4673ec566505e396c4fd399c | train | class | class PartSalePriceList(generics.ListCreateAPIView):
"""
API endpoint for list view of PartSalePriceBreak model
"""
queryset = PartSellPriceBreak.objects.all()
serializer_class = part_serializers.PartSalePriceSerializer
filter_backends = [
DjangoFilterBackend
]
filter_fields =... | class PartSalePriceList(generics.ListCreateAPIView):
| """
API endpoint for list view of PartSalePriceBreak model
"""
queryset = PartSellPriceBreak.objects.all()
serializer_class = part_serializers.PartSalePriceSerializer
filter_backends = [
DjangoFilterBackend
]
filter_fields = [
'part',
]
| name']
class PartSalePriceDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Detail endpoint for PartSellPriceBreak model
"""
queryset = PartSellPriceBreak.objects.all()
serializer_class = part_serializers.PartSalePriceSerializer
class PartSalePriceList(generics.ListCreateAPIView):
| 64 | 64 | 75 | 12 | 51 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartSalePriceList | PartSalePriceList | 281 | 295 | 281 | 281 | 7bbc5c0674e56d35912a68d508a40af55869315a | bigcode/the-stack | train |
b6213affa289175613c82765 | train | class | class PartAttachmentDetail(generics.RetrieveUpdateDestroyAPIView, AttachmentMixin):
"""
Detail endpoint for PartAttachment model
"""
queryset = PartAttachment.objects.all()
serializer_class = part_serializers.PartAttachmentSerializer
| class PartAttachmentDetail(generics.RetrieveUpdateDestroyAPIView, AttachmentMixin):
| """
Detail endpoint for PartAttachment model
"""
queryset = PartAttachment.objects.all()
serializer_class = part_serializers.PartAttachmentSerializer
| upload).
"""
queryset = PartAttachment.objects.all()
serializer_class = part_serializers.PartAttachmentSerializer
filter_backends = [
DjangoFilterBackend,
]
filter_fields = [
'part',
]
class PartAttachmentDetail(generics.RetrieveUpdateDestroyAPIView, AttachmentMixin):
| 63 | 64 | 47 | 16 | 47 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartAttachmentDetail | PartAttachmentDetail | 342 | 348 | 342 | 342 | 4a71180d56a2fe3453a5ac50f549341aad3ba7d0 | bigcode/the-stack | train |
799787799fca177dffd5ce19 | train | class | class PartFilter(rest_filters.FilterSet):
"""
Custom filters for the PartList endpoint.
Uses the django_filters extension framework
"""
# Filter by parts which have (or not) an IPN value
has_ipn = rest_filters.BooleanFilter(label='Has IPN', method='filter_has_ipn')
def filter_has_ipn(self,... | class PartFilter(rest_filters.FilterSet):
| """
Custom filters for the PartList endpoint.
Uses the django_filters extension framework
"""
# Filter by parts which have (or not) an IPN value
has_ipn = rest_filters.BooleanFilter(label='Has IPN', method='filter_has_ipn')
def filter_has_ipn(self, queryset, name, value):
value = ... | if inactive
if not part.active:
# Delete
return super(PartDetail, self).destroy(request, *args, **kwargs)
else:
# Return 405 error
message = f'Part \'{part.name}\' (pk = {part.pk}) is active: cannot delete'
return Response(status=status.HTTP_4... | 194 | 194 | 649 | 8 | 185 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartFilter | PartFilter | 769 | 865 | 769 | 769 | 65d9bd9d02df235f080f0820b670233996757f6e | bigcode/the-stack | train |
f5041cf781cb7a5badde417a | train | class | class CategoryTree(generics.ListAPIView):
"""
API endpoint for accessing a list of PartCategory objects ready for rendering a tree.
"""
queryset = PartCategory.objects.all()
serializer_class = part_serializers.CategoryTree
filter_backends = [
DjangoFilterBackend,
filters.Orderi... | class CategoryTree(generics.ListAPIView):
| """
API endpoint for accessing a list of PartCategory objects ready for rendering a tree.
"""
queryset = PartCategory.objects.all()
serializer_class = part_serializers.CategoryTree
filter_backends = [
DjangoFilterBackend,
filters.OrderingFilter,
]
# Order by tree level... | .get_ancestors(include_self=True)
queryset = queryset.filter(category__in=[cat.pk for cat in parents])
else:
queryset = queryset.filter(category=category)
except (ValueError, PartCategory.DoesNotExist):
pass
return queryset
cl... | 64 | 64 | 91 | 9 | 54 | rkalman/InvenTree | InvenTree/part/api.py | Python | CategoryTree | CategoryTree | 255 | 269 | 255 | 255 | da1a8921933e0d29015cf11ca52e9c0b468cb85c | bigcode/the-stack | train |
8d2b15001adaad7f37cb7231 | train | class | class PartParameterList(generics.ListCreateAPIView):
""" API endpoint for accessing a list of PartParameter objects
- GET: Return list of PartParameter objects
- POST: Create a new PartParameter object
"""
queryset = PartParameter.objects.all()
serializer_class = part_serializers.PartParameter... | class PartParameterList(generics.ListCreateAPIView):
| """ API endpoint for accessing a list of PartParameter objects
- GET: Return list of PartParameter objects
- POST: Create a new PartParameter object
"""
queryset = PartParameter.objects.all()
serializer_class = part_serializers.PartParameterSerializer
filter_backends = [
DjangoFil... | =cats)
template_ids = parameters.values_list('template').distinct()
queryset = queryset.filter(pk__in=[el[0] for el in template_ids])
except (ValueError, PartCategory.DoesNotExist):
pass
return queryset
class PartParameterList(generics.ListCreateAPIVi... | 64 | 64 | 95 | 11 | 52 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartParameterList | PartParameterList | 1,506 | 1,523 | 1,506 | 1,506 | 3b3b40680af9976fbd53f1d7b3df778601114d24 | bigcode/the-stack | train |
e5ceb7d6b271d5ddf9728652 | train | class | class PartSerialNumberDetail(generics.RetrieveAPIView):
"""
API endpoint for returning extra serial number information about a particular part
"""
queryset = Part.objects.all()
def retrieve(self, request, *args, **kwargs):
part = self.get_object()
# Calculate the "latest" serial ... | class PartSerialNumberDetail(generics.RetrieveAPIView):
| """
API endpoint for returning extra serial number information about a particular part
"""
queryset = Part.objects.all()
def retrieve(self, request, *args, **kwargs):
part = self.get_object()
# Calculate the "latest" serial number
latest = part.getLatestSerialNumber()
... | ics.RetrieveUpdateAPIView):
"""
API endpoint for viewing / updating Part metadata
"""
def get_serializer(self, *args, **kwargs):
return MetadataSerializer(Part, *args, **kwargs)
queryset = Part.objects.all()
class PartSerialNumberDetail(generics.RetrieveAPIView):
| 64 | 64 | 124 | 12 | 52 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartSerialNumberDetail | PartSerialNumberDetail | 608 | 632 | 608 | 608 | 3eceba629d10d6b1ab7f72d41b0a6cb1933bd69c | bigcode/the-stack | train |
068698dd9533cf9bdde5996e | train | class | class PartAttachmentList(generics.ListCreateAPIView, AttachmentMixin):
"""
API endpoint for listing (and creating) a PartAttachment (file upload).
"""
queryset = PartAttachment.objects.all()
serializer_class = part_serializers.PartAttachmentSerializer
filter_backends = [
DjangoFilterBa... | class PartAttachmentList(generics.ListCreateAPIView, AttachmentMixin):
| """
API endpoint for listing (and creating) a PartAttachment (file upload).
"""
queryset = PartAttachment.objects.all()
serializer_class = part_serializers.PartAttachmentSerializer
filter_backends = [
DjangoFilterBackend,
]
filter_fields = [
'part',
]
| .objects.all()
serializer_class = part_serializers.PartInternalPriceSerializer
permission_required = 'roles.sales_order.show'
filter_backends = [
DjangoFilterBackend
]
filter_fields = [
'part',
]
class PartAttachmentList(generics.ListCreateAPIView, AttachmentMixin):
| 63 | 64 | 77 | 14 | 49 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartAttachmentList | PartAttachmentList | 325 | 339 | 325 | 325 | 8ef0829c96099fb215193334b9c8cfd5c4ec0d0b | bigcode/the-stack | train |
169091563fc5bb66fa5a7b78 | train | class | class PartCopyBOM(generics.CreateAPIView):
"""
API endpoint for duplicating a BOM
"""
queryset = Part.objects.all()
serializer_class = part_serializers.PartCopyBOMSerializer
def get_serializer_context(self):
ctx = super().get_serializer_context()
try:
ctx['part'] ... | class PartCopyBOM(generics.CreateAPIView):
| """
API endpoint for duplicating a BOM
"""
queryset = Part.objects.all()
serializer_class = part_serializers.PartCopyBOMSerializer
def get_serializer_context(self):
ctx = super().get_serializer_context()
try:
ctx['part'] = Part.objects.get(pk=self.kwargs.get('pk',... | .getLatestSerialNumber()
data = {
'latest': latest,
}
if latest is not None:
next_serial = increment(latest)
if next_serial != increment:
data['next'] = next_serial
return Response(data)
class PartCopyBOM(generics.CreateAPIView):
| 64 | 64 | 92 | 11 | 53 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartCopyBOM | PartCopyBOM | 635 | 652 | 635 | 635 | 90c1f6e2ddbef1112f5d22fc58ba3a3b83740e34 | bigcode/the-stack | train |
3133f38eaa9c30e8def516a9 | train | class | class CategoryList(generics.ListCreateAPIView):
""" API endpoint for accessing a list of PartCategory objects.
- GET: Return a list of PartCategory objects
- POST: Create a new PartCategory object
"""
queryset = PartCategory.objects.all()
serializer_class = part_serializers.CategorySerializer
... | class CategoryList(generics.ListCreateAPIView):
| """ API endpoint for accessing a list of PartCategory objects.
- GET: Return a list of PartCategory objects
- POST: Create a new PartCategory object
"""
queryset = PartCategory.objects.all()
serializer_class = part_serializers.CategorySerializer
def get_serializer_context(self):
... | Related
from .models import BomItem, BomItemSubstitute
from .models import PartParameter, PartParameterTemplate
from .models import PartAttachment, PartTestTemplate
from .models import PartSellPriceBreak, PartInternalPriceBreak
from .models import PartCategoryParameterTemplate
from company.models import Company, Manuf... | 186 | 186 | 622 | 10 | 175 | rkalman/InvenTree | InvenTree/part/api.py | Python | CategoryList | CategoryList | 55 | 169 | 55 | 55 | fc776c7041def3a50535afbb20c1cab9eaf70288 | bigcode/the-stack | train |
efe3106c4859356745ce59f0 | train | class | class PartTestTemplateList(generics.ListCreateAPIView):
"""
API endpoint for listing (and creating) a PartTestTemplate.
"""
queryset = PartTestTemplate.objects.all()
serializer_class = part_serializers.PartTestTemplateSerializer
def filter_queryset(self, queryset):
"""
Filter t... | class PartTestTemplateList(generics.ListCreateAPIView):
| """
API endpoint for listing (and creating) a PartTestTemplate.
"""
queryset = PartTestTemplate.objects.all()
serializer_class = part_serializers.PartTestTemplateSerializer
def filter_queryset(self, queryset):
"""
Filter the test list queryset.
If filtering by 'part', ... | serializer_class = part_serializers.PartAttachmentSerializer
class PartTestTemplateDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Detail endpoint for PartTestTemplate model
"""
queryset = PartTestTemplate.objects.all()
serializer_class = part_serializers.PartTestTemplateSerializer
class P... | 71 | 71 | 238 | 12 | 58 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartTestTemplateList | PartTestTemplateList | 360 | 401 | 360 | 360 | f75308c181f18841fb691486562b3b311ee9a511 | bigcode/the-stack | train |
b3599dfd84b5fe58ad0f08fa | train | class | class CategoryDetail(generics.RetrieveUpdateDestroyAPIView):
"""
API endpoint for detail view of a single PartCategory object
"""
serializer_class = part_serializers.CategorySerializer
queryset = PartCategory.objects.all()
def get_serializer_context(self):
ctx = super().get_serializer... | class CategoryDetail(generics.RetrieveUpdateDestroyAPIView):
| """
API endpoint for detail view of a single PartCategory object
"""
serializer_class = part_serializers.CategorySerializer
queryset = PartCategory.objects.all()
def get_serializer_context(self):
ctx = super().get_serializer_context()
try:
ctx['starred_categories'... | ',
'lft',
]
# Use hierarchical ordering by default
ordering = [
'tree_id',
'lft',
'name'
]
search_fields = [
'name',
'description',
]
class CategoryDetail(generics.RetrieveUpdateDestroyAPIView):
| 63 | 64 | 190 | 12 | 51 | rkalman/InvenTree | InvenTree/part/api.py | Python | CategoryDetail | CategoryDetail | 172 | 201 | 172 | 172 | affcfdab8692b2589854c81778e25470c0a11646 | bigcode/the-stack | train |
ad239a2a8ba55ea620f75e4f | train | class | class PartParameterTemplateList(generics.ListCreateAPIView):
""" API endpoint for accessing a list of PartParameterTemplate objects.
- GET: Return list of PartParameterTemplate objects
- POST: Create a new PartParameterTemplate object
"""
queryset = PartParameterTemplate.objects.all()
serializ... | class PartParameterTemplateList(generics.ListCreateAPIView):
| """ API endpoint for accessing a list of PartParameterTemplate objects.
- GET: Return list of PartParameterTemplate objects
- POST: Create a new PartParameterTemplate object
"""
queryset = PartParameterTemplate.objects.all()
serializer_class = part_serializers.PartParameterTemplateSerializer
... | if part is not None:
try:
part = Part.objects.get(pk=part)
queryset = queryset.filter(Q(part_1=part) | Q(part_2=part))
except (ValueError, Part.DoesNotExist):
pass
return queryset
class PartRelatedDetail(generics.RetrieveUpdateDestroy... | 118 | 118 | 395 | 12 | 105 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartParameterTemplateList | PartParameterTemplateList | 1,443 | 1,503 | 1,443 | 1,443 | 812d49f71c53458eebd9d746587abafc1363e27e | bigcode/the-stack | train |
bda0499a93aa151c9f33b1c4 | train | class | class CategoryParameterList(generics.ListAPIView):
""" API endpoint for accessing a list of PartCategoryParameterTemplate objects.
- GET: Return a list of PartCategoryParameterTemplate objects
"""
queryset = PartCategoryParameterTemplate.objects.all()
serializer_class = part_serializers.CategoryPa... | class CategoryParameterList(generics.ListAPIView):
| """ API endpoint for accessing a list of PartCategoryParameterTemplate objects.
- GET: Return a list of PartCategoryParameterTemplate objects
"""
queryset = PartCategoryParameterTemplate.objects.all()
serializer_class = part_serializers.CategoryParameterTemplateSerializer
def get_queryset(sel... | return response
class CategoryMetadata(generics.RetrieveUpdateAPIView):
"""API endpoint for viewing / updating PartCategory metadata"""
def get_serializer(self, *args, **kwargs):
return MetadataSerializer(PartCategory, *args, **kwargs)
queryset = PartCategory.objects.all()
class CategoryParamet... | 70 | 70 | 235 | 10 | 60 | rkalman/InvenTree | InvenTree/part/api.py | Python | CategoryParameterList | CategoryParameterList | 213 | 252 | 213 | 213 | bb8da83d2c883621b1a7fb380cbd75975a827bff | bigcode/the-stack | train |
4a3914178bd6432d7e937785 | train | class | class PartTestTemplateDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Detail endpoint for PartTestTemplate model
"""
queryset = PartTestTemplate.objects.all()
serializer_class = part_serializers.PartTestTemplateSerializer
| class PartTestTemplateDetail(generics.RetrieveUpdateDestroyAPIView):
| """
Detail endpoint for PartTestTemplate model
"""
queryset = PartTestTemplate.objects.all()
serializer_class = part_serializers.PartTestTemplateSerializer
| ]
class PartAttachmentDetail(generics.RetrieveUpdateDestroyAPIView, AttachmentMixin):
"""
Detail endpoint for PartAttachment model
"""
queryset = PartAttachment.objects.all()
serializer_class = part_serializers.PartAttachmentSerializer
class PartTestTemplateDetail(generics.RetrieveUpdateDestr... | 64 | 64 | 48 | 14 | 49 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartTestTemplateDetail | PartTestTemplateDetail | 351 | 357 | 351 | 351 | a206b7813b439b29b179a49b91fab1f768b65121 | bigcode/the-stack | train |
f957ee350a8d42ee9a7712fe | train | class | class PartInternalPriceList(generics.ListCreateAPIView):
"""
API endpoint for list view of PartInternalPriceBreak model
"""
queryset = PartInternalPriceBreak.objects.all()
serializer_class = part_serializers.PartInternalPriceSerializer
permission_required = 'roles.sales_order.show'
filter_... | class PartInternalPriceList(generics.ListCreateAPIView):
| """
API endpoint for list view of PartInternalPriceBreak model
"""
queryset = PartInternalPriceBreak.objects.all()
serializer_class = part_serializers.PartInternalPriceSerializer
permission_required = 'roles.sales_order.show'
filter_backends = [
DjangoFilterBackend
]
filte... | ]
class PartInternalPriceDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Detail endpoint for PartInternalPriceBreak model
"""
queryset = PartInternalPriceBreak.objects.all()
serializer_class = part_serializers.PartInternalPriceSerializer
class PartInternalPriceList(generics.ListCreateAPIView)... | 64 | 64 | 85 | 12 | 51 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartInternalPriceList | PartInternalPriceList | 307 | 322 | 307 | 307 | fa601b6e844cf6dcb5657a6d0592a9b672e78a8a | bigcode/the-stack | train |
9f00c3b17102fb8fbf39e820 | train | class | class BomItemValidate(generics.UpdateAPIView):
""" API endpoint for validating a BomItem """
# Very simple serializers
class BomItemValidationSerializer(serializers.Serializer):
valid = serializers.BooleanField(default=False)
queryset = BomItem.objects.all()
serializer_class = BomItemVali... | class BomItemValidate(generics.UpdateAPIView):
| """ API endpoint for validating a BomItem """
# Very simple serializers
class BomItemValidationSerializer(serializers.Serializer):
valid = serializers.BooleanField(default=False)
queryset = BomItem.objects.all()
serializer_class = BomItemValidationSerializer
def update(self, request,... | (self, *args, **kwargs):
queryset = super().get_queryset(*args, **kwargs)
queryset = self.get_serializer_class().setup_eager_loading(queryset)
queryset = self.get_serializer_class().annotate_queryset(queryset)
return queryset
class BomItemValidate(generics.UpdateAPIView):
| 64 | 64 | 154 | 10 | 53 | rkalman/InvenTree | InvenTree/part/api.py | Python | BomItemValidate | BomItemValidate | 1,868 | 1,894 | 1,868 | 1,868 | 22c6ad793e189ff9b6719d0d454dd4383c02c1e9 | bigcode/the-stack | train |
ad6e235f5ca4d34ad0bf6872 | train | class | class PartRelatedDetail(generics.RetrieveUpdateDestroyAPIView):
"""
API endpoint for accessing detail view of a PartRelated object
"""
queryset = PartRelated.objects.all()
serializer_class = part_serializers.PartRelationSerializer
| class PartRelatedDetail(generics.RetrieveUpdateDestroyAPIView):
| """
API endpoint for accessing detail view of a PartRelated object
"""
queryset = PartRelated.objects.all()
serializer_class = part_serializers.PartRelationSerializer
| try:
part = Part.objects.get(pk=part)
queryset = queryset.filter(Q(part_1=part) | Q(part_2=part))
except (ValueError, Part.DoesNotExist):
pass
return queryset
class PartRelatedDetail(generics.RetrieveUpdateDestroyAPIView):
| 64 | 64 | 49 | 13 | 50 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartRelatedDetail | PartRelatedDetail | 1,434 | 1,440 | 1,434 | 1,434 | f788ffd363b8951653ee30dd813e63d5ae1cffc1 | bigcode/the-stack | train |
8f8ee4600df74fcac18f1ad2 | train | class | class PartSalePriceDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Detail endpoint for PartSellPriceBreak model
"""
queryset = PartSellPriceBreak.objects.all()
serializer_class = part_serializers.PartSalePriceSerializer
| class PartSalePriceDetail(generics.RetrieveUpdateDestroyAPIView):
| """
Detail endpoint for PartSellPriceBreak model
"""
queryset = PartSellPriceBreak.objects.all()
serializer_class = part_serializers.PartSalePriceSerializer
| = part_serializers.CategoryTree
filter_backends = [
DjangoFilterBackend,
filters.OrderingFilter,
]
# Order by tree level (top levels first) and then name
ordering = ['level', 'name']
class PartSalePriceDetail(generics.RetrieveUpdateDestroyAPIView):
| 64 | 64 | 50 | 14 | 50 | rkalman/InvenTree | InvenTree/part/api.py | Python | PartSalePriceDetail | PartSalePriceDetail | 272 | 278 | 272 | 272 | 09dcbe0e4c1ff0957eff36319f41d241d53a2860 | bigcode/the-stack | train |
b65a463c0026f9338024cf0d | train | class | class MapSum(object):
class Node:
def __init__(self):
self.val = 0
self.dict = dict()
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = MapSum.Node()
def insert(self, key: str, val: int) -> None:
cur_node = ... | class MapSum(object):
| class Node:
def __init__(self):
self.val = 0
self.dict = dict()
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = MapSum.Node()
def insert(self, key: str, val: int) -> None:
cur_node = self.root
for ... | 整数)的键值对。字符串表示键,整数表示值。如果键已经存在,那么原来的键值对将被替代成新的键值对。
# 对于方法 sum,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。
class MapSum(object):
| 72 | 72 | 241 | 5 | 67 | agnes-yang/LeetCode-Solutions-in-Good-Style | 23-trie/python/0677-map-sum-pairs.py | Python | MapSum | MapSum | 7 | 44 | 7 | 7 | 8eb072d84364372e0842fbf0c9ceff18ef2eb822 | bigcode/the-stack | train |
e8ecc9bf4f8975f043b8e128 | train | function | def SegmentCollection(mode="agg-fast", *args, **kwargs):
"""
mode: string
- "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness)
- "agg" (speed: slower, size: medium, output: perfect, no dash)
"""
if mode == "raw":
return RawSegmentCollection(*args,... | def SegmentCollection(mode="agg-fast", *args, **kwargs):
| """
mode: string
- "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness)
- "agg" (speed: slower, size: medium, output: perfect, no dash)
"""
if mode == "raw":
return RawSegmentCollection(*args, **kwargs)
return AggSegmentCollection(*args, **kwarg... | 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
from . raw_segment_collection import RawSegmentCollection
from . agg_segment_collection import AggSegmentCollection
def SegmentCollection(mode="a... | 64 | 64 | 102 | 14 | 49 | antoineMoPa/glumpy | glumpy/graphics/collections/segment_collection.py | Python | SegmentCollection | SegmentCollection | 9 | 18 | 9 | 9 | b1f12f4ef67a4660633ffd8cfe9014f2b2889c8b | bigcode/the-stack | train |
15088d24d5a569eef51747c3 | train | function | @requires_duration
@apply_to_mask
def time_symmetrize(clip):
"""
Returns a clip that plays the current clip once forwards and
then once backwards. This is very practival to make video that
loop well, e.g. to create animated GIFs.
This effect is automatically applied to the clip's mask and audio
... | @requires_duration
@apply_to_mask
def time_symmetrize(clip):
| """
Returns a clip that plays the current clip once forwards and
then once backwards. This is very practival to make video that
loop well, e.g. to create animated GIFs.
This effect is automatically applied to the clip's mask and audio
if they exist.
"""
return concatenate_videoclips([cli... | from moviepy.decorators import apply_to_audio, apply_to_mask, requires_duration
from moviepy.video.compositing.concatenate import concatenate_videoclips
from .time_mirror import time_mirror
@requires_duration
@apply_to_mask
def time_symmetrize(clip):
| 58 | 64 | 99 | 17 | 40 | RichardPienaar/moviepy | moviepy/video/fx/time_symmetrize.py | Python | time_symmetrize | time_symmetrize | 7 | 17 | 7 | 9 | 4ca3af0b3c9246934c2133ea52a5319f08141c0a | bigcode/the-stack | train |
15fd04cec749c942e9375ab3 | train | class | class Book:
def __init__(self, name, author, pages):
self.name = name
self.author = author
self.pages = pages
| class Book:
| def __init__(self, name, author, pages):
self.name = name
self.author = author
self.pages = pages
| class Book:
| 3 | 64 | 34 | 3 | 0 | Veselin-Stoilov/software-university-OOP | first_steps_in_oop/class_book.py | Python | Book | Book | 1 | 5 | 1 | 1 | c0e6cf8d37aae33e17d23c858c31e2940b8487c2 | bigcode/the-stack | train |
9d33dfa7f33c546517638ecb | train | class | class Leverfun:
stock_api = 'https://app.leverfun.com/timelyInfo/timelyOrderForm'
def __init__(self):
self.stocks_dict = dict()
def stocks(self, stock_codes):
if type(stock_codes) is not list:
stock_codes = [stock_codes]
threads = []
for stock in stock_codes:
... | class Leverfun:
| stock_api = 'https://app.leverfun.com/timelyInfo/timelyOrderForm'
def __init__(self):
self.stocks_dict = dict()
def stocks(self, stock_codes):
if type(stock_codes) is not list:
stock_codes = [stock_codes]
threads = []
for stock in stock_codes:
threa... | import asyncio
import aiohttp
import ssl
class Leverfun:
| 14 | 150 | 501 | 4 | 9 | gitrobi/easyquotation | test_lf.py | Python | Leverfun | Leverfun | 8 | 58 | 8 | 8 | 633c13a803e54b2f90608c9fd07ec8274151c28f | bigcode/the-stack | train |
ad5637fec7eb845b2dc9a671 | train | class | class TtmlApi(BaseApi):
@poscheck_except(2)
def __init__(self, api_key, tenant_org_id=None, base_url=None, logger=None):
# type: (str, str, str, BitmovinApiLoggerBase) -> None
super(TtmlApi, self).__init__(
api_key=api_key,
tenant_org_id=tenant_org_id,
base_u... | class TtmlApi(BaseApi):
@poscheck_except(2)
| def __init__(self, api_key, tenant_org_id=None, base_url=None, logger=None):
# type: (str, str, str, BitmovinApiLoggerBase) -> None
super(TtmlApi, self).__init__(
api_key=api_key,
tenant_org_id=tenant_org_id,
base_url=base_url,
logger=logger
)... | # coding: utf-8
from __future__ import absolute_import
from bitmovin_api_sdk.common import BaseApi, BitmovinApiLoggerBase
from bitmovin_api_sdk.common.poscheck import poscheck_except
from bitmovin_api_sdk.models.response_envelope import ResponseEnvelope
from bitmovin_api_sdk.models.response_error import ResponseError... | 104 | 157 | 525 | 15 | 88 | hofmannben/bitmovin-api-sdk-python | bitmovin_api_sdk/encoding/encodings/muxings/cmaf/captions/ttml/ttml_api.py | Python | TtmlApi | TtmlApi | 12 | 64 | 12 | 13 | f7586f6a3cbbdce4cf397d7c865671dfd4fb264d | bigcode/the-stack | train |
07cbeda647cb82383aa55ed2 | train | class | class SomaFMClient:
CHANNELS_URI = "https://api.somafm.com/channels.xml"
# All channels seem to have this combination of quality/encoding available
FALLBACK_QUALITY = "fast"
FALLBACK_ENCODING = "mp3"
channels = {}
images = {}
def __init__(self, proxy_config=None, user_agent=None):
... | class SomaFMClient:
| CHANNELS_URI = "https://api.somafm.com/channels.xml"
# All channels seem to have this combination of quality/encoding available
FALLBACK_QUALITY = "fast"
FALLBACK_ENCODING = "mp3"
channels = {}
images = {}
def __init__(self, proxy_config=None, user_agent=None):
super().__init__()
... | import collections
import logging
import re
from urllib.parse import urlsplit
import requests
from mopidy import httpclient
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
logger = logging.getLogger(__name__)
#
# Channels are playlist and Album
# PLS are t... | 92 | 256 | 1,045 | 5 | 87 | jakebriggs/mopidy-somafm | mopidy_somafm/somafm.py | Python | SomaFMClient | SomaFMClient | 25 | 165 | 25 | 26 | 5110cbd8941fa0ea1eccdf407326f8a863f7de62 | bigcode/the-stack | train |
c0910fa622966b1c955b220d | train | function | def register_custom_filters():
"""
Register custom filters for the Django admin.
This function is called in AppConfig.ready() (ralph.admin.apps).
"""
field_filter_mapper = [
(lambda f: bool(f.choices), ChoicesListFilter),
(lambda f: isinstance(f, (
models.DecimalFiel... | def register_custom_filters():
| """
Register custom filters for the Django admin.
This function is called in AppConfig.ready() (ralph.admin.apps).
"""
field_filter_mapper = [
(lambda f: bool(f.choices), ChoicesListFilter),
(lambda f: isinstance(f, (
models.DecimalField, models.IntegerField
... | yield {
'selected': self.value() or False,
'parameter_name': self.parameter_name,
}
def queryset(self, request, queryset):
if not self.value():
liquidated_status = self.model._meta.get_field(
'status'
).choices.liquidated.id
... | 84 | 84 | 281 | 5 | 78 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | register_custom_filters | register_custom_filters | 448 | 487 | 448 | 448 | ddab9d62773d88b32117014dedf22e1c2d7e32c1 | bigcode/the-stack | train |
734d1591c791bd3981f79332 | train | class | class NumberListFilter(DateListFilter):
"""Renders filter form with decimal field."""
template = 'admin/filters/number_filter.html'
def queryset(self, request, queryset):
if any(self.value()):
value = self.value()
if value[0]:
queryset = queryset.filter(**{... | class NumberListFilter(DateListFilter):
| """Renders filter form with decimal field."""
template = 'admin/filters/number_filter.html'
def queryset(self, request, queryset):
if any(self.value()):
value = self.value()
if value[0]:
queryset = queryset.filter(**{
'{}__gte'.format(sel... | ,
'parameter_name_end': self.parameter_name_end,
'date_start': value[0],
'date_end': value[1],
'date_format': date_format_to_human(
get_format('DATE_INPUT_FORMATS')[0]
)
}
class NumberListFilter(DateListFilter):
| 64 | 64 | 207 | 8 | 56 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | NumberListFilter | NumberListFilter | 207 | 239 | 207 | 208 | 35f6f255990f806320f985e3dfb2ff343979d588 | bigcode/the-stack | train |
dd8b40512dc1ef87d9707985 | train | class | class BooleanListFilter(ChoicesListFilter):
_choices_list = [
('1', _('Yes')),
('0', _('No')),
]
| class BooleanListFilter(ChoicesListFilter):
| _choices_list = [
('1', _('Yes')),
('0', _('No')),
]
| == self.value(),
'value': lookup,
'display': title,
'parameter_name': self.field_path,
}
def queryset(self, request, queryset):
if self.value():
return queryset.filter(**{self.field_path: self.value()})
class BooleanListFilter(Choices... | 64 | 64 | 31 | 9 | 55 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | BooleanListFilter | BooleanListFilter | 131 | 136 | 131 | 132 | 70fbd87fed0f32fd1a1a655e589967f34c609896 | bigcode/the-stack | train |
3984d586bdae7caac09d6e6e | train | function | @lru_cache()
def date_format_to_human(value):
"""
Convert Python format date to human.
Example:
>>> date_format_to_human('%Y-%m-%d')
YYYY-MM-DD
:param value: Date format example: %Y-%m
"""
maps = {
'%y': 'YY',
'%Y': 'YYYY',
'%m': 'MM',
'%d': 'DD'... | @lru_cache()
def date_format_to_human(value):
| """
Convert Python format date to human.
Example:
>>> date_format_to_human('%Y-%m-%d')
YYYY-MM-DD
:param value: Date format example: %Y-%m
"""
maps = {
'%y': 'YY',
'%Y': 'YYYY',
'%m': 'MM',
'%d': 'DD',
}
for k, v in maps.items():
... | .admin.autocomplete import AUTOCOMPLETE_EMPTY_VALUE
from ralph.admin.helpers import get_field_by_relation_path
SEARCH_OR_SEPARATORS_REGEX = re.compile(r'[;|]')
SEARCH_AND_SEPARATORS_REGEX = re.compile(r'[&]')
@lru_cache()
def date_format_to_human(value):
| 63 | 64 | 117 | 13 | 51 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | date_format_to_human | date_format_to_human | 30 | 49 | 30 | 31 | dce27aa9798c9be1b58ae67bdfe5ab5da977ee83 | bigcode/the-stack | train |
aa7a51861d2cbf609c278c67 | train | class | class RelatedAutocompleteFieldListFilter(RelatedFieldListFilter):
"""Filter for Foregin key field."""
template = "admin/filters/related_filter.html"
empty_value = AUTOCOMPLETE_EMPTY_VALUE
def __init__(self, field, request, params, model, model_admin, field_path):
super().__init__(field, reque... | class RelatedAutocompleteFieldListFilter(RelatedFieldListFilter):
| """Filter for Foregin key field."""
template = "admin/filters/related_filter.html"
empty_value = AUTOCOMPLETE_EMPTY_VALUE
def __init__(self, field, request, params, model, model_admin, field_path):
super().__init__(field, request, params, model, model_admin, field_path)
self.field_mode... | request, queryset):
if self.value():
for value in SEARCH_AND_SEPARATORS_REGEX.split(self.value()):
queryset = queryset.filter(tags__name=value.strip())
return queryset
class RelatedFieldListFilter(ChoicesListFilter):
"""
Filter for related fields (ForeignKeys) whic... | 155 | 155 | 518 | 12 | 143 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | RelatedAutocompleteFieldListFilter | RelatedAutocompleteFieldListFilter | 295 | 369 | 295 | 296 | 622bec89d6d2696837ed496d0c3b0d56031aba6c | bigcode/the-stack | train |
1f96905d87fa7f1303d872b4 | train | class | class DateListFilter(BaseCustomFilter):
"""Renders filter form with date field."""
template = 'admin/filters/date_filter.html'
def __init__(self, field, request, params, model, model_admin, field_path):
used_parameters = {}
self.parameter_name_start = field_path + '__start'
self.p... | class DateListFilter(BaseCustomFilter):
| """Renders filter form with date field."""
template = 'admin/filters/date_filter.html'
def __init__(self, field, request, params, model, model_admin, field_path):
used_parameters = {}
self.parameter_name_start = field_path + '__start'
self.parameter_name_end = field_path + '__end'
... |
}
for lookup, title in self.choices_list:
yield {
'selected': smart_text(lookup) == self.value(),
'value': lookup,
'display': title,
'parameter_name': self.field_path,
}
def queryset(self, request, queryset):
... | 120 | 121 | 404 | 8 | 112 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | DateListFilter | DateListFilter | 139 | 204 | 139 | 140 | 1a563e25c112806485f1ec85c34a112c9249311e | bigcode/the-stack | train |
c9619e73610aa47daf8c04f5 | train | class | class RelatedFieldListFilter(ChoicesListFilter):
"""
Filter for related fields (ForeignKeys) which is displayed as regular HTML
select list (all options are fetched at once).
"""
def label_for_instance(self, obj):
return smart_text(obj)
@property
def choices_list(self):
mode... | class RelatedFieldListFilter(ChoicesListFilter):
| """
Filter for related fields (ForeignKeys) which is displayed as regular HTML
select list (all options are fetched at once).
"""
def label_for_instance(self, obj):
return smart_text(obj)
@property
def choices_list(self):
model = get_model_from_relation(self.field)
q... | .pattern[1:-1]))
multiple = False
def queryset(self, request, queryset):
if self.value():
for value in SEARCH_AND_SEPARATORS_REGEX.split(self.value()):
queryset = queryset.filter(tags__name=value.strip())
return queryset
class RelatedFieldListFilter(ChoicesListFilter... | 64 | 64 | 105 | 10 | 53 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | RelatedFieldListFilter | RelatedFieldListFilter | 280 | 292 | 280 | 280 | f9b409116ead082eff8717fcf6a5fe82fb39eab1 | bigcode/the-stack | train |
de7cfc14eb8c89285078f76d | train | class | class LiquidatedStatusFilter(SimpleListFilter):
title = _('show liquidated')
parameter_name = 'liquidated'
template = "admin/filters/checkbox_filter.html"
def __init__(self, request, params, model, model_admin):
super().__init__(request, params, model, model_admin)
self.model = model
... | class LiquidatedStatusFilter(SimpleListFilter):
| title = _('show liquidated')
parameter_name = 'liquidated'
template = "admin/filters/checkbox_filter.html"
def __init__(self, request, params, model, model_admin):
super().__init__(request, params, model, model_admin)
self.model = model
def lookups(self, request, model_admin):
... | {
'field_name': self.title
}
)
raise IncorrectLookupParameters()
else:
queryset = queryset.filter(**{
self.field_path + '__in': root.get_descendants(
include_self=True
... | 64 | 64 | 185 | 9 | 54 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | LiquidatedStatusFilter | LiquidatedStatusFilter | 417 | 445 | 417 | 418 | 377a7132c07c2a002ca09740caf3ce3c69ed59e4 | bigcode/the-stack | train |
81e0616c19c751c77d030a0f | train | class | class TagsListFilter(TextListFilter):
"""Filter by taggit tags."""
separators = " and ".join(list(SEARCH_AND_SEPARATORS_REGEX.pattern[1:-1]))
multiple = False
def queryset(self, request, queryset):
if self.value():
for value in SEARCH_AND_SEPARATORS_REGEX.split(self.value()):
... | class TagsListFilter(TextListFilter):
| """Filter by taggit tags."""
separators = " and ".join(list(SEARCH_AND_SEPARATORS_REGEX.pattern[1:-1]))
multiple = False
def queryset(self, request, queryset):
if self.value():
for value in SEARCH_AND_SEPARATORS_REGEX.split(self.value()):
queryset = queryset.filter(t... | )
return queryset.filter(query)
def choices(self, cl):
return ({
'current_value': self.value(),
'parameter_name': self.field_path,
'separators': self.separators,
'multiple': self.multiple
},)
class TagsListFilter(TextListFilter):
| 64 | 64 | 85 | 8 | 56 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | TagsListFilter | TagsListFilter | 268 | 277 | 268 | 268 | c24cdea7cba38432a739d2d73ee87d00ee201fa8 | bigcode/the-stack | train |
26cd341add5f405c2f19d2a1 | train | class | class ChoicesListFilter(BaseCustomFilter):
"""Renders filter form with choices field."""
template = 'admin/filters/choices_filter.html'
_choices_list = []
@property
def choices_list(self):
return self._choices_list
@choices_list.setter
def choices_list(self, value):
self.... | class ChoicesListFilter(BaseCustomFilter):
| """Renders filter form with choices field."""
template = 'admin/filters/choices_filter.html'
_choices_list = []
@property
def choices_list(self):
return self._choices_list
@choices_list.setter
def choices_list(self, value):
self._choices_list = value
def choices(self,... | returns None.
"""
return self.used_parameters.get(self.field_path, None)
def has_output(self):
return True
def lookups(self, request, model_admin):
return None
def expected_parameters(self):
return [self.lookup_kwarg]
class ChoicesListFilter(BaseCustomFilter):
| 64 | 64 | 192 | 8 | 56 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | ChoicesListFilter | ChoicesListFilter | 95 | 128 | 95 | 96 | ffbd1115d4c1fccd02aec1707a62d7e47ab32ca6 | bigcode/the-stack | train |
177d16cbc2fda10f85ad51f6 | train | class | class TextListFilter(BaseCustomFilter):
"""Renders filter form with char field."""
template = "admin/filters/text_filter.html"
separators = " or ".join(list(SEARCH_OR_SEPARATORS_REGEX.pattern[1:-1]))
multiple = True
def queryset(self, request, queryset):
if self.value():
query... | class TextListFilter(BaseCustomFilter):
| """Renders filter form with char field."""
template = "admin/filters/text_filter.html"
separators = " or ".join(list(SEARCH_OR_SEPARATORS_REGEX.pattern[1:-1]))
multiple = True
def queryset(self, request, queryset):
if self.value():
query = Q()
for value in SEARCH_OR... | step = 1
yield {
'parameter_name_start': self.parameter_name_start,
'parameter_name_end': self.parameter_name_end,
'start_value': value[0],
'end_value': value[1],
'step': step
}
class TextListFilter(BaseCustomFilter):
| 64 | 64 | 166 | 8 | 56 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | TextListFilter | TextListFilter | 242 | 265 | 242 | 243 | e84fcbb027b56b7bbae8784c23b63dc78dc9f6af | bigcode/the-stack | train |
61606ef170dde03bc8ed70f9 | train | class | class TreeRelatedFieldListFilter(RelatedFieldListFilter):
"""
Related filter for TreeForeignKeys.
"""
def __init__(self, field, request, params, model, model_admin, field_path):
self.level_indicator = DEFAULT_LEVEL_INDICATOR
super().__init__(field, request, params, model, model_admin, fi... | class TreeRelatedFieldListFilter(RelatedFieldListFilter):
| """
Related filter for TreeForeignKeys.
"""
def __init__(self, field, request, params, model, model_admin, field_path):
self.level_indicator = DEFAULT_LEVEL_INDICATOR
super().__init__(field, request, params, model, model_admin, field_path)
def _get_level_indicator(self, obj):
... | 'detailsurl': reverse(
'admin:{}_{}_autocomplete_details'.format(*model_options)
),
}
return ({
'value': self.value(),
'attrs': flatatt(widget_options),
'name': self.field_path,
'related_url': self.get_related_url(),... | 92 | 92 | 307 | 12 | 80 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | TreeRelatedFieldListFilter | TreeRelatedFieldListFilter | 372 | 414 | 372 | 372 | 0abffafec2df900bcf6fabdd6045b4dbb4d0cad8 | bigcode/the-stack | train |
4776498d04b1a05980088a0d | train | class | class BaseCustomFilter(FieldListFilter):
"""Base class for custom filters."""
def __init__(self, field, request, params, model, model_admin, field_path):
self.lookup_kwarg = field_path
self.model = model
try:
if field.flatchoices:
self.choices_list = field.f... | class BaseCustomFilter(FieldListFilter):
| """Base class for custom filters."""
def __init__(self, field, request, params, model, model_admin, field_path):
self.lookup_kwarg = field_path
self.model = model
try:
if field.flatchoices:
self.choices_list = field.flatchoices
except AttributeError:
... | : Date format example: %Y-%m
"""
maps = {
'%y': 'YY',
'%Y': 'YYYY',
'%m': 'MM',
'%d': 'DD',
}
for k, v in maps.items():
value = value.replace(k, v)
return value
class BaseCustomFilter(FieldListFilter):
| 76 | 76 | 256 | 8 | 67 | angry-tony/cmdb-ralph | src/ralph/admin/filters.py | Python | BaseCustomFilter | BaseCustomFilter | 52 | 92 | 52 | 53 | 4ccdf38dde759df53192604e26b39c0c598cccb1 | bigcode/the-stack | train |
5ef6f007e76a5747c88c6b58 | train | function | @bot.on_message(
~filters.private
& filters.text
& ~filters.command("start")
& ~filters.edited,
group=69,
)
async def chat(_, message):
if message.reply_to_message:
if not message.reply_to_message.from_user:
return
from_user_id = message.reply_to_message.from_user.id
... | @bot.on_message(
~filters.private
& filters.text
& ~filters.command("start")
& ~filters.edited,
group=69,
)
async def chat(_, message):
| if message.reply_to_message:
if not message.reply_to_message.from_user:
return
from_user_id = message.reply_to_message.from_user.id
if from_user_id != bot_id:
return
else:
match = re.search(
"[.|\n]{0,}iris[.|\n]{0,}",
message.text.... | message.reply_text(responsess2)
await message._client.send_chat_action(chat_id, "cancel")
@bot.on_message(
~filters.private
& filters.text
& ~filters.command("start")
& ~filters.edited,
group=69,
)
async def chat(_, message):
| 64 | 64 | 143 | 42 | 22 | Punnisher80/NellyX | Nelly.py | Python | chat | chat | 58 | 80 | 58 | 65 | 0d32aaabb41b080600a82ed1209626825f0b1462 | bigcode/the-stack | train |
52ae6494aa5c6a0129df4cd0 | train | function | @bot.on_message(
filters.private
& ~filters.command("start")
& ~filters.edited
)
async def chatpm(_, message):
if not message.text:
await message.reply_text("What's that,,,,I can't read that,,,")
return
await type_and_send(message)
| @bot.on_message(
filters.private
& ~filters.command("start")
& ~filters.edited
)
async def chatpm(_, message):
| if not message.text:
await message.reply_text("What's that,,,,I can't read that,,,")
return
await type_and_send(message)
| 0,}",
message.text.strip(),
flags=re.IGNORECASE,
)
if not match:
return
await type_and_send(message)
@bot.on_message(
filters.private
& ~filters.command("start")
& ~filters.edited
)
async def chatpm(_, message):
| 64 | 64 | 63 | 32 | 32 | Punnisher80/NellyX | Nelly.py | Python | chatpm | chatpm | 82 | 91 | 82 | 87 | 644f716f108d6af69a3a4f3e564f67cd9a6052d0 | bigcode/the-stack | train |
4bcce6494b82da5e2223ac5f | train | function | @bot.on_message(filters.command("start") & ~filters.edited)
async def startt(_, message):
await message.reply_text("Hi, I'm Nelly AI chatbot By @kayaspirerproject")
| @bot.on_message(filters.command("start") & ~filters.edited)
async def startt(_, message):
| await message.reply_text("Hi, I'm Nelly AI chatbot By @kayaspirerproject")
| .edited
)
async def chatpm(_, message):
if not message.text:
await message.reply_text("What's that,,,,I can't read that,,,")
return
await type_and_send(message)
@bot.on_message(filters.command("start") & ~filters.edited)
async def startt(_, message):
| 64 | 64 | 42 | 22 | 42 | Punnisher80/NellyX | Nelly.py | Python | startt | startt | 94 | 96 | 94 | 95 | 7ddf22a7746eb3d94f31cd6755a5fc6083c03950 | bigcode/the-stack | train |
956a938f96408028bc62ae47 | train | function | async def type_and_send(message):
chat_id = message.chat.id
user_id = message.from_user.id if message.from_user else 0
query = message.text.strip()
await message._client.send_chat_action(chat_id, "typing")
response, _ = await gather(lunaQuery(query, user_id), sleep(2))
if "Luna" in response:
... | async def type_and_send(message):
| chat_id = message.chat.id
user_id = message.from_user.id if message.from_user else 0
query = message.text.strip()
await message._client.send_chat_action(chat_id, "typing")
response, _ = await gather(lunaQuery(query, user_id), sleep(2))
if "Luna" in response:
responsee = response.replace(... | result.translatedText
)
resp = (await arq.luna(query, user_id)).result
return (
resp
if LANGUAGE == "en"
else (
await arq.translate(resp, LANGUAGE)
).result.translatedText
)
async def type_and_send(message):
| 64 | 64 | 205 | 7 | 57 | Punnisher80/NellyX | Nelly.py | Python | type_and_send | type_and_send | 36 | 55 | 36 | 36 | b1629bb944ad7bbf7ebc64057d2c37a0b8382c3e | bigcode/the-stack | train |
f800cf0a257d62579827c8f5 | train | function | async def lunaQuery(query: str, user_id: int):
query = (
query
if LANGUAGE == "en"
else (await arq.translate(query, "en")).result.translatedText
)
resp = (await arq.luna(query, user_id)).result
return (
resp
if LANGUAGE == "en"
else (
await arq... | async def lunaQuery(query: str, user_id: int):
| query = (
query
if LANGUAGE == "en"
else (await arq.translate(query, "en")).result.translatedText
)
resp = (await arq.luna(query, user_id)).result
return (
resp
if LANGUAGE == "en"
else (
await arq.translate(resp, LANGUAGE)
).result.tra... | , ARQ_API_BASE_URL, LANGUAGE
bot_token= BOT_TOKEN
print("[INFO]: Checking... Your Details")
bot_id = int(bot_token.split(":")[0])
print("[INFO]: Code running by master Aspirer")
arq = None
async def lunaQuery(query: str, user_id: int):
| 64 | 64 | 96 | 13 | 50 | Punnisher80/NellyX | Nelly.py | Python | lunaQuery | lunaQuery | 20 | 33 | 20 | 20 | fc6730758abdf0dbeed4f78a24747bc758c1df16 | bigcode/the-stack | train |
dd85314e7e60bd36c89eadff | train | function | async def main():
global arq
session = ClientSession()
arq = ARQ(ARQ_API_BASE_URL, ARQ_API_KEY, session)
await bot.start()
print(
"""
Your Nelly Is Deployed Successfully.
"""
)
await idle()
| async def main():
| global arq
session = ClientSession()
arq = ARQ(ARQ_API_BASE_URL, ARQ_API_KEY, session)
await bot.start()
print(
"""
Your Nelly Is Deployed Successfully.
"""
)
await idle()
| that,,,,I can't read that,,,")
return
await type_and_send(message)
@bot.on_message(filters.command("start") & ~filters.edited)
async def startt(_, message):
await message.reply_text("Hi, I'm Nelly AI chatbot By @kayaspirerproject")
async def main():
| 64 | 64 | 60 | 4 | 60 | Punnisher80/NellyX | Nelly.py | Python | main | main | 99 | 110 | 99 | 99 | 78ac86276fc4154b2696f313c04df3e058995427 | bigcode/the-stack | train |
5fffb57dc7ea0c65575862c8 | train | class | class ImageInline(admin.StackedInline):
model = Image
extra = 1
fields = (('name', 'image'),
('title', 'sentence'),
('description'),
)
exclude = ('slug',)
| class ImageInline(admin.StackedInline):
| model = Image
extra = 1
fields = (('name', 'image'),
('title', 'sentence'),
('description'),
)
exclude = ('slug',)
| fafa'),
('color'),
)
class SubMenuAdmin(admin.ModelAdmin):
list_display = ['subtitle']
fields = (('submenu'),
('subtitle', 'subslug'),
('submark', 'subfafa'),
('subcolor'),
)
class ImageInline(admin.StackedInline):
| 64 | 64 | 49 | 8 | 56 | vovagod/projectseven | mysite/base/BaseAdmin.py | Python | ImageInline | ImageInline | 26 | 33 | 26 | 26 | 66b783d7b8dfb741b9e8120d2b71f474f4f3b3ed | bigcode/the-stack | train |
8c1b7f46cfe2d17544d18b66 | train | function | def str_to_class(str):
try:
obj = getattr(sys.modules[__name__], str)
except AttributeError:
return None
return obj
| def str_to_class(str):
| try:
obj = getattr(sys.modules[__name__], str)
except AttributeError:
return None
return obj
| , form, formset, change):
instances = formset.save(commit=False)
for obj in formset.deleted_objects:
obj.delete()
for instance in instances:
instance.desc_html = markdown(instance.description)
instance.save()
formset.save_m2m()
def str_to_class(str):
| 63 | 64 | 35 | 6 | 57 | vovagod/projectseven | mysite/base/BaseAdmin.py | Python | str_to_class | str_to_class | 64 | 69 | 64 | 64 | a0015240aa0b6fd72fbcbbba248cec453e838de5 | bigcode/the-stack | train |
92c33b03367e439af9cd5091 | train | class | class BaseAdmin(admin.ModelAdmin):
list_display = ['menu', 'title','timestamp' ]
fields = (('menu', 'title'),
('slug'),
('subtitle', 'sentence'),
('description'),
('urllink', 'filenum', 'flag'),
('image'),
('data1', 'data2', 'da... | class BaseAdmin(admin.ModelAdmin):
| list_display = ['menu', 'title','timestamp' ]
fields = (('menu', 'title'),
('slug'),
('subtitle', 'sentence'),
('description'),
('urllink', 'filenum', 'flag'),
('image'),
('data1', 'data2', 'data3', 'data4'),
)
... | ('subcolor'),
)
class ImageInline(admin.StackedInline):
model = Image
extra = 1
fields = (('name', 'image'),
('title', 'sentence'),
('description'),
)
exclude = ('slug',)
class BaseAdmin(admin.ModelAdmin):
| 63 | 64 | 171 | 7 | 56 | vovagod/projectseven | mysite/base/BaseAdmin.py | Python | BaseAdmin | BaseAdmin | 36 | 60 | 36 | 36 | 1a8089b2319e188c449c35da0b12a6edf247a0f8 | bigcode/the-stack | train |
22eaf11a9b303cbbb696d8ca | train | class | class MenuAdmin(admin.ModelAdmin):
list_display = ['title']
fields = (('title', 'slug'),
('mark', 'fafa'),
('color'),
)
| class MenuAdmin(admin.ModelAdmin):
| list_display = ['title']
fields = (('title', 'slug'),
('mark', 'fafa'),
('color'),
)
| import sys
from django.contrib import admin
from django.core.exceptions import ValidationError
from django.apps import apps
from markdown import markdown
from .models import Base, Menu, SubMenu, Image
class MenuAdmin(admin.ModelAdmin):
| 48 | 64 | 38 | 7 | 40 | vovagod/projectseven | mysite/base/BaseAdmin.py | Python | MenuAdmin | MenuAdmin | 9 | 14 | 9 | 9 | b871f302ef6c4465f61ad713942468b7fe132f75 | bigcode/the-stack | train |
7e9e8403a88b04fd77450777 | train | class | class SubMenuAdmin(admin.ModelAdmin):
list_display = ['subtitle']
fields = (('submenu'),
('subtitle', 'subslug'),
('submark', 'subfafa'),
('subcolor'),
)
| class SubMenuAdmin(admin.ModelAdmin):
| list_display = ['subtitle']
fields = (('submenu'),
('subtitle', 'subslug'),
('submark', 'subfafa'),
('subcolor'),
)
| from markdown import markdown
from .models import Base, Menu, SubMenu, Image
class MenuAdmin(admin.ModelAdmin):
list_display = ['title']
fields = (('title', 'slug'),
('mark', 'fafa'),
('color'),
)
class SubMenuAdmin(admin.ModelAdmin):
| 64 | 64 | 47 | 8 | 56 | vovagod/projectseven | mysite/base/BaseAdmin.py | Python | SubMenuAdmin | SubMenuAdmin | 17 | 23 | 17 | 17 | e352e0711660968e59659571a073b7179535e58a | bigcode/the-stack | train |
428552b4fe1a76239f0b3f71 | train | function | @given(strategies.lists_pairs)
def test_basic(pair: AlternativeNativeListsPair) -> None:
alternative, native = pair
alternative_result, native_result = alternative.clear(), native.clear()
assert alternative_result is native_result is None
assert are_alternative_native_lists_equal(alternative, native)
| @given(strategies.lists_pairs)
def test_basic(pair: AlternativeNativeListsPair) -> None:
| alternative, native = pair
alternative_result, native_result = alternative.clear(), native.clear()
assert alternative_result is native_result is None
assert are_alternative_native_lists_equal(alternative, native)
| from hypothesis import given
from tests.utils import (AlternativeNativeListsPair,
are_alternative_native_lists_equal)
from . import strategies
@given(strategies.lists_pairs)
def test_basic(pair: AlternativeNativeListsPair) -> None:
| 50 | 64 | 65 | 22 | 27 | lycantropos/cppbuiltins | tests/lists_tests/test_clear.py | Python | test_basic | test_basic | 8 | 15 | 8 | 9 | 83e75aa64ab9400fe3d11ee91b7ea039fe82bafa | bigcode/the-stack | train |
9b92720e306e10bd07cfbd5d | train | class | class Solution(object):
def minWindow(self, S, T):
"""
Algorithm:
two pointers
Aggressively enclose the chars until find all T, and then shrink the window as far as possible
:param S: str
:param T: str
:return: str
"""
min_win = [0,... | class Solution(object):
| def minWindow(self, S, T):
"""
Algorithm:
two pointers
Aggressively enclose the chars until find all T, and then shrink the window as far as possible
:param S: str
:param T: str
:return: str
"""
min_win = [0, sys.maxint] # [start, e... | and a string T, find the minimum window in S which will contain all the characters in T in complexity
O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".
If there are multiple such wi... | 116 | 117 | 391 | 4 | 112 | ChiFire/legend_LeetCode | 076 Minimum Window Substring.py | Python | Solution | Solution | 20 | 60 | 20 | 20 | 405b5c21eb3e0d8974e14ac0437942d05377d4ac | bigcode/the-stack | train |
46895e304fa9512a6a5a1aa8 | train | class | class Ejercicios(TemplateView):
def get_template(self, t, n):
_t = ['attributes', 'headings']
_n = [1, 2, 3, 4, 5, 6, 7, 8, 9]
if str(t) not in _t:
raise Exception('Not in the whitelist')
if str(n) not in _n:
raise Exception('Not in the whitelist')
... | class Ejercicios(TemplateView):
| def get_template(self, t, n):
_t = ['attributes', 'headings']
_n = [1, 2, 3, 4, 5, 6, 7, 8, 9]
if str(t) not in _t:
raise Exception('Not in the whitelist')
if str(n) not in _n:
raise Exception('Not in the whitelist')
return '{0}/{1}'.format(t, n)
... | import unicode_literals
from django.shortcuts import render
from django.views.generic import ListView, CreateView, TemplateView, UpdateView, DeleteView
from .forms import EstudianteModelForm, AsignaturaModelForm
from .models import Estudiante, Asignatura
class Ejercicios(TemplateView):
| 64 | 64 | 152 | 8 | 55 | ErickAgrazal/django-docker-compose | src/apps/home/views.py | Python | Ejercicios | Ejercicios | 11 | 26 | 11 | 11 | e7f522507070713c48a868a38db7891d94a43010 | bigcode/the-stack | train |
39973ff2203a5e4fa7d484d6 | train | class | class EstudianteCreateView(CreateView):
template_name = "estudiante_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/estudiantes'
form_class = EstudianteModelForm
| class EstudianteCreateView(CreateView):
| template_name = "estudiante_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/estudiantes'
form_class = EstudianteModelForm
| .html"
class EstudianteListView(ListView):
template_name = "estudiante_list.html"
model = Estudiante
http_method_names = [u'get', ]
def get_queryset(self):
qs = super().get_queryset()
return qs.filter()
class EstudianteCreateView(CreateView):
| 64 | 64 | 49 | 8 | 56 | ErickAgrazal/django-docker-compose | src/apps/home/views.py | Python | EstudianteCreateView | EstudianteCreateView | 43 | 47 | 43 | 43 | f94a3a7c1583a06093be24f364bb6812e4969098 | bigcode/the-stack | train |
0af855b000e4afb73ecac879 | train | class | class EstudianteListView(ListView):
template_name = "estudiante_list.html"
model = Estudiante
http_method_names = [u'get', ]
def get_queryset(self):
qs = super().get_queryset()
return qs.filter()
| class EstudianteListView(ListView):
| template_name = "estudiante_list.html"
model = Estudiante
http_method_names = [u'get', ]
def get_queryset(self):
qs = super().get_queryset()
return qs.filter()
| def get(self, request, *args, **kwargs):
template_name = self.get_template(self.kwargs.get('t'), self.kwargs.get('n'))
return render(request, template_name)
class HomeView(TemplateView):
template_name = "home.html"
class EstudianteListView(ListView):
| 64 | 64 | 54 | 8 | 56 | ErickAgrazal/django-docker-compose | src/apps/home/views.py | Python | EstudianteListView | EstudianteListView | 33 | 40 | 33 | 33 | bdb8526607b8d14b077b4a3e077663e6cce14eb0 | bigcode/the-stack | train |
face1ca345bd97032c8b3a82 | train | class | class HomeView(TemplateView):
template_name = "home.html"
| class HomeView(TemplateView):
| template_name = "home.html"
| the whitelist')
return '{0}/{1}'.format(t, n)
def get(self, request, *args, **kwargs):
template_name = self.get_template(self.kwargs.get('t'), self.kwargs.get('n'))
return render(request, template_name)
class HomeView(TemplateView):
| 64 | 64 | 15 | 7 | 57 | ErickAgrazal/django-docker-compose | src/apps/home/views.py | Python | HomeView | HomeView | 29 | 30 | 29 | 29 | 561c59560f5a4eb313d3a93882295233ee13956d | bigcode/the-stack | train |
20a4143b025abe65e1c730fe | train | class | class AsignaturaCreateView(CreateView):
template_name = "asignatura_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/asignaturas'
form_class = AsignaturaModelForm
| class AsignaturaCreateView(CreateView):
| template_name = "asignatura_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/asignaturas'
form_class = AsignaturaModelForm
| ignaturaListView(ListView):
template_name = "asignatura_list.html"
model = Asignatura
http_method_names = [u'get', ]
def get_queryset(self):
qs = super().get_queryset()
return qs.filter()
class AsignaturaCreateView(CreateView):
| 64 | 64 | 53 | 9 | 55 | ErickAgrazal/django-docker-compose | src/apps/home/views.py | Python | AsignaturaCreateView | AsignaturaCreateView | 74 | 78 | 74 | 74 | 514e9fa65f3b06783d7eb280d72c069a8ea63552 | bigcode/the-stack | train |
7bafb0c671b228093aed6a7e | train | class | class EstudianteDeleteView(DeleteView):
template_name = "estudiante_delete.html"
model = Estudiante
success_url = '/estudiantes'
| class EstudianteDeleteView(DeleteView):
| template_name = "estudiante_delete.html"
model = Estudiante
success_url = '/estudiantes'
|
class EstudianteUpdateView(UpdateView):
template_name = "estudiante_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/estudiantes'
form_class = EstudianteModelForm
model = Estudiante
class EstudianteDeleteView(DeleteView):
| 64 | 64 | 32 | 8 | 55 | ErickAgrazal/django-docker-compose | src/apps/home/views.py | Python | EstudianteDeleteView | EstudianteDeleteView | 58 | 61 | 58 | 58 | 2a02c2feea307eb2293bfcaad6c5d73f95725a05 | bigcode/the-stack | train |
641bf845dd26e1f6561ebe3a | train | class | class EstudianteUpdateView(UpdateView):
template_name = "estudiante_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/estudiantes'
form_class = EstudianteModelForm
model = Estudiante
| class EstudianteUpdateView(UpdateView):
| template_name = "estudiante_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/estudiantes'
form_class = EstudianteModelForm
model = Estudiante
| _queryset()
return qs.filter()
class EstudianteCreateView(CreateView):
template_name = "estudiante_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/estudiantes'
form_class = EstudianteModelForm
class EstudianteUpdateView(UpdateView):
| 64 | 64 | 55 | 8 | 55 | ErickAgrazal/django-docker-compose | src/apps/home/views.py | Python | EstudianteUpdateView | EstudianteUpdateView | 50 | 55 | 50 | 50 | 0f738a1f57e95d98dd2d089992b28a82c11161e8 | bigcode/the-stack | train |
bdd94c5915d7a6a13e2cbc6b | train | class | class AsignaturaDeleteView(DeleteView):
template_name = "asignatura_delete.html"
model = Asignatura
success_url = '/asignaturas'
| class AsignaturaDeleteView(DeleteView):
| template_name = "asignatura_delete.html"
model = Asignatura
success_url = '/asignaturas'
| View(UpdateView):
template_name = "asignatura_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/asignaturas'
model = Asignatura
form_class = AsignaturaModelForm
class AsignaturaDeleteView(DeleteView):
| 64 | 64 | 36 | 9 | 54 | ErickAgrazal/django-docker-compose | src/apps/home/views.py | Python | AsignaturaDeleteView | AsignaturaDeleteView | 89 | 92 | 89 | 89 | d3dc1cc6fabe769d99d368f891659c5de36b8d9b | bigcode/the-stack | train |
0eea4430a88531e4fee6551f | train | class | class AsignaturaUpdateView(UpdateView):
template_name = "asignatura_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/asignaturas'
model = Asignatura
form_class = AsignaturaModelForm
| class AsignaturaUpdateView(UpdateView):
| template_name = "asignatura_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/asignaturas'
model = Asignatura
form_class = AsignaturaModelForm
| .filter()
class AsignaturaCreateView(CreateView):
template_name = "asignatura_create.html"
http_method_names = [u'get', u'post', ]
success_url = '/asignaturas'
form_class = AsignaturaModelForm
class AsignaturaUpdateView(UpdateView):
| 64 | 64 | 60 | 9 | 54 | ErickAgrazal/django-docker-compose | src/apps/home/views.py | Python | AsignaturaUpdateView | AsignaturaUpdateView | 81 | 86 | 81 | 81 | 2be44e946d4bd73e1c240bd43cfa1e277a319d0e | bigcode/the-stack | train |
8b2427c36a4a23d5e6c218c2 | train | class | class AsignaturaListView(ListView):
template_name = "asignatura_list.html"
model = Asignatura
http_method_names = [u'get', ]
def get_queryset(self):
qs = super().get_queryset()
return qs.filter()
| class AsignaturaListView(ListView):
| template_name = "asignatura_list.html"
model = Asignatura
http_method_names = [u'get', ]
def get_queryset(self):
qs = super().get_queryset()
return qs.filter()
| success_url = '/estudiantes'
form_class = EstudianteModelForm
model = Estudiante
class EstudianteDeleteView(DeleteView):
template_name = "estudiante_delete.html"
model = Estudiante
success_url = '/estudiantes'
class AsignaturaListView(ListView):
| 64 | 64 | 57 | 9 | 55 | ErickAgrazal/django-docker-compose | src/apps/home/views.py | Python | AsignaturaListView | AsignaturaListView | 64 | 71 | 64 | 64 | 2fe9bbc83d1d7620f26fa2e3de14371f3c917b1b | bigcode/the-stack | train |
462c0b309b222490b7369ad8 | train | function | def configure_logger(app):
"""Configure loggers."""
handler = logging.StreamHandler(sys.stdout)
if not app.logger.handlers:
app.logger.addHandler(handler)
| def configure_logger(app):
| """Configure loggers."""
handler = logging.StreamHandler(sys.stdout)
if not app.logger.handlers:
app.logger.addHandler(handler)
| ."""
return {"db": db, "User": user.models.User}
app.shell_context_processor(shell_context)
def register_commands(app):
"""Register Click commands."""
app.cli.add_command(commands.test)
app.cli.add_command(commands.lint)
app.cli.add_command(commands.users)
def configure_logger(app):
| 64 | 64 | 34 | 5 | 59 | ser/motracker | motracker/app.py | Python | configure_logger | configure_logger | 112 | 116 | 112 | 112 | 1fc13d809bd7c1598edb64407279c8f4940c339b | bigcode/the-stack | train |
99a645da753c89b6a98378e1 | train | function | def create_app(config_object="motracker.settings"):
"""Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
:param config_object: The configuration object to use.
"""
app = Flask(__name__.split(".")[0])
app.config.from_object(config_object)
register... | def create_app(config_object="motracker.settings"):
| """Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
:param config_object: The configuration object to use.
"""
app = Flask(__name__.split(".")[0])
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
re... | public, user
from motracker.extensions import (
bcrypt,
cache,
csrf_protect,
db,
debug_toolbar,
filez,
login_manager,
mail,
migrate,
ws,
store,
webpack,
)
def create_app(config_object="motracker.settings"):
| 64 | 64 | 113 | 11 | 53 | ser/motracker | motracker/app.py | Python | create_app | create_app | 32 | 46 | 32 | 32 | 12794c14bbdf05f749adc9e7cce469a6f4752206 | bigcode/the-stack | train |
be45bc7390560a6d1dd60735 | train | function | def register_errorhandlers(app):
"""Register error handlers."""
def render_error(error):
"""Render error template."""
# If a HTTPException, pull the `code` attribute; default to 500
error_code = getattr(error, "code", 500)
return render_template("{0}.html".format(error_code)), e... | def register_errorhandlers(app):
| """Register error handlers."""
def render_error(error):
"""Render error template."""
# If a HTTPException, pull the `code` attribute; default to 500
error_code = getattr(error, "code", 500)
return render_template("{0}.html".format(error_code)), error_code
for errcode in [40... | ws.init_app(app)
return None
def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(public.views.blueprint)
app.register_blueprint(user.views.blueprint)
app.register_blueprint(gpsdb.views.blueprint)
return None
def register_errorhandlers(app):
| 64 | 64 | 100 | 6 | 57 | ser/motracker | motracker/app.py | Python | register_errorhandlers | register_errorhandlers | 81 | 92 | 81 | 81 | f4b9406ed0f2d049d3a9c15431770747f996f694 | bigcode/the-stack | train |
71fa8a8cc5d163307bf787b1 | train | function | def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(public.views.blueprint)
app.register_blueprint(user.views.blueprint)
app.register_blueprint(gpsdb.views.blueprint)
return None
| def register_blueprints(app):
| """Register Flask blueprints."""
app.register_blueprint(public.views.blueprint)
app.register_blueprint(user.views.blueprint)
app.register_blueprint(gpsdb.views.blueprint)
return None
| _protect.init_app(app)
login_manager.init_app(app)
debug_toolbar.init_app(app)
mail.init_app(app)
migrate.init_app(app, db)
webpack.init_app(app)
KVSessionExtension(store, app)
ws.init_app(app)
return None
def register_blueprints(app):
| 64 | 64 | 49 | 6 | 57 | ser/motracker | motracker/app.py | Python | register_blueprints | register_blueprints | 73 | 78 | 73 | 73 | 3ad6b733042d1b2f09afaad09b900009b0bc325b | bigcode/the-stack | train |
7c3871cf3c00130511b2f755 | train | function | def register_extensions(app):
"""Register Flask extensions."""
bcrypt.init_app(app)
cache.init_app(app)
db.init_app(app)
csrf_protect.init_app(app)
login_manager.init_app(app)
debug_toolbar.init_app(app)
mail.init_app(app)
migrate.init_app(app, db)
webpack.init_app(app)
KVSes... | def register_extensions(app):
| """Register Flask extensions."""
bcrypt.init_app(app)
cache.init_app(app)
db.init_app(app)
csrf_protect.init_app(app)
login_manager.init_app(app)
debug_toolbar.init_app(app)
mail.init_app(app)
migrate.init_app(app, db)
webpack.init_app(app)
KVSessionExtension(store, app)
... | _configuration(app):
configure_uploads(app, filez)
patch_request_class(app, size=25000000)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.debug = True
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
def register_extensions(app):
| 64 | 64 | 89 | 5 | 59 | ser/motracker | motracker/app.py | Python | register_extensions | register_extensions | 57 | 70 | 57 | 57 | b165eefd0ffea8d004ab3f5b2329ac156ba91d42 | bigcode/the-stack | train |
5619f0e123b38ccfdc7e2437 | train | function | def register_shellcontext(app):
"""Register shell context objects."""
def shell_context():
"""Shell context objects."""
return {"db": db, "User": user.models.User}
app.shell_context_processor(shell_context)
| def register_shellcontext(app):
| """Register shell context objects."""
def shell_context():
"""Shell context objects."""
return {"db": db, "User": user.models.User}
app.shell_context_processor(shell_context)
|
error_code = getattr(error, "code", 500)
return render_template("{0}.html".format(error_code)), error_code
for errcode in [401, 404, 500]:
app.errorhandler(errcode)(render_error)
return None
def register_shellcontext(app):
| 64 | 64 | 46 | 6 | 57 | ser/motracker | motracker/app.py | Python | register_shellcontext | register_shellcontext | 95 | 102 | 95 | 95 | c11d0e4015f5c3dc35bff4de52748dcb0d382fd0 | bigcode/the-stack | train |
f95599bf02841f176ee46df6 | train | function | def register_configuration(app):
configure_uploads(app, filez)
patch_request_class(app, size=25000000)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.debug = True
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
| def register_configuration(app):
| configure_uploads(app, filez)
patch_request_class(app, size=25000000)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.debug = True
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
| Flask(__name__.split(".")[0])
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
register_configuration(app)
register_errorhandlers(app)
register_shellcontext(app)
register_commands(app)
configure_logger(app)
return app
def register_configuration... | 64 | 64 | 61 | 5 | 58 | ser/motracker | motracker/app.py | Python | register_configuration | register_configuration | 49 | 54 | 49 | 49 | 609c5c7632288531c077240163b325fa2d3c96b2 | bigcode/the-stack | train |
5d91a936a795ff2cbc692421 | train | function | def register_commands(app):
"""Register Click commands."""
app.cli.add_command(commands.test)
app.cli.add_command(commands.lint)
app.cli.add_command(commands.users)
| def register_commands(app):
| """Register Click commands."""
app.cli.add_command(commands.test)
app.cli.add_command(commands.lint)
app.cli.add_command(commands.users)
| app.errorhandler(errcode)(render_error)
return None
def register_shellcontext(app):
"""Register shell context objects."""
def shell_context():
"""Shell context objects."""
return {"db": db, "User": user.models.User}
app.shell_context_processor(shell_context)
def register_commands(ap... | 64 | 64 | 36 | 5 | 59 | ser/motracker | motracker/app.py | Python | register_commands | register_commands | 105 | 109 | 105 | 105 | dc9ec3b993aab04961a094b4203b4add3b913f15 | bigcode/the-stack | train |
501fcf7026d951a4b390f264 | train | class | class RpcDispatcher(object):
"""Dispatch rpc messages according to the requested API version.
This class can be used as the top level 'manager' for a service. It
contains a list of underlying managers that have an API_VERSION attribute.
"""
def __init__(self, callbacks):
"""Initialize the... | class RpcDispatcher(object):
| """Dispatch rpc messages according to the requested API version.
This class can be used as the top level 'manager' for a service. It
contains a list of underlying managers that have an API_VERSION attribute.
"""
def __init__(self, callbacks):
"""Initialize the rpc dispatcher.
:pa... | .py) should be bumped.
The implementation of the method must not expect the parameter to be present.::
def some_remote_method(self, arg1, arg2, newarg=None):
# The code needs to deal with newarg=None for cases
# where an older client sends a message without it.
pass
On the client side, the... | 116 | 116 | 389 | 5 | 110 | hyunsun/quantum | quantum/openstack/common/rpc/dispatcher.py | Python | RpcDispatcher | RpcDispatcher | 89 | 138 | 89 | 89 | b33af89334b2c6e529534525f6b8042b3e82c7a6 | bigcode/the-stack | train |
5f7c696d002df13303f74600 | train | function | def rhs(t,state):
'''
State should contain a list or array of number density of all particle and temperature.
in order of:
HI, HII, e, HeI, HeII, HeIII, HM, H2I, H2II, T
'''
from Rate import generate_k
# extract the number density of each element including species and temp a... | def rhs(t,state):
| '''
State should contain a list or array of number density of all particle and temperature.
in order of:
HI, HII, e, HeI, HeII, HeIII, HM, H2I, H2II, T
'''
from Rate import generate_k
# extract the number density of each element including species and temp and time step and so... | from Rate import generate_k
import numpy as np
def rhs(t,state):
| 16 | 256 | 1,447 | 5 | 10 | Thirty-OneR/Astr496_assignment03 | assignment_03/rhs.py | Python | rhs | rhs | 4 | 89 | 4 | 4 | 640f77304dc7a2b1ddea0a5ef08aeac396c1249b | bigcode/the-stack | train |
c7ffa173246bcf7da18b6973 | train | function | def test_RouteEntry_invalidCompression():
"""Should work as expected."""
with pytest.raises(ValueError):
proxy.RouteEntry(
funct,
"my-function",
"/endpoint/test/<id>",
payload_compression_method="nope",
)
| def test_RouteEntry_invalidCompression():
| """Should work as expected."""
with pytest.raises(ValueError):
proxy.RouteEntry(
funct,
"my-function",
"/endpoint/test/<id>",
payload_compression_method="nope",
)
| ",
binary_b64encode=True,
)
assert route.endpoint == funct
assert route.methods == ["POST"]
assert route.cors
assert route.token == "Yo"
assert route.compression == "deflate"
assert route.b64encode
def test_RouteEntry_invalidCompression():
| 64 | 64 | 53 | 8 | 55 | dmmop/lambda-proxy | tests/test_proxy.py | Python | test_RouteEntry_invalidCompression | test_RouteEntry_invalidCompression | 97 | 105 | 97 | 97 | 8e011a0c9e5dd1b27da730e5b64bfb3be2a23bd4 | bigcode/the-stack | train |
8e04d6d5639d147c8e869112 | train | function | def test_API_noLog():
"""Should work as expected."""
app = proxy.API(name="test", configure_logs=False)
assert app.name == "test"
assert not app.debug
assert app.log
# Clear logger handlers
for h in app.log.handlers:
app.log.removeHandler(h)
| def test_API_noLog():
| """Should work as expected."""
app = proxy.API(name="test", configure_logs=False)
assert app.name == "test"
assert not app.debug
assert app.log
# Clear logger handlers
for h in app.log.handlers:
app.log.removeHandler(h)
| == "test"
assert len(list(app.routes.keys())) == 0
assert not app.debug
assert app.log.getEffectiveLevel() == 40 # ERROR
# Clear logger handlers
for h in app.log.handlers:
app.log.removeHandler(h)
def test_API_noLog():
| 64 | 64 | 66 | 6 | 58 | dmmop/lambda-proxy | tests/test_proxy.py | Python | test_API_noLog | test_API_noLog | 134 | 143 | 134 | 134 | 426d994d4b0e82f28b65c8e2d51dc2e8fc60c79a | bigcode/the-stack | train |
0dc906a977392f698d43ecb0 | train | function | def test_headersNull():
"""Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy"))
app._add_route("/test/<user>", funct, methods=["GET"], cors=True)
event = {
"path": "/test/remotepixel",
"httpMethod": "GET",
... | def test_headersNull():
| """Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy"))
app._add_route("/test/<user>", funct, methods=["GET"], cors=True)
event = {
"path": "/test/remotepixel",
"httpMethod": "GET",
"headers": None,
... | ": "GET",
"Access-Control-Allow-Origin": "*",
"Content-Type": "text/plain",
},
"statusCode": 200,
}
res = app(event, {})
assert res == resp
funct.assert_called_with(user="remotepixel")
def test_headersNull():
| 64 | 64 | 195 | 5 | 59 | dmmop/lambda-proxy | tests/test_proxy.py | Python | test_headersNull | test_headersNull | 382 | 406 | 382 | 382 | c3cd02a6a0757e182d6fe59cdeecdfa891aa6f5e | bigcode/the-stack | train |
e210b424e2fae376efa6a9fb | train | function | def test_API_docCustomDomain():
"""Should work as expected."""
app = proxy.API(name="test")
@app.route("/test", methods=["POST"])
def _post(body: str) -> Tuple[str, str, str]:
"""Return something."""
return ("OK", "text/plain", "Yo")
@app.route("/<user>", methods=["GET"], tag=["use... | def test_API_docCustomDomain():
| """Should work as expected."""
app = proxy.API(name="test")
@app.route("/test", methods=["POST"])
def _post(body: str) -> Tuple[str, str, str]:
"""Return something."""
return ("OK", "text/plain", "Yo")
@app.route("/<user>", methods=["GET"], tag=["users"], description="a route")
... | api_apigw_content == body
event = {
"path": "/docs",
"httpMethod": "GET",
"headers": {"Host": "afakeapi.execute-api.us-east-1.amazonaws.com"},
"requestContext": {"stage": "production"},
"queryStringParameters": {},
}
headers = {
"Access-Control-Allow-Credenti... | 168 | 168 | 561 | 7 | 161 | dmmop/lambda-proxy | tests/test_proxy.py | Python | test_API_docCustomDomain | test_API_docCustomDomain | 1,281 | 1,347 | 1,281 | 1,281 | c897e2d9cd1055ecbf81c27441c325ada5104c98 | bigcode/the-stack | train |
00501c424abaceb93770f394 | train | function | def test_proxy_APIpathCustomDomain():
"""Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy"))
app._add_route("/test/<string:user>/<name>", funct, methods=["GET"], cors=True)
event = {
"resource": "/{something+}",
... | def test_proxy_APIpathCustomDomain():
| """Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy"))
app._add_route("/test/<string:user>/<name>", funct, methods=["GET"], cors=True)
event = {
"resource": "/{something+}",
"pathParameters": {"something": "... | ": "GET",
"Access-Control-Allow-Origin": "*",
"Content-Type": "text/plain",
},
"statusCode": 200,
}
res = app(event, {})
assert res == resp
funct.assert_called_with(user="remote", name="pixel")
def test_proxy_APIpathCustomDomain():
| 68 | 68 | 227 | 8 | 60 | dmmop/lambda-proxy | tests/test_proxy.py | Python | test_proxy_APIpathCustomDomain | test_proxy_APIpathCustomDomain | 285 | 311 | 285 | 285 | 4397eaa3cac366c5c16962871f71e931f4abb91f | bigcode/the-stack | train |
e0b50444fca9761b9e4f2373 | train | function | def test_path_to_openapi_converters():
"""Convert proxy path to openapi path."""
path = "/<string:num>/<test>-<regex([0-1]{4}):var>"
assert "/{num}/{test}-{var}" == proxy._path_to_openapi(path)
| def test_path_to_openapi_converters():
| """Convert proxy path to openapi path."""
path = "/<string:num>/<test>-<regex([0-1]{4}):var>"
assert "/{num}/{test}-{var}" == proxy._path_to_openapi(path)
| -9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/([A-Z0-9]{5})/([a-z]{1})$"
== proxy._path_to_regex(path)
)
def test_path_to_openapi_converters():
| 64 | 64 | 60 | 9 | 55 | dmmop/lambda-proxy | tests/test_proxy.py | Python | test_path_to_openapi_converters | test_path_to_openapi_converters | 61 | 64 | 61 | 61 | 61711658ea37532dd4736f0c0bcb56560553b4b6 | bigcode/the-stack | train |
481c8ffb8cf7661e02fc844d | train | function | def test_API_functionError():
"""Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", side_effect=Exception("hey something went wrong"))
app._add_route("/test/<user>", funct, methods=["GET"], cors=True)
event = {
"path": "/test/remotepixel",
"httpMethod... | def test_API_functionError():
| """Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", side_effect=Exception("hey something went wrong"))
app._add_route("/test/<user>", funct, methods=["GET"], cors=True)
event = {
"path": "/test/remotepixel",
"httpMethod": "GET",
"headers": {... | "}',
"headers": {"Content-Type": "application/json"},
"statusCode": 500,
}
res = app(event, {})
assert res == resp
# Clear logger handlers
for h in app.log.handlers:
app.log.removeHandler(h)
def test_API_functionError():
| 64 | 64 | 208 | 6 | 58 | dmmop/lambda-proxy | tests/test_proxy.py | Python | test_API_functionError | test_API_functionError | 895 | 922 | 895 | 895 | f231a22c0b97c875d2880e44c8a14a374e5dc91d | bigcode/the-stack | train |
f61b74716eae99929a28dd39 | train | function | def test_API_otherCompression():
"""Test other compression."""
body = b"thisisafakeencodedjpeg"
zlib_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS)
deflate_compress = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
zlibbody = zlib_compress.compress(body) + zlib_compress.flush()
... | def test_API_otherCompression():
| """Test other compression."""
body = b"thisisafakeencodedjpeg"
zlib_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS)
deflate_compress = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
zlibbody = zlib_compress.compress(body) + zlib_compress.flush()
deflbody = deflate_compress.co... | statusCode": 200,
}
res = app(event, {})
assert res == resp
event = {
"path": "/test_compress_b64/remotepixel.json",
"httpMethod": "GET",
"headers": {},
"queryStringParameters": {},
}
resp = {
"body": json.dumps({"test": 0}),
"headers": {
... | 155 | 155 | 517 | 6 | 148 | dmmop/lambda-proxy | tests/test_proxy.py | Python | test_API_otherCompression | test_API_otherCompression | 614 | 680 | 614 | 614 | 0296bd0d21bcef7823751cfe64e981f580147085 | bigcode/the-stack | train |
d0c590bdaebe4c1ed344e4e5 | train | function | def test_ttl():
"""Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy"))
app._add_route(
"/test/<string:user>/<name>", funct, methods=["GET"], cors=True, ttl=3600
)
funct_error = Mock(__name__="Mock", return_value=... | def test_ttl():
| """Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", return_value=("OK", "text/plain", "heyyyy"))
app._add_route(
"/test/<string:user>/<name>", funct, methods=["GET"], cors=True, ttl=3600
)
funct_error = Mock(__name__="Mock", return_value=("NOK", "text/pl... | "body": "heyyyy",
"headers": {
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Origin": "*",
"Content-Type": "text/plain",
},
"statusCode": 200,
}
res = app(event, {})
ass... | 96 | 96 | 321 | 5 | 91 | dmmop/lambda-proxy | tests/test_proxy.py | Python | test_ttl | test_ttl | 314 | 352 | 314 | 314 | 359450b54f4da51ec6006a5bb2c62e4bcff59361 | bigcode/the-stack | train |
242be4df192d879b1b15e86c | train | function | def test_proxy_API():
"""Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", return_value=(204, "text/plain", "heyyyy"))
app._add_route("/test", funct, methods=["GET"], cors=True)
event = {
"path": "/test",
"httpMethod": "GET",
"headers": {},
... | def test_proxy_API():
| """Add and parse route."""
app = proxy.API(name="test")
funct = Mock(__name__="Mock", return_value=(204, "text/plain", "heyyyy"))
app._add_route("/test", funct, methods=["GET"], cors=True)
event = {
"path": "/test",
"httpMethod": "GET",
"headers": {},
"queryStringPar... | "GET",
"Access-Control-Allow-Origin": "*",
"Content-Type": "text/plain",
},
"statusCode": 200,
}
res = app(event, {})
assert res == resp
funct.assert_called_with(user="remote", name="pixel")
def test_proxy_API():
| 64 | 64 | 176 | 5 | 59 | dmmop/lambda-proxy | tests/test_proxy.py | Python | test_proxy_API | test_proxy_API | 202 | 225 | 202 | 202 | fd0078c6f64a17d7c47926bfe60b9aef2a3607fa | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.