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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cef9a29ea2cfc1b40064276d | train | function | def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'onder_test_app_28871.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"ava... | def main():
| os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'onder_test_app_28871.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on yo... | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
| 26 | 64 | 97 | 3 | 22 | crowdbotics-apps/onder-test-app-28871 | backend/manage.py | Python | main | main | 7 | 17 | 7 | 7 | f50cb2eb6f7f42d107c7dad2eb08cfc118af8804 | bigcode/the-stack | train |
f315422f48666588d2a1418b | train | class | class Looker31SDK(api_methods.APIMethods):
# region ApiAuth: API Authentication
# login() using api3credentials is automated in the client
def login_user(self, user_id: int) -> api_methods.APIMethods:
return super().login_user(user_id)
def logout(self) -> None:
super().logout()
... | class Looker31SDK(api_methods.APIMethods):
# region ApiAuth: API Authentication
# login() using api3credentials is automated in the client
| def login_user(self, user_id: int) -> api_methods.APIMethods:
return super().login_user(user_id)
def logout(self) -> None:
super().logout()
# endregion
# region Auth: Manage User Authentication Configuration
# ### Create SSO Embed URL
#
# Creates an SSO embed URL and cryp... | to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPL... | 256 | 256 | 76,683 | 35 | 220 | vyozik/test-1 | python/looker_sdk/sdk/api31/methods.py | Python | Looker31SDK | Looker31SDK | 35 | 9,380 | 35 | 40 | b33a7ffb52e788d9cc6e1a9a9b78246520ec0f68 | bigcode/the-stack | train |
b30d35802ad594679eff15e6 | train | class | class IsAuthorOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.author == request.user
| class IsAuthorOrReadOnly(permissions.BasePermission):
| def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.author == request.user
| from rest_framework import permissions
class IsAuthorOrReadOnly(permissions.BasePermission):
| 18 | 64 | 48 | 12 | 5 | CodeClan5/Second-Hand | api/permissions.py | Python | IsAuthorOrReadOnly | IsAuthorOrReadOnly | 4 | 10 | 4 | 5 | 9f37bdac09a88a88d1ecd69e9d1588648e9e243f | bigcode/the-stack | train |
569095f0890192e5877eafce | train | class | @override_settings(ABSOLUTE_URL_OVERRIDES={})
class GenericViewsSitemapTests(SitemapTestsBase):
def test_generic_sitemap(self):
"A minimal generic sitemap can be rendered"
response = self.client.get('/generic/sitemap.xml')
expected = ''
for username in User.objects.values_list("user... | @override_settings(ABSOLUTE_URL_OVERRIDES={})
class GenericViewsSitemapTests(SitemapTestsBase):
| def test_generic_sitemap(self):
"A minimal generic sitemap can be rendered"
response = self.client.get('/generic/sitemap.xml')
expected = ''
for username in User.objects.values_list("username", flat=True):
expected += "<url><loc>%s/users/%s/</loc></url>" % (self.base_url,... | from django.contrib.auth.models import User
from django.test.utils import override_settings
from .base import SitemapTestsBase
@override_settings(ABSOLUTE_URL_OVERRIDES={})
class GenericViewsSitemapTests(SitemapTestsBase):
| 48 | 64 | 159 | 24 | 23 | vsajip/django | django/contrib/sitemaps/tests/generic.py | Python | GenericViewsSitemapTests | GenericViewsSitemapTests | 6 | 19 | 6 | 8 | 7283a39168d7ec6f7e9aa0c99a930d26c0e9ce59 | bigcode/the-stack | train |
3aae56d8ee0df728406cce11 | train | class | class DataPreparation:
""" Prepares the patent landscape data. """
RAND_SEED = 314159
inputs_as_text = None
inputs_as_embedding_idxs = None
labels_as_idxs = None
refs_tokenizer = None
refs_one_hot = None
cpc_tokenizer = None
cpc_one_hot = None
max_seq_length = None
padded_tra... | class DataPreparation:
| """ Prepares the patent landscape data. """
RAND_SEED = 314159
inputs_as_text = None
inputs_as_embedding_idxs = None
labels_as_idxs = None
refs_tokenizer = None
refs_one_hot = None
cpc_tokenizer = None
cpc_one_hot = None
max_seq_length = None
padded_train_embed_idxs_x = None
... | """
Used for patent landscaping use-case.
"""
from fiz_lernmodule import tokenizer
from keras.preprocessing import sequence
import random
import numpy as np
class DataPreparation:
| 35 | 256 | 1,841 | 4 | 30 | gingergenius/patent-embedding-visualization | src/fiz_lernmodule/.ipynb_checkpoints/data_preparation-checkpoint.py | Python | DataPreparation | DataPreparation | 11 | 224 | 11 | 11 | 5499bf2e4796876a2fe23f319b6d1af7c8a37ba0 | bigcode/the-stack | train |
8fa7d96d5e0524b62381c401 | train | class | class B(A):
def func():
pass
| class B(A):
| def func():
pass
| from module1 import *
class B(A):
| 9 | 64 | 11 | 4 | 5 | confitarlaburra/pteros2.0 | src/python/bindings/test_1.py | Python | B | B | 3 | 5 | 3 | 3 | 9e2e67784228e67808b0cbbf726b60493c6256f4 | bigcode/the-stack | train |
ef002965919b230ab32418d4 | train | class | class ComplianceReportService(object):
"""
Helper functions for Credit Calculation
"""
@staticmethod
def get_organization_compliance_reports(organization):
"""
Fetch the compliance reports with various rules based on the user's
organization
"""
# Government O... | class ComplianceReportService(object):
| """
Helper functions for Credit Calculation
"""
@staticmethod
def get_organization_compliance_reports(organization):
"""
Fetch the compliance reports with various rules based on the user's
organization
"""
# Government Organization -- assume OrganizationType ... | from django.db.models import Q
from api.models.ComplianceReport import ComplianceReport, ComplianceReportWorkflowState
from api.models.ComplianceReportHistory import ComplianceReportHistory
from api.models.Organization import Organization
class ComplianceReportService(object):
| 47 | 133 | 445 | 6 | 40 | KMenke/tfrs | backend/api/services/ComplianceReportService.py | Python | ComplianceReportService | ComplianceReportService | 8 | 74 | 8 | 8 | 28d47deef85772ffae3906899bf05dd241684033 | bigcode/the-stack | train |
e24295c0b957eec08d9cef5f | train | class | class SanicFCM:
def __init__(self, app=None):
self.app = app
self.fcm = None
if app:
self.init_app(app)
def init_app(self, app):
self.fcm = FCM(app.config.FCM_API_KEY)
return self
| class SanicFCM:
| def __init__(self, app=None):
self.app = app
self.fcm = None
if app:
self.init_app(app)
def init_app(self, app):
self.fcm = FCM(app.config.FCM_API_KEY)
return self
| from .fcm import FCM, FCMMessage
__all__ = ('SanicFCM', 'FCM', 'FCMMessage')
__version__ = '0.0.1'
class SanicFCM:
| 48 | 64 | 65 | 6 | 42 | Asmodius/sanic-fcm | sanic_fcm/__init__.py | Python | SanicFCM | SanicFCM | 8 | 17 | 8 | 8 | cd310f20a27792a914e50982914a7ba008ebfbc8 | bigcode/the-stack | train |
7bf1e8e49ee72134588fa8c1 | train | class | class SynergyNetFaceAlignmentTracker(FaceAlignmentTracker):
def __init__(self, config):
super().__init__(config)
# preprocessing
self.IMG_SIZE = 120
self.image_transform = transforms.Compose([ToTensor(), Normalize(mean=127.5, std=128)])
# model
self.device = 'cuda:0'... | class SynergyNetFaceAlignmentTracker(FaceAlignmentTracker):
| def __init__(self, config):
super().__init__(config)
# preprocessing
self.IMG_SIZE = 120
self.image_transform = transforms.Compose([ToTensor(), Normalize(mean=127.5, std=128)])
# model
self.device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
self.synerg... | import cv2
import numpy as np
import torch
from torchvision import transforms
from . import FaceAlignmentTracker, FaceAlignmentTrackerInput
from ..networks.synergy_net import SynergyNet, ToTensor, Normalize, predict_pose, crop_img
class SynergyNetFaceAlignmentTracker(FaceAlignmentTracker):
| 64 | 136 | 454 | 12 | 51 | Mirevi/face-synthesizer-JVRB | tracking/face_alignment_tracking/synergynet_face_alignment_tracker.py | Python | SynergyNetFaceAlignmentTracker | SynergyNetFaceAlignmentTracker | 10 | 51 | 10 | 10 | 1f5ec8561b5a9f6e5e217bc8a706e5acd0eac6ac | bigcode/the-stack | train |
5f3ec99742d1d6a688c030aa | train | class | class Email(object):
def __init__(self, email=None, name=None):
self._name = None
self._email = None
if email is not None:
self.email = email
if name is not None:
self.name = name
@property
def name(self):
return self._name
@name.setter... | class Email(object):
| def __init__(self, email=None, name=None):
self._name = None
self._email = None
if email is not None:
self.email = email
if name is not None:
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, va... | (self):
return self._custom_args
def add_custom_arg(self, custom_arg):
if self._custom_args is None:
self._custom_args = []
self._custom_args.append(custom_arg)
################################################################
# The following objects are meant to be extended wi... | 64 | 64 | 172 | 4 | 59 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | Email | Email | 260 | 294 | 260 | 261 | 4238fc10f1e751a27910ee9f592e45b2beef5ca2 | bigcode/the-stack | train |
06c270ed04d30dc665dd4ecd | train | class | class TrackingSettings(object):
def __init__(self):
self._click_tracking = None
self._open_tracking = None
self._subscription_tracking = None
self._ganalytics = None
@property
def click_tracking(self):
return self._click_tracking
@click_tracking.setter
def ... | class TrackingSettings(object):
| def __init__(self):
self._click_tracking = None
self._open_tracking = None
self._subscription_tracking = None
self._ganalytics = None
@property
def click_tracking(self):
return self._click_tracking
@click_tracking.setter
def click_tracking(self, value):
... | ["utm_medium"] = self.utm_medium
if self.utm_term is not None:
ganalytics["utm_term"] = self.utm_term
if self.utm_content is not None:
ganalytics["utm_content"] = self.utm_content
if self.utm_campaign is not None:
ganalytics["utm_campaign"] = self.utm_campaign... | 93 | 93 | 312 | 5 | 87 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | TrackingSettings | TrackingSettings | 1,236 | 1,287 | 1,236 | 1,237 | d338168c87aa5e3a8618a08ca193099fa3bb3553 | bigcode/the-stack | train |
0fec36d6870b2e521e6d313b | train | class | class Attachment(object):
def __init__(self):
self._content = None
self._type = None
self._filename = None
self._disposition = None
self._content_id = None
@property
def content(self):
return self._content
@content.setter
def content(self, value):
... | class Attachment(object):
| def __init__(self):
self._content = None
self._type = None
self._filename = None
self._disposition = None
self._content_id = None
@property
def content(self):
return self._content
@content.setter
def content(self, value):
self._content = valu... | utions is not None:
substitutions = {}
for key in self.substitutions:
substitutions.update(key)
personalization["substitutions"] = substitutions
if self.custom_args is not None:
custom_args = {}
for key in self.custom_args:
... | 99 | 99 | 330 | 4 | 94 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | Attachment | Attachment | 617 | 682 | 617 | 618 | df172e97c250645452e337279ed5382f1d93fce3 | bigcode/the-stack | train |
7091e87c31d935f651078aee | train | class | class CustomArg(object):
def __init__(self, key=None, value=None):
self._key = None
self._value = None
if key is not None:
self.key = key
if value is not None:
self.value = value
@property
def key(self):
return self._key
@key.setter
... | class CustomArg(object):
| def __init__(self, key=None, value=None):
self._key = None
self._value = None
if key is not None:
self.key = key
if value is not None:
self.value = value
@property
def key(self):
return self._key
@key.setter
def key(self, value):
... | self._value
@value.setter
def value(self, value):
self._value = value
def get(self):
section = {}
if self.key is not None and self.value is not None:
section[self.key] = self.value
return section
class CustomArg(object):
| 64 | 64 | 165 | 5 | 58 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | CustomArg | CustomArg | 439 | 471 | 439 | 440 | da2d441cf615823f53b21851571f5d24f779e988 | bigcode/the-stack | train |
a082631239f6d8a6ccc3007a | train | class | class Header(object):
def __init__(self, key=None, value=None):
self._key = None
self._value = None
if key is not None:
self.key = key
if value is not None:
self.value = value
@property
def key(self):
return self._key
@key.setter
de... | class Header(object):
| def __init__(self, key=None, value=None):
self._key = None
self._value = None
if key is not None:
self.key = key
if value is not None:
self.value = value
@property
def key(self):
return self._key
@key.setter
def key(self, value):
... | def value(self, value):
self._value = value
def get(self):
content = {}
if self.type is not None:
content["type"] = self.type
if self.value is not None:
content["value"] = self.value
return content
class Header(object):
| 64 | 64 | 161 | 4 | 59 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | Header | Header | 335 | 366 | 335 | 336 | 944ef3ec43c0a5b38025e9a9a660ad806751e24e | bigcode/the-stack | train |
a202f8b0bd9bf4236e049e27 | train | class | class MailSettings(object):
def __init__(self):
self._bcc_settings = None
self._bypass_list_management = None
self._footer_settings = None
self._sandbox_mode = None
self._spam_check = None
@property
def bcc_settings(self):
return self._bcc_settings
@bcc... | class MailSettings(object):
| def __init__(self):
self._bcc_settings = None
self._bypass_list_management = None
self._footer_settings = None
self._sandbox_mode = None
self._spam_check = None
@property
def bcc_settings(self):
return self._bcc_settings
@bcc_settings.setter
def bcc_... | post_to_url(self):
return self._post_to_url
@post_to_url.setter
def post_to_url(self, value):
self._post_to_url = value
def get(self):
spam_check = {}
if self.enable is not None:
spam_check["enable"] = self.enable
if self.threshold is not None:
... | 118 | 118 | 396 | 5 | 112 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | MailSettings | MailSettings | 933 | 999 | 933 | 934 | 61f0cd082de8df0976bc79442e37a7499fa26a9b | bigcode/the-stack | train |
8f7489ba89375488c49b909b | train | class | class SpamCheck(object):
def __init__(self, enable=None, threshold=None, post_to_url=None):
self._enable = None
self._threshold = None
self._post_to_url = None
if enable is not None:
self.enable = enable
if threshold is not None:
self.threshold = th... | class SpamCheck(object):
| def __init__(self, enable=None, threshold=None, post_to_url=None):
self._enable = None
self._threshold = None
self._post_to_url = None
if enable is not None:
self.enable = enable
if threshold is not None:
self.threshold = threshold
if post_t... | enable is not None:
self.enable = enable
@property
def enable(self):
return self._enable
@enable.setter
def enable(self, value):
self._enable = value
def get(self):
sandbox_mode = {}
if self.enable is not None:
sandbox_mode["enable"] = self... | 83 | 83 | 278 | 5 | 77 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | SpamCheck | SpamCheck | 880 | 930 | 880 | 881 | ddeab006728021779fe006a152c98b114fd77a35 | bigcode/the-stack | train |
72a118368dc0a87256511a49 | train | class | class Content(object):
def __init__(self, type_=None, value=None):
self._type = None
self._value = None
if type_ is not None:
self.type = type_
if value is not None:
self.value = value
@property
def type(self):
return self._type
@type.... | class Content(object):
| def __init__(self, type_=None, value=None):
self._type = None
self._value = None
if type_ is not None:
self.type = type_
if value is not None:
self.value = value
@property
def type(self):
return self._type
@type.setter
def type(self... | def email(self, value):
self._email = value
def get(self):
email = {}
if self.name is not None:
email["name"] = self.name
if self.email is not None:
email["email"] = self.email
return email
class Content(object):
| 64 | 64 | 174 | 4 | 59 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | Content | Content | 297 | 332 | 297 | 298 | b95568092d6b432a6ce45c91063ed4593030476a | bigcode/the-stack | train |
1d7fe01c648e735f2c771497 | train | class | class SubscriptionTracking(object):
def __init__(self, enable=None, text=None, html=None, substitution_tag=None):
self._enable = None
self._text = None
self._html = None
self._substitution_tag = None
if enable is not None:
self.enable = enable
if text is... | class SubscriptionTracking(object):
| def __init__(self, enable=None, text=None, html=None, substitution_tag=None):
self._enable = None
self._text = None
self._html = None
self._substitution_tag = None
if enable is not None:
self.enable = enable
if text is not None:
self.text = te... | @property
def substitution_tag(self):
return self._substitution_tag
@substitution_tag.setter
def substitution_tag(self, value):
self._substitution_tag = value
def get(self):
open_tracking = {}
if self.enable is not None:
open_tracking["enable"] = self.en... | 104 | 104 | 348 | 5 | 98 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | SubscriptionTracking | SubscriptionTracking | 1,077 | 1,139 | 1,077 | 1,078 | 72df1e9ff14cded967498e22240a4631a7c6e37d | bigcode/the-stack | train |
4ab49114cc1fda17e3c67865 | train | class | class Ganalytics(object):
def __init__(self,
enable=None,
utm_source=None,
utm_medium=None,
utm_term=None,
utm_content=None,
utm_campaign=None):
self._enable = None
self._utm_source = None
... | class Ganalytics(object):
| def __init__(self,
enable=None,
utm_source=None,
utm_medium=None,
utm_term=None,
utm_content=None,
utm_campaign=None):
self._enable = None
self._utm_source = None
self._utm_medium = None
... | text = value
@property
def html(self):
return self._html
@html.setter
def html(self, value):
self._html = value
@property
def substitution_tag(self):
return self._substitution_tag
@substitution_tag.setter
def substitution_tag(self, value):
self._substi... | 178 | 178 | 596 | 5 | 172 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | Ganalytics | Ganalytics | 1,142 | 1,233 | 1,142 | 1,143 | 67cdaa9470b3ea407276d94c4cddd763d518a259 | bigcode/the-stack | train |
1eccaceaa4b486ad375ad332 | train | class | class Substitution(object):
def __init__(self, key=None, value=None):
self._key = None
self._value = None
if key is not None:
self.key = key
if value is not None:
self.value = value
@property
def key(self):
return self._key
@key.setter... | class Substitution(object):
| def __init__(self, key=None, value=None):
self._key = None
self._value = None
if key is not None:
self.key = key
if value is not None:
self.value = value
@property
def key(self):
return self._key
@key.setter
def key(self, value):
... | self._value
@value.setter
def value(self, value):
self._value = value
def get(self):
header = {}
if self.key is not None and self.value is not None:
header[self.key] = self.value
return header
class Substitution(object):
| 64 | 64 | 162 | 5 | 58 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | Substitution | Substitution | 369 | 401 | 369 | 370 | 3dcd90d54e90f7ce4bef3bd045b0aa99643fd6f0 | bigcode/the-stack | train |
c4abef01cbcc1d50b51aa777 | train | class | class OpenTracking(object):
def __init__(self, enable=None, substitution_tag=None):
self._enable = None
self._substitution_tag = None
if enable is not None:
self.enable = enable
if substitution_tag is not None:
self.substitution_tag = substitution_tag
@... | class OpenTracking(object):
| def __init__(self, enable=None, substitution_tag=None):
self._enable = None
self._substitution_tag = None
if enable is not None:
self.enable = enable
if substitution_tag is not None:
self.substitution_tag = substitution_tag
@property
def enable(self)... | enable_text = value
def get(self):
click_tracking = {}
if self.enable is not None:
click_tracking["enable"] = self.enable
if self.enable_text is not None:
click_tracking["enable_text"] = self.enable_text
return click_tracking
class OpenTracking(object):
| 64 | 64 | 198 | 5 | 58 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | OpenTracking | OpenTracking | 1,040 | 1,074 | 1,040 | 1,041 | fc07560a3da3a11f6e53efe1a296c20b9eb7722a | bigcode/the-stack | train |
40e6c3001c41a685375a7eb2 | train | class | class Mail(object):
"""Creates the response body for v3/mail/send"""
def __init__(
self, from_email=None, subject=None, to_email=None, content=None):
self._from_email = None
self._subject = None
self._template_id = None
self._send_at = None
self._batch_id = No... | class Mail(object):
| """Creates the response body for v3/mail/send"""
def __init__(
self, from_email=None, subject=None, to_email=None, content=None):
self._from_email = None
self._subject = None
self._template_id = None
self._send_at = None
self._batch_id = None
self._asm... | """v3/mail/send response body builder"""
class Mail(object):
| 13 | 256 | 1,430 | 4 | 9 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | Mail | Mail | 4 | 252 | 4 | 4 | 63bb1a40ed19f17dbc68f8df8a1e3ede76960da2 | bigcode/the-stack | train |
cf8b7c2061c15b8602da19e7 | train | class | class BCCSettings(object):
def __init__(self, enable=None, email=None):
self._enable = None
self._email = None
if enable is not None:
self.enable = enable
if email is not None:
self.email = email
@property
def enable(self):
return self._ena... | class BCCSettings(object):
| def __init__(self, enable=None, email=None):
self._enable = None
self._email = None
if enable is not None:
self.enable = enable
if email is not None:
self.email = email
@property
def enable(self):
return self._enable
@enable.setter
... | value
def get(self):
asm = {}
if self.group_id is not None:
asm["group_id"] = self.group_id
if self.groups_to_display is not None:
asm["groups_to_display"] = self.groups_to_display
return asm
class BCCSettings(object):
| 64 | 64 | 190 | 6 | 57 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | BCCSettings | BCCSettings | 742 | 778 | 742 | 743 | 660653637ff0d5a29b60a0577891e8250fbf5743 | bigcode/the-stack | train |
0f6dda7243d9b40a4a7814e3 | train | class | class Category(object):
def __init__(self, name=None):
self._name = None
if name is not None:
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
def get(self):
return self.na... | class Category(object):
| def __init__(self, name=None):
self._name = None
if name is not None:
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
def get(self):
return self.name
| if self.filename is not None:
attachment["filename"] = self.filename
if self.disposition is not None:
attachment["disposition"] = self.disposition
if self.content_id is not None:
attachment["content_id"] = self.content_id
return attachment
class Category(ob... | 64 | 64 | 79 | 4 | 59 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | Category | Category | 685 | 701 | 685 | 686 | e782a74f6f80ceb5e203ce0eecd49ab9935ba70e | bigcode/the-stack | train |
bf6a944a88ec3264785ec6c0 | train | class | class BypassListManagement(object):
def __init__(self, enable=None):
self._enable = None
if enable is not None:
self.enable = enable
@property
def enable(self):
return self._enable
@enable.setter
def enable(self, value):
self._enable = value
def g... | class BypassListManagement(object):
| def __init__(self, enable=None):
self._enable = None
if enable is not None:
self.enable = enable
@property
def enable(self):
return self._enable
@enable.setter
def enable(self, value):
self._enable = value
def get(self):
bypass_list_managem... | bcc_settings = {}
if self.enable is not None:
bcc_settings["enable"] = self.enable
if self.email is not None:
email = self.email.get()
bcc_settings["email"] = email["email"]
return bcc_settings
class BypassListManagement(object):
| 64 | 64 | 107 | 7 | 56 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | BypassListManagement | BypassListManagement | 781 | 801 | 781 | 782 | 71e3eb977afc0b5bfbe6ea711cfa944694d5f81b | bigcode/the-stack | train |
1e55a9ba671bbc48f4f7d9ee | train | class | class ASM(object):
def __init__(self, group_id=None, groups_to_display=None):
self._group_id = None
self._groups_to_display = None
if group_id is not None:
self._group_id = group_id
if groups_to_display is not None:
self._groups_to_display = groups_to_displ... | class ASM(object):
| def __init__(self, group_id=None, groups_to_display=None):
self._group_id = None
self._groups_to_display = None
if group_id is not None:
self._group_id = group_id
if groups_to_display is not None:
self._groups_to_display = groups_to_display
@property
... | None
if name is not None:
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
def get(self):
return self.name
class ASM(object):
| 64 | 64 | 213 | 4 | 59 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | ASM | ASM | 704 | 739 | 704 | 705 | c627316065ec431805da5cc29c5fa3a1d78c98c9 | bigcode/the-stack | train |
667a8443dbb21b4e0c66aaaa | train | class | class ClickTracking(object):
def __init__(self, enable=None, enable_text=None):
self._enable = None
self._enable_text = None
if enable is not None:
self.enable = enable
if enable_text is not None:
self.enable_text = enable_text
@property
def enable... | class ClickTracking(object):
| def __init__(self, enable=None, enable_text=None):
self._enable = None
self._enable_text = None
if enable is not None:
self.enable = enable
if enable_text is not None:
self.enable_text = enable_text
@property
def enable(self):
return self._e... | = self.footer_settings.get()
if self.sandbox_mode is not None:
mail_settings["sandbox_mode"] = self.sandbox_mode.get()
if self.spam_check is not None:
mail_settings["spam_check"] = self.spam_check.get()
return mail_settings
class ClickTracking(object):
| 64 | 64 | 190 | 5 | 58 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | ClickTracking | ClickTracking | 1,002 | 1,037 | 1,002 | 1,003 | ccb4081bfb5430997fde9e787a72cd360db1b42f | bigcode/the-stack | train |
42bd095d3cf004a8e16605d7 | train | class | class Section(object):
def __init__(self, key=None, value=None):
self._key = None
self._value = None
if key is not None:
self.key = key
if value is not None:
self.value = value
@property
def key(self):
return self._key
@key.setter
... | class Section(object):
| def __init__(self, key=None, value=None):
self._key = None
self._value = None
if key is not None:
self.key = key
if value is not None:
self.value = value
@property
def key(self):
return self._key
@key.setter
def key(self, value):
... | return self._value
@value.setter
def value(self, value):
self._value = value
def get(self):
substitution = {}
if self.key is not None and self.value is not None:
substitution[self.key] = self.value
return substitution
class Section(object):
| 64 | 64 | 161 | 4 | 59 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | Section | Section | 404 | 436 | 404 | 405 | 7f63ab5e1083748c50f565022f769ae4a47e098b | bigcode/the-stack | train |
fb57a34d1f1c42e91fc39559 | train | class | class Personalization(object):
def __init__(self):
self._tos = None
self._ccs = None
self._bccs = None
self._subject = None
self._headers = None
self._substitutions = None
self._custom_args = None
self._send_at = None
@property
def tos(self):... | class Personalization(object):
| def __init__(self):
self._tos = None
self._ccs = None
self._bccs = None
self._subject = None
self._headers = None
self._substitutions = None
self._custom_args = None
self._send_at = None
@property
def tos(self):
return self._tos
@... |
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
def get(self):
section = {}
if self.key is not None and self.value is not None:
section[self.key] = self.value
return section
class CustomArg(object):
... | 237 | 237 | 791 | 5 | 231 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | Personalization | Personalization | 474 | 614 | 474 | 475 | ef69d25485852a7d650975ee96b0c1f379cc8603 | bigcode/the-stack | train |
6500c72cf10115dd67965741 | train | class | class SandBoxMode(object):
def __init__(self, enable=None):
self._enable = None
if enable is not None:
self.enable = enable
@property
def enable(self):
return self._enable
@enable.setter
def enable(self, value):
self._enable = value
def get(self):... | class SandBoxMode(object):
| def __init__(self, enable=None):
self._enable = None
if enable is not None:
self.enable = enable
@property
def enable(self):
return self._enable
@enable.setter
def enable(self, value):
self._enable = value
def get(self):
sandbox_mode = {}
... | if self.enable is not None:
footer_settings["enable"] = self.enable
if self.text is not None:
footer_settings["text"] = self.text
if self.html is not None:
footer_settings["html"] = self.html
return footer_settings
class SandBoxMode(object):
| 64 | 64 | 103 | 6 | 57 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | SandBoxMode | SandBoxMode | 857 | 877 | 857 | 858 | bd81ad2829063a4062b38c88a6ab5ae2a69c70ca | bigcode/the-stack | train |
b3b792f6a259e89dfce9dafa | train | class | class FooterSettings(object):
def __init__(self, enable=None, text=None, html=None):
self._enable = None
self._text = None
self._html = None
if enable is not None:
self.enable = enable
if text is not None:
self.text = text
if html is not No... | class FooterSettings(object):
| def __init__(self, enable=None, text=None, html=None):
self._enable = None
self._text = None
self._html = None
if enable is not None:
self.enable = enable
if text is not None:
self.text = text
if html is not None:
self.html = htm... | @property
def enable(self):
return self._enable
@enable.setter
def enable(self, value):
self._enable = value
def get(self):
bypass_list_management = {}
if self.enable is not None:
bypass_list_management["enable"] = self.enable
return bypass_list_... | 75 | 75 | 252 | 5 | 69 | daspots/dasapp | lib/sendgrid/helpers/mail/mail.py | Python | FooterSettings | FooterSettings | 804 | 854 | 804 | 805 | 128cae785a280e31e0a34b588600812494334b0d | bigcode/the-stack | train |
e2f95738d71bc1121ba5ace9 | train | function | @contextlib.contextmanager
def safe_query_string(request):
"""
Turn the QUERY_STRING into a unicode- and ascii-safe string.
We need unicode so it can be combined with a reversed URL, but it has to be
ascii to go in a Location header. iri_to_uri seems like a good compromise.
"""
qs = request.ME... | @contextlib.contextmanager
def safe_query_string(request):
| """
Turn the QUERY_STRING into a unicode- and ascii-safe string.
We need unicode so it can be combined with a reversed URL, but it has to be
ascii to go in a Location header. iri_to_uri seems like a good compromise.
"""
qs = request.META.get('QUERY_STRING', '')
try:
request.META['Q... | newurl = request.path[:-1]
if request.GET:
with safe_query_string(request):
newurl += '?' + request.META.get('QUERY_STRING', '')
return HttpResponsePermanentRedirect(newurl)
else:
return response
@contextlib.contextmanager
def s... | 64 | 64 | 116 | 12 | 51 | varundey/addons-server | src/olympia/amo/middleware.py | Python | safe_query_string | safe_query_string | 176 | 189 | 176 | 177 | 9f9580219207729524fb1362a7b2bd4062cdb349 | bigcode/the-stack | train |
f024517d746a0784ac904e48 | train | class | class AuthenticationMiddlewareWithoutAPI(AuthenticationMiddleware):
"""
Like AuthenticationMiddleware, but disabled for the API, which uses its
own authentication mechanism.
"""
def process_request(self, request):
legacy_or_drf_api = request.is_api or request.is_legacy_api
if legacy_... | class AuthenticationMiddlewareWithoutAPI(AuthenticationMiddleware):
| """
Like AuthenticationMiddleware, but disabled for the API, which uses its
own authentication mechanism.
"""
def process_request(self, request):
legacy_or_drf_api = request.is_api or request.is_legacy_api
if legacy_or_drf_api and not auth_path.match(request.path):
reques... | legacy api requests too - IdentifyAPIRequestMiddleware is v3+
# TODO - remove this when legacy_api goes away
# https://github.com/mozilla/addons-server/issues/9274
request.is_legacy_api = request.path_info.startswith('/api/')
class AuthenticationMiddlewareWithoutAPI(AuthenticationMiddleware):
| 63 | 64 | 99 | 8 | 55 | varundey/addons-server | src/olympia/amo/middleware.py | Python | AuthenticationMiddlewareWithoutAPI | AuthenticationMiddlewareWithoutAPI | 107 | 119 | 107 | 107 | 8bd5dfc8df938536f9452fe399b51df46670a77e | bigcode/the-stack | train |
32ea9375116f02df3898e007 | train | class | class CorsMiddleware(_CorsMiddleware, MiddlewareMixin):
"""Wrapper to allow old style Middleware to work with django 1.10+.
Will be unneeded once
https://github.com/mstriemer/django-cors-headers/pull/3 is merged and a
new release of django-cors-headers-multi is available."""
pass
| class CorsMiddleware(_CorsMiddleware, MiddlewareMixin):
| """Wrapper to allow old style Middleware to work with django 1.10+.
Will be unneeded once
https://github.com/mstriemer/django-cors-headers/pull/3 is merged and a
new release of django-cors-headers-multi is available."""
pass
| = uuid.uuid4().hex
def process_response(self, request, response):
request_id = getattr(request, 'request_id', None)
if request_id:
response['X-AMO-Request-ID'] = request.request_id
return response
class CorsMiddleware(_CorsMiddleware, MiddlewareMixin):
| 64 | 64 | 76 | 10 | 53 | varundey/addons-server | src/olympia/amo/middleware.py | Python | CorsMiddleware | CorsMiddleware | 333 | 338 | 333 | 333 | c450fd8adad07226f84f0d207262115d33f6385e | bigcode/the-stack | train |
1c08987cce7d3538b3655938 | train | class | class NonAtomicRequestsForSafeHttpMethodsMiddleware(MiddlewareMixin):
"""
Middleware to make the view non-atomic if the HTTP method used is safe,
in order to avoid opening and closing a useless transaction.
"""
def process_view(self, request, view_func, view_args, view_kwargs):
# This uses u... | class NonAtomicRequestsForSafeHttpMethodsMiddleware(MiddlewareMixin):
| """
Middleware to make the view non-atomic if the HTTP method used is safe,
in order to avoid opening and closing a useless transaction.
"""
def process_view(self, request, view_func, view_args, view_kwargs):
# This uses undocumented django APIS:
# - transaction.get_connection() foll... | request.META['QUERY_STRING'] = iri_to_uri(qs)
yield
finally:
request.META['QUERY_STRING'] = qs
class CommonMiddleware(common.CommonMiddleware):
def process_request(self, request):
with safe_query_string(request):
return super(CommonMiddleware, self).process_request... | 79 | 79 | 264 | 13 | 66 | varundey/addons-server | src/olympia/amo/middleware.py | Python | NonAtomicRequestsForSafeHttpMethodsMiddleware | NonAtomicRequestsForSafeHttpMethodsMiddleware | 199 | 218 | 199 | 199 | f5bf20ec1e9073280ef6296016f14cbbced3abbf | bigcode/the-stack | train |
fd3641d03f6d4c1ca43877f3 | train | class | class CommonMiddleware(common.CommonMiddleware):
def process_request(self, request):
with safe_query_string(request):
return super(CommonMiddleware, self).process_request(request)
| class CommonMiddleware(common.CommonMiddleware):
| def process_request(self, request):
with safe_query_string(request):
return super(CommonMiddleware, self).process_request(request)
| _to_uri seems like a good compromise.
"""
qs = request.META.get('QUERY_STRING', '')
try:
request.META['QUERY_STRING'] = iri_to_uri(qs)
yield
finally:
request.META['QUERY_STRING'] = qs
class CommonMiddleware(common.CommonMiddleware):
| 64 | 64 | 34 | 7 | 56 | varundey/addons-server | src/olympia/amo/middleware.py | Python | CommonMiddleware | CommonMiddleware | 192 | 196 | 192 | 193 | 31217b7d9e5fa5c1d9fad309a8d25d1f202848a0 | bigcode/the-stack | train |
a7ed6ffa2f1838aaf5a90ecf | train | class | class LocaleAndAppURLMiddleware(MiddlewareMixin):
"""
1. search for locale first
2. see if there are acceptable apps
3. save those matched parameters in the request
4. strip them from the URL so we can do stuff
"""
def process_request(self, request):
# Find locale, app
prefi... | class LocaleAndAppURLMiddleware(MiddlewareMixin):
| """
1. search for locale first
2. see if there are acceptable apps
3. save those matched parameters in the request
4. strip them from the URL so we can do stuff
"""
def process_request(self, request):
# Find locale, app
prefixer = urlresolvers.Prefixer(request)
# Al... | Middleware
from django.db import transaction
from django.urls import is_valid_path
from django.http import (
HttpResponsePermanentRedirect, HttpResponseRedirect,
JsonResponse)
from django.middleware import common
from django.utils.cache import patch_cache_control, patch_vary_headers
from django.utils.deprecatio... | 188 | 188 | 627 | 10 | 178 | varundey/addons-server | src/olympia/amo/middleware.py | Python | LocaleAndAppURLMiddleware | LocaleAndAppURLMiddleware | 37 | 104 | 37 | 37 | e306fed35f780e579a256e4e586ca6f8d73bca0b | bigcode/the-stack | train |
a69405ca41eed414d8b6448e | train | class | class SetRemoteAddrFromForwardedFor(MiddlewareMixin):
"""
Set request.META['REMOTE_ADDR'] from request.META['HTTP_X_FORWARDED_FOR'].
Our application servers should always be behind a load balancer that sets
this header correctly.
"""
def is_valid_ip(self, ip):
for af in (socket.AF_INET,... | class SetRemoteAddrFromForwardedFor(MiddlewareMixin):
| """
Set request.META['REMOTE_ADDR'] from request.META['HTTP_X_FORWARDED_FOR'].
Our application servers should always be behind a load balancer that sets
this header correctly.
"""
def is_valid_ip(self, ip):
for af in (socket.AF_INET, socket.AF_INET6):
try:
so... | )
def process_exception(self, request, exception):
if not settings.READ_ONLY:
return
if isinstance(exception, mysql.OperationalError):
if request.is_api:
return self._render_api_error()
return render(request, 'amo/read-only.html', status=503)
cla... | 72 | 72 | 242 | 12 | 60 | varundey/addons-server | src/olympia/amo/middleware.py | Python | SetRemoteAddrFromForwardedFor | SetRemoteAddrFromForwardedFor | 253 | 287 | 253 | 253 | 3968f1b86961c9df6c5ad70cba30b5ff2aeb61b8 | bigcode/the-stack | train |
0e73b1c25efc909cd4b27841 | train | class | class NoVarySessionMiddleware(SessionMiddleware):
"""
SessionMiddleware sets Vary: Cookie anytime request.session is accessed.
request.session is accessed indirectly anytime request.user is touched.
We always touch request.user to see if the user is authenticated, so every
request would be sending v... | class NoVarySessionMiddleware(SessionMiddleware):
| """
SessionMiddleware sets Vary: Cookie anytime request.session is accessed.
request.session is accessed indirectly anytime request.user is touched.
We always touch request.user to see if the user is authenticated, so every
request would be sending vary, so we'd get no caching.
We skip the cach... | _drf_api = request.is_api or request.is_legacy_api
if legacy_or_drf_api and not auth_path.match(request.path):
request.user = AnonymousUser()
else:
return super(
AuthenticationMiddlewareWithoutAPI,
self).process_request(request)
class NoVarySession... | 65 | 65 | 217 | 9 | 56 | varundey/addons-server | src/olympia/amo/middleware.py | Python | NoVarySessionMiddleware | NoVarySessionMiddleware | 122 | 150 | 122 | 122 | 823a7ebb5171af4dbaaacffd5909c00766d08364 | bigcode/the-stack | train |
a71bfd35283feaba315fb2e5 | train | class | class RequestIdMiddleware(MiddlewareMixin):
"""Middleware that adds a unique request-id to every incoming request.
This can be used to track a request across different system layers,
e.g to correlate logs with sentry exceptions.
We are exposing this request id in the `X-AMO-Request-ID` response header... | class RequestIdMiddleware(MiddlewareMixin):
| """Middleware that adds a unique request-id to every incoming request.
This can be used to track a request across different system layers,
e.g to correlate logs with sentry exceptions.
We are exposing this request id in the `X-AMO-Request-ID` response header.
"""
def process_request(self, req... | OOKIES:
request.COOKIES[settings.SESSION_COOKIE_NAME] = '******'
# Clearing out all cookies in request.META. They will already
# be sent with request.COOKIES.
request.META['HTTP_COOKIE'] = '******'
class RequestIdMiddleware(MiddlewareMixin):
| 64 | 64 | 135 | 8 | 56 | varundey/addons-server | src/olympia/amo/middleware.py | Python | RequestIdMiddleware | RequestIdMiddleware | 312 | 330 | 312 | 312 | 1800b09a5c48c6f03fc96537d0b374883b289fcb | bigcode/the-stack | train |
a02c500679819eda086d5784 | train | class | class ScrubRequestOnException(MiddlewareMixin):
"""
Hide sensitive information so they're not recorded in error logging.
* passwords in request.POST
* sessionid in request.COOKIES
"""
def process_exception(self, request, exception):
# Get a copy so it's mutable.
request.POST = r... | class ScrubRequestOnException(MiddlewareMixin):
| """
Hide sensitive information so they're not recorded in error logging.
* passwords in request.POST
* sessionid in request.COOKIES
"""
def process_exception(self, request, exception):
# Get a copy so it's mutable.
request.POST = request.POST.copy()
for key in request.PO... | ips.append(request.META['REMOTE_ADDR'])
known = getattr(settings, 'KNOWN_PROXIES', [])
ips.reverse()
for ip in ips:
request.META['REMOTE_ADDR'] = ip
if ip not in known:
break
class ScrubRequestOnException(MiddlewareMixin):
| 64 | 64 | 169 | 10 | 53 | varundey/addons-server | src/olympia/amo/middleware.py | Python | ScrubRequestOnException | ScrubRequestOnException | 290 | 309 | 290 | 290 | 770cd0485d8ea13fd5162fe8766cc15beeb5f50b | bigcode/the-stack | train |
c57f6740b362786da58cc3f9 | train | class | class RemoveSlashMiddleware(MiddlewareMixin):
"""
Middleware that tries to remove a trailing slash if there was a 404.
If the response is a 404 because url resolution failed, we'll look for a
better url without a trailing slash.
"""
def process_response(self, request, response):
if (re... | class RemoveSlashMiddleware(MiddlewareMixin):
| """
Middleware that tries to remove a trailing slash if there was a 404.
If the response is a 404 because url resolution failed, we'll look for a
better url without a trailing slash.
"""
def process_response(self, request, response):
if (response.status_code == 404 and
... | ', None)
new_response = (
super(NoVarySessionMiddleware, self)
.process_response(request, response))
if vary:
new_response['Vary'] = vary
else:
del new_response['Vary']
return new_response
class RemoveSlashMiddleware(MiddlewareMixin):
| 64 | 64 | 172 | 8 | 55 | varundey/addons-server | src/olympia/amo/middleware.py | Python | RemoveSlashMiddleware | RemoveSlashMiddleware | 153 | 173 | 153 | 153 | 6ae59ef5207e8537279d967d6090aab791cff600 | bigcode/the-stack | train |
197b458e16bbc7023caeea52 | train | class | class ReadOnlyMiddleware(MiddlewareMixin):
"""Middleware that announces a downtime which for us usually means
putting the site into read only mode.
Supports issuing `Retry-After` header.
"""
ERROR_MSG = _(
u'Some features are temporarily disabled while we '
u'perform website mainten... | class ReadOnlyMiddleware(MiddlewareMixin):
| """Middleware that announces a downtime which for us usually means
putting the site into read only mode.
Supports issuing `Retry-After` header.
"""
ERROR_MSG = _(
u'Some features are temporarily disabled while we '
u'perform website maintenance. We\'ll be back to '
u'full ca... | the middlewares are run.
is_method_safe = request.method in ('HEAD', 'GET', 'OPTIONS', 'TRACE')
if is_method_safe and not transaction.get_connection().in_atomic_block:
transaction._non_atomic_requests(view_func, using='default')
return None
class ReadOnlyMiddleware(MiddlewareMixin):... | 66 | 66 | 220 | 8 | 57 | varundey/addons-server | src/olympia/amo/middleware.py | Python | ReadOnlyMiddleware | ReadOnlyMiddleware | 221 | 250 | 221 | 221 | d720dfb95b88fbb9119edbd270338e02b96c45f1 | bigcode/the-stack | train |
e168181dda8b91e2ceb943ba | train | function | def main():
broker = DemoPostProcess(logger, config)
if config.MODE == 'broker':
worker = Worker(Demo, broker, config, logger)
worker.start()
elif config.MODE == 'job':
scripter = Scripter(Demo, broker, config, logger)
scripter.start()
else:
logger.error("We do no... | def main():
| broker = DemoPostProcess(logger, config)
if config.MODE == 'broker':
worker = Worker(Demo, broker, config, logger)
worker.start()
elif config.MODE == 'job':
scripter = Scripter(Demo, broker, config, logger)
scripter.start()
else:
logger.error("We do not support cu... | broker-demo [options]
Options:
-h --help Show this screen.
"""
from demo.app import Worker
from demo.job_app import Scripter
from demo import config
from .logger import logger
from demo.api_imp import Demo
from demo.post_process_imp import DemoPostProcess
def main():
| 64 | 64 | 88 | 3 | 60 | Bhaskers-Blu-Org1/ibm-cloud-dublin-meetup | meetup-2020-03-10/keda-demo/broker-demo/demo/__main__.py | Python | main | main | 20 | 29 | 20 | 20 | 3d3fb32684235808d9bf3142df142086b3cf297f | bigcode/the-stack | train |
353deeaea569c28fa6dfff7b | train | function | def filelineno():
"""
Return the line number in the current file. Before the first line
has been read, returns 0. After the last line of the last file has
been read, returns the line number of that line within the file.
"""
if not _state:
raise RuntimeError("no active input()")
retur... | def filelineno():
| """
Return the line number in the current file. Before the first line
has been read, returns 0. After the last line of the last file has
been read, returns the line number of that line within the file.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.filelinen... | Before the first line has been read, returns 0. After the last line
of the last file has been read, returns the line number of that line.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.lineno()
def filelineno():
| 64 | 64 | 82 | 5 | 59 | cafealternativo/cpython | Lib/fileinput.py | Python | filelineno | filelineno | 146 | 154 | 146 | 146 | 26a382467dcf5a64850955ffb7196b6a3fb66f7e | bigcode/the-stack | train |
bb286a3abd753df2824a480b | train | function | def filename():
"""
Return the name of the file currently being read.
Before the first line has been read, returns None.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.filename()
| def filename():
| """
Return the name of the file currently being read.
Before the first line has been read, returns None.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.filename()
| function has no effect;
it cannot be used to skip the first file. After the last line of the
last file has been read, this function has no effect.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.nextfile()
def filename():
| 64 | 64 | 52 | 3 | 61 | cafealternativo/cpython | Lib/fileinput.py | Python | filename | filename | 127 | 134 | 127 | 127 | 75968fb002375f1767a88b7a1a75f39a2096a824 | bigcode/the-stack | train |
8e2c38e38c94b50c2c34fb92 | train | function | def fileno():
"""
Return the file number of the current file. When no file is currently
opened, returns -1.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.fileno()
| def fileno():
| """
Return the file number of the current file. When no file is currently
opened, returns -1.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.fileno()
| has been read, returns 0. After the last line of the last file has
been read, returns the line number of that line within the file.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.filelineno()
def fileno():
| 64 | 64 | 54 | 4 | 60 | cafealternativo/cpython | Lib/fileinput.py | Python | fileno | fileno | 156 | 163 | 156 | 156 | 38250a634ee8740f233ca4612ccb3ddfdcd6ea81 | bigcode/the-stack | train |
d8a03845cad80b1e4aecffb1 | train | function | def lineno():
"""
Return the cumulative line number of the line that has just been read.
Before the first line has been read, returns 0. After the last line
of the last file has been read, returns the line number of that line.
"""
if not _state:
raise RuntimeError("no active input()")
... | def lineno():
| """
Return the cumulative line number of the line that has just been read.
Before the first line has been read, returns 0. After the last line
of the last file has been read, returns the line number of that line.
"""
if not _state:
raise RuntimeError("no active input()")
return _stat... | ")
return _state.nextfile()
def filename():
"""
Return the name of the file currently being read.
Before the first line has been read, returns None.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.filename()
def lineno():
| 64 | 64 | 81 | 4 | 60 | cafealternativo/cpython | Lib/fileinput.py | Python | lineno | lineno | 136 | 144 | 136 | 136 | 4c54898ffd253e2e77aba4ac23a4bc6e2dcc26e7 | bigcode/the-stack | train |
2d85a92ed4175318e1bf33f5 | train | function | def input(files=None, inplace=False, backup="", bufsize=0,
mode="r", openhook=None):
"""Return an instance of the FileInput class, which can be iterated.
The parameters are passed to the constructor of the FileInput class.
The returned instance, in addition to being an iterator,
keeps global ... | def input(files=None, inplace=False, backup="", bufsize=0,
mode="r", openhook=None):
| """Return an instance of the FileInput class, which can be iterated.
The parameters are passed to the constructor of the FileInput class.
The returned instance, in addition to being an iterator,
keeps global state for the functions of this module,.
"""
global _state
if _state and _state._fi... | filename", "lineno", "filelineno",
"isfirstline", "isstdin", "FileInput"]
_state = None
DEFAULT_BUFSIZE = 8*1024
def input(files=None, inplace=False, backup="", bufsize=0,
mode="r", openhook=None):
| 64 | 64 | 131 | 24 | 39 | cafealternativo/cpython | Lib/fileinput.py | Python | input | input | 91 | 103 | 91 | 92 | 46b9c69c18f8b44c967bcefc87967de66f499de4 | bigcode/the-stack | train |
761c3e5ebfbedf177e55bf76 | train | class | class FileInput:
"""FileInput([files[, inplace[, backup[, bufsize, [, mode[, openhook]]]]]])
Class FileInput is the implementation of the module; its methods
filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
nextfile() and close() correspond to the functions of the same name
in ... | class FileInput:
| """FileInput([files[, inplace[, backup[, bufsize, [, mode[, openhook]]]]]])
Class FileInput is the implementation of the module; its methods
filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
nextfile() and close() correspond to the functions of the same name
in the module.
I... | Error("no active input()")
return _state.lineno()
def filelineno():
"""
Return the line number in the current file. Before the first line
has been read, returns 0. After the last line of the last file has
been read, returns the line number of that line within the file.
"""
if not _state:
... | 256 | 256 | 1,457 | 4 | 252 | cafealternativo/cpython | Lib/fileinput.py | Python | FileInput | FileInput | 183 | 389 | 183 | 183 | 2e3535672860fb1e159cf9b15677af5acf92a238 | bigcode/the-stack | train |
f74b64866aa129cb50138da5 | train | function | def isfirstline():
"""
Returns true the line just read is the first line of its file,
otherwise returns false.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.isfirstline()
| def isfirstline():
| """
Returns true the line just read is the first line of its file,
otherwise returns false.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.isfirstline()
| state.filelineno()
def fileno():
"""
Return the file number of the current file. When no file is currently
opened, returns -1.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.fileno()
def isfirstline():
| 64 | 64 | 53 | 5 | 59 | cafealternativo/cpython | Lib/fileinput.py | Python | isfirstline | isfirstline | 165 | 172 | 165 | 165 | 3b6cc919608eaa3698310ad69566efafc1f60ad9 | bigcode/the-stack | train |
d832167892706829e6a1e716 | train | function | def hook_encoded(encoding):
def openhook(filename, mode):
return open(filename, mode, encoding=encoding)
return openhook
| def hook_encoded(encoding):
| def openhook(filename, mode):
return open(filename, mode, encoding=encoding)
return openhook
| (filename)[1]
if ext == '.gz':
import gzip
return gzip.open(filename, mode)
elif ext == '.bz2':
import bz2
return bz2.BZ2File(filename, mode)
else:
return open(filename, mode)
def hook_encoded(encoding):
| 64 | 64 | 30 | 6 | 58 | cafealternativo/cpython | Lib/fileinput.py | Python | hook_encoded | hook_encoded | 404 | 407 | 404 | 404 | 6e5ec90640be511d0a4743472ae102adfeb951fd | bigcode/the-stack | train |
aec6e02939ed5a4290481300 | train | function | def isstdin():
"""
Returns true if the last line was read from sys.stdin,
otherwise returns false.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.isstdin()
| def isstdin():
| """
Returns true if the last line was read from sys.stdin,
otherwise returns false.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.isstdin()
| return _state.fileno()
def isfirstline():
"""
Returns true the line just read is the first line of its file,
otherwise returns false.
"""
if not _state:
raise RuntimeError("no active input()")
return _state.isfirstline()
def isstdin():
| 64 | 64 | 49 | 4 | 60 | cafealternativo/cpython | Lib/fileinput.py | Python | isstdin | isstdin | 174 | 181 | 174 | 174 | 4f20b6785917107266385a67cd1aca0763417b4b | bigcode/the-stack | train |
6a5412be6e9bc9655afb9fe5 | train | function | def hook_compressed(filename, mode):
ext = os.path.splitext(filename)[1]
if ext == '.gz':
import gzip
return gzip.open(filename, mode)
elif ext == '.bz2':
import bz2
return bz2.BZ2File(filename, mode)
else:
return open(filename, mode)
| def hook_compressed(filename, mode):
| ext = os.path.splitext(filename)[1]
if ext == '.gz':
import gzip
return gzip.open(filename, mode)
elif ext == '.bz2':
import bz2
return bz2.BZ2File(filename, mode)
else:
return open(filename, mode)
| return self._file.fileno()
except ValueError:
return -1
else:
return -1
def isfirstline(self):
return self._filelineno == 1
def isstdin(self):
return self._isstdin
def hook_compressed(filename, mode):
| 64 | 64 | 72 | 8 | 55 | cafealternativo/cpython | Lib/fileinput.py | Python | hook_compressed | hook_compressed | 392 | 401 | 392 | 392 | 77426de1a239313595ee6c3c2f285b4bd5763791 | bigcode/the-stack | train |
f5d812e2cfcaeab2c09ba850 | train | function | def _test():
import getopt
inplace = False
backup = False
opts, args = getopt.getopt(sys.argv[1:], "ib:")
for o, a in opts:
if o == '-i': inplace = True
if o == '-b': backup = a
for line in input(args, inplace=inplace, backup=backup):
if line[-1:] == '\n': line = line[:-1... | def _test():
| import getopt
inplace = False
backup = False
opts, args = getopt.getopt(sys.argv[1:], "ib:")
for o, a in opts:
if o == '-i': inplace = True
if o == '-b': backup = a
for line in input(args, inplace=inplace, backup=backup):
if line[-1:] == '\n': line = line[:-1]
if ... | bz2':
import bz2
return bz2.BZ2File(filename, mode)
else:
return open(filename, mode)
def hook_encoded(encoding):
def openhook(filename, mode):
return open(filename, mode, encoding=encoding)
return openhook
def _test():
| 64 | 64 | 168 | 4 | 59 | cafealternativo/cpython | Lib/fileinput.py | Python | _test | _test | 410 | 423 | 410 | 410 | 551e264abc8276ddb5a1a655c676e82a0f4fc79b | bigcode/the-stack | train |
09d40027592691a269372c30 | train | function | def close():
"""Close the sequence."""
global _state
state = _state
_state = None
if state:
state.close()
| def close():
| """Close the sequence."""
global _state
state = _state
_state = None
if state:
state.close()
| state for the functions of this module,.
"""
global _state
if _state and _state._file:
raise RuntimeError("input() already active")
_state = FileInput(files, inplace, backup, bufsize, mode, openhook)
return _state
def close():
| 64 | 64 | 34 | 3 | 60 | cafealternativo/cpython | Lib/fileinput.py | Python | close | close | 105 | 111 | 105 | 105 | dc983d3f21f59d35ef4ef6c9020cf16d0bf951c0 | bigcode/the-stack | train |
7915bc62679fac0fcf8eeaff | train | function | def nextfile():
"""
Close the current file so that the next iteration will read the first
line from the next file (if any); lines not read from the file will
not count towards the cumulative line count. The filename is not
changed until after the first line of the next file has been read.
Before... | def nextfile():
| """
Close the current file so that the next iteration will read the first
line from the next file (if any); lines not read from the file will
not count towards the cumulative line count. The filename is not
changed until after the first line of the next file has been read.
Before the first line ... | ")
_state = FileInput(files, inplace, backup, bufsize, mode, openhook)
return _state
def close():
"""Close the sequence."""
global _state
state = _state
_state = None
if state:
state.close()
def nextfile():
| 64 | 64 | 139 | 4 | 60 | cafealternativo/cpython | Lib/fileinput.py | Python | nextfile | nextfile | 113 | 125 | 113 | 113 | f04e2686696ad7695e3bc936a71764f9a3f7dc1f | bigcode/the-stack | train |
c5e089cbf22893f3f6babd74 | train | function | @pytest.mark.parametrize(["arg", "delayed"],
list(
itertools.product(["local_fs", "s3_fs"],
[True, False])))
def test_view(
dask_client, # pylint: disable=redefined-outer-name,unused-argument
arg,
delayed,
... | @pytest.mark.parametrize(["arg", "delayed"],
list(
itertools.product(["local_fs", "s3_fs"],
[True, False])))
def test_view(
dask_client, # pylint: disable=redefined-outer-name,unused-argument
arg,
delayed,
... | """Test the creation of a view."""
tested_fs = request.getfixturevalue(arg)
create_test_collection(tested_fs, delayed=False)
instance = convenience.create_view(str(tested_fs.view),
view.ViewReference(
str(tested_fs.collec... | # Copyright (c) 2022 CNES
#
# All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""
Test of views
=============
"""
import itertools
import numpy
import pytest
from .. import convenience, meta, view
# pylint: disable=unused-import # Need to import... | 191 | 256 | 1,205 | 65 | 125 | CNES/zcollection | zcollection/tests/test_view.py | Python | test_view | test_view | 23 | 172 | 23 | 32 | 1d5e4b10a0be49c22f4983f26c0eb98c7f8df765 | bigcode/the-stack | train |
a00d895ea0564ee89f503763 | train | function | def main():
# step1: make dictionary
make_vocab_dict(opt.plm_vocab_file, opt.lang)
# step2: tokenization
if opt.plm_type == "bert":
from pytorch_pretrained_bert import BertTokenizer
# "en": bert-base-uncased "ch": bert-base-chinese
tokenizer = BertTokenizer.from_pretrained(opt... | def main():
# step1: make dictionary
| make_vocab_dict(opt.plm_vocab_file, opt.lang)
# step2: tokenization
if opt.plm_type == "bert":
from pytorch_pretrained_bert import BertTokenizer
# "en": bert-base-uncased "ch": bert-base-chinese
tokenizer = BertTokenizer.from_pretrained(opt.pretrain_tokenizer)
elif opt.plm_type... | + "." + opt.plm_type + ".tok"
with open(new_data, "w", encoding="utf-8") as f_tok:
for sent in tokenized_sents:
sent = " ".join(sent)
f_tok.write(sent)
f_tok.write('\n')
def main():
# step1: make dictionary
| 71 | 71 | 238 | 11 | 60 | quanpn90/NMTGMinor | pretrain_module/tokenization.py | Python | main | main | 67 | 93 | 67 | 69 | 7c23aef604004f61d5477ff8aa32d1e557ef6483 | bigcode/the-stack | train |
0aac0aa84f5667127dcd5d4c | train | function | def make_vocab_dict(vocab_file, lang):
"""Loads a vocabulary file into a dictionary."""
index = 0
vocab = open(vocab_file, "r")
word2idx = open(opt.plm_type + "_word2idx."+lang, "w")
idx2word = open(opt.plm_type + "_idx2word."+lang, "w")
while True:
word = vocab.readline()
# the ... | def make_vocab_dict(vocab_file, lang):
| """Loads a vocabulary file into a dictionary."""
index = 0
vocab = open(vocab_file, "r")
word2idx = open(opt.plm_type + "_word2idx."+lang, "w")
idx2word = open(opt.plm_type + "_idx2word."+lang, "w")
while True:
word = vocab.readline()
# the last line
if not word:
... | and at the end of each sentence""")
parser.add_argument('-special_bos', default='<s>',
help='special bos token.')
parser.add_argument('-special_eos', default='</s>',
help='special eso token.')
opt = parser.parse_args()
def make_vocab_dict(vocab_file, lang):
| 64 | 64 | 165 | 10 | 54 | quanpn90/NMTGMinor | pretrain_module/tokenization.py | Python | make_vocab_dict | make_vocab_dict | 26 | 44 | 26 | 26 | fccc4e6f1c3c6a327cdf9c232560cdbc2cecbb2b | bigcode/the-stack | train |
d37ae740a7169aee643f93e9 | train | function | def tokenize_data(raw_data, tokenizer):
with open(raw_data, "r", encoding="utf-8") as f_raw:
tokenized_sents = []
for line in f_raw:
sent = line.strip()
tokenized_sent = tokenizer.tokenize(sent)
if opt.add_special_tok:
tokenized_sent.insert(0, opt.... | def tokenize_data(raw_data, tokenizer):
| with open(raw_data, "r", encoding="utf-8") as f_raw:
tokenized_sents = []
for line in f_raw:
sent = line.strip()
tokenized_sent = tokenizer.tokenize(sent)
if opt.add_special_tok:
tokenized_sent.insert(0, opt.special_bos)
tokenized_s... | idx2word.write(str(index) + " " + word + "\n")
word2idx.write(word + " " + str(index) + "\n")
index += 1
vocab.close()
word2idx.close()
idx2word.close()
def tokenize_data(raw_data, tokenizer):
| 64 | 64 | 163 | 8 | 56 | quanpn90/NMTGMinor | pretrain_module/tokenization.py | Python | tokenize_data | tokenize_data | 47 | 64 | 47 | 47 | e05eb6a5f16a15e8cee88da60affd2a53a93a3ea | bigcode/the-stack | train |
bef2e51a1669c291c2a1edf1 | train | function | def test_get_invalid_url_should_throw_exception():
client = MockHttpClient()
with pytest.raises(NuException):
client.get('invalid.url')
| def test_get_invalid_url_should_throw_exception():
| client = MockHttpClient()
with pytest.raises(NuException):
client.get('invalid.url')
| .nubank import Nubank
@pytest.fixture(scope="module")
def nubank_client():
client = Nubank(client=MockHttpClient())
client.authenticate_with_qr_code('12345678912', 'hunter12', 'some-uuid')
return client
def test_get_invalid_url_should_throw_exception():
| 64 | 64 | 31 | 9 | 54 | Vicmendon/pynubank | tests/test_mock_http_client.py | Python | test_get_invalid_url_should_throw_exception | test_get_invalid_url_should_throw_exception | 19 | 22 | 19 | 19 | 6e0bf08e84967d70454a622f271d3448e664ff70 | bigcode/the-stack | train |
475fd34572ace99eff902773 | train | function | def test_check_not_tested_new_methods(nubank_client):
default_params = {
'get_bill_details': {
'bill': {'_links': {'self': {'href': 'https://mocked-proxy-url/api/bills/abcde-fghi-jklmn-opqrst-uvxz'}}}
},
'get_account_investments_yield': {
'date': datetime.now(),
... | def test_check_not_tested_new_methods(nubank_client):
| default_params = {
'get_bill_details': {
'bill': {'_links': {'self': {'href': 'https://mocked-proxy-url/api/bills/abcde-fghi-jklmn-opqrst-uvxz'}}}
},
'get_account_investments_yield': {
'date': datetime.now(),
},
'get_card_statement_details': {
... | _invalid_url_should_throw_exception():
client = MockHttpClient()
with pytest.raises(NuException):
client.get('invalid.url')
def test_post_invalid_url_should_throw_exception():
client = MockHttpClient()
with pytest.raises(NuException):
client.post('invalid.url', {})
def test_check_not_t... | 73 | 74 | 247 | 13 | 60 | Vicmendon/pynubank | tests/test_mock_http_client.py | Python | test_check_not_tested_new_methods | test_check_not_tested_new_methods | 31 | 57 | 31 | 31 | fe7ab170c7104265b6b9db9bdc786708a0fa03af | bigcode/the-stack | train |
7be4198977f66360d9e3d501 | train | function | @pytest.fixture(scope="module")
def nubank_client():
client = Nubank(client=MockHttpClient())
client.authenticate_with_qr_code('12345678912', 'hunter12', 'some-uuid')
return client
| @pytest.fixture(scope="module")
def nubank_client():
| client = Nubank(client=MockHttpClient())
client.authenticate_with_qr_code('12345678912', 'hunter12', 'some-uuid')
return client
| import inspect
from datetime import datetime
from uuid import uuid4
import pytest
from pynubank import MockHttpClient
from pynubank.exception import NuException
from pynubank.nubank import Nubank
@pytest.fixture(scope="module")
def nubank_client():
| 57 | 64 | 48 | 11 | 45 | Vicmendon/pynubank | tests/test_mock_http_client.py | Python | nubank_client | nubank_client | 12 | 16 | 12 | 13 | 4742049d66ba7084bd8ef3878f0d0d1e10e3e6e2 | bigcode/the-stack | train |
fbece11ddf992365fbe64721 | train | function | def test_post_invalid_url_should_throw_exception():
client = MockHttpClient()
with pytest.raises(NuException):
client.post('invalid.url', {})
| def test_post_invalid_url_should_throw_exception():
| client = MockHttpClient()
with pytest.raises(NuException):
client.post('invalid.url', {})
| .authenticate_with_qr_code('12345678912', 'hunter12', 'some-uuid')
return client
def test_get_invalid_url_should_throw_exception():
client = MockHttpClient()
with pytest.raises(NuException):
client.get('invalid.url')
def test_post_invalid_url_should_throw_exception():
| 64 | 64 | 32 | 9 | 55 | Vicmendon/pynubank | tests/test_mock_http_client.py | Python | test_post_invalid_url_should_throw_exception | test_post_invalid_url_should_throw_exception | 25 | 28 | 25 | 25 | 861ad101c0fe7d1a9ec2d6531acae703e18d9f8b | bigcode/the-stack | train |
9aff6da604a30a814b3aa969 | train | class | class OffPolicyVectorizedSampler(BatchSampler):
"""This class implements OffPolicyVectorizedSampler.
Args:
algo (metarl.np.RLAlgorithm): Algorithm.
env (metarl.envs.MetaRLEnv): Environment.
n_envs (int): Number of parallel environments managed by sampler.
no_reset (bool): Reset ... | class OffPolicyVectorizedSampler(BatchSampler):
| """This class implements OffPolicyVectorizedSampler.
Args:
algo (metarl.np.RLAlgorithm): Algorithm.
env (metarl.envs.MetaRLEnv): Environment.
n_envs (int): Number of parallel environments managed by sampler.
no_reset (bool): Reset environment between samples or not.
"""
... | """This module implements a Vectorized Sampler used for OffPolicy Algorithms.
It diffs from OnPolicyVectorizedSampler in two parts:
- The num of envs is defined by rollout_batch_size. In
OnPolicyVectorizedSampler, the number of envs can be decided by batch_size
and max_path_length. But OffPolicy algorithms usually ... | 160 | 256 | 1,431 | 10 | 149 | icml2020submission6857/metarl | src/metarl/sampler/off_policy_vectorized_sampler.py | Python | OffPolicyVectorizedSampler | OffPolicyVectorizedSampler | 21 | 195 | 21 | 21 | ff0996c1fa7cf11d30e31975f96ab6962463603d | bigcode/the-stack | train |
92d2ad203c19e7da07e5ee00 | train | function | def select_imregions(ptype, full_im1, full_im2, overlap_pixels):
"""Select image regions to extract keypoints from."""
if ptype == 'z':
im1 = full_im1
im2 = full_im2
elif ptype in 'y':
y1 = full_im1.shape[0] - overlap_pixels[0]
y2 = overlap_pixels[0]
im1 = full_im1[y... | def select_imregions(ptype, full_im1, full_im2, overlap_pixels):
| """Select image regions to extract keypoints from."""
if ptype == 'z':
im1 = full_im1
im2 = full_im2
elif ptype in 'y':
y1 = full_im1.shape[0] - overlap_pixels[0]
y2 = overlap_pixels[0]
im1 = full_im1[y1:, :]
im2 = full_im2[:y2, :]
elif ptype in 'x':
... | = tf.rescale(imgs[p[0][0]][p[0][1]], 1./ds)
full_im2 = tf.rescale(imgs[p[1][0]][p[1][1]], 1./ds)
else:
full_im1 = imgs[p[0][0]][p[0][1]]
full_im2 = imgs[p[1][0]][p[1][1]]
return full_im1, full_im2
def select_imregions(ptype, full_im1, full_im2, overlap_pixels):
| 117 | 117 | 393 | 18 | 98 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | select_imregions | select_imregions | 271 | 302 | 271 | 271 | 8f7593458f6f945bc27485847d37c8f3675f5f06 | bigcode/the-stack | train |
91399414215d006b38e145de | train | function | def plot_pair_ransac(outputdir, pairstring, p, full_im1, full_im2,
kp_im1, kp_im2, matches, inliers):
"""Create plots of orb keypoints vs. ransac inliers."""
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(2, 1)
plot_matches(ax1, full_im1, full_im2, kp_im1, kp_im2,
... | def plot_pair_ransac(outputdir, pairstring, p, full_im1, full_im2,
kp_im1, kp_im2, matches, inliers):
| """Create plots of orb keypoints vs. ransac inliers."""
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(2, 1)
plot_matches(ax1, full_im1, full_im2, kp_im1, kp_im2,
matches, only_matches=True)
ax1.axis('off')
plot_matches(ax2, full_im1, full_im2, kp_im1, kp_im2,
... | 1] += imshape[1] - 2 * overlap_pixels[1]
return kp_im1, kp_im2
def plot_pair_ransac(outputdir, pairstring, p, full_im1, full_im2,
kp_im1, kp_im2, matches, inliers):
| 64 | 64 | 196 | 36 | 27 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | plot_pair_ransac | plot_pair_ransac | 332 | 349 | 332 | 333 | 4df9be2d6930816c5e960ed376df8d1b4ed68b88 | bigcode/the-stack | train |
cf841755f2fda4f9a85c5eea | train | function | def read_connectivities(confilename):
"""Read pair connectivities from file.
specified for each pair per line as:
type imno1 imno2
where type is one of x y tlbr trbl
connectivities = [['z', 0, 0], ['z', 1, 1], ['z', 2, 2], ['z', 3, 3],
['y', 0, 2], ['y', 1, 3],
... | def read_connectivities(confilename):
| """Read pair connectivities from file.
specified for each pair per line as:
type imno1 imno2
where type is one of x y tlbr trbl
connectivities = [['z', 0, 0], ['z', 1, 1], ['z', 2, 2], ['z', 3, 3],
['y', 0, 2], ['y', 1, 3],
['x', 0, 1], ['x', 2, 3],
... | ], dtype=int)
displacements = tuple(sum(local_n[0:r]) for r in range(0, size))
comm.Scatterv([nrs, tuple(local_n), displacements,
SLL], local_nrs, root=0)
return local_nrs
def read_connectivities(confilename):
| 66 | 66 | 222 | 7 | 58 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | read_connectivities | read_connectivities | 148 | 166 | 148 | 148 | 7f92f950c6137877257a7546ec95c68b990abaaf | bigcode/the-stack | train |
f25dc9ea4c9786327b8c9f54 | train | function | def find_missing_pairs(directory, unique_pairs, offsets, ds):
"""Get a list of missing pairs.
list is of the form [[slcIm1, tileIm1], [slcIm2, tileIm2], 'type']
"""
missing_pairs = []
for p in unique_pairs:
pairstring = generate_pairstring(offsets, ds, p)
pairfile = path.join(direc... | def find_missing_pairs(directory, unique_pairs, offsets, ds):
| """Get a list of missing pairs.
list is of the form [[slcIm1, tileIm1], [slcIm2, tileIm2], 'type']
"""
missing_pairs = []
for p in unique_pairs:
pairstring = generate_pairstring(offsets, ds, p)
pairfile = path.join(directory, pairstring + ".pickle")
try:
open(pa... | ], pair[0], pair[2]] not in unique_pairs) &
(pair[0] != pair[1]) &
(pair[1][0] != n_slcs)):
unique_pairs.append(pair)
return unique_pairs
def find_missing_pairs(directory, unique_pairs, offsets, ds):
| 64 | 64 | 118 | 13 | 50 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | find_missing_pairs | find_missing_pairs | 203 | 218 | 203 | 203 | 4047ab4aa143ef3990f33a83664cd5e59c1b0897 | bigcode/the-stack | train |
cf22b79caad8e3c6e3ada8d1 | train | function | def get_keypoints(orb, im):
"""Get matching keypoints."""
orb.detect_and_extract(im)
kp = orb.keypoints
ds = orb.descriptors
return kp, ds
| def get_keypoints(orb, im):
| """Get matching keypoints."""
orb.detect_and_extract(im)
kp = orb.keypoints
ds = orb.descriptors
return kp, ds
| y2 = full_im2.shape[0] - 2 * overlap_pixels[0]
im1 = full_im1[:y1, x1:]
im2 = full_im2[y2:, :x2]
return im1, im2
def get_keypoints(orb, im):
| 64 | 64 | 43 | 9 | 54 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | get_keypoints | get_keypoints | 305 | 312 | 305 | 305 | 15e5e53a49600ea74bf07704b6f0534ac35b4ed0 | bigcode/the-stack | train |
83506a20f923e11aa03d2183 | train | function | def reset_imregions(ptype, kp_im1, kp_im2, overlap_pixels, imshape):
"""Transform keypoints back to full image space."""
if ptype in 'z':
pass
elif ptype in 'y':
kp_im1[:, 0] += imshape[0] - overlap_pixels[0]
elif ptype in 'x':
kp_im1[:, 1] += imshape[1] - overlap_pixels[1]
e... | def reset_imregions(ptype, kp_im1, kp_im2, overlap_pixels, imshape):
| """Transform keypoints back to full image space."""
if ptype in 'z':
pass
elif ptype in 'y':
kp_im1[:, 0] += imshape[0] - overlap_pixels[0]
elif ptype in 'x':
kp_im1[:, 1] += imshape[1] - overlap_pixels[1]
elif ptype in 'tlbr': # TopLeft - BottomRight
kp_im1[:, 0] +=... | im1, im2
def get_keypoints(orb, im):
"""Get matching keypoints."""
orb.detect_and_extract(im)
kp = orb.keypoints
ds = orb.descriptors
return kp, ds
def reset_imregions(ptype, kp_im1, kp_im2, overlap_pixels, imshape):
| 70 | 70 | 235 | 21 | 48 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | reset_imregions | reset_imregions | 315 | 329 | 315 | 315 | 6f7eee06106ad3f4eef34cbf9b750649cc0a0bbf | bigcode/the-stack | train |
c99e32b5443db439203d0f6f | train | function | def find_small_pairs(directory, unique_pairs, offsets, ds, npairs=100):
"""Get a list of failed pairs.
list is of the form [[slcIm1, tileIm1], [slcIm2, tileIm2], 'type']
"""
failed_pairs = []
for p in unique_pairs:
pairstring = generate_pairstring(offsets, ds, p)
pairfile = path.jo... | def find_small_pairs(directory, unique_pairs, offsets, ds, npairs=100):
| """Get a list of failed pairs.
list is of the form [[slcIm1, tileIm1], [slcIm2, tileIm2], 'type']
"""
failed_pairs = []
for p in unique_pairs:
pairstring = generate_pairstring(offsets, ds, p)
pairfile = path.join(directory, pairstring + ".pickle")
p, src, _, model, _ = pick... | (offsets, ds, p)
pairfile = path.join(directory, pairstring + ".pickle")
try:
open(pairfile, 'rb')
except:
missing_pairs.append(p)
return missing_pairs
def find_small_pairs(directory, unique_pairs, offsets, ds, npairs=100):
| 64 | 64 | 156 | 18 | 45 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | find_small_pairs | find_small_pairs | 221 | 238 | 221 | 221 | e88f0b3baa7dcf1599cbccfa5476711b09df0af2 | bigcode/the-stack | train |
eb99823574f28d608ac78020 | train | function | def downsample_images(p, imgs, ds):
"""Subsample images with downsample_factor"""
if ds > 1:
full_im1 = tf.rescale(imgs[p[0][0]][p[0][1]], 1./ds)
full_im2 = tf.rescale(imgs[p[1][0]][p[1][1]], 1./ds)
else:
full_im1 = imgs[p[0][0]][p[0][1]]
full_im2 = imgs[p[1][0]][p[1][1]]
... | def downsample_images(p, imgs, ds):
| """Subsample images with downsample_factor"""
if ds > 1:
full_im1 = tf.rescale(imgs[p[0][0]][p[0][1]], 1./ds)
full_im2 = tf.rescale(imgs[p[1][0]][p[1][1]], 1./ds)
else:
full_im1 = imgs[p[0][0]][p[0][1]]
full_im2 = imgs[p[1][0]][p[1][1]]
return full_im1, full_im2
| p)
pairfile = path.join(directory, pairstring + ".pickle")
p, _, _, model, _ = pickle.load(open(pairfile, 'rb'))
if np.isnan(model.params).any():
failed_pairs.append(p)
return failed_pairs
def downsample_images(p, imgs, ds):
| 64 | 64 | 130 | 10 | 53 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | downsample_images | downsample_images | 258 | 268 | 258 | 258 | 811c748b330e1460d07de0671f001c1551d1126e | bigcode/the-stack | train |
fb2122e5f99b8a04f9fa4ecb | train | function | def main(argv):
"""Generate matching point-pairs for stack registration."""
# parse arguments
parser = ArgumentParser(description="""
Generate matching point-pairs for stack registration.""")
parser.add_argument('imgdir',
help='a directory with images')
parser.add_ar... | def main(argv):
| """Generate matching point-pairs for stack registration."""
# parse arguments
parser = ArgumentParser(description="""
Generate matching point-pairs for stack registration.""")
parser.add_argument('imgdir',
help='a directory with images')
parser.add_argument('outputdi... | #!/usr/bin/env python
import sys
from os import path, makedirs
from argparse import ArgumentParser
import pickle
import math
from random import sample
import numpy as np
from time import time
from scipy.signal import gaussian
from skimage import io
from skimage.feature import ORB, match_descriptors, plot_matches
fro... | 116 | 256 | 1,039 | 4 | 112 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | main | main | 25 | 126 | 25 | 25 | 6e547589897478528b1c313659009cf4d9b12260 | bigcode/the-stack | train |
da0fcba348658e98fd8ad041 | train | function | def scatter_series(n, comm, size, rank, SLL):
"""Scatter a series of jobnrs over processes."""
nrs = np.array(range(0, n), dtype=int)
local_n = np.ones(size, dtype=int) * n / size
local_n[0:n % size] += 1
local_nrs = np.zeros(local_n[rank], dtype=int)
displacements = tuple(sum(local_n[0:r]) for... | def scatter_series(n, comm, size, rank, SLL):
| """Scatter a series of jobnrs over processes."""
nrs = np.array(range(0, n), dtype=int)
local_n = np.ones(size, dtype=int) * n / size
local_n[0:n % size] += 1
local_nrs = np.zeros(local_n[rank], dtype=int)
displacements = tuple(sum(local_n[0:r]) for r in range(0, size))
comm.Scatterv([nrs, ... | , plotpairs,
residual_threshold, num_inliers, transformname)
# FIXME: handle case where get_pair fails
allpairs.append(pair)
return allpairs
# ========================================================================== #
# function defs
# ===================================... | 63 | 64 | 140 | 14 | 49 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | scatter_series | scatter_series | 134 | 145 | 134 | 134 | 1c83cc4d676a1e3f411eb6c36ed74c8f0fbd5a5a | bigcode/the-stack | train |
00321f99349d995abc96bb48 | train | function | def generate_pairstring(offsets, ds, p):
"""Get the pair identifier."""
pairstring = 'pair' + \
'_c' + str(offsets) + \
'_d' + str(ds) + \
'_s' + str(p[0][0]).zfill(4) + \
'-t' + str(p[0][1]) + \
'_s' + str(p[1][0]).zfill(4) +... | def generate_pairstring(offsets, ds, p):
| """Get the pair identifier."""
pairstring = 'pair' + \
'_c' + str(offsets) + \
'_d' + str(ds) + \
'_s' + str(p[0][0]).zfill(4) + \
'-t' + str(p[0][1]) + \
'_s' + str(p[1][0]).zfill(4) + \
'-t' + str(p[1][1])
... | """
with open(confilename) as f:
con = [line.rstrip('\n').split() for line in f]
con = [[c[0], int(c[1]), int(c[2])] for c in con]
return con
def generate_pairstring(offsets, ds, p):
| 64 | 64 | 117 | 11 | 52 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | generate_pairstring | generate_pairstring | 169 | 180 | 169 | 169 | 0251575dc3536ff012f4e90fe1e0e07de9eb7b80 | bigcode/the-stack | train |
bec87a166f0b1b0a9558da33 | train | function | def find_failed_pairs(directory, unique_pairs, offsets, ds):
"""Get a list of failed pairs.
list is of the form [[slcIm1, tileIm1], [slcIm2, tileIm2], 'type']
"""
failed_pairs = []
for p in unique_pairs:
pairstring = generate_pairstring(offsets, ds, p)
pairfile = path.join(director... | def find_failed_pairs(directory, unique_pairs, offsets, ds):
| """Get a list of failed pairs.
list is of the form [[slcIm1, tileIm1], [slcIm2, tileIm2], 'type']
"""
failed_pairs = []
for p in unique_pairs:
pairstring = generate_pairstring(offsets, ds, p)
pairfile = path.join(directory, pairstring + ".pickle")
p, _, _, model, _ = pickle... | , _ = pickle.load(open(pairfile, 'rb'))
population = range(0, src.shape[0])
try:
sample(population, npairs)
except ValueError:
failed_pairs.append(p)
return failed_pairs
def find_failed_pairs(directory, unique_pairs, offsets, ds):
| 64 | 64 | 131 | 13 | 50 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | find_failed_pairs | find_failed_pairs | 241 | 255 | 241 | 241 | 49776d76644ff7c6aea746db63ad95e20f3a2991 | bigcode/the-stack | train |
b73a1f09a7b64161f90880f6 | train | function | def get_pair(outputdir, imgs, p, offsets, ds,
overlap_fraction, orb,
plotpairs=0, res_th=10, num_inliers=100,
transformname="EuclideanTransform"):
"""Create inlier keypoint pairs."""
pair_tstart = time()
overlap_pixels = [int(math.ceil(d * of * 1/ds))
... | def get_pair(outputdir, imgs, p, offsets, ds,
overlap_fraction, orb,
plotpairs=0, res_th=10, num_inliers=100,
transformname="EuclideanTransform"):
| """Create inlier keypoint pairs."""
pair_tstart = time()
overlap_pixels = [int(math.ceil(d * of * 1/ds))
for d, of in zip(imgs[0][0].shape, overlap_fraction)]
f1, f2 = downsample_images(p, imgs, ds)
p1, p2 = select_imregions(p[2], f1, f2, overlap_pixels)
kp1, de1 = get_k... | 2) = plt.subplots(2, 1)
plot_matches(ax1, full_im1, full_im2, kp_im1, kp_im2,
matches, only_matches=True)
ax1.axis('off')
plot_matches(ax2, full_im1, full_im2, kp_im1, kp_im2,
matches[inliers], only_matches=True)
ax2.axis('off')
plotdir = path.join(outputdir, 'plotp... | 174 | 174 | 583 | 45 | 129 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | get_pair | get_pair | 352 | 399 | 352 | 355 | 14a00d502ea86c42ac1c5f9d179f3990c38efbfc | bigcode/the-stack | train |
04e06191791bd62435026093 | train | function | def generate_unique_pairs(n_slcs, offsets, connectivities):
"""Get a list of unique pairs with certain connectivity.
list is of the form [[slcIm1, tileIm1], [slcIm2, tileIm2], 'type']
"""
all_pairs = [[[slc, c[1]], [slc+o, c[2]], c[0]]
for slc in range(0, n_slcs)
for ... | def generate_unique_pairs(n_slcs, offsets, connectivities):
| """Get a list of unique pairs with certain connectivity.
list is of the form [[slcIm1, tileIm1], [slcIm2, tileIm2], 'type']
"""
all_pairs = [[[slc, c[1]], [slc+o, c[2]], c[0]]
for slc in range(0, n_slcs)
for o in range(0, offsets+1)
for c in connectiv... | \
'-t' + str(p[0][1]) + \
'_s' + str(p[1][0]).zfill(4) + \
'-t' + str(p[1][1])
return pairstring
def generate_unique_pairs(n_slcs, offsets, connectivities):
| 64 | 64 | 184 | 13 | 50 | michielkleinnijenhuis/EM | reg/get_pairs.py | Python | generate_unique_pairs | generate_unique_pairs | 183 | 200 | 183 | 183 | 43edc1b03977a6eaef1539df51e07de5ac0b5be9 | bigcode/the-stack | train |
ae8de2dfbce499ebf052292f | train | function | def find_triplet():
for a in range(1, 500):
for b in range(1, 500):
c = np.sqrt(a**2 + b**2)
if a + b + c == 1000:
print(f"Triplet found!")
print(f"a: {a}, b: {b}, c: {c}")
print(f"a + b + c = {a + b + c}")
print(f"Pro... | def find_triplet():
| for a in range(1, 500):
for b in range(1, 500):
c = np.sqrt(a**2 + b**2)
if a + b + c == 1000:
print(f"Triplet found!")
print(f"a: {a}, b: {b}, c: {c}")
print(f"a + b + c = {a + b + c}")
print(f"Product abc = {a*b*c}")... | = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
import numpy as np
# Brute force: start computing triplets until the correct one has been found
def find_triplet():
| 64 | 64 | 109 | 5 | 58 | gboluwaga/ProjectEuler | problem009.py | Python | find_triplet | find_triplet | 17 | 28 | 17 | 17 | f8519933eec09ed807f2f9084b248e4dbcdc9016 | bigcode/the-stack | train |
bbcf1c9c338a183b31dcef7d | train | class | class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="family", parent_name="layout.yaxis.title.font", **kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type... | class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
| def __init__(
self, plotly_name="family", parent_name="layout.yaxis.title.font", **kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "ticks"),
no_blank=kwargs.pop("n... | import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
| 20 | 64 | 107 | 12 | 7 | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | env/Lib/site-packages/plotly/validators/layout/yaxis/title/font/_family.py | Python | FamilyValidator | FamilyValidator | 4 | 15 | 4 | 4 | 5da03378ab756caf5b686822cc12eba36d871c1d | bigcode/the-stack | train |
cc55b5583310bbe7670a7e3c | train | function | def set_measurement_mode(mode):
"""Set the AS7262 measurement mode.
:param mode: 0-3
"""
_as7262.CONTROL.set_measurement_mode(mode)
| def set_measurement_mode(mode):
| """Set the AS7262 measurement mode.
:param mode: 0-3
"""
_as7262.CONTROL.set_measurement_mode(mode)
| def set_gain(gain):
"""Set the gain amount of the AS7262.
:param gain: gain multiplier, one of 1, 3.7, 16 or 64
"""
_as7262.CONTROL.set_gain_x(gain)
def set_measurement_mode(mode):
| 64 | 64 | 42 | 7 | 57 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | set_measurement_mode | set_measurement_mode | 204 | 210 | 204 | 204 | 8af339a6a5925d228fea3324530aa1cc10cb4628 | bigcode/the-stack | train |
7d789d91eb6517f88c5da91e | train | function | def set_indicator_led(state):
"""Set the AS7262 indicator LED state.
:param state: True = On, False = Off
"""
_as7262.LED_CONTROL.set_indicator_enable(state)
| def set_indicator_led(state):
| """Set the AS7262 indicator LED state.
:param state: True = On, False = Off
"""
_as7262.LED_CONTROL.set_indicator_enable(state)
| LED_CONTROL.set_indicator_current_limit_ma(current)
def set_illumination_led(state):
"""Set the AS7262 illumination LED state.
:param state: True = On, False = Off
"""
_as7262.LED_CONTROL.set_illumination_enable(state)
def set_indicator_led(state):
| 64 | 64 | 45 | 6 | 58 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | set_indicator_led | set_indicator_led | 249 | 255 | 249 | 249 | 61ef3db47f37916bbb5238dd26e144eda6569407 | bigcode/the-stack | train |
3f5bc113b849dff5d085939f | train | function | def set_illumination_led(state):
"""Set the AS7262 illumination LED state.
:param state: True = On, False = Off
"""
_as7262.LED_CONTROL.set_illumination_enable(state)
| def set_illumination_led(state):
| """Set the AS7262 illumination LED state.
:param state: True = On, False = Off
"""
_as7262.LED_CONTROL.set_illumination_enable(state)
| """Set the AS7262 indicator LED current in milliamps.
:param current: Value in milliamps, one of 1, 2, 4 or 8
"""
_as7262.LED_CONTROL.set_indicator_current_limit_ma(current)
def set_illumination_led(state):
| 64 | 64 | 49 | 8 | 56 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | set_illumination_led | set_illumination_led | 240 | 246 | 240 | 240 | ec8c6ed31381cf17b582bed44cf5a92592fe1400 | bigcode/the-stack | train |
8385fc312f84ed4947f4e531 | train | function | def set_illumination_led_current(current):
"""Set the AS7262 illumination LED current in milliamps.
:param current: Value in milliamps, one of 12.5, 25, 50 or 100
"""
_as7262.LED_CONTROL.set_illumination_current_limit_ma(current)
| def set_illumination_led_current(current):
| """Set the AS7262 illumination LED current in milliamps.
:param current: Value in milliamps, one of 12.5, 25, 50 or 100
"""
_as7262.LED_CONTROL.set_illumination_current_limit_ma(current)
| (mode)
def set_integration_time(time_ms):
"""Set the AS7262 sensor integration time in milliseconds.
:param time_ms: Time in milliseconds from 0 to ~91
"""
_as7262.INTEGRATION_TIME.set_ms(time_ms)
def set_illumination_led_current(current):
| 64 | 64 | 70 | 9 | 55 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | set_illumination_led_current | set_illumination_led_current | 222 | 228 | 222 | 222 | b0e86d718f6d946a7233ca85c83e82d1a897f9c7 | bigcode/the-stack | train |
d635507627970cd236c0e1bb | train | function | def get_version():
"""Get the hardware type, version and firmware version from the AS7262."""
with _as7262.VERSION as VERSION:
fw_version = VERSION.get_fw_version()
hw_version = VERSION.get_hw_version()
hw_type = VERSION.get_hw_type()
return hw_type, hw_version, fw_version
| def get_version():
| """Get the hardware type, version and firmware version from the AS7262."""
with _as7262.VERSION as VERSION:
fw_version = VERSION.get_fw_version()
hw_version = VERSION.get_hw_version()
hw_type = VERSION.get_hw_type()
return hw_type, hw_version, fw_version
| _as7262.LED_CONTROL.set_illumination_enable(state)
def set_indicator_led(state):
"""Set the AS7262 indicator LED state.
:param state: True = On, False = Off
"""
_as7262.LED_CONTROL.set_indicator_enable(state)
def get_version():
| 64 | 64 | 69 | 4 | 60 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | get_version | get_version | 258 | 265 | 258 | 258 | fc7344273c1eae946693064df9451d05c840d3d8 | bigcode/the-stack | train |
16797cd1a1aa130fba4c09d3 | train | class | class IntegrationTimeAdapter(Adapter):
"""Scale integration time in ms to LSBs."""
def _decode(self, value):
return value / 2.8
def _encode(self, value):
return int(value * 2.8) & 0xff
| class IntegrationTimeAdapter(Adapter):
| """Scale integration time in ms to LSBs."""
def _decode(self, value):
return value / 2.8
def _encode(self, value):
return int(value * 2.8) & 0xff
| minor_version, sub_version)
class FloatAdapter(Adapter):
"""Convert a 4 byte register set into a float."""
def _decode(self, value):
b = _int_to_bytes(value, 4)
return struct.unpack('>f', bytearray(b))[0]
class IntegrationTimeAdapter(Adapter):
| 64 | 64 | 58 | 6 | 58 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | IntegrationTimeAdapter | IntegrationTimeAdapter | 79 | 86 | 79 | 79 | dfdc1247c31b6f19a14320946546688d739670d6 | bigcode/the-stack | train |
d16f6b59e0e2f83827941e1a | train | class | class CalibratedValues:
"""Store the 6 band spectral values."""
def __init__(self, red, orange, yellow, green, blue, violet): # noqa D107
self.red = red
self.orange = orange
self.yellow = yellow
self.green = green
self.blue = blue
self.violet = violet
def _... | class CalibratedValues:
| """Store the 6 band spectral values."""
def __init__(self, red, orange, yellow, green, blue, violet): # noqa D107
self.red = red
self.orange = orange
self.yellow = yellow
self.green = green
self.blue = blue
self.violet = violet
def __iter__(self): # noqa D... | # Polling for the state of the reset flag does not work here
# since the fragile virtual register state machine cannot
# respond while in a soft reset condition
# So, just wait long enough for it to reset fully...
time.sleep(2.0)
class CalibratedValues:
| 64 | 64 | 121 | 6 | 58 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | CalibratedValues | CalibratedValues | 165 | 178 | 165 | 165 | 49d01e2e9ea0e1df4f487b3f29e0d4b16ddff014 | bigcode/the-stack | train |
4a5c43fb2b2a50f06599adbb | train | function | def get_calibrated_values(timeout=10):
"""Return an instance of CalibratedValues containing the 6 spectral bands."""
t_start = time.time()
while _as7262.CONTROL.get_data_ready() == 0 and (time.time() - t_start) <= timeout:
pass
with _as7262.CALIBRATED_DATA as DATA:
return CalibratedValue... | def get_calibrated_values(timeout=10):
| """Return an instance of CalibratedValues containing the 6 spectral bands."""
t_start = time.time()
while _as7262.CONTROL.get_data_ready() == 0 and (time.time() - t_start) <= timeout:
pass
with _as7262.CALIBRATED_DATA as DATA:
return CalibratedValues(DATA.get_r(),
... | .blue = blue
self.violet = violet
def __iter__(self): # noqa D107
for colour in ['red', 'orange', 'yellow', 'green', 'blue', 'violet']:
yield getattr(self, colour)
def get_calibrated_values(timeout=10):
| 64 | 64 | 114 | 10 | 54 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | get_calibrated_values | get_calibrated_values | 181 | 192 | 181 | 181 | d079e35583443cecc0f3c44d3bba4735f04ab8ff | bigcode/the-stack | train |
2bb1e0286294631ef68d9a72 | train | class | class as7262VirtualRegisterBus():
"""AS7262 Virtual Register.
This class implements the wacky virtual register setup
of the AS7262 annd allows i2cdevice.Device to "just work"
without having to worry about how registers are actually
read or written under the hood.
"""
def __init__(self, bu... | class as7262VirtualRegisterBus():
| """AS7262 Virtual Register.
This class implements the wacky virtual register setup
of the AS7262 annd allows i2cdevice.Device to "just work"
without having to worry about how registers are actually
read or written under the hood.
"""
def __init__(self, bus=1):
"""Initialise virtua... | """Library for the AS7262 Visble Light Spectral Sensor."""
import time
import struct
import smbus
from i2cdevice import Device, Register, BitField, _int_to_bytes
from i2cdevice.adapter import Adapter, LookupAdapter
__version__ = '0.0.2'
class as7262VirtualRegisterBus():
| 73 | 124 | 416 | 8 | 65 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | as7262VirtualRegisterBus | as7262VirtualRegisterBus | 12 | 58 | 12 | 12 | aed6a0fbd9b98c741f3c628c45e036d8862c8343 | bigcode/the-stack | train |
8ef0e02b7c21a65ac303d435 | train | function | def set_integration_time(time_ms):
"""Set the AS7262 sensor integration time in milliseconds.
:param time_ms: Time in milliseconds from 0 to ~91
"""
_as7262.INTEGRATION_TIME.set_ms(time_ms)
| def set_integration_time(time_ms):
| """Set the AS7262 sensor integration time in milliseconds.
:param time_ms: Time in milliseconds from 0 to ~91
"""
_as7262.INTEGRATION_TIME.set_ms(time_ms)
| """
_as7262.CONTROL.set_gain_x(gain)
def set_measurement_mode(mode):
"""Set the AS7262 measurement mode.
:param mode: 0-3
"""
_as7262.CONTROL.set_measurement_mode(mode)
def set_integration_time(time_ms):
| 64 | 64 | 53 | 8 | 56 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | set_integration_time | set_integration_time | 213 | 219 | 213 | 213 | 837f648f51f273b4852bac994a86ab32612f4ac2 | bigcode/the-stack | train |
631355ec405f48cb855f41a8 | train | function | def set_indicator_led_current(current):
"""Set the AS7262 indicator LED current in milliamps.
:param current: Value in milliamps, one of 1, 2, 4 or 8
"""
_as7262.LED_CONTROL.set_indicator_current_limit_ma(current)
| def set_indicator_led_current(current):
| """Set the AS7262 indicator LED current in milliamps.
:param current: Value in milliamps, one of 1, 2, 4 or 8
"""
_as7262.LED_CONTROL.set_indicator_current_limit_ma(current)
| AS7262 illumination LED current in milliamps.
:param current: Value in milliamps, one of 12.5, 25, 50 or 100
"""
_as7262.LED_CONTROL.set_illumination_current_limit_ma(current)
def set_indicator_led_current(current):
| 64 | 64 | 64 | 7 | 57 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | set_indicator_led_current | set_indicator_led_current | 231 | 237 | 231 | 231 | 46ab5fb27c3f0cb27434b3aaa87d46229fa4bf39 | bigcode/the-stack | train |
b2f67597ecd1b47a56262d81 | train | function | def soft_reset():
"""Set the soft reset register bit of the AS7262."""
_as7262.CONTROL.set_reset(1)
# Polling for the state of the reset flag does not work here
# since the fragile virtual register state machine cannot
# respond while in a soft reset condition
# So, just wait long enough for it ... | def soft_reset():
| """Set the soft reset register bit of the AS7262."""
_as7262.CONTROL.set_reset(1)
# Polling for the state of the reset flag does not work here
# since the fragile virtual register state machine cannot
# respond while in a soft reset condition
# So, just wait long enough for it to reset fully...
... | in field.adapter.lookup_table:
value = field.adapter.lookup_table[key]
name = 'AS7262_{register}_{field}_{key}'.format(
register=register.name,
field=field.name,
key=key
).upper()
locals()[name] ... | 64 | 64 | 89 | 4 | 59 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | soft_reset | soft_reset | 155 | 162 | 155 | 155 | 4af54808ca5ff56ded18ddd62d13a970ce107996 | bigcode/the-stack | train |
9fa4ea8436c0b94cac3bd44a | train | function | def set_gain(gain):
"""Set the gain amount of the AS7262.
:param gain: gain multiplier, one of 1, 3.7, 16 or 64
"""
_as7262.CONTROL.set_gain_x(gain)
| def set_gain(gain):
| """Set the gain amount of the AS7262.
:param gain: gain multiplier, one of 1, 3.7, 16 or 64
"""
_as7262.CONTROL.set_gain_x(gain)
| _start) <= timeout:
pass
with _as7262.CALIBRATED_DATA as DATA:
return CalibratedValues(DATA.get_r(),
DATA.get_o(),
DATA.get_y(),
DATA.get_g(),
DATA.get_b(),
... | 64 | 64 | 57 | 6 | 58 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | set_gain | set_gain | 195 | 201 | 195 | 195 | 54cf68806bd9ff94b15dda7600071d7e98434658 | bigcode/the-stack | train |
8ce01a692b4ae86fdd5f0b13 | train | class | class FloatAdapter(Adapter):
"""Convert a 4 byte register set into a float."""
def _decode(self, value):
b = _int_to_bytes(value, 4)
return struct.unpack('>f', bytearray(b))[0]
| class FloatAdapter(Adapter):
| """Convert a 4 byte register set into a float."""
def _decode(self, value):
b = _int_to_bytes(value, 4)
return struct.unpack('>f', bytearray(b))[0]
| 2) | ((value & 0b1100000000000000) >> 14)
sub_version = (value & 0b0011111100000000) >> 8
return '{}.{}.{}'.format(major_version, minor_version, sub_version)
class FloatAdapter(Adapter):
| 64 | 64 | 52 | 5 | 59 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | FloatAdapter | FloatAdapter | 71 | 76 | 71 | 71 | 04fa8936339fbccd0fa2088824ff3059748cefc0 | bigcode/the-stack | train |
ff4eb97192f1826e4aad0a0c | train | class | class FWVersionAdapter(Adapter):
"""Convert the AS7262 firmware version number to a human-readable string."""
def _decode(self, value):
major_version = (value & 0x00F0) >> 4
minor_version = ((value & 0x000F) << 2) | ((value & 0b1100000000000000) >> 14)
sub_version = (value & 0b001111110... | class FWVersionAdapter(Adapter):
| """Convert the AS7262 firmware version number to a human-readable string."""
def _decode(self, value):
major_version = (value & 0x00F0) >> 4
minor_version = ((value & 0x000F) << 2) | ((value & 0b1100000000000000) >> 14)
sub_version = (value & 0b0011111100000000) >> 8
return '{}.... | , 0x01, register + offset)
while True:
if (self.get_status(address) & 0b01) == 1:
break
result.append(self._i2c_bus.read_byte_data(address, 0x02))
return result
class FWVersionAdapter(Adapter):
| 64 | 64 | 121 | 6 | 57 | FingerLeakers/as7262-python | library/as7262/__init__.py | Python | FWVersionAdapter | FWVersionAdapter | 61 | 68 | 61 | 61 | 0f7521dbc15db969dcfa50d1392db38971e0b76a | bigcode/the-stack | train |
eda831b18f2397077978a507 | train | class | class KoubeiCateringDishCommruleQueryResponse(AlipayResponse):
def __init__(self):
super(KoubeiCateringDishCommruleQueryResponse, self).__init__()
self._kbdish_comm_rule_info_list = None
self._page_no = None
self._page_size = None
self._total_count = None
self._total... | class KoubeiCateringDishCommruleQueryResponse(AlipayResponse):
| def __init__(self):
super(KoubeiCateringDishCommruleQueryResponse, self).__init__()
self._kbdish_comm_rule_info_list = None
self._page_no = None
self._page_size = None
self._total_count = None
self._total_page = None
@property
def kbdish_comm_rule_info_list(s... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.KbdishCommRuleInfo import KbdishCommRuleInfo
class KoubeiCateringDishCommruleQueryResponse(AlipayResponse):
| 69 | 144 | 481 | 16 | 52 | antopen/alipay-sdk-python-all | alipay/aop/api/response/KoubeiCateringDishCommruleQueryResponse.py | Python | KoubeiCateringDishCommruleQueryResponse | KoubeiCateringDishCommruleQueryResponse | 9 | 69 | 9 | 10 | 77b1778caa791e7c72799c79aa413495faa420ab | bigcode/the-stack | train |
03663f60f99f0bdce06e1a36 | train | function | def toggle_vis(event):
ax_main.collections[0].set_visible(not ax_main.collections[0].get_visible())
fig.canvas.draw_idle()
| def toggle_vis(event):
| ax_main.collections[0].set_visible(not ax_main.collections[0].get_visible())
fig.canvas.draw_idle()
| centres[:,2].max()+2)/2))],rwidth=0.8,log=True)
ax_size_hist.set_xlabel('Diameter (pixels)')
ax_size_hist.grid(True)
fig.canvas.draw_idle()
return update
def reset(event):
sdist.reset()
def toggle_vis(event):
| 64 | 64 | 30 | 5 | 59 | aliFrancis/mars-crater-catalogue | src/cluster_slider.py | Python | toggle_vis | toggle_vis | 48 | 50 | 48 | 48 | 98de11d3423c228ef3098313b49b10c8350465fb | bigcode/the-stack | train |
c3da010ccf626be9c494978a | train | function | def reset(event):
sdist.reset()
| def reset(event):
| sdist.reset()
| 2],[2*i for i in range(int((centres[:,2].max()+2)/2))],rwidth=0.8,log=True)
ax_size_hist.set_xlabel('Diameter (pixels)')
ax_size_hist.grid(True)
fig.canvas.draw_idle()
return update
def reset(event):
| 64 | 64 | 9 | 4 | 59 | aliFrancis/mars-crater-catalogue | src/cluster_slider.py | Python | reset | reset | 45 | 46 | 45 | 45 | 308f7bd82f6a3d15ef8ebd73c6811472b42ca6a1 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.