index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
49,920 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/header.py | 84,85 | 1,95 | get | Header | 91,95 | 85,95 | class Header(object):
"""A header to specify specific handling instructions for your email.
If the name or value contain Unicode characters, they must be properly
encoded. You may not overwrite the following reserved headers:
x-sg-id, x-sg-eid, received, dkim-signature, Content-Type,
Content-Transf... | class Header(object):
"""A header to specify specific handling instructions for your email.
If the name or value contain Unicode characters, they must be properly
encoded. You may not overwrite the following reserved headers:
x-sg-id, x-sg-eid, received, dkim-signature, Content-Type,
Content-Transf... | header = {}
if self.key is not None and self.value is not None:
header[self.key] = self.value
return header
| """
Get a JSON-ready representation of this Header.
:returns: This Header, ready for use in a request body.
:rtype: dict
"""
header = {}
if self.key is not None and self.value is not None:
header[self.key] = self.value
return header
| 18 | 682 | 42 | 724 | class Header(object):
"""A header to specify specific handling instructions for your email.
If the name or value contain Unicode characters, they must be properly
encoded. You may not overwrite the following reserved headers:
x-sg-id, x-sg-eid, received, dkim-signature, Content-Type,
Content-Transf... | class Header(object):
"""A header to specify specific handling instructions for your email.
If the name or value contain Unicode characters, they must be properly
encoded. You may not overwrite the following reserved headers:
x-sg-id, x-sg-eid, received, dkim-signature, Content-Type,
Content-Transf... |
49,921 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/html_content.py | 46,47 | 5,60 | get | HtmlContent | 53,60 | 47,60 | class HtmlContent(Content):
"""HTML content to be included in your email."""
def __init__(self, content):
"""Create an HtmlContent with the specified MIME type and content.
:param content: The HTML content.
:type content: string
"""
self._content = None
self._va... | class HtmlContent(Content):
"""HTML content to be included in your email."""
def __init__(self, content):
"""Create an HtmlContent with the specified MIME type and content.
:param content: The HTML content.
:type content: string
"""
self._content = None
self._va... | content = {}
if self.mime_type is not None:
content["type"] = self.mime_type
if self.content is not None:
content["value"] = self.content
return content
| """
Get a JSON-ready representation of this HtmlContent.
:returns: This HtmlContent, ready for use in a request body.
:rtype: dict
"""
content = {}
if self.mime_type is not None:
content["type"] = self.mime_type
if self.content is not None:
... | 21 | 319 | 63 | 382 | from .content import Content
from .validators import ValidateApiKey
class HtmlContent(Content):
"""HTML content to be included in your email."""
def __init__(self, content):
"""Create an HtmlContent with the specified MIME type and content.
:param content: The HTML content.
:type con... | from .content import Content
from .validators import ValidateApiKey
class HtmlContent(Content):
"""HTML content to be included in your email."""
def __init__(self, content):
"""Create an HtmlContent with the specified MIME type and content.
:param content: The HTML content.
:type con... |
49,922 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/ip_pool_name.py | 24,26 | 1,41 | ip_pool_name | IpPoolName | 31,33 | 26,33 | class IpPoolName(object):
"""The IP Pool that you would like to send this email from."""
def __init__(self, ip_pool_name=None):
"""Create a IpPoolName object
:param ip_pool_name: The IP Pool that you would like to send this
email from.
:type ip_pool_name: s... | class IpPoolName(object):
"""The IP Pool that you would like to send this email from."""
def __init__(self, ip_pool_name=None):
"""Create a IpPoolName object
:param ip_pool_name: The IP Pool that you would like to send this
email from.
:type ip_pool_name: s... | self._ip_pool_name = value
| """The IP Pool that you would like to send this email from.
:param value: The IP Pool that you would like to send this email from.
:type value: string
"""
self._ip_pool_name = value
| 3 | 332 | 14 | 346 | class IpPoolName(object):
"""The IP Pool that you would like to send this email from."""
def __init__(self, ip_pool_name=None):
"""Create a IpPoolName object
:param ip_pool_name: The IP Pool that you would like to send this
email from.
:type ip_pool_name: s... | class IpPoolName(object):
"""The IP Pool that you would like to send this email from."""
def __init__(self, ip_pool_name=None):
"""Create a IpPoolName object
:param ip_pool_name: The IP Pool that you would like to send this
email from.
:type ip_pool_name: s... |
49,925 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/open_tracking.py | 67,68 | 1,81 | get | OpenTracking | 74,81 | 68,81 | class OpenTracking(object):
"""
Allows you to track whether the email was opened or not, by including a
single pixel image in the body of the content. When the pixel is loaded,
we log that the email was opened.
"""
def __init__(self, enable=None, substitution_tag=None):
"""Create an Ope... | class OpenTracking(object):
"""
Allows you to track whether the email was opened or not, by including a
single pixel image in the body of the content. When the pixel is loaded,
we log that the email was opened.
"""
def __init__(self, enable=None, substitution_tag=None):
"""Create an Ope... | open_tracking = {}
if self.enable is not None:
open_tracking["enable"] = self.enable
if self.substitution_tag is not None:
open_tracking["substitution_tag"] = self.substitution_tag.get()
return open_tracking
| """
Get a JSON-ready representation of this OpenTracking.
:returns: This OpenTracking, ready for use in a request body.
:rtype: dict
"""
open_tracking = {}
if self.enable is not None:
open_tracking["enable"] = self.enable
if self.substitution... | 21 | 600 | 81 | 681 | class OpenTracking(object):
"""
Allows you to track whether the email was opened or not, by including a
single pixel image in the body of the content. When the pixel is loaded,
we log that the email was opened.
"""
def __init__(self, enable=None, substitution_tag=None):
"""Create an Ope... | class OpenTracking(object):
"""
Allows you to track whether the email was opened or not, by including a
single pixel image in the body of the content. When the pixel is loaded,
we log that the email was opened.
"""
def __init__(self, enable=None, substitution_tag=None):
"""Create an Ope... |
49,926 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/open_tracking_substitution_tag.py | 28,30 | 1,50 | open_tracking_substitution_tag | OpenTrackingSubstitutionTag | 39,41 | 30,41 | class OpenTrackingSubstitutionTag(object):
"""The open tracking substitution tag of an SubscriptionTracking object."""
def __init__(self, open_tracking_substitution_tag=None):
"""Create a OpenTrackingSubstitutionTag object
:param open_tracking_substitution_tag: Allows you to specify a
... | class OpenTrackingSubstitutionTag(object):
"""The open tracking substitution tag of an SubscriptionTracking object."""
def __init__(self, open_tracking_substitution_tag=None):
"""Create a OpenTrackingSubstitutionTag object
:param open_tracking_substitution_tag: Allows you to specify a
... | self._open_tracking_substitution_tag = value
| """Allows you to specify a substitution tag that you can insert in
the body of your email at a location that you desire. This tag will
be replaced by the open tracking pixel.
:param value: Allows you to specify a substitution tag that you can
insert in the body of your email at ... | 3 | 493 | 18 | 511 | class OpenTrackingSubstitutionTag(object):
"""The open tracking substitution tag of an SubscriptionTracking object."""
def __init__(self, open_tracking_substitution_tag=None):
"""Create a OpenTrackingSubstitutionTag object
:param open_tracking_substitution_tag: Allows you to specify a
... | class OpenTrackingSubstitutionTag(object):
"""The open tracking substitution tag of an SubscriptionTracking object."""
def __init__(self, open_tracking_substitution_tag=None):
"""Create a OpenTrackingSubstitutionTag object
:param open_tracking_substitution_tag: Allows you to specify a
... |
49,928 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/plain_text_content.py | 47,48 | 5,61 | get | PlainTextContent | 54,61 | 48,61 | class PlainTextContent(Content):
"""Plain text content to be included in your email.
"""
def __init__(self, content):
"""Create a PlainTextContent with the specified MIME type and content.
:param content: The actual text content.
:type content: string
"""
self._cont... | class PlainTextContent(Content):
"""Plain text content to be included in your email.
"""
def __init__(self, content):
"""Create a PlainTextContent with the specified MIME type and content.
:param content: The actual text content.
:type content: string
"""
self._cont... | content = {}
if self.mime_type is not None:
content["type"] = self.mime_type
if self.content is not None:
content["value"] = self.content
return content
| """
Get a JSON-ready representation of this PlainTextContent.
:returns: This PlainTextContent, ready for use in a request body.
:rtype: dict
"""
content = {}
if self.mime_type is not None:
content["type"] = self.mime_type
if self.content is n... | 21 | 326 | 63 | 389 | from .content import Content
from .validators import ValidateApiKey
class PlainTextContent(Content):
"""Plain text content to be included in your email.
"""
def __init__(self, content):
"""Create a PlainTextContent with the specified MIME type and content.
:param content: The actual text... | from .content import Content
from .validators import ValidateApiKey
class PlainTextContent(Content):
"""Plain text content to be included in your email.
"""
def __init__(self, content):
"""Create a PlainTextContent with the specified MIME type and content.
:param content: The actual text... |
49,929 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/sandbox_mode.py | 34,35 | 1,45 | get | SandBoxMode | 41,45 | 35,45 | class SandBoxMode(object):
"""Setting for sandbox mode.
This allows you to send a test email to ensure that your request body is
valid and formatted correctly.
"""
def __init__(self, enable=None):
"""Create an enabled or disabled SandBoxMode.
:param enable: Whether this is a test re... | class SandBoxMode(object):
"""Setting for sandbox mode.
This allows you to send a test email to ensure that your request body is
valid and formatted correctly.
"""
def __init__(self, enable=None):
"""Create an enabled or disabled SandBoxMode.
:param enable: Whether this is a test re... | sandbox_mode = {}
if self.enable is not None:
sandbox_mode["enable"] = self.enable
return sandbox_mode
| """
Get a JSON-ready representation of this SandBoxMode.
:returns: This SandBoxMode, ready for use in a request body.
:rtype: dict
"""
sandbox_mode = {}
if self.enable is not None:
sandbox_mode["enable"] = self.enable
return sandbox_mode
| 13 | 284 | 42 | 326 | class SandBoxMode(object):
"""Setting for sandbox mode.
This allows you to send a test email to ensure that your request body is
valid and formatted correctly.
"""
def __init__(self, enable=None):
"""Create an enabled or disabled SandBoxMode.
:param enable: Whether this is a test re... | class SandBoxMode(object):
"""Setting for sandbox mode.
This allows you to send a test email to ensure that your request body is
valid and formatted correctly.
"""
def __init__(self, enable=None):
"""Create an enabled or disabled SandBoxMode.
:param enable: Whether this is a test re... |
49,930 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/section.py | 28,30 | 1,65 | key | Section | 35,37 | 30,37 | class Section(object):
"""A block section of code to be used as a substitution."""
def __init__(self, key=None, value=None):
"""Create a section with the given key and value.
:param key: section of code key
:type key: string
:param value: section of code value
:type val... | class Section(object):
"""A block section of code to be used as a substitution."""
def __init__(self, key=None, value=None):
"""Create a section with the given key and value.
:param key: section of code key
:type key: string
:param value: section of code value
:type val... | self._key = value
| """A section of code's key.
:param key: section of code key
:type key: string
"""
self._key = value
| 3 | 422 | 10 | 432 | class Section(object):
"""A block section of code to be used as a substitution."""
def __init__(self, key=None, value=None):
"""Create a section with the given key and value.
:param key: section of code key
:type key: string
:param value: section of code value
:type val... | class Section(object):
"""A block section of code to be used as a substitution."""
def __init__(self, key=None, value=None):
"""Create a section with the given key and value.
:param key: section of code key
:type key: string
:param value: section of code value
:type val... |
49,931 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/send_at.py | 47,49 | 1,80 | personalization | SendAt | 53,55 | 49,55 | class SendAt(object):
"""A unix timestamp allowing you to specify when you want your
email to be delivered. This may be overridden by the
personalizations[x].send_at parameter. You can't schedule more
than 72 hours in advance. If you have the flexibility, it's
better to schedule mail for off-peak ti... | class SendAt(object):
"""A unix timestamp allowing you to specify when you want your
email to be delivered. This may be overridden by the
personalizations[x].send_at parameter. You can't schedule more
than 72 hours in advance. If you have the flexibility, it's
better to schedule mail for off-peak ti... | return self._personalization
| """The Personalization object or Personalization object index
:rtype: Personalization, integer
"""
return self._personalization
| 2 | 630 | 10 | 640 | class SendAt(object):
"""A unix timestamp allowing you to specify when you want your
email to be delivered. This may be overridden by the
personalizations[x].send_at parameter. You can't schedule more
than 72 hours in advance. If you have the flexibility, it's
better to schedule mail for off-peak ti... | class SendAt(object):
"""A unix timestamp allowing you to specify when you want your
email to be delivered. This may be overridden by the
personalizations[x].send_at parameter. You can't schedule more
than 72 hours in advance. If you have the flexibility, it's
better to schedule mail for off-peak ti... |
49,932 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/spam_check.py | 96,97 | 5,113 | get | SpamCheck | 103,113 | 97,113 | class SpamCheck(object):
"""This allows you to test the content of your email for spam."""
def __init__(self, enable=None, threshold=None, post_to_url=None):
"""Create a SpamCheck to test the content of your email for spam.
:param enable: If this setting is applied.
:type enable: boole... | class SpamCheck(object):
"""This allows you to test the content of your email for spam."""
def __init__(self, enable=None, threshold=None, post_to_url=None):
"""Create a SpamCheck to test the content of your email for spam.
:param enable: If this setting is applied.
:type enable: boole... | spam_check = {}
if self.enable is not None:
spam_check["enable"] = self.enable
if self.threshold is not None:
spam_check["threshold"] = self.threshold.get()
if self.post_to_url is not None:
spam_check["post_to_url"] = self.post_to_url.get()
r... | """
Get a JSON-ready representation of this SpamCheck.
:returns: This SpamCheck, ready for use in a request body.
:rtype: dict
"""
spam_check = {}
if self.enable is not None:
spam_check["enable"] = self.enable
if self.threshold is not None:
... | 29 | 896 | 117 | 1,013 | from .spam_threshold import SpamThreshold
from .spam_url import SpamUrl
class SpamCheck(object):
"""This allows you to test the content of your email for spam."""
def __init__(self, enable=None, threshold=None, post_to_url=None):
"""Create a SpamCheck to test the content of your email for spam.
... | from .spam_threshold import SpamThreshold
from .spam_url import SpamUrl
class SpamCheck(object):
"""This allows you to test the content of your email for spam."""
def __init__(self, enable=None, threshold=None, post_to_url=None):
"""Create a SpamCheck to test the content of your email for spam.
... |
49,933 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/spam_threshold.py | 31,33 | 1,54 | spam_threshold | SpamThreshold | 44,46 | 33,46 | class SpamThreshold(object):
"""The threshold used to determine if your content qualifies as spam
on a scale from 1 to 10, with 10 being most strict, or most likely
to be considered as spam."""
def __init__(self, spam_threshold=None):
"""Create a SpamThreshold object
:param spam_... | class SpamThreshold(object):
"""The threshold used to determine if your content qualifies as spam
on a scale from 1 to 10, with 10 being most strict, or most likely
to be considered as spam."""
def __init__(self, spam_threshold=None):
"""Create a SpamThreshold object
:param spam_... | self._spam_threshold = value
| """The threshold used to determine if your content
qualifies as spam on a scale from 1 to 10, with
10 being most strict, or most likely to be
considered as spam.
:param value: The threshold used to determine if your content
qualifies as spam on a scale from 1 to... | 3 | 499 | 14 | 513 | class SpamThreshold(object):
"""The threshold used to determine if your content qualifies as spam
on a scale from 1 to 10, with 10 being most strict, or most likely
to be considered as spam."""
def __init__(self, spam_threshold=None):
"""Create a SpamThreshold object
:param spam_... | class SpamThreshold(object):
"""The threshold used to determine if your content qualifies as spam
on a scale from 1 to 10, with 10 being most strict, or most likely
to be considered as spam."""
def __init__(self, spam_threshold=None):
"""Create a SpamThreshold object
:param spam_... |
49,934 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/spam_url.py | 26,28 | 1,45 | spam_url | SpamUrl | 35,37 | 28,37 | class SpamUrl(object):
"""An Inbound Parse URL that you would like a copy of your email
along with the spam report to be sent to."""
def __init__(self, spam_url=None):
"""Create a SpamUrl object
:param spam_url: An Inbound Parse URL that you would like a copy of
... | class SpamUrl(object):
"""An Inbound Parse URL that you would like a copy of your email
along with the spam report to be sent to."""
def __init__(self, spam_url=None):
"""Create a SpamUrl object
:param spam_url: An Inbound Parse URL that you would like a copy of
... | self._spam_url = value
| """An Inbound Parse URL that you would like a copy of your email
along with the spam report to be sent to.
:param value: An Inbound Parse URL that you would like a copy of your
email along with the spam report to be sent to.
:type value: string
"""
... | 3 | 389 | 13 | 402 | class SpamUrl(object):
"""An Inbound Parse URL that you would like a copy of your email
along with the spam report to be sent to."""
def __init__(self, spam_url=None):
"""Create a SpamUrl object
:param spam_url: An Inbound Parse URL that you would like a copy of
... | class SpamUrl(object):
"""An Inbound Parse URL that you would like a copy of your email
along with the spam report to be sent to."""
def __init__(self, spam_url=None):
"""Create a SpamUrl object
:param spam_url: An Inbound Parse URL that you would like a copy of
... |
49,935 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/subject.py | 45,47 | 1,70 | personalization | Subject | 53,55 | 47,55 | class Subject(object):
"""A subject for an email message."""
def __init__(self, subject, p=None):
"""Create a Subject.
:param subject: The subject for an email
:type subject: string
:param name: p is the Personalization object or Personalization object
inde... | class Subject(object):
"""A subject for an email message."""
def __init__(self, subject, p=None):
"""Create a Subject.
:param subject: The subject for an email
:type subject: string
:param name: p is the Personalization object or Personalization object
inde... | self._personalization = value
| """The Personalization object or Personalization object index
:param value: The Personalization object or Personalization object
index
:type value: Personalization, integer
"""
self._personalization = value
| 3 | 442 | 11 | 453 | class Subject(object):
"""A subject for an email message."""
def __init__(self, subject, p=None):
"""Create a Subject.
:param subject: The subject for an email
:type subject: string
:param name: p is the Personalization object or Personalization object
inde... | class Subject(object):
"""A subject for an email message."""
def __init__(self, subject, p=None):
"""Create a Subject.
:param subject: The subject for an email
:type subject: string
:param name: p is the Personalization object or Personalization object
inde... |
49,936 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/subscription_html.py | 26,28 | 1,46 | subscription_html | SubscriptionHtml | 36,38 | 28,38 | class SubscriptionHtml(object):
"""The HTML of an SubscriptionTracking."""
def __init__(self, subscription_html=None):
"""Create a SubscriptionHtml object
:param subscription_html: Html to be appended to the email, with the
subscription tracking link. You may ... | class SubscriptionHtml(object):
"""The HTML of an SubscriptionTracking."""
def __init__(self, subscription_html=None):
"""Create a SubscriptionHtml object
:param subscription_html: Html to be appended to the email, with the
subscription tracking link. You may ... | self._subscription_html = value
| """Html to be appended to the email, with the subscription tracking link.
You may control where the link is by using the tag <% %>
:param value: Html to be appended to the email, with the subscription
tracking link. You may control where the link is by using
... | 3 | 385 | 13 | 398 | class SubscriptionHtml(object):
"""The HTML of an SubscriptionTracking."""
def __init__(self, subscription_html=None):
"""Create a SubscriptionHtml object
:param subscription_html: Html to be appended to the email, with the
subscription tracking link. You may ... | class SubscriptionHtml(object):
"""The HTML of an SubscriptionTracking."""
def __init__(self, subscription_html=None):
"""Create a SubscriptionHtml object
:param subscription_html: Html to be appended to the email, with the
subscription tracking link. You may ... |
49,937 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/subscription_substitution_tag.py | 34,36 | 1,59 | subscription_substitution_tag | SubscriptionSubstitutionTag | 48,50 | 36,50 | class SubscriptionSubstitutionTag(object):
"""The subscription substitution tag of an SubscriptionTracking."""
def __init__(self, subscription_substitution_tag=None):
"""Create a SubscriptionSubstitutionTag object
:param subscription_substitution_tag: A tag that will be replaced with
... | class SubscriptionSubstitutionTag(object):
"""The subscription substitution tag of an SubscriptionTracking."""
def __init__(self, subscription_substitution_tag=None):
"""Create a SubscriptionSubstitutionTag object
:param subscription_substitution_tag: A tag that will be replaced with
... | self._subscription_substitution_tag = value
| """A tag that will be replaced with the unsubscribe URL. for example:
[unsubscribe_url]. If this parameter is used, it will override both
the text and html parameters. The URL of the link will be placed at
the substitution tag's location, with no additional formatting.
... | 3 | 588 | 16 | 604 | class SubscriptionSubstitutionTag(object):
"""The subscription substitution tag of an SubscriptionTracking."""
def __init__(self, subscription_substitution_tag=None):
"""Create a SubscriptionSubstitutionTag object
:param subscription_substitution_tag: A tag that will be replaced with
... | class SubscriptionSubstitutionTag(object):
"""The subscription substitution tag of an SubscriptionTracking."""
def __init__(self, subscription_substitution_tag=None):
"""Create a SubscriptionSubstitutionTag object
:param subscription_substitution_tag: A tag that will be replaced with
... |
49,938 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/subscription_text.py | 17,19 | 1,46 | subscription_text | SubscriptionText | 24,26 | 19,26 | class SubscriptionText(object):
"""The text of an SubscriptionTracking."""
def __init__(self, subscription_text=None):
"""Create a SubscriptionText object
:param subscription_text: Text to be appended to the email, with the
subscription tracking link. You may ... | class SubscriptionText(object):
"""The text of an SubscriptionTracking."""
def __init__(self, subscription_text=None):
"""Create a SubscriptionText object
:param subscription_text: Text to be appended to the email, with the
subscription tracking link. You may ... | return self._subscription_text
| """Text to be appended to the email, with the subscription tracking link.
You may control where the link is by using the tag <% %>
:rtype: string
"""
return self._subscription_text
| 2 | 384 | 12 | 396 | class SubscriptionText(object):
"""The text of an SubscriptionTracking."""
def __init__(self, subscription_text=None):
"""Create a SubscriptionText object
:param subscription_text: Text to be appended to the email, with the
subscription tracking link. You may ... | class SubscriptionText(object):
"""The text of an SubscriptionTracking."""
def __init__(self, subscription_text=None):
"""Create a SubscriptionText object
:param subscription_text: Text to be appended to the email, with the
subscription tracking link. You may ... |
49,939 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/subscription_tracking.py | 122,123 | 1,143 | get | SubscriptionTracking | 129,143 | 123,143 | class SubscriptionTracking(object):
"""Allows you to insert a subscription management link at the bottom of the
text and html bodies of your email. If you would like to specify the
location of the link within your email, you may use the substitution_tag.
"""
def __init__(
self, enable=N... | class SubscriptionTracking(object):
"""Allows you to insert a subscription management link at the bottom of the
text and html bodies of your email. If you would like to specify the
location of the link within your email, you may use the substitution_tag.
"""
def __init__(
self, enable=N... | subscription_tracking = {}
if self.enable is not None:
subscription_tracking["enable"] = self.enable
if self.text is not None:
subscription_tracking["text"] = self.text.get()
if self.html is not None:
subscription_tracking["html"] = self.html.get()
... | """
Get a JSON-ready representation of this SubscriptionTracking.
:returns: This SubscriptionTracking, ready for use in a request body.
:rtype: dict
"""
subscription_tracking = {}
if self.enable is not None:
subscription_tracking["enable"] = self.enab... | 38 | 1,170 | 145 | 1,315 | class SubscriptionTracking(object):
"""Allows you to insert a subscription management link at the bottom of the
text and html bodies of your email. If you would like to specify the
location of the link within your email, you may use the substitution_tag.
"""
def __init__(
self, enable=N... | class SubscriptionTracking(object):
"""Allows you to insert a subscription management link at the bottom of the
text and html bodies of your email. If you would like to specify the
location of the link within your email, you may use the substitution_tag.
"""
def __init__(
self, enable=N... |
49,940 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/substitution.py | 80,81 | 1,91 | get | Substitution | 87,91 | 81,91 | class Substitution(object):
"""A string substitution to be applied to the text and HTML contents of
the body of your email, as well as in the Subject and Reply-To parameters.
"""
def __init__(self, key=None, value=None, p=None):
"""Create a Substitution with the given key and value.
:p... | class Substitution(object):
"""A string substitution to be applied to the text and HTML contents of
the body of your email, as well as in the Subject and Reply-To parameters.
"""
def __init__(self, key=None, value=None, p=None):
"""Create a Substitution with the given key and value.
:p... | substitution = {}
if self.key is not None and self.value is not None:
substitution[self.key] = self.value
return substitution
| """
Get a JSON-ready representation of this Substitution.
:returns: This Substitution, ready for use in a request body.
:rtype: dict
"""
substitution = {}
if self.key is not None and self.value is not None:
substitution[self.key] = self.value
... | 18 | 615 | 45 | 660 | class Substitution(object):
"""A string substitution to be applied to the text and HTML contents of
the body of your email, as well as in the Subject and Reply-To parameters.
"""
def __init__(self, key=None, value=None, p=None):
"""Create a Substitution with the given key and value.
:p... | class Substitution(object):
"""A string substitution to be applied to the text and HTML contents of
the body of your email, as well as in the Subject and Reply-To parameters.
"""
def __init__(self, key=None, value=None, p=None):
"""Create a Substitution with the given key and value.
:p... |
49,941 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/template_id.py | 23,25 | 1,40 | template_id | TemplateId | 30,32 | 25,32 | class TemplateId(object):
"""The template ID of an Attachment object."""
def __init__(self, template_id=None):
"""Create a TemplateId object
:param template_id: The template id for the message
:type template_id: string, optional
"""
self._template_id = None
if ... | class TemplateId(object):
"""The template ID of an Attachment object."""
def __init__(self, template_id=None):
"""Create a TemplateId object
:param template_id: The template id for the message
:type template_id: string, optional
"""
self._template_id = None
if ... | self._template_id = value
| """The template id for the message
:param value: The template id for the message
:type value: string
"""
self._template_id = value
| 3 | 267 | 12 | 279 | class TemplateId(object):
"""The template ID of an Attachment object."""
def __init__(self, template_id=None):
"""Create a TemplateId object
:param template_id: The template id for the message
:type template_id: string, optional
"""
self._template_id = None
if ... | class TemplateId(object):
"""The template ID of an Attachment object."""
def __init__(self, template_id=None):
"""Create a TemplateId object
:param template_id: The template id for the message
:type template_id: string, optional
"""
self._template_id = None
if ... |
49,942 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/tracking_settings.py | 100,102 | 1,135 | ganalytics | TrackingSettings | 106,108 | 102,108 | class TrackingSettings(object):
"""Settings to track how recipients interact with your email."""
def __init__(self,
click_tracking=None,
open_tracking=None,
subscription_tracking=None,
ganalytics=None):
"""Create a TrackingSettings obj... | class TrackingSettings(object):
"""Settings to track how recipients interact with your email."""
def __init__(self,
click_tracking=None,
open_tracking=None,
subscription_tracking=None,
ganalytics=None):
"""Create a TrackingSettings obj... | return self._ganalytics
| """Settings for Google Analytics.
:rtype: Ganalytics
"""
return self._ganalytics
| 2 | 1,153 | 11 | 1,164 | class TrackingSettings(object):
"""Settings to track how recipients interact with your email."""
def __init__(self,
click_tracking=None,
open_tracking=None,
subscription_tracking=None,
ganalytics=None):
"""Create a TrackingSettings obj... | class TrackingSettings(object):
"""Settings to track how recipients interact with your email."""
def __init__(self,
click_tracking=None,
open_tracking=None,
subscription_tracking=None,
ganalytics=None):
"""Create a TrackingSettings obj... |
49,943 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/utm_campaign.py | 16,18 | 1,41 | utm_campaign | UtmCampaign | 22,24 | 18,24 | class UtmCampaign(object):
"""The utm campaign of an Ganalytics object."""
def __init__(self, utm_campaign=None):
"""Create a UtmCampaign object
:param utm_campaign: The name of the campaign
:type utm_campaign: string, optional
"""
self._utm_campaign = None
if... | class UtmCampaign(object):
"""The utm campaign of an Ganalytics object."""
def __init__(self, utm_campaign=None):
"""Create a UtmCampaign object
:param utm_campaign: The name of the campaign
:type utm_campaign: string, optional
"""
self._utm_campaign = None
if... | return self._utm_campaign
| """The name of the campaign
:rtype: string
"""
return self._utm_campaign
| 2 | 298 | 13 | 311 | class UtmCampaign(object):
"""The utm campaign of an Ganalytics object."""
def __init__(self, utm_campaign=None):
"""Create a UtmCampaign object
:param utm_campaign: The name of the campaign
:type utm_campaign: string, optional
"""
self._utm_campaign = None
if... | class UtmCampaign(object):
"""The utm campaign of an Ganalytics object."""
def __init__(self, utm_campaign=None):
"""Create a UtmCampaign object
:param utm_campaign: The name of the campaign
:type utm_campaign: string, optional
"""
self._utm_campaign = None
if... |
49,944 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/utm_content.py | 16,18 | 1,41 | utm_content | UtmContent | 22,24 | 18,24 | class UtmContent(object):
"""The utm content of an Ganalytics object."""
def __init__(self, utm_content=None):
"""Create a UtmContent object
:param utm_content: Used to differentiate your campaign from advertisements.
:type utm_content: string, optional
"""
self._utm_c... | class UtmContent(object):
"""The utm content of an Ganalytics object."""
def __init__(self, utm_content=None):
"""Create a UtmContent object
:param utm_content: Used to differentiate your campaign from advertisements.
:type utm_content: string, optional
"""
self._utm_c... | return self._utm_content
| """Used to differentiate your campaign from advertisements.
:rtype: string
"""
return self._utm_content
| 2 | 302 | 12 | 314 | class UtmContent(object):
"""The utm content of an Ganalytics object."""
def __init__(self, utm_content=None):
"""Create a UtmContent object
:param utm_content: Used to differentiate your campaign from advertisements.
:type utm_content: string, optional
"""
self._utm_c... | class UtmContent(object):
"""The utm content of an Ganalytics object."""
def __init__(self, utm_content=None):
"""Create a UtmContent object
:param utm_content: Used to differentiate your campaign from advertisements.
:type utm_content: string, optional
"""
self._utm_c... |
49,945 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/utm_medium.py | 16,18 | 1,41 | utm_medium | UtmMedium | 22,24 | 18,24 | class UtmMedium(object):
"""The utm medium of an Ganalytics object."""
def __init__(self, utm_medium=None):
"""Create a UtmMedium object
:param utm_medium: Name of the marketing medium. (e.g. Email)
:type utm_medium: string, optional
"""
self._utm_medium = None
... | class UtmMedium(object):
"""The utm medium of an Ganalytics object."""
def __init__(self, utm_medium=None):
"""Create a UtmMedium object
:param utm_medium: Name of the marketing medium. (e.g. Email)
:type utm_medium: string, optional
"""
self._utm_medium = None
... | return self._utm_medium
| """Name of the marketing medium. (e.g. Email)
:rtype: string
"""
return self._utm_medium
| 2 | 318 | 12 | 330 | class UtmMedium(object):
"""The utm medium of an Ganalytics object."""
def __init__(self, utm_medium=None):
"""Create a UtmMedium object
:param utm_medium: Name of the marketing medium. (e.g. Email)
:type utm_medium: string, optional
"""
self._utm_medium = None
... | class UtmMedium(object):
"""The utm medium of an Ganalytics object."""
def __init__(self, utm_medium=None):
"""Create a UtmMedium object
:param utm_medium: Name of the marketing medium. (e.g. Email)
:type utm_medium: string, optional
"""
self._utm_medium = None
... |
49,946 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/utm_source.py | 25,27 | 1,44 | utm_source | UtmSource | 34,36 | 27,36 | class UtmSource(object):
"""The utm source of an Ganalytics object."""
def __init__(self, utm_source=None):
"""Create a UtmSource object
:param utm_source: Name of the referrer source.
(e.g. Google, SomeDomain.com, or Marketing Email)
:type utm_source: string, optional
... | class UtmSource(object):
"""The utm source of an Ganalytics object."""
def __init__(self, utm_source=None):
"""Create a UtmSource object
:param utm_source: Name of the referrer source.
(e.g. Google, SomeDomain.com, or Marketing Email)
:type utm_source: string, optional
... | self._utm_source = value
| """Name of the referrer source. (e.g. Google, SomeDomain.com, or
Marketing Email)
:param value: Name of the referrer source.
(e.g. Google, SomeDomain.com, or Marketing Email)
:type value: string
"""
self._utm_source = value
| 3 | 360 | 13 | 373 | class UtmSource(object):
"""The utm source of an Ganalytics object."""
def __init__(self, utm_source=None):
"""Create a UtmSource object
:param utm_source: Name of the referrer source.
(e.g. Google, SomeDomain.com, or Marketing Email)
:type utm_source: string, optional
... | class UtmSource(object):
"""The utm source of an Ganalytics object."""
def __init__(self, utm_source=None):
"""Create a UtmSource object
:param utm_source: Name of the referrer source.
(e.g. Google, SomeDomain.com, or Marketing Email)
:type utm_source: string, optional
... |
49,947 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/utm_term.py | 16,18 | 1,41 | utm_term | UtmTerm | 22,24 | 18,24 | class UtmTerm(object):
"""The utm term of an Ganalytics object."""
def __init__(self, utm_term=None):
"""Create a UtmTerm object
:param utm_term: Used to identify any paid keywords.
:type utm_term: string, optional
"""
self._utm_term = None
if utm_term is not ... | class UtmTerm(object):
"""The utm term of an Ganalytics object."""
def __init__(self, utm_term=None):
"""Create a UtmTerm object
:param utm_term: Used to identify any paid keywords.
:type utm_term: string, optional
"""
self._utm_term = None
if utm_term is not ... | return self._utm_term
| """Used to identify any paid keywords.
:rtype: string
"""
return self._utm_term
| 2 | 290 | 12 | 302 | class UtmTerm(object):
"""The utm term of an Ganalytics object."""
def __init__(self, utm_term=None):
"""Create a UtmTerm object
:param utm_term: Used to identify any paid keywords.
:type utm_term: string, optional
"""
self._utm_term = None
if utm_term is not ... | class UtmTerm(object):
"""The utm term of an Ganalytics object."""
def __init__(self, utm_term=None):
"""Create a UtmTerm object
:param utm_term: Used to identify any paid keywords.
:type utm_term: string, optional
"""
self._utm_term = None
if utm_term is not ... |
49,948 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/validators.py | 30,31 | 4,70 | validate_message_dict | ValidateApiKey | 40,57 | 31,57 | class ValidateApiKey(object):
"""Validates content to ensure SendGrid API key is not present"""
regexes = None
def __init__(self, regex_strings=None, use_default=True):
"""Create an API key validator
:param regex_strings: list of regex strings
:type regex_strings: list(str... | class ValidateApiKey(object):
"""Validates content to ensure SendGrid API key is not present"""
regexes = None
def __init__(self, regex_strings=None, use_default=True):
"""Create an API key validator
:param regex_strings: list of regex strings
:type regex_strings: list(str... |
# Handle string in edge-case
if isinstance(request_body, str):
self.validate_message_text(request_body)
# Default param
elif isinstance(request_body, dict):
contents = request_body.get("content", list())
for content in contents:
if ... | """With the JSON dict that will be sent to SendGrid's API,
check the content for SendGrid API keys - throw exception if found.
:param request_body: The JSON dict that will be sent to SendGrid's
API.
:type request_body: JSON serializable structur... | 40 | 512 | 162 | 674 | from .exceptions import ApiKeyIncludedException
class ValidateApiKey(object):
"""Validates content to ensure SendGrid API key is not present"""
regexes = None
def __init__(self, regex_strings=None, use_default=True):
"""Create an API key validator
:param regex_strings: list of regex... | from .exceptions import ApiKeyIncludedException
class ValidateApiKey(object):
"""Validates content to ensure SendGrid API key is not present"""
regexes = None
def __init__(self, regex_strings=None, use_default=True):
"""Create an API key validator
:param regex_strings: list of regex... |
49,949 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/stats/stats.py | 338,339 | 307,347 | get | Category | 344,347 | 339,347 | class Category(object):
"""
Represents a searchable statistics category to be used in a CategoryStats object
"""
def __init__(self, name=None):
"""Create a Category object
:param name: name of category, defaults to None
:type name: string, optional
"""
se... | class Category(object):
"""
Represents a searchable statistics category to be used in a CategoryStats object
"""
def __init__(self, name=None):
"""Create a Category object
:param name: name of category, defaults to None
:type name: string, optional
"""
se... | return self.name
| """
Get a string representation of Category.
:return: string of the category's name
"""
return self.name
| 2 | 233 | 11 | 244 | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... |
49,950 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/stats/stats.py | 196,197 | 175,241 | get | CategoryStats | 202,222 | 197,222 | class CategoryStats(Stats):
"""
object for building query params for a category statistics request
"""
def __init__(self, start_date=None, categories=None):
"""Create a CategoryStats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
... | class CategoryStats(Stats):
"""
object for building query params for a category statistics request
"""
def __init__(self, start_date=None, categories=None):
"""Create a CategoryStats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
... | stats = {}
if self.start_date is not None:
stats["start_date"] = self.start_date
if self.end_date is not None:
stats["end_date"] = self.end_date
if self.aggregated_by is not None:
stats["aggregated_by"] = self.aggregated_by
if self.sort_by_metr... | """
Get a JSON-ready representation of this CategoryStats.
:return: response category stats dict
"""
stats = {}
if self.start_date is not None:
stats["start_date"] = self.start_date
if self.end_date is not None:
stats["end_date"] = self.en... | 73 | 362 | 252 | 614 | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... |
49,951 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/stats/stats.py | 131,133 | 1,175 | sort_by_direction | Stats | 138,140 | 133,140 | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... | self._sort_by_direction = value
| """Direction data will be sorted, either 'asc' or 'desc'
:param value: Direction of data, either 'asc' or 'desc'
:type value: string
"""
self._sort_by_direction = value
| 3 | 1,331 | 14 | 1,345 | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... |
49,952 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/stats/stats.py | 369,371 | 347,385 | name | Subuser | 376,378 | 371,378 | class Subuser(object):
"""
Represents a searchable subuser to be used in a SubuserStats object
"""
def __init__(self, name=None):
"""Create a Subuser object
:param name: name of subuser, defaults to None
:type name: string, optional
"""
self._name = N... | class Subuser(object):
"""
Represents a searchable subuser to be used in a SubuserStats object
"""
def __init__(self, name=None):
"""Create a Subuser object
:param name: name of subuser, defaults to None
:type name: string, optional
"""
self._name = N... | self._name = value
| """Set name of the subuser
:param value: name of the subuser
:type value: string
"""
self._name = value
| 3 | 243 | 10 | 253 | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... |
49,953 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/stats/stats.py | 262,263 | 241,307 | get | SubuserStats | 268,288 | 263,288 | class SubuserStats(Stats):
"""
object of building query params for a subuser statistics request
"""
def __init__(self, start_date=None, subusers=None):
"""Create a SubuserStats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:... | class SubuserStats(Stats):
"""
object of building query params for a subuser statistics request
"""
def __init__(self, start_date=None, subusers=None):
"""Create a SubuserStats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:... | stats = {}
if self.start_date is not None:
stats["start_date"] = self.start_date
if self.end_date is not None:
stats["end_date"] = self.end_date
if self.aggregated_by is not None:
stats["aggregated_by"] = self.aggregated_by
if self.sort_by_metr... | """
Get a JSON-ready representation of this SubuserStats.
:return: response subuser stats dict
"""
stats = {}
if self.start_date is not None:
stats["start_date"] = self.start_date
if self.end_date is not None:
stats["end_date"] = self.end_... | 73 | 392 | 254 | 646 | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... | class Stats(object):
"""
Object for building query params for a global email statistics request
"""
def __init__(
self, start_date=None):
"""Create a Stats object
:param start_date: Date of when stats should begin in YYYY-MM-DD format, defaults to None
:type start_da... |
49,954 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/setup.py | 10,11 | 1,46 | getRequires | 11,18 | 11,18 | import io
import os
from setuptools import setup, find_packages
__version__ = None
with open('sendgrid/version.py') as f:
exec(f.read())
def getRequires():
FILL_FUNC_BODYdir_path = os.path.abspath(os.path.dirname(__file__))
readme = io.open(os.path.join(dir_path, 'README.rst'), encoding='utf-8').read()
setup(
... | import io
import os
from setuptools import setup, find_packages
__version__ = None
with open('sendgrid/version.py') as f:
exec(f.read())
def getRequires():
FILL_FUNC_BODYdir_path = os.path.abspath(os.path.dirname(__file__))
readme = io.open(os.path.join(dir_path, 'README.rst'), encoding='utf-8').read()
setup(
... | deps = [
'python_http_client>=3.2.1',
'starkbank-ecdsa>=2.0.1'
]
return deps
| deps = [
'python_http_client>=3.2.1',
'starkbank-ecdsa>=2.0.1'
]
return deps
| 8 | 447 | 55 | 502 | import io
import os
from setuptools import setup, find_packages
__version__ = None
with open('sendgrid/version.py') as f:
exec(f.read())
def getRequires():
FILL_FUNC_BODYdir_path = os.path.abspath(os.path.dirname(__file__))
readme = io.open(os.path.join(dir_path, 'README.rst'), encoding='utf-8').read()
setup(
... | import io
import os
from setuptools import setup, find_packages
__version__ = None
with open('sendgrid/version.py') as f:
exec(f.read())
def getRequires():
FILL_FUNC_BODYdir_path = os.path.abspath(os.path.dirname(__file__))
readme = io.open(os.path.join(dir_path, 'README.rst'), encoding='utf-8').read()
setup(
... | |
50,097 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/cursor.py | 52,53 | 6,107 | next_leaf | Cursor | 60,91 | 53,91 | class Cursor:
"""
Represents a cursor. A cursor understands how to navigate
a database (on-disk) page, i.e. reading and understanding header values.
A cursor exposes an interface to read, insert and delete rows.
"""
def __init__(self, pager: Pager, tree: Tree):
self.tree = tree
... | class Cursor:
"""
Represents a cursor. A cursor understands how to navigate
a database (on-disk) page, i.e. reading and understanding header values.
A cursor exposes an interface to read, insert and delete rows.
"""
def __init__(self, pager: Pager, tree: Tree):
self.tree = tree
... | # starting point
node = self.pager.get_page(self.page_num)
if Tree.is_node_root(node) is True:
# there is nothing
self.end_of_table = True
return
node_max_value = self.tree.get_node_max_key(node)
assert node_max_value is not None
pare... | """
move self.page_num and self.cell_num to next leaf and next cell
this method requires the self.page_num start at a leaf node.
NOTE: if starting from an internal node, to get to a leaf use `first_leaf` method
:return:
"""
# starting point
node = self.pa... | 126 | 737 | 410 | 1,147 | from .constants import INTERNAL_NODE_MAX_CELLS
from .btree import Tree, NodeType
from .pager import Pager
class Cursor:
"""
Represents a cursor. A cursor understands how to navigate
a database (on-disk) page, i.e. reading and understanding header values.
A cursor exposes an interface to read, insert a... | from .constants import INTERNAL_NODE_MAX_CELLS
from .btree import Tree, NodeType
from .pager import Pager
class Cursor:
"""
Represents a cursor. A cursor understands how to navigate
a database (on-disk) page, i.e. reading and understanding header values.
A cursor exposes an interface to read, insert a... |
50,098 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/datatypes.py | 211,212 | 1,216 | is_term_valid_for_datatype | 215,216 | 212,216 | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... | return data_type.is_valid_term(term)
| """
Return True, if term is valid for given datatype
"""
return data_type.is_valid_term(term)
| 2 | 1,513 | 16 | 1,529 | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... | |
50,099 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/datatypes.py | 206,208 | 192,211 | deserialize | Blob | 208,211 | 208,211 | class Blob(DataType):
"""
This represent an as-is byte string
"""
is_fixed_length = False
fixed_length = 0
is_serializable = True
typename = "Blob"
@staticmethod
def serialize(value: bytes) -> bytes:
return value
@staticmethod
def deserialize(bstring: bytes) -> byt... | class Blob(DataType):
"""
This represent an as-is byte string
"""
is_fixed_length = False
fixed_length = 0
is_serializable = True
typename = "Blob"
@staticmethod
def serialize(value: bytes) -> bytes:
return value
@staticmethod
def deserialize(bstring: bytes) -> byt... | return bstring
| return bstring
| 2 | 113 | 10 | 123 | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... |
50,100 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/datatypes.py | 159,161 | 145,169 | deserialize | Boolean | 161,164 | 161,164 | class Boolean(DataType):
"""
represents a variable length text
"""
is_fixed_length = False
fixed_length = 0
is_serializable = True
typename = "Text"
@staticmethod
def serialize(value: bool):
return struct.pack("=?", value)
@staticmethod
def deserialize(bstring: byt... | class Boolean(DataType):
"""
represents a variable length text
"""
is_fixed_length = False
fixed_length = 0
is_serializable = True
typename = "Text"
@staticmethod
def serialize(value: bool):
return struct.pack("=?", value)
@staticmethod
def deserialize(bstring: byt... | tpl = struct.unpack("=?", bstring)
return tpl[0]
| tpl = struct.unpack("=?", bstring)
return tpl[0]
| 6 | 140 | 28 | 168 | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... |
50,101 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/datatypes.py | 34,36 | 13,63 | serialize | DataType | 41,43 | 36,43 | class DataType:
"""
This is a datatype of a value in the database.
This provides an interface to provide serde of implemented type
and details of underlying encoding.
Note: There can be multiple underlying (physical) types for a given
datatype. Datatype is logical and can be implemented in mul... | class DataType:
"""
This is a datatype of a value in the database.
This provides an interface to provide serde of implemented type
and details of underlying encoding.
Note: There can be multiple underlying (physical) types for a given
datatype. Datatype is logical and can be implemented in mul... | raise NotImplementedError
| """
serialize argument `value` to byte string
:param value:
:return:
"""
raise NotImplementedError
| 2 | 365 | 11 | 376 | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... |
50,102 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/datatypes.py | 78,80 | 63,87 | deserialize | Integer | 80,82 | 80,82 | class Integer(DataType):
"""
Represents a fixed-size integer
"""
is_fixed_length = True
fixed_length = INTEGER_SIZE
is_serializable = True
typename = "Integer"
@staticmethod
def serialize(value: int) -> bytes:
# print("In integer::serialize")
return value.to_bytes(I... | class Integer(DataType):
"""
Represents a fixed-size integer
"""
is_fixed_length = True
fixed_length = INTEGER_SIZE
is_serializable = True
typename = "Integer"
@staticmethod
def serialize(value: int) -> bytes:
# print("In integer::serialize")
return value.to_bytes(I... | return int.from_bytes(bstring, sys.byteorder)
| return int.from_bytes(bstring, sys.byteorder)
| 3 | 173 | 20 | 193 | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... |
50,103 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/datatypes.py | 99,101 | 87,122 | serialize | Real | 105,108 | 101,108 | class Real(DataType):
"""
Represents a fixed-size floating point number.
Note: The usual concerns around finite-precision and
rounding hold here.
"""
is_fixed_length = True
fixed_length = REAL_SIZE
is_serializable = True
typename = "Real"
@staticmethod
def serialize(value: ... | class Real(DataType):
"""
Represents a fixed-size floating point number.
Note: The usual concerns around finite-precision and
rounding hold here.
"""
is_fixed_length = True
fixed_length = REAL_SIZE
is_serializable = True
typename = "Real"
@staticmethod
def serialize(value: ... | # encodes float according to native byteorder ('=')
return struct.pack("=f", value)
| """
:param value:
:return:
"""
# encodes float according to native byteorder ('=')
return struct.pack("=f", value)
| 11 | 220 | 30 | 250 | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... |
50,104 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/datatypes.py | 136,138 | 122,145 | deserialize | Text | 138,140 | 138,140 | class Text(DataType):
"""
represents a variable length text
"""
is_fixed_length = False
fixed_length = 0
is_serializable = True
typename = "Text"
@staticmethod
def serialize(value: str):
return value.encode("utf-8")
@staticmethod
def deserialize(bstring: bytes):
FI... | class Text(DataType):
"""
represents a variable length text
"""
is_fixed_length = False
fixed_length = 0
is_serializable = True
typename = "Text"
@staticmethod
def serialize(value: str):
return value.encode("utf-8")
@staticmethod
def deserialize(bstring: bytes):
FI... | return bstring.decode("utf-8")
| return bstring.decode("utf-8")
| 2 | 139 | 15 | 154 | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... | """
Database, i.e. storage layer datatypes, as distinct from: 1) parsed AST datatype, 2) execution datatype (i.e. impl
language datatype)
"""
import sys
import struct
from abc import ABCMeta
from typing import Any, Type
from .constants import INTEGER_SIZE, REAL_SIZE
class DataType:
"""
This is a datatype of ... |
50,107 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/functions.py | 85,88 | 32,178 | validate_args | FunctionDefinition | 96,154 | 88,154 | class FunctionDefinition:
"""
Represents a function definition, for both scalar and aggregate functions.
:param func_name: name of function; not strictly needed; used for debugging
:param pos_params: list of positional arguments.
NOTE: a scalar function can accept multiple positional arguments,... | class FunctionDefinition:
"""
Represents a function definition, for both scalar and aggregate functions.
:param func_name: name of function; not strictly needed; used for debugging
:param pos_params: list of positional arguments.
NOTE: a scalar function can accept multiple positional arguments,... | # 1. validate positional params
# 1.1. check arity- positional params are all required
if len(pos_args) != len(self.pos_params):
return Response(
False,
error_message=f"Arity mismatch between expected positional params [{len(pos_args)}] "
... | """
Validate pos and named args.
Validate pos args on existence and type;
validate named args on name, and type
Args:
pos_args: list of literals
named_args: dict of param_name -> literal
"""
# 1. validate positional params
# 1.1. ch... | 235 | 882 | 703 | 1,585 | """
This implements functions. Specifically:
- the function declaration interface
-- and the ability to get the return type
- Here, I assume the datatype are the same as those exposed to ddl definitions, i.e.
Integer, Float, Text, Blob.
- the ability to execute the functions
There will be 2... | """
This implements functions. Specifically:
- the function declaration interface
-- and the ability to get the return type
- Here, I assume the datatype are the same as those exposed to ddl definitions, i.e.
Integer, Float, Text, Blob.
- the ability to execute the functions
There will be 2... |
50,109 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/interface.py | 130,131 | 36,225 | do_meta_command | LearnDB | 137,169 | 131,169 | class LearnDB:
"""
This provides programmatic interface for interacting with databases managed by Learndb.
This class defines the handle
An example flow is like:
```
# create handler instance
db = LearnDB(db_filepath)
# submit statement
resp = db.handle_input("select col_a from foo... | class LearnDB:
"""
This provides programmatic interface for interacting with databases managed by Learndb.
This class defines the handle
An example flow is like:
```
# create handler instance
db = LearnDB(db_filepath)
# submit statement
resp = db.handle_input("select col_a from foo... | if command == ".quit":
print("goodbye")
self.close()
sys.exit(EXIT_SUCCESS)
elif command.startswith(".btree"):
# .btree expects table-name
splits = command.split(" ")
if len(splits) != 2:
print("Invalid argument to .... | """
handle execution of meta command
:param command:
:param db:
:return:
"""
if command == ".quit":
print("goodbye")
self.close()
sys.exit(EXIT_SUCCESS)
elif command.startswith(".btree"):
# .btree expects tab... | 102 | 1,308 | 432 | 1,740 | from __future__ import annotations
"""
This module contains the highest level user-interaction and resource allocation
i.e. management of entities, like parser, virtual machine, pager, etc. that implement
the DBMS functionality that is learndb.
"""
import os
import os.path
import sys
import logging
from typing import... | from __future__ import annotations
"""
This module contains the highest level user-interaction and resource allocation
i.e. management of entities, like parser, virtual machine, pager, etc. that implement
the DBMS functionality that is learndb.
"""
import os
import os.path
import sys
import logging
from typing import... |
50,110 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/lang_parser/sqlhandler.py | 70,71 | 14,78 | debug | SqlFrontEnd | 74,78 | 71,78 | class SqlFrontEnd:
"""
Parser for learndb lang, based on lark definition
"""
def __init__(self, raise_exception=False, debug_mode=True):
self.parser = None
# parse tree generated by Lark
self.parse_tree = None
# abstract syntax tree, output of parse tree being transforme... | class SqlFrontEnd:
"""
Parser for learndb lang, based on lark definition
"""
def __init__(self, raise_exception=False, debug_mode=True):
self.parser = None
# parse tree generated by Lark
self.parse_tree = None
# abstract syntax tree, output of parse tree being transforme... | logger.info("Outputting parse tree (untransformed)...")
print(self.parse_tree.pretty())
logger.info("Outputting AST...")
print(self.tree)
| """
print some debug info on recent parse
"""
logger.info("Outputting parse tree (untransformed)...")
print(self.parse_tree.pretty())
logger.info("Outputting AST...")
print(self.tree)
| 8 | 459 | 53 | 512 | from __future__ import annotations
import logging
from lark import Lark
from lark.exceptions import UnexpectedInput # root of all lark exceptions
from .symbols import ToAst
from .grammar import GRAMMAR
logger = logging.getLogger(__name__)
class SqlFrontEnd:
"""
Parser for learndb lang, based on lark defi... | from __future__ import annotations
import logging
from lark import Lark
from lark.exceptions import UnexpectedInput # root of all lark exceptions
from .symbols import ToAst
from .grammar import GRAMMAR
logger = logging.getLogger(__name__)
class SqlFrontEnd:
"""
Parser for learndb lang, based on lark defi... |
50,111 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/lang_parser/utils.py | 19,20 | 1,35 | pascal_to_snake | 25,35 | 20,35 | import re
class TokenizeError(Exception):
pass
class ParseError(Exception):
pass
def camel_to_snake(name: str) -> str:
"""
change casing abcdXyz -> abcd_xyz
"""
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
def pascal_to_snake(name) -> str:
FILL_FUNC_BODY | import re
class TokenizeError(Exception):
pass
class ParseError(Exception):
pass
def camel_to_snake(name: str) -> str:
"""
change casing abcdXyz -> abcd_xyz
"""
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
def pascal_to_snake(name) -> str:
"""
convert case
HelloWorld ... | snake_name = []
for i, ch in enumerate(name):
if i == 0:
snake_name.append(ch.lower())
elif ch.isupper():
snake_name.append("_" + ch.lower())
else:
snake_name.append(ch)
return "".join(snake_name)
| """
convert case
HelloWorld -> hello_world
:return:
"""
snake_name = []
for i, ch in enumerate(name):
if i == 0:
snake_name.append(ch.lower())
elif ch.isupper():
snake_name.append("_" + ch.lower())
else:
snake_name.append(ch)
r... | 22 | 155 | 101 | 256 | import re
class TokenizeError(Exception):
pass
class ParseError(Exception):
pass
def camel_to_snake(name: str) -> str:
"""
change casing abcdXyz -> abcd_xyz
"""
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
def pascal_to_snake(name) -> str:
FILL_FUNC_BODY | import re
class TokenizeError(Exception):
pass
class ParseError(Exception):
pass
def camel_to_snake(name: str) -> str:
"""
change casing abcdXyz -> abcd_xyz
"""
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
def pascal_to_snake(name) -> str:
"""
convert case
HelloWorld ... | |
50,112 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/lang_parser/visitor.py | 29,30 | 15,45 | visit | Visitor | 33,45 | 30,45 | class Visitor:
"""
Conceptually, Visitor is an interface/abstract class,
where different concrete Visitors, e.g. AstPrinter can handle
different tasks, e.g. printing tree, evaluating tree.
This indirection allows us to add new behaviors for the parser
via a new concrete class; instead of either:... | class Visitor:
"""
Conceptually, Visitor is an interface/abstract class,
where different concrete Visitors, e.g. AstPrinter can handle
different tasks, e.g. printing tree, evaluating tree.
This indirection allows us to add new behaviors for the parser
via a new concrete class; instead of either:... | suffix = camel_to_snake(symbol.__class__.__name__)
# determine the name of the handler method from class of expr
# NB: this requires the class and handler have the
# same name in PascalCase and snake_case, respectively
handler = f"visit_{suffix}"
if hasattr(self, handler)... | """
this will determine which specific handler to invoke; dispatch
"""
suffix = camel_to_snake(symbol.__class__.__name__)
# determine the name of the handler method from class of expr
# NB: this requires the class and handler have the
# same name in PascalCase and... | 57 | 206 | 164 | 370 | from __future__ import annotations
import logging
from .utils import camel_to_snake
class HandlerNotFoundException(Exception):
"""
A specific handler (method) is not found;
defined by me
"""
pass
class Visitor:
"""
Conceptually, Visitor is an interface/abstract class,
where differen... | from __future__ import annotations
import logging
from .utils import camel_to_snake
class HandlerNotFoundException(Exception):
"""
A specific handler (method) is not found;
defined by me
"""
pass
class Visitor:
"""
Conceptually, Visitor is an interface/abstract class,
where differen... |
50,113 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/name_registry.py | 42,43 | 10,67 | resolve_name | NameRegistry | 47,59 | 43,59 | class NameRegistry:
"""
This entity is responsible for registering and resolving column name and types
from records and schemas.
TODO: split this into SchemaReader, and RecordReader
"""
def __init__(self):
# record used to resolve values
self.record = None
# schema to re... | class NameRegistry:
"""
This entity is responsible for registering and resolving column name and types
from records and schemas.
TODO: split this into SchemaReader, and RecordReader
"""
def __init__(self):
# record used to resolve values
self.record = None
# schema to re... | if isinstance(operand, ColumnName):
try:
val = self.record.get(operand.name)
return Response(True, body=val)
except InvalidNameException as e:
logging.error(f"Attempted lookup on unknown column [{operand.name}]")
logging.err... | """
This is only valid if called on a name, i.e. is_name(operand) == True.
Note: This returns Response to distinguish resolve failed, from resolved to None
"""
if isinstance(operand, ColumnName):
try:
val = self.record.get(operand.name)
... | 37 | 434 | 152 | 586 | import logging
from lark import Token
from .dataexchange import Response
from .lang_parser.symbols import ColumnName
from .record_utils import InvalidNameException
class NameRegistry:
"""
This entity is responsible for registering and resolving column name and types
from records and schemas.
TODO: s... | import logging
from lark import Token
from .dataexchange import Response
from .lang_parser.symbols import ColumnName
from .record_utils import InvalidNameException
class NameRegistry:
"""
This entity is responsible for registering and resolving column name and types
from records and schemas.
TODO: s... |
50,115 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/pipe.py | 24,25 | 4,26 | reset | Pipe | 25,26 | 25,26 | class Pipe:
"""
Used to read results from select expr
"""
def __init__(self):
self.store = deque()
def write(self, msg):
self.store.append(msg)
def has_msgs(self) -> bool:
return len(self.store) > 0
def read(self):
"""
Read message and remove from ... | class Pipe:
"""
Used to read results from select expr
"""
def __init__(self):
self.store = deque()
def write(self, msg):
self.store.append(msg)
def has_msgs(self) -> bool:
return len(self.store) > 0
def read(self):
"""
Read message and remove from ... | self.store = deque()
| self.store = deque()
| 3 | 137 | 10 | 147 | from collections import deque
class Pipe:
"""
Used to read results from select expr
"""
def __init__(self):
self.store = deque()
def write(self, msg):
self.store.append(msg)
def has_msgs(self) -> bool:
return len(self.store) > 0
def read(self):
"""
... | from collections import deque
class Pipe:
"""
Used to read results from select expr
"""
def __init__(self):
self.store = deque()
def write(self, msg):
self.store.append(msg)
def has_msgs(self) -> bool:
return len(self.store) > 0
def read(self):
"""
... |
50,117 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/schema.py | 58,59 | 46,65 | get_column_by_name | AbstractSchema | 59,61 | 59,61 | class AbstractSchema:
"""
Defines interface for all schema types.
NOTE: this doesn't enforce that implementation classes implement all interface methods.
TODO: Consider formalizing the interface using abc.ABCMeta; see: https://realpython.com/python-interface/
"""
@property
def columns(self... | class AbstractSchema:
"""
Defines interface for all schema types.
NOTE: this doesn't enforce that implementation classes implement all interface methods.
TODO: Consider formalizing the interface using abc.ABCMeta; see: https://realpython.com/python-interface/
"""
@property
def columns(self... | raise NotImplementedError
| raise NotImplementedError
| 2 | 147 | 11 | 158 | from __future__ import annotations
"""
This contain structures to generate and manipulate
logical schema- (column name, column type).
The physical representation (number of bytes,
length of encoding) of the schema is contained in serde.py.
While, records- i.e. data-containing objects with the structure
specified by ... | from __future__ import annotations
"""
This contain structures to generate and manipulate
logical schema- (column name, column type).
The physical representation (number of bytes,
length of encoding) of the schema is contained in serde.py.
While, records- i.e. data-containing objects with the structure
specified by ... |
50,118 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/schema.py | 192,194 | 177,235 | columns | GroupedSchema | 194,210 | 194,210 | class GroupedSchema(AbstractSchema):
"""
Represents a grouped multi or simple schema
"""
def __init__(
self,
schema: Union[SimpleSchema, ScopedSchema],
group_by_columns: List[ColumnName],
):
# all columns, i.e. group-by and non- group-by columns
self.schema =... | class GroupedSchema(AbstractSchema):
"""
Represents a grouped multi or simple schema
"""
def __init__(
self,
schema: Union[SimpleSchema, ScopedSchema],
group_by_columns: List[ColumnName],
):
# all columns, i.e. group-by and non- group-by columns
self.schema =... | if isinstance(self.schema, SimpleSchema):
return self.schema.columns
else:
assert isinstance(self.schema, ScopedSchema)
# the children schema store columns without the alias
# we will create a new (flat) column list with
# alias prepended to co... | if isinstance(self.schema, SimpleSchema):
return self.schema.columns
else:
assert isinstance(self.schema, ScopedSchema)
# the children schema store columns without the alias
# we will create a new (flat) column list with
# alias prepended to co... | 68 | 404 | 177 | 581 | from __future__ import annotations
"""
This contain structures to generate and manipulate
logical schema- (column name, column type).
The physical representation (number of bytes,
length of encoding) of the schema is contained in serde.py.
While, records- i.e. data-containing objects with the structure
specified by ... | from __future__ import annotations
"""
This contain structures to generate and manipulate
logical schema- (column name, column type).
The physical representation (number of bytes,
length of encoding) of the schema is contained in serde.py.
While, records- i.e. data-containing objects with the structure
specified by ... |
50,119 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/schema.py | 166,167 | 122,177 | get_column_by_name | ScopedSchema | 167,177 | 167,177 | class ScopedSchema(AbstractSchema):
"""
Represents a scoped (by table_alias) collection of schema
"""
def __init__(self, schemas: dict):
self.schemas = schemas # table_name -> Schema
def get_table_names(self):
return self.schemas.keys()
@classmethod
def from_single_schema... | class ScopedSchema(AbstractSchema):
"""
Represents a scoped (by table_alias) collection of schema
"""
def __init__(self, schemas: dict):
self.schemas = schemas # table_name -> Schema
def get_table_names(self):
return self.schemas.keys()
@classmethod
def from_single_schema... | name_parts = name.split(".")
assert len(name_parts) == 2
table_alias, column_name = name_parts
table_schema = self.schemas[table_alias]
for column in table_schema.columns:
if column.name.lower() == column_name:
return column
return None
| name_parts = name.split(".")
assert len(name_parts) == 2
table_alias, column_name = name_parts
table_schema = self.schemas[table_alias]
for column in table_schema.columns:
if column.name.lower() == column_name:
return column
return None
| 26 | 397 | 94 | 491 | from __future__ import annotations
"""
This contain structures to generate and manipulate
logical schema- (column name, column type).
The physical representation (number of bytes,
length of encoding) of the schema is contained in serde.py.
While, records- i.e. data-containing objects with the structure
specified by ... | from __future__ import annotations
"""
This contain structures to generate and manipulate
logical schema- (column name, column type).
The physical representation (number of bytes,
length of encoding) of the schema is contained in serde.py.
While, records- i.e. data-containing objects with the structure
specified by ... |
50,120 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/schema.py | 87,89 | 65,122 | columns | SimpleSchema | 89,91 | 89,91 | class SimpleSchema(AbstractSchema):
"""
Represents a schema. This includes
logical aspects (name) and physical aspects
(number of bytes of storage, fixed vs. variable length encoding)
Note: a schema must be valid. If the schema is invalid, this
should be raised prior to creating. This is partic... | class SimpleSchema(AbstractSchema):
"""
Represents a schema. This includes
logical aspects (name) and physical aspects
(number of bytes of storage, fixed vs. variable length encoding)
Note: a schema must be valid. If the schema is invalid, this
should be raised prior to creating. This is partic... | return self.cols
| return self.cols
| 2 | 488 | 10 | 498 | from __future__ import annotations
"""
This contain structures to generate and manipulate
logical schema- (column name, column type).
The physical representation (number of bytes,
length of encoding) of the schema is contained in serde.py.
While, records- i.e. data-containing objects with the structure
specified by ... | from __future__ import annotations
"""
This contain structures to generate and manipulate
logical schema- (column name, column type).
The physical representation (number of bytes,
length of encoding) of the schema is contained in serde.py.
While, records- i.e. data-containing objects with the structure
specified by ... |
50,123 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/statemanager.py | 67,68 | 50,112 | register_aliased_source | Scope | 68,70 | 68,70 | class Scope:
"""
A scope is a logical environment, within which names and objects are contained/defined.
A passive entity that exposes add, remove, has_ {recordset, groupedrecordset,
"""
def __init__(self):
self.aliased_source = {}
# NOTE: previously this was a list, but now since T... | class Scope:
"""
A scope is a logical environment, within which names and objects are contained/defined.
A passive entity that exposes add, remove, has_ {recordset, groupedrecordset,
"""
def __init__(self):
self.aliased_source = {}
# NOTE: previously this was a list, but now since T... | raise NotImplementedError
| raise NotImplementedError
| 2 | 604 | 11 | 615 | """
class representing a logical-database
support API to read/write data via Table
and creating tables etc.
"""
import random
import string
from collections import UserList, UserDict
from typing import Optional, List, Union, Tuple
from .btree import Tree
from .constants import CATALOG_ROOT_PAGE_NUM
from .dataexchange ... | """
class representing a logical-database
support API to read/write data via Table
and creating tables etc.
"""
import random
import string
from collections import UserList, UserDict
from typing import Optional, List, Union, Tuple
from .btree import Tree
from .constants import CATALOG_ROOT_PAGE_NUM
from .dataexchange ... |
50,126 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/value_generators.py | 128,129 | 118,136 | get_value | ValueGeneratorFromNoRecordOverExpr | 132,136 | 129,136 | class ValueGeneratorFromNoRecordOverExpr:
"""
Generate value from a no-record. Where the value is the result of evaluating an expr.
The expr can be composed of column refs, literals, function calls, and algebraic combinations of these.
"""
def __init__(self, or_clause: OrClause, interpreter: Expres... | class ValueGeneratorFromNoRecordOverExpr:
"""
Generate value from a no-record. Where the value is the result of evaluating an expr.
The expr can be composed of column refs, literals, function calls, and algebraic combinations of these.
"""
def __init__(self, or_clause: OrClause, interpreter: Expres... | value = self.interpreter.evaluate_over_no_record(self.or_clause)
return value
| """
Evaluate the or_clause
"""
value = self.interpreter.evaluate_over_no_record(self.or_clause)
return value
| 5 | 154 | 36 | 190 | """
Contains classes corresponding to value generators.
ValueGenerators are used in to evaluate select clauses. They are objects
that track the formal parameters passed to the select clause. Then
when iterating over a recordset, the valueGenerator takes a record, and returns a single output value
"""
from dataclasses ... | """
Contains classes corresponding to value generators.
ValueGenerators are used in to evaluate select clauses. They are objects
that track the formal parameters passed to the select clause. Then
when iterating over a recordset, the valueGenerator takes a record, and returns a single output value
"""
from dataclasses ... |
50,127 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/value_generators.py | 146,147 | 136,150 | get_value | ValueGeneratorFromRecordGroupOverExpr | 148,150 | 147,150 | class ValueGeneratorFromRecordGroupOverExpr:
"""
Generate value from pair of group_key, and recordset for record group. Where the value is the result of evaluating an expr.
The expr can be composed of column refs, literals, function calls, and algebraic combinations of these.
"""
def __init__(self,... | class ValueGeneratorFromRecordGroupOverExpr:
"""
Generate value from pair of group_key, and recordset for record group. Where the value is the result of evaluating an expr.
The expr can be composed of column refs, literals, function calls, and algebraic combinations of these.
"""
def __init__(self,... | value = self.interpreter.evaluate_over_grouped_record(self.or_clause, record)
return value
| """ """
value = self.interpreter.evaluate_over_grouped_record(self.or_clause, record)
return value
| 6 | 156 | 35 | 191 | """
Contains classes corresponding to value generators.
ValueGenerators are used in to evaluate select clauses. They are objects
that track the formal parameters passed to the select clause. Then
when iterating over a recordset, the valueGenerator takes a record, and returns a single output value
"""
from dataclasses ... | """
Contains classes corresponding to value generators.
ValueGenerators are used in to evaluate select clauses. They are objects
that track the formal parameters passed to the select clause. Then
when iterating over a recordset, the valueGenerator takes a record, and returns a single output value
"""
from dataclasses ... |
50,128 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/value_generators.py | 110,111 | 98,118 | get_value | ValueGeneratorFromRecordOverExpr | 114,118 | 111,118 | class ValueGeneratorFromRecordOverExpr:
"""
Generate value from a single record. Where the value is the result of evaluating an expr.
The expr can be composed of column refs, literals, function calls, and algebraic combinations of these.
This generalizes the ValueGeneratorFromRecordOverFunc, ValueExtra... | class ValueGeneratorFromRecordOverExpr:
"""
Generate value from a single record. Where the value is the result of evaluating an expr.
The expr can be composed of column refs, literals, function calls, and algebraic combinations of these.
This generalizes the ValueGeneratorFromRecordOverFunc, ValueExtra... | value = self.interpreter.evaluate_over_record(self.or_clause, record)
return value
| """
Evaluate the or_clause
"""
value = self.interpreter.evaluate_over_record(self.or_clause, record)
return value
| 6 | 182 | 36 | 218 | """
Contains classes corresponding to value generators.
ValueGenerators are used in to evaluate select clauses. They are objects
that track the formal parameters passed to the select clause. Then
when iterating over a recordset, the valueGenerator takes a record, and returns a single output value
"""
from dataclasses ... | """
Contains classes corresponding to value generators.
ValueGenerators are used in to evaluate select clauses. They are objects
that track the formal parameters passed to the select clause. Then
when iterating over a recordset, the valueGenerator takes a record, and returns a single output value
"""
from dataclasses ... |
50,129 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/value_generators.py | 72,73 | 44,98 | get_value | ValueGeneratorFromRecordOverFunc | 76,98 | 73,98 | class ValueGeneratorFromRecordOverFunc:
"""
Generate value from a single record.
This is used in a select clause, e.g.
select cola from foo
or
select upper(cola) from foo
"""
def __init__(
self,
pos_args: List[SelectableAtom],
named_args: Dict[str, Selectable... | class ValueGeneratorFromRecordOverFunc:
"""
Generate value from a single record.
This is used in a select clause, e.g.
select cola from foo
or
select upper(cola) from foo
"""
def __init__(
self,
pos_args: List[SelectableAtom],
named_args: Dict[str, Selectable... | # evaluate pos_args, i.e. convert SelectableAtom to a value that can be passed to a function
evaluated_pos_args = []
for arg in self.pos_args:
if isinstance(arg, LiteralSelectableAtom):
# evaluate any literals, by unboxing from `LiteralSelectableAtom`
... | """
This is invoked when iterating over a recordset with each record
"""
# evaluate pos_args, i.e. convert SelectableAtom to a value that can be passed to a function
evaluated_pos_args = []
for arg in self.pos_args:
if isinstance(arg, LiteralSelectableAtom):
... | 79 | 246 | 291 | 537 | """
Contains classes corresponding to value generators.
ValueGenerators are used in to evaluate select clauses. They are objects
that track the formal parameters passed to the select clause. Then
when iterating over a recordset, the valueGenerator takes a record, and returns a single output value
"""
from dataclasses ... | """
Contains classes corresponding to value generators.
ValueGenerators are used in to evaluate select clauses. They are objects
that track the formal parameters passed to the select clause. Then
when iterating over a recordset, the valueGenerator takes a record, and returns a single output value
"""
from dataclasses ... |
50,130 | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py | /home/hieuvd/dung_repo/raw/stars_03/spandanb_learndb-py/learndb-py/learndb/vm_utils.py | 14,15 | 1,28 | datatype_from_symbolic_datatype | 18,28 | 15,28 | from enum import Enum, auto
from typing import Type
from .datatypes import DataType, Integer, Real, Blob, Text
from .lang_parser.symbols import SymbolicDataType
class EvalMode(Enum):
NoSchema = auto()
Scalar = auto()
Grouped = auto()
def datatype_from_symbolic_datatype(data_type: SymbolicDataType) -> T... | from enum import Enum, auto
from typing import Type
from .datatypes import DataType, Integer, Real, Blob, Text
from .lang_parser.symbols import SymbolicDataType
class EvalMode(Enum):
NoSchema = auto()
Scalar = auto()
Grouped = auto()
def datatype_from_symbolic_datatype(data_type: SymbolicDataType) -> T... | if data_type == SymbolicDataType.Integer:
return Integer
elif data_type == SymbolicDataType.Real:
return Real
elif data_type == SymbolicDataType.Blob:
return Blob
elif data_type == SymbolicDataType.Text:
return Text
else:
raise Exception(f"Unknown type {data_t... | """
Convert symbols.DataType to datatypes.DataType
"""
if data_type == SymbolicDataType.Integer:
return Integer
elif data_type == SymbolicDataType.Real:
return Real
elif data_type == SymbolicDataType.Blob:
return Blob
elif data_type == SymbolicDataType.Text:
r... | 29 | 140 | 103 | 243 | from enum import Enum, auto
from typing import Type
from .datatypes import DataType, Integer, Real, Blob, Text
from .lang_parser.symbols import SymbolicDataType
class EvalMode(Enum):
NoSchema = auto()
Scalar = auto()
Grouped = auto()
def datatype_from_symbolic_datatype(data_type: SymbolicDataType) -> T... | from enum import Enum, auto
from typing import Type
from .datatypes import DataType, Integer, Real, Blob, Text
from .lang_parser.symbols import SymbolicDataType
class EvalMode(Enum):
NoSchema = auto()
Scalar = auto()
Grouped = auto()
def datatype_from_symbolic_datatype(data_type: SymbolicDataType) -> T... | |
50,251 | /home/hieuvd/dung_repo/raw/stars_03/swirlai_swirl-search/swirl-search | /home/hieuvd/dung_repo/raw/stars_03/swirlai_swirl-search/swirl-search/manage.py | 7,8 | 1,23 | main | 9,21 | 8,21 | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
FILL_FUNC_BODYif __name__ == '__main__':
main()
| #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
FILL_FUNC_BODYif __name__ == '__main__':
main()
| os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'swirl_server.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 your PYTHO... | """Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'swirl_server.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 "
... | 42 | 66 | 145 | 211 | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
FILL_FUNC_BODYif __name__ == '__main__':
main()
| #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
FILL_FUNC_BODYif __name__ == '__main__':
main()
| |
50,252 | /home/hieuvd/dung_repo/raw/stars_03/swirlai_swirl-search/swirl-search | /home/hieuvd/dung_repo/raw/stars_03/swirlai_swirl-search/swirl-search/scripts/fix_csv.py | 16,17 | 1,61 | main | 17,57 | 17,57 |
'''
@author: Sid Probstein
@contact: sid@swirl.today
'''
import argparse
import sys
import os
import csv
module_name = 'fix_csv.py'
##################################################
def main(argv):
FILL_FUNC_BODYif __name__ == "__main__":
main(sys.argv)
# end |
'''
@author: Sid Probstein
@contact: sid@swirl.today
'''
import argparse
import sys
import os
import csv
module_name = 'fix_csv.py'
##################################################
def main(argv):
FILL_FUNC_BODYif __name__ == "__main__":
main(sys.argv)
# end |
# arguments
parser = argparse.ArgumentParser(description="Fix CSV file for loading into SQLite3")
parser.add_argument('filespec', help="path to a csv file to fix")
parser.add_argument('-d', '--debug', action="store_true", help="provide debugging information")
parser.add_argument('-o', '--output', h... |
# arguments
parser = argparse.ArgumentParser(description="Fix CSV file for loading into SQLite3")
parser.add_argument('filespec', help="path to a csv file to fix")
parser.add_argument('-d', '--debug', action="store_true", help="provide debugging information")
parser.add_argument('-o', '--output', h... | 104 | 102 | 446 | 548 |
'''
@author: Sid Probstein
@contact: sid@swirl.today
'''
import argparse
import sys
import os
import csv
module_name = 'fix_csv.py'
##################################################
def main(argv):
FILL_FUNC_BODYif __name__ == "__main__":
main(sys.argv)
# end |
'''
@author: Sid Probstein
@contact: sid@swirl.today
'''
import argparse
import sys
import os
import csv
module_name = 'fix_csv.py'
##################################################
def main(argv):
FILL_FUNC_BODYif __name__ == "__main__":
main(sys.argv)
# end | |
50,254 | /home/hieuvd/dung_repo/raw/stars_03/swirlai_swirl-search/swirl-search | /home/hieuvd/dung_repo/raw/stars_03/swirlai_swirl-search/swirl-search/swirl/connectors/oes_common.py | 14,15 | 3,53 | log_invalid_credentials | OpenElasticCommon | 15,18 | 15,18 | class OpenElasticCommon(Connector):
""" Code common to both open search and elastic connectors"""
def __init__(self, provider_id, search_id, update, request_id=''):
super().__init__(provider_id, search_id, update, request_id)
########################################
def str_to_bool(self,s):
... | class OpenElasticCommon(Connector):
""" Code common to both open search and elastic connectors"""
def __init__(self, provider_id, search_id, update, request_id=''):
super().__init__(provider_id, search_id, update, request_id)
########################################
def str_to_bool(self,s):
... | self.error("invalid credentials: {self.provider.credentials}")
self.status = "ERR_INVALID_CREDENTIALS"
| self.error("invalid credentials: {self.provider.credentials}")
self.status = "ERR_INVALID_CREDENTIALS"
| 6 | 463 | 40 | 503 | from swirl.connectors.connector import Connector
class OpenElasticCommon(Connector):
""" Code common to both open search and elastic connectors"""
def __init__(self, provider_id, search_id, update, request_id=''):
super().__init__(provider_id, search_id, update, request_id)
#####################... | from swirl.connectors.connector import Connector
class OpenElasticCommon(Connector):
""" Code common to both open search and elastic connectors"""
def __init__(self, provider_id, search_id, update, request_id=''):
super().__init__(provider_id, search_id, update, request_id)
#####################... |
50,255 | /home/hieuvd/dung_repo/raw/stars_03/swirlai_swirl-search/swirl-search | /home/hieuvd/dung_repo/raw/stars_03/swirlai_swirl-search/swirl-search/swirl/processors/result_map_converter.py | 17,18 | 8,51 | __clean_key | ResultMapConverter | 19,27 | 18,27 | class ResultMapConverter():
__BTC_CONVERT_METHOD_PAT = r'sw_btcconvert\((.*)\)'
__URL_ENCODE_METHOD_PAT = r'sw_urlencode\((.*)\)'
def __init__(self, key):
self.__key = key
self.__found_directive = None
def __clean_key(self):
FILL_FUNC_BODY def __optional_convert_value(self, v):
... | class ResultMapConverter():
__BTC_CONVERT_METHOD_PAT = r'sw_btcconvert\((.*)\)'
__URL_ENCODE_METHOD_PAT = r'sw_urlencode\((.*)\)'
def __init__(self, key):
self.__key = key
self.__found_directive = None
def __clean_key(self):
"""Extract directive if it exists and remove it from... | if self.__key is None:
return None
self.__found_directive = re.search(ResultMapConverter.__BTC_CONVERT_METHOD_PAT, self.__key) or \
re.search(ResultMapConverter.__URL_ENCODE_METHOD_PAT, self.__key)
if self.__found_directive:
self.__key = se... | """Extract directive if it exists and remove it from key"""
if self.__key is None:
return None
self.__found_directive = re.search(ResultMapConverter.__BTC_CONVERT_METHOD_PAT, self.__key) or \
re.search(ResultMapConverter.__URL_ENCODE_METHOD_PAT, self._... | 21 | 398 | 114 | 512 | import re
from decimal import Decimal, getcontext
from urllib.parse import quote
# Ensure the precision is set sufficiently high outside the class
getcontext().prec = 10
class ResultMapConverter():
__BTC_CONVERT_METHOD_PAT = r'sw_btcconvert\((.*)\)'
__URL_ENCODE_METHOD_PAT = r'sw_urlencode\((.*)\)'
def ... | import re
from decimal import Decimal, getcontext
from urllib.parse import quote
# Ensure the precision is set sufficiently high outside the class
getcontext().prec = 10
class ResultMapConverter():
__BTC_CONVERT_METHOD_PAT = r'sw_btcconvert\((.*)\)'
__URL_ENCODE_METHOD_PAT = r'sw_urlencode\((.*)\)'
def ... |
50,256 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/setup.py | 16,17 | 1,109 | setup_package | 17,107 | 17,107 | """Web server Tableau uses to run Python scripts.
TabPy (the Tableau Python Server) is an external service implementation
which expands Tableau's capabilities by allowing users to execute Python
scripts and saved functions via Tableau's table calculations.
"""
import os
from setuptools import setup, find_packages
imp... | """Web server Tableau uses to run Python scripts.
TabPy (the Tableau Python Server) is an external service implementation
which expands Tableau's capabilities by allowing users to execute Python
scripts and saved functions via Tableau's table calculations.
"""
import os
from setuptools import setup, find_packages
imp... | def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="tabpy",
version=read("tabpy/VERSION"),
description=DOCLINES[0],
long_description="\n".join(DOCLINES[1:]) + "\n" + read("CHANGELOG"),
long_description_content_type="te... | def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="tabpy",
version=read("tabpy/VERSION"),
description=DOCLINES[0],
long_description="\n".join(DOCLINES[1:]) + "\n" + read("CHANGELOG"),
long_description_content_type="te... | 191 | 131 | 997 | 1,128 | """Web server Tableau uses to run Python scripts.
TabPy (the Tableau Python Server) is an external service implementation
which expands Tableau's capabilities by allowing users to execute Python
scripts and saved functions via Tableau's table calculations.
"""
import os
from setuptools import setup, find_packages
imp... | """Web server Tableau uses to run Python scripts.
TabPy (the Tableau Python Server) is an external service implementation
which expands Tableau's capabilities by allowing users to execute Python
scripts and saved functions via Tableau's table calculations.
"""
import os
from setuptools import setup, find_packages
imp... | |
50,257 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/models/deploy_models.py | 9,10 | 1,27 | main | 10,25 | 10,25 | import os
from pathlib import Path
import platform
import subprocess
import sys
from tabpy.models.utils import setup_utils
def main():
FILL_FUNC_BODYif __name__ == "__main__":
main()
| import os
from pathlib import Path
import platform
import subprocess
import sys
from tabpy.models.utils import setup_utils
def main():
FILL_FUNC_BODYif __name__ == "__main__":
main()
| # Determine if we run python or python3
py = "python" if platform.system() == "Windows" else "python3"
file_path = sys.argv[1] if len(sys.argv) > 1 else setup_utils.get_default_config_file_path()
print(f"Using config file at {file_path}")
port, auth_on, prefix = setup_utils.parse_config(file_path)... | # Determine if we run python or python3
py = "python" if platform.system() == "Windows" else "python3"
file_path = sys.argv[1] if len(sys.argv) > 1 else setup_utils.get_default_config_file_path()
print(f"Using config file at {file_path}")
port, auth_on, prefix = setup_utils.parse_config(file_path)... | 65 | 62 | 218 | 280 | import os
from pathlib import Path
import platform
import subprocess
import sys
from tabpy.models.utils import setup_utils
def main():
FILL_FUNC_BODYif __name__ == "__main__":
main()
| import os
from pathlib import Path
import platform
import subprocess
import sys
from tabpy.models.utils import setup_utils
def main():
FILL_FUNC_BODYif __name__ == "__main__":
main()
| |
50,258 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/models/scripts/ANOVA.py | 5,6 | 1,23 | anova | 11,21 | 6,21 | import scipy.stats as stats
from tabpy.models.utils import setup_utils
def anova(_arg1, _arg2, *_argN):
FILL_FUNC_BODYif __name__ == "__main__":
setup_utils.deploy_model("anova", anova, "Returns the p-value form an ANOVA test")
| import scipy.stats as stats
from tabpy.models.utils import setup_utils
def anova(_arg1, _arg2, *_argN):
"""
ANOVA is a statistical hypothesis test that is used to compare
two or more group means for equality.For more information on
the function and how to use it please refer to tabpy-tools.md
"""
... |
cols = [_arg1, _arg2] + list(_argN)
for col in cols:
if not isinstance(col[0], (int, float)):
print("values must be numeric")
raise ValueError
_, p_value = stats.f_oneway(_arg1, _arg2, *_argN)
return p_value
| """
ANOVA is a statistical hypothesis test that is used to compare
two or more group means for equality.For more information on
the function and how to use it please refer to tabpy-tools.md
"""
cols = [_arg1, _arg2] + list(_argN)
for col in cols:
if not isinstance(col[0], (int, floa... | 29 | 144 | 104 | 248 | import scipy.stats as stats
from tabpy.models.utils import setup_utils
def anova(_arg1, _arg2, *_argN):
FILL_FUNC_BODYif __name__ == "__main__":
setup_utils.deploy_model("anova", anova, "Returns the p-value form an ANOVA test")
| import scipy.stats as stats
from tabpy.models.utils import setup_utils
def anova(_arg1, _arg2, *_argN):
"""
ANOVA is a statistical hypothesis test that is used to compare
two or more group means for equality.For more information on
the function and how to use it please refer to tabpy-tools.md
"""
... | |
50,259 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/models/scripts/SentimentAnalysis.py | 17,18 | 1,53 | SentimentAnalysis | 24,47 | 18,47 | from textblob import TextBlob
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from tabpy.models.utils import setup_utils
import ssl
_ctx = ssl._create_unverified_context
ssl._create_default_https_context = _ctx
nltk.download("vader_lexicon")
nltk.download("punkt")
def SentimentAnalysis(_a... | from textblob import TextBlob
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from tabpy.models.utils import setup_utils
import ssl
_ctx = ssl._create_unverified_context
ssl._create_default_https_context = _ctx
nltk.download("vader_lexicon")
nltk.download("punkt")
def SentimentAnalysis(_a... | if not (isinstance(_arg1[0], str)):
raise TypeError
supportedLibraries = {"nltk", "textblob"}
library = library.lower()
if library not in supportedLibraries:
raise ValueError
scores = []
if library == "nltk":
sid = SentimentIntensityAnalyzer()
for text in _arg1... | """
Sentiment Analysis is a procedure that assigns a score from -1 to 1
for a piece of text with -1 being negative and 1 being positive. For
more information on the function and how to use it please refer to
tabpy-tools.md
"""
if not (isinstance(_arg1[0], str)):
raise TypeError
... | 55 | 257 | 207 | 464 | from textblob import TextBlob
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from tabpy.models.utils import setup_utils
import ssl
_ctx = ssl._create_unverified_context
ssl._create_default_https_context = _ctx
nltk.download("vader_lexicon")
nltk.download("punkt")
def SentimentAnalysis(_a... | from textblob import TextBlob
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from tabpy.models.utils import setup_utils
import ssl
_ctx = ssl._create_unverified_context
ssl._create_default_https_context = _ctx
nltk.download("vader_lexicon")
nltk.download("punkt")
def SentimentAnalysis(_a... | |
50,260 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/models/scripts/tTest.py | 5,6 | 1,40 | ttest | 12,38 | 6,38 | from scipy import stats
from tabpy.models.utils import setup_utils
def ttest(_arg1, _arg2):
FILL_FUNC_BODYif __name__ == "__main__":
setup_utils.deploy_model("ttest", ttest, "Returns the p-value form a t-test")
| from scipy import stats
from tabpy.models.utils import setup_utils
def ttest(_arg1, _arg2):
"""
T-Test is a statistical hypothesis test that is used to compare
two sample means or a sample’s mean against a known population mean.
For more information on the function and how to use it please refer
t... | # one sample test with mean
if len(_arg2) == 1:
test_stat, p_value = stats.ttest_1samp(_arg1, _arg2)
return p_value
# two sample t-test where _arg1 is numeric and _arg2 is a binary factor
elif len(set(_arg2)) == 2:
# each sample in _arg1 needs to have a corresponding classificati... | """
T-Test is a statistical hypothesis test that is used to compare
two sample means or a sample’s mean against a known population mean.
For more information on the function and how to use it please refer
to tabpy-tools.md
"""
# one sample test with mean
if len(_arg2) == 1:
test_... | 104 | 145 | 327 | 472 | from scipy import stats
from tabpy.models.utils import setup_utils
def ttest(_arg1, _arg2):
FILL_FUNC_BODYif __name__ == "__main__":
setup_utils.deploy_model("ttest", ttest, "Returns the p-value form a t-test")
| from scipy import stats
from tabpy.models.utils import setup_utils
def ttest(_arg1, _arg2):
"""
T-Test is a statistical hypothesis test that is used to compare
two sample means or a sample’s mean against a known population mean.
For more information on the function and how to use it please refer
t... | |
50,261 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/models/utils/setup_utils.py | 45,46 | 1,59 | deploy_model | 46,59 | 46,59 | import configparser
import getpass
import os
import sys
from tabpy.tabpy_tools.client import Client
def get_default_config_file_path():
import tabpy
pkg_path = os.path.dirname(tabpy.__file__)
config_file_path = os.path.join(pkg_path, "tabpy_server", "common", "default.conf")
return config_file_path
... | import configparser
import getpass
import os
import sys
from tabpy.tabpy_tools.client import Client
def get_default_config_file_path():
import tabpy
pkg_path = os.path.dirname(tabpy.__file__)
config_file_path = os.path.join(pkg_path, "tabpy_server", "common", "default.conf")
return config_file_path
... | # running from deploy_models.py
config_file_path = sys.argv[1] if len(sys.argv) > 1 else get_default_config_file_path()
port, auth_on, prefix = parse_config(config_file_path)
connection = Client(f"{prefix}://localhost:{port}/")
if auth_on:
# credentials are passed in from setup.py
... | # running from deploy_models.py
config_file_path = sys.argv[1] if len(sys.argv) > 1 else get_default_config_file_path()
port, auth_on, prefix = parse_config(config_file_path)
connection = Client(f"{prefix}://localhost:{port}/")
if auth_on:
# credentials are passed in from setup.py
... | 50 | 426 | 202 | 628 | import configparser
import getpass
import os
import sys
from tabpy.tabpy_tools.client import Client
def get_default_config_file_path():
import tabpy
pkg_path = os.path.dirname(tabpy.__file__)
config_file_path = os.path.join(pkg_path, "tabpy_server", "common", "default.conf")
return config_file_path
... | import configparser
import getpass
import os
import sys
from tabpy.tabpy_tools.client import Client
def get_default_config_file_path():
import tabpy
pkg_path = os.path.dirname(tabpy.__file__)
config_file_path = os.path.join(pkg_path, "tabpy_server", "common", "default.conf")
return config_file_path
... | |
50,262 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy.py | 19,20 | 1,54 | read_version | 20,35 | 20,35 | """
TabPy Server.
Usage:
tabpy [-h] | [--help]
tabpy [--config <CONFIG>] [--disable-auth-warning]
Options:
-h --help Show this screen.
--config <CONFIG> Path to a config file.
--disable-auth-warning Disable authentication warning.
"""
import docopt
import os
from pathlib import P... | """
TabPy Server.
Usage:
tabpy [-h] | [--help]
tabpy [--config <CONFIG>] [--disable-auth-warning]
Options:
-h --help Show this screen.
--config <CONFIG> Path to a config file.
--disable-auth-warning Disable authentication warning.
"""
import docopt
import os
from pathlib import P... | ver = "unknown"
import tabpy
pkg_path = os.path.dirname(tabpy.__file__)
ver_file_path = os.path.join(pkg_path, "VERSION")
if Path(ver_file_path).exists():
with open(ver_file_path) as f:
ver = f.read().strip()
else:
ver = f"Version Unknown, (file {ver_file_path} not ... | ver = "unknown"
import tabpy
pkg_path = os.path.dirname(tabpy.__file__)
ver_file_path = os.path.join(pkg_path, "VERSION")
if Path(ver_file_path).exists():
with open(ver_file_path) as f:
ver = f.read().strip()
else:
ver = f"Version Unknown, (file {ver_file_path} not ... | 32 | 248 | 138 | 386 | """
TabPy Server.
Usage:
tabpy [-h] | [--help]
tabpy [--config <CONFIG>] [--disable-auth-warning]
Options:
-h --help Show this screen.
--config <CONFIG> Path to a config file.
--disable-auth-warning Disable authentication warning.
"""
import docopt
import os
from pathlib import P... | """
TabPy Server.
Usage:
tabpy [-h] | [--help]
tabpy [--config <CONFIG>] [--disable-auth-warning]
Options:
-h --help Show this screen.
--config <CONFIG> Path to a config file.
--disable-auth-warning Disable authentication warning.
"""
import docopt
import os
from pathlib import P... | |
50,265 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/app/app.py | 176,177 | 169,181 | try_exit | TabPyTornadoApp | 177,181 | 177,181 | class TabPyTornadoApp(tornado.web.Application):
is_closing = False
def signal_handler(self, signal, _):
logger.critical(f"Exiting on signal {signal}...")
self.is_closing = True
def try_exit(self):
FILL_FUNC_BODY | class TabPyTornadoApp(tornado.web.Application):
is_closing = False
def signal_handler(self, signal, _):
logger.critical(f"Exiting on signal {signal}...")
self.is_closing = True
def try_exit(self):
FILL_FUNC_BODY | if self.is_closing:
tornado.ioloop.IOLoop.instance().stop()
logger.info("Shutting down TabPy...")
| if self.is_closing:
tornado.ioloop.IOLoop.instance().stop()
logger.info("Shutting down TabPy...")
| 6 | 88 | 47 | 135 | import concurrent.futures
import configparser
import logging
import multiprocessing
import os
import shutil
import signal
import sys
import _thread
import tornado
from tornado.http1connection import HTTP1Connection
import tabpy
import tabpy.tabpy_server.app.arrow_server as pa
from tabpy.tabpy import __version__
from ... | import concurrent.futures
import configparser
import logging
import multiprocessing
import os
import shutil
import signal
import sys
import _thread
import tornado
from tornado.http1connection import HTTP1Connection
import tabpy
import tabpy.tabpy_server.app.arrow_server as pa
from tabpy.tabpy import __version__
from ... |
50,266 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/app/util.py | 11,12 | 1,89 | validate_cert | 12,33 | 12,33 | import csv
from datetime import datetime
import logging
from OpenSSL import crypto
import os
logger = logging.getLogger(__name__)
def validate_cert(cert_file_path):
FILL_FUNC_BODYdef parse_pwd_file(pwd_file_name):
"""
Parses passwords file and returns set of credentials.
Parameters
----------
p... | import csv
from datetime import datetime
import logging
from OpenSSL import crypto
import os
logger = logging.getLogger(__name__)
def validate_cert(cert_file_path):
FILL_FUNC_BODYdef parse_pwd_file(pwd_file_name):
"""
Parses passwords file and returns set of credentials.
Parameters
----------
p... | with open(cert_file_path, "r") as f:
cert_buf = f.read()
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_buf)
date_format, encoding = "%Y%m%d%H%M%SZ", "ascii"
not_before = datetime.strptime(cert.get_notBefore().decode(encoding), date_format)
not_after = datetime.strptime(cert.get_... | with open(cert_file_path, "r") as f:
cert_buf = f.read()
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_buf)
date_format, encoding = "%Y%m%d%H%M%SZ", "ascii"
not_before = datetime.strptime(cert.get_notBefore().decode(encoding), date_format)
not_after = datetime.strptime(cert.get_... | 70 | 523 | 278 | 801 | import csv
from datetime import datetime
import logging
from OpenSSL import crypto
import os
logger = logging.getLogger(__name__)
def validate_cert(cert_file_path):
FILL_FUNC_BODYdef parse_pwd_file(pwd_file_name):
"""
Parses passwords file and returns set of credentials.
Parameters
----------
p... | import csv
from datetime import datetime
import logging
from OpenSSL import crypto
import os
logger = logging.getLogger(__name__)
def validate_cert(cert_file_path):
FILL_FUNC_BODYdef parse_pwd_file(pwd_file_name):
"""
Parses passwords file and returns set of credentials.
Parameters
----------
p... | |
50,267 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/common/endpoint_file_mgr.py | 42,43 | 1,95 | grab_files | 46,58 | 43,58 | """
This module provides functionality required for managing endpoint objects in
TabPy. It provides a way to download endpoint files from remote
and then properly cleanup local the endpoint files on update/remove of endpoint
objects.
The local temporary files for TabPy will by default located at
/tmp/query_objects... | """
This module provides functionality required for managing endpoint objects in
TabPy. It provides a way to download endpoint files from remote
and then properly cleanup local the endpoint files on update/remove of endpoint
objects.
The local temporary files for TabPy will by default located at
/tmp/query_objects... | if not os.path.isdir(directory):
return
else:
for name in os.listdir(directory):
full_path = os.path.join(directory, name)
if os.path.isdir(full_path):
for entry in grab_files(full_path):
yield entry
elif os.path.isfile(full... | """
Generator that returns all files in a directory.
"""
if not os.path.isdir(directory):
return
else:
for name in os.listdir(directory):
full_path = os.path.join(directory, name)
if os.path.isdir(full_path):
for entry in grab_files(full_path):... | 25 | 746 | 113 | 859 | """
This module provides functionality required for managing endpoint objects in
TabPy. It provides a way to download endpoint files from remote
and then properly cleanup local the endpoint files on update/remove of endpoint
objects.
The local temporary files for TabPy will by default located at
/tmp/query_objects... | """
This module provides functionality required for managing endpoint objects in
TabPy. It provides a way to download endpoint files from remote
and then properly cleanup local the endpoint files on update/remove of endpoint
objects.
The local temporary files for TabPy will by default located at
/tmp/query_objects... | |
50,268 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/common/util.py | 1,2 | 1,4 | format_exception | 2,4 | 2,4 | def format_exception(e, context):
FILL_FUNC_BODY | def format_exception(e, context):
FILL_FUNC_BODY | err_msg = f"{e.__class__.__name__} : {str(e)}"
return err_msg
| err_msg = f"{e.__class__.__name__} : {str(e)}"
return err_msg
| 7 | 20 | 32 | 52 | def format_exception(e, context):
FILL_FUNC_BODY | def format_exception(e, context):
FILL_FUNC_BODY | |
50,270 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/base_handler.py | 61,62 | 16,118 | _log_context_info | ContextLoggerWrapper | 62,88 | 62,88 | class ContextLoggerWrapper:
"""
This class appends request context to logged messages.
"""
@staticmethod
def _generate_call_id():
return str(uuid.uuid4())
def __init__(self, request: tornado.httputil.HTTPServerRequest):
self.call_id = self._generate_call_id()
self.set_r... | class ContextLoggerWrapper:
"""
This class appends request context to logged messages.
"""
@staticmethod
def _generate_call_id():
return str(uuid.uuid4())
def __init__(self, request: tornado.httputil.HTTPServerRequest):
self.call_id = self._generate_call_id()
self.set_r... | if not self.log_request_context:
return
context = f"Call ID: {self.call_id}"
if self.remote_ip is not None:
context += f", Caller: {self.remote_ip}"
if self.method is not None:
context += f", Method: {self.method}"
if self.url is not None:
... | if not self.log_request_context:
return
context = f"Call ID: {self.call_id}"
if self.remote_ip is not None:
context += f", Caller: {self.remote_ip}"
if self.method is not None:
context += f", Method: {self.method}"
if self.url is not None:
... | 76 | 654 | 255 | 909 | import base64
import binascii
import concurrent
import json
import logging
import tornado.web
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers.util import hash_password
from tabpy.tabpy_server.handlers.util import AuthErrorStates
import uuid
STAGING_THREAD = concur... | import base64
import binascii
import concurrent
import json
import logging
import tornado.web
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers.util import hash_password
from tabpy.tabpy_server.handlers.util import AuthErrorStates
import uuid
STAGING_THREAD = concur... |
50,271 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/basic_auth_server_middleware_factory.py | 13,14 | 9,16 | sending_headers | BasicAuthServerMiddleware | 14,16 | 14,16 | class BasicAuthServerMiddleware(ServerMiddleware):
def __init__(self, token):
self.token = token
def sending_headers(self):
FILL_FUNC_BODY | class BasicAuthServerMiddleware(ServerMiddleware):
def __init__(self, token):
self.token = token
def sending_headers(self):
FILL_FUNC_BODY | return {"authorization": f"Bearer {self.token}"}
| return {"authorization": f"Bearer {self.token}"}
| 4 | 51 | 20 | 71 | import base64
import secrets
from pyarrow.flight import ServerMiddlewareFactory, ServerMiddleware
from pyarrow.flight import FlightUnauthenticatedError
from tabpy.tabpy_server.handlers.util import hash_password
class BasicAuthServerMiddleware(ServerMiddleware):
def __init__(self, token):
self.token = tok... | import base64
import secrets
from pyarrow.flight import ServerMiddlewareFactory, ServerMiddleware
from pyarrow.flight import FlightUnauthenticatedError
from tabpy.tabpy_server.handlers.util import hash_password
class BasicAuthServerMiddleware(ServerMiddleware):
def __init__(self, token):
self.token = tok... |
50,272 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/basic_auth_server_middleware_factory.py | 27,28 | 16,49 | start_call | BasicAuthServerMiddlewareFactory | 28,49 | 28,49 | class BasicAuthServerMiddlewareFactory(ServerMiddlewareFactory):
def __init__(self, creds):
self.creds = creds
self.tokens = {}
def is_valid_user(self, username, password):
if username not in self.creds:
return False
hashed_pwd = hash_password(username, password)
... | class BasicAuthServerMiddlewareFactory(ServerMiddlewareFactory):
def __init__(self, creds):
self.creds = creds
self.tokens = {}
def is_valid_user(self, username, password):
if username not in self.creds:
return False
hashed_pwd = hash_password(username, password)
... | auth_header = None
for header in headers:
if header.lower() == "authorization":
auth_header = headers[header][0]
break
if not auth_header:
raise FlightUnauthenticatedError("No credentials supplied")
auth_type, _, value = a... | auth_header = None
for header in headers:
if header.lower() == "authorization":
auth_header = headers[header][0]
break
if not auth_header:
raise FlightUnauthenticatedError("No credentials supplied")
auth_type, _, value = a... | 59 | 136 | 236 | 372 | import base64
import secrets
from pyarrow.flight import ServerMiddlewareFactory, ServerMiddleware
from pyarrow.flight import FlightUnauthenticatedError
from tabpy.tabpy_server.handlers.util import hash_password
class BasicAuthServerMiddleware(ServerMiddleware):
def __init__(self, token):
self.token = tok... | import base64
import secrets
from pyarrow.flight import ServerMiddlewareFactory, ServerMiddleware
from pyarrow.flight import FlightUnauthenticatedError
from tabpy.tabpy_server.handlers.util import hash_password
class BasicAuthServerMiddleware(ServerMiddleware):
def __init__(self, token):
self.token = tok... |
50,273 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/endpoints_handler.py | 29,31 | 17,77 | post | EndpointsHandler | 31,77 | 31,77 | class EndpointsHandler(ManagementHandler):
def initialize(self, app):
super(EndpointsHandler, self).initialize(app)
def get(self):
if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
self._add_CORS_header()
s... | class EndpointsHandler(ManagementHandler):
def initialize(self, app):
super(EndpointsHandler, self).initialize(app)
def get(self):
if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
self._add_CORS_header()
s... | if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
try:
if not self.request.body:
self.error_out(400, "Input body cannot be empty")
self.finish()
return
try:
... | if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
try:
if not self.request.body:
self.error_out(400, "Input body cannot be empty")
self.finish()
return
try:
... | 110 | 142 | 511 | 653 | """
HTTP handeler to serve general endpoints request, specifically
http://myserver:9004/endpoints
For how individual endpoint requests are served look
at endpoint_handler.py
"""
import json
import logging
from tabpy.tabpy_server.common.util import format_exception
from tabpy.tabpy_server.handlers import ManagementHan... | """
HTTP handeler to serve general endpoints request, specifically
http://myserver:9004/endpoints
For how individual endpoint requests are served look
at endpoint_handler.py
"""
import json
import logging
from tabpy.tabpy_server.common.util import format_exception
from tabpy.tabpy_server.handlers import ManagementHan... |
50,274 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/management_handler.py | 16,17 | 1,151 | copy_from_local | 17,37 | 17,37 | import logging
import os
import shutil
from re import compile as _compile
from uuid import uuid4 as random_uuid
from tornado import gen
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers import BaseHandler
from tabpy.tabpy_server.handlers.base_handler import STAGING_... | import logging
import os
import shutil
from re import compile as _compile
from uuid import uuid4 as random_uuid
from tornado import gen
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers import BaseHandler
from tabpy.tabpy_server.handlers.base_handler import STAGING_... | if is_dir:
if not os.path.exists(remotepath):
# remote folder does not exist
shutil.copytree(localpath, remotepath)
else:
# remote folder exists, copy each file
src_files = os.listdir(localpath)
for file_name in src_files:
f... | if is_dir:
if not os.path.exists(remotepath):
# remote folder does not exist
shutil.copytree(localpath, remotepath)
else:
# remote folder exists, copy each file
src_files = os.listdir(localpath)
for file_name in src_files:
f... | 54 | 1,277 | 238 | 1,515 | import logging
import os
import shutil
from re import compile as _compile
from uuid import uuid4 as random_uuid
from tornado import gen
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers import BaseHandler
from tabpy.tabpy_server.handlers.base_handler import STAGING_... | import logging
import os
import shutil
from re import compile as _compile
from uuid import uuid4 as random_uuid
from tornado import gen
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers import BaseHandler
from tabpy.tabpy_server.handlers.base_handler import STAGING_... | |
50,275 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/management_handler.py | 45,47 | 37,151 | _add_or_update_endpoint | ManagementHandler | 50,144 | 47,144 | class ManagementHandler(BaseHandler):
def initialize(self, app):
super(ManagementHandler, self).initialize(app)
self.port = self.settings[SettingsParameters.Port]
def _get_protocol(self):
return "http://"
@gen.coroutine
def _add_or_update_endpoint(self, action, name, version, r... | class ManagementHandler(BaseHandler):
def initialize(self, app):
super(ManagementHandler, self).initialize(app)
self.port = self.settings[SettingsParameters.Port]
def _get_protocol(self):
return "http://"
@gen.coroutine
def _add_or_update_endpoint(self, action, name, version, r... | self.logger.log(logging.DEBUG, f"Adding/updating model {name}...")
if not isinstance(name, str):
msg = "Endpoint name must be a string"
self.logger.log(logging.CRITICAL, msg)
raise TypeError(msg)
name_checker = _compile(r"^[a-zA-Z0-9-_\s]+$")
if not ... | """
Add or update an endpoint
"""
self.logger.log(logging.DEBUG, f"Adding/updating model {name}...")
if not isinstance(name, str):
msg = "Endpoint name must be a string"
self.logger.log(logging.CRITICAL, msg)
raise TypeError(msg)
name... | 233 | 201 | 1,011 | 1,212 | import logging
import os
import shutil
from re import compile as _compile
from uuid import uuid4 as random_uuid
from tornado import gen
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers import BaseHandler
from tabpy.tabpy_server.handlers.base_handler import STAGING_... | import logging
import os
import shutil
from re import compile as _compile
from uuid import uuid4 as random_uuid
from tornado import gen
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers import BaseHandler
from tabpy.tabpy_server.handlers.base_handler import STAGING_... |
50,276 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/no_op_auth_handler.py | 7,8 | 3,9 | is_valid | NoOpAuthHandler | 8,9 | 8,9 | class NoOpAuthHandler(ServerAuthHandler):
def authenticate(self, outgoing, incoming):
pass
def is_valid(self, token):
FILL_FUNC_BODY | class NoOpAuthHandler(ServerAuthHandler):
def authenticate(self, outgoing, incoming):
pass
def is_valid(self, token):
FILL_FUNC_BODY | return ""
| return ""
| 2 | 50 | 5 | 55 | from pyarrow.flight import ServerAuthHandler
class NoOpAuthHandler(ServerAuthHandler):
def authenticate(self, outgoing, incoming):
pass
def is_valid(self, token):
FILL_FUNC_BODY | from pyarrow.flight import ServerAuthHandler
class NoOpAuthHandler(ServerAuthHandler):
def authenticate(self, outgoing, incoming):
pass
def is_valid(self, token):
FILL_FUNC_BODY |
50,279 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/service_info_handler.py | 10,11 | 6,24 | get | ServiceInfoHandler | 11,24 | 11,24 | class ServiceInfoHandler(ManagementHandler):
def initialize(self, app):
super(ServiceInfoHandler, self).initialize(app)
def get(self):
FILL_FUNC_BODY | class ServiceInfoHandler(ManagementHandler):
def initialize(self, app):
super(ServiceInfoHandler, self).initialize(app)
def get(self):
FILL_FUNC_BODY | if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
self._add_CORS_header()
info = {}
info["description"] = self.tabpy_state.get_description()
info["creation_time"] = self.tabpy_state.creation_time
inf... | if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
self._add_CORS_header()
info = {}
info["description"] = self.tabpy_state.get_description()
info["creation_time"] = self.tabpy_state.creation_time
inf... | 29 | 51 | 194 | 245 | import json
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers import ManagementHandler
from tabpy.tabpy_server.handlers.util import AuthErrorStates
class ServiceInfoHandler(ManagementHandler):
def initialize(self, app):
super(ServiceInfoHandler, self).ini... | import json
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers import ManagementHandler
from tabpy.tabpy_server.handlers.util import AuthErrorStates
class ServiceInfoHandler(ManagementHandler):
def initialize(self, app):
super(ServiceInfoHandler, self).ini... |
50,280 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/status_handler.py | 7,8 | 6,30 | initialize | StatusHandler | 8,10 | 8,10 | class StatusHandler(BaseHandler):
def initialize(self, app):
FILL_FUNC_BODY def get(self):
if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
self._add_CORS_header()
status_dict = {}
for k, v in self.python_s... | class StatusHandler(BaseHandler):
def initialize(self, app):
FILL_FUNC_BODY def get(self):
if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
self._add_CORS_header()
status_dict = {}
for k, v in self.python_s... | super(StatusHandler, self).initialize(app)
| super(StatusHandler, self).initialize(app)
| 2 | 217 | 17 | 234 | import json
import logging
from tabpy.tabpy_server.handlers import BaseHandler
from tabpy.tabpy_server.handlers.util import AuthErrorStates
class StatusHandler(BaseHandler):
def initialize(self, app):
FILL_FUNC_BODY def get(self):
if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
... | import json
import logging
from tabpy.tabpy_server.handlers import BaseHandler
from tabpy.tabpy_server.handlers.util import AuthErrorStates
class StatusHandler(BaseHandler):
def initialize(self, app):
FILL_FUNC_BODY def get(self):
if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
... |
50,281 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/upload_destination_handler.py | 11,12 | 10,22 | initialize | UploadDestinationHandler | 12,14 | 12,14 | class UploadDestinationHandler(ManagementHandler):
def initialize(self, app):
FILL_FUNC_BODY def get(self):
if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
path = self.settings[SettingsParameters.StateFilePath]
pat... | class UploadDestinationHandler(ManagementHandler):
def initialize(self, app):
FILL_FUNC_BODY def get(self):
if self.should_fail_with_auth_error() != AuthErrorStates.NONE:
self.fail_with_auth_error()
return
path = self.settings[SettingsParameters.StateFilePath]
pat... | super(UploadDestinationHandler, self).initialize(app)
| super(UploadDestinationHandler, self).initialize(app)
| 2 | 131 | 19 | 150 | from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers import ManagementHandler
import os
from tabpy.tabpy_server.handlers.util import AuthErrorStates
_QUERY_OBJECT_STAGING_FOLDER = "staging"
class UploadDestinationHandler(ManagementHandler):
def initialize(self, a... | from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.handlers import ManagementHandler
import os
from tabpy.tabpy_server.handlers.util import AuthErrorStates
_QUERY_OBJECT_STAGING_FOLDER = "staging"
class UploadDestinationHandler(ManagementHandler):
def initialize(self, a... |
50,282 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/handlers/util.py | 11,12 | 1,39 | hash_password | 33,39 | 12,39 | import binascii
from hashlib import pbkdf2_hmac
from enum import Enum, auto
class AuthErrorStates(Enum):
NONE = auto()
NotAuthorized = auto()
NotRequired = auto()
def hash_password(username, pwd):
FILL_FUNC_BODY | import binascii
from hashlib import pbkdf2_hmac
from enum import Enum, auto
class AuthErrorStates(Enum):
NONE = auto()
NotAuthorized = auto()
NotRequired = auto()
def hash_password(username, pwd):
"""
Hashes password using PKDBF2 method:
hash = PKDBF2('sha512', pwd, salt=username, 10000)
... | salt = f"_$salt@tabpy:{username.lower()}$_"
hash = pbkdf2_hmac(
hash_name="sha512", password=pwd.encode(), salt=salt.encode(), iterations=10000
)
return binascii.hexlify(hash).decode()
| """
Hashes password using PKDBF2 method:
hash = PKDBF2('sha512', pwd, salt=username, 10000)
Parameters
----------
username : str
User name (login). Used as salt for hashing.
User name is lowercased befor being used in hashing.
Salt is formatted as '_$salt@tabpy:<username... | 13 | 254 | 93 | 347 | import binascii
from hashlib import pbkdf2_hmac
from enum import Enum, auto
class AuthErrorStates(Enum):
NONE = auto()
NotAuthorized = auto()
NotRequired = auto()
def hash_password(username, pwd):
FILL_FUNC_BODY | import binascii
from hashlib import pbkdf2_hmac
from enum import Enum, auto
class AuthErrorStates(Enum):
NONE = auto()
NotAuthorized = auto()
NotRequired = auto()
def hash_password(username, pwd):
"""
Hashes password using PKDBF2 method:
hash = PKDBF2('sha512', pwd, salt=username, 10000)
... | |
50,283 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/management/util.py | 27,28 | 1,46 | _get_state_from_file | 28,46 | 28,46 | import logging
import os
try:
from ConfigParser import ConfigParser as _ConfigParser
except ImportError:
from configparser import ConfigParser as _ConfigParser
from tabpy.tabpy_server.app.app_parameters import ConfigParameters, SettingsParameters
def write_state_config(state, settings, logger=logging.getLogg... | import logging
import os
try:
from ConfigParser import ConfigParser as _ConfigParser
except ImportError:
from configparser import ConfigParser as _ConfigParser
from tabpy.tabpy_server.app.app_parameters import ConfigParameters, SettingsParameters
def write_state_config(state, settings, logger=logging.getLogg... | state_key = os.path.join(state_path, "state.ini")
tmp_state_file = state_key
if not os.path.exists(tmp_state_file):
msg = f"Missing config file at {tmp_state_file}"
logger.log(logging.CRITICAL, msg)
raise ValueError(msg)
config = _ConfigParser(allow_no_value=True)
config.op... | state_key = os.path.join(state_path, "state.ini")
tmp_state_file = state_key
if not os.path.exists(tmp_state_file):
msg = f"Missing config file at {tmp_state_file}"
logger.log(logging.CRITICAL, msg)
raise ValueError(msg)
config = _ConfigParser(allow_no_value=True)
config.op... | 49 | 278 | 212 | 490 | import logging
import os
try:
from ConfigParser import ConfigParser as _ConfigParser
except ImportError:
from configparser import ConfigParser as _ConfigParser
from tabpy.tabpy_server.app.app_parameters import ConfigParameters, SettingsParameters
def write_state_config(state, settings, logger=logging.getLogg... | import logging
import os
try:
from ConfigParser import ConfigParser as _ConfigParser
except ImportError:
from configparser import ConfigParser as _ConfigParser
from tabpy.tabpy_server.app.app_parameters import ConfigParameters, SettingsParameters
def write_state_config(state, settings, logger=logging.getLogg... | |
50,284 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/psws/callbacks.py | 92,93 | 1,206 | _get_latest_service_state | 102,139 | 93,139 | import logging
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.common.messages import (
LoadObject,
DeleteObjects,
ListObjects,
ObjectList,
)
from tabpy.tabpy_server.common.endpoint_file_mgr import cleanup_endpoint_files
from tabpy.tabpy_server.common.util im... | import logging
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.common.messages import (
LoadObject,
DeleteObjects,
ListObjects,
ObjectList,
)
from tabpy.tabpy_server.common.endpoint_file_mgr import cleanup_endpoint_files
from tabpy.tabpy_server.common.util im... | # Shortcut when nothing is changed
changes = {"endpoints": {}}
# update endpoints
new_endpoints = new_ps_state.get_endpoints()
diff = {}
current_endpoints = python_service.ps.query_objects
for (endpoint_name, endpoint_info) in new_endpoints.items():
existing_endpoint = current_endpo... | """
Update the endpoints from the latest remote state file.
Returns
--------
(has_changes, endpoint_diff):
has_changes: True or False
endpoint_diff: Summary of what has changed, one entry for each changes
"""
# Shortcut when nothing is changed
changes = {"endpoints": {}}... | 99 | 1,547 | 402 | 1,949 | import logging
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.common.messages import (
LoadObject,
DeleteObjects,
ListObjects,
ObjectList,
)
from tabpy.tabpy_server.common.endpoint_file_mgr import cleanup_endpoint_files
from tabpy.tabpy_server.common.util im... | import logging
from tabpy.tabpy_server.app.app_parameters import SettingsParameters
from tabpy.tabpy_server.common.messages import (
LoadObject,
DeleteObjects,
ListObjects,
ObjectList,
)
from tabpy.tabpy_server.common.endpoint_file_mgr import cleanup_endpoint_files
from tabpy.tabpy_server.common.util im... | |
50,285 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/psws/python_service.py | 85,88 | 64,276 | _load_object | PythonService | 88,122 | 88,122 | class PythonService:
"""
This class is a simple wrapper maintaining loaded query objects from
the current TabPy instance. `query_objects` is a dictionary that
maps query object URI to query objects
The query_objects schema is as follow:
{'version': <current-successfuly-loaded-version>,
'l... | class PythonService:
"""
This class is a simple wrapper maintaining loaded query objects from
the current TabPy instance. `query_objects` is a dictionary that
maps query object URI to query objects
The query_objects schema is as follow:
{'version': <current-successfuly-loaded-version>,
'l... | try:
logger.info(
f"Loading object:, URI={object_uri}, "
f"URL={object_url}, version={object_version}, "
f"is_updated={is_update}"
)
if object_type == "model":
po = QueryObject.load(object_url)
elif o... | try:
logger.info(
f"Loading object:, URI={object_uri}, "
f"URL={object_url}, version={object_version}, "
f"is_updated={is_update}"
)
if object_type == "model":
po = QueryObject.load(object_url)
elif o... | 75 | 1,660 | 349 | 2,009 | import concurrent.futures
import logging
from tabpy.tabpy_server.common.util import format_exception
from tabpy.tabpy_server.common.messages import (
LoadObject,
DeleteObjects,
FlushObjects,
CountObjects,
ListObjects,
UnknownMessage,
LoadFailed,
ObjectsDeleted,
ObjectsFlushed,
Qu... | import concurrent.futures
import logging
from tabpy.tabpy_server.common.util import format_exception
from tabpy.tabpy_server.common.messages import (
LoadObject,
DeleteObjects,
FlushObjects,
CountObjects,
ListObjects,
UnknownMessage,
LoadFailed,
ObjectsDeleted,
ObjectsFlushed,
Qu... |
50,286 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_server/psws/python_service.py | 37,38 | 28,64 | manage_request | PythonServiceHandler | 38,64 | 38,64 | class PythonServiceHandler:
"""
A wrapper around PythonService object that receives requests and calls the
corresponding methods.
"""
def __init__(self, ps):
self.ps = ps
def manage_request(self, msg):
FILL_FUNC_BODY | class PythonServiceHandler:
"""
A wrapper around PythonService object that receives requests and calls the
corresponding methods.
"""
def __init__(self, ps):
self.ps = ps
def manage_request(self, msg):
FILL_FUNC_BODY | try:
logger.debug(f"Received request {type(msg).__name__}")
if isinstance(msg, LoadObject):
response = self.ps.load_object(*msg)
elif isinstance(msg, DeleteObjects):
response = self.ps.delete_objects(msg.uris)
elif isinstance(msg, F... | try:
logger.debug(f"Received request {type(msg).__name__}")
if isinstance(msg, LoadObject):
response = self.ps.load_object(*msg)
elif isinstance(msg, DeleteObjects):
response = self.ps.delete_objects(msg.uris)
elif isinstance(msg, F... | 63 | 71 | 272 | 343 | import concurrent.futures
import logging
from tabpy.tabpy_server.common.util import format_exception
from tabpy.tabpy_server.common.messages import (
LoadObject,
DeleteObjects,
FlushObjects,
CountObjects,
ListObjects,
UnknownMessage,
LoadFailed,
ObjectsDeleted,
ObjectsFlushed,
Qu... | import concurrent.futures
import logging
from tabpy.tabpy_server.common.util import format_exception
from tabpy.tabpy_server.common.messages import (
LoadObject,
DeleteObjects,
FlushObjects,
CountObjects,
ListObjects,
UnknownMessage,
LoadFailed,
ObjectsDeleted,
ObjectsFlushed,
Qu... |
50,287 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_tools/custom_query_object.py | 72,73 | 8,84 | get_doc_string | CustomQueryObject | 74,79 | 73,79 | class CustomQueryObject(_QueryObject):
def __init__(self, query, description=""):
"""Create a new CustomQueryObject.
Parameters
-----------
query : function
Function that defines a custom query method. The query can have any
signature, but input and output o... | class CustomQueryObject(_QueryObject):
def __init__(self, query, description=""):
"""Create a new CustomQueryObject.
Parameters
-----------
query : function
Function that defines a custom query method. The query can have any
signature, but input and output o... | if self.custom_query.__doc__ is not None:
return self.custom_query.__doc__
else:
return "-- no docstring found in query function --"
| """Get doc string from customized query"""
if self.custom_query.__doc__ is not None:
return self.custom_query.__doc__
else:
return "-- no docstring found in query function --"
| 17 | 498 | 50 | 548 | import logging
from .query_object import QueryObject as _QueryObject
logger = logging.getLogger(__name__)
class CustomQueryObject(_QueryObject):
def __init__(self, query, description=""):
"""Create a new CustomQueryObject.
Parameters
-----------
query : function
Fun... | import logging
from .query_object import QueryObject as _QueryObject
logger = logging.getLogger(__name__)
class CustomQueryObject(_QueryObject):
def __init__(self, query, description=""):
"""Create a new CustomQueryObject.
Parameters
-----------
query : function
Fun... |
50,288 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_tools/query_object.py | 73,75 | 13,109 | load | QueryObject | 77,84 | 75,84 | class QueryObject(abc.ABC):
"""
Derived class needs to implement the following interface:
* query() -- given input, return query result
* get_doc_string() -- returns documentation for the Query Object
"""
def __init__(self, description=""):
self.description = description
def ge... | class QueryObject(abc.ABC):
"""
Derived class needs to implement the following interface:
* query() -- given input, return query result
* get_doc_string() -- returns documentation for the Query Object
"""
def __init__(self, description=""):
self.description = description
def ge... | new_po = None
new_po = cls._load_local(path)
logger.info(f'Loaded query object "{type(new_po).__name__}" successfully')
return new_po
| """ Load query object from given path
"""
new_po = None
new_po = cls._load_local(path)
logger.info(f'Loaded query object "{type(new_po).__name__}" successfully')
return new_po
| 13 | 713 | 64 | 777 | import abc
import logging
import os
import json
import shutil
import cloudpickle as _cloudpickle
logger = logging.getLogger(__name__)
class QueryObject(abc.ABC):
"""
Derived class needs to implement the following interface:
* query() -- given input, return query result
* get_doc_string() -- ret... | import abc
import logging
import os
import json
import shutil
import cloudpickle as _cloudpickle
logger = logging.getLogger(__name__)
class QueryObject(abc.ABC):
"""
Derived class needs to implement the following interface:
* query() -- given input, return query result
* get_doc_string() -- ret... |
50,289 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_tools/rest_client.py | 12,13 | 1,253 | to_epoch | 13,16 | 13,16 | from .rest import RESTObject, RESTProperty
from datetime import datetime
def from_epoch(value):
if isinstance(value, datetime):
return value
else:
return datetime.utcfromtimestamp(value)
def to_epoch(value):
FILL_FUNC_BODYclass Endpoint(RESTObject):
"""Represents an endpoint.
Note t... | from .rest import RESTObject, RESTProperty
from datetime import datetime
def from_epoch(value):
if isinstance(value, datetime):
return value
else:
return datetime.utcfromtimestamp(value)
def to_epoch(value):
FILL_FUNC_BODYclass Endpoint(RESTObject):
"""Represents an endpoint.
Note t... | return (value - datetime(1970, 1, 1)).total_seconds()
| return (value - datetime(1970, 1, 1)).total_seconds()
| 6 | 1,857 | 28 | 1,885 | from .rest import RESTObject, RESTProperty
from datetime import datetime
def from_epoch(value):
if isinstance(value, datetime):
return value
else:
return datetime.utcfromtimestamp(value)
def to_epoch(value):
FILL_FUNC_BODYclass Endpoint(RESTObject):
"""Represents an endpoint.
Note t... | from .rest import RESTObject, RESTProperty
from datetime import datetime
def from_epoch(value):
if isinstance(value, datetime):
return value
else:
return datetime.utcfromtimestamp(value)
def to_epoch(value):
FILL_FUNC_BODYclass Endpoint(RESTObject):
"""Represents an endpoint.
Note t... | |
50,290 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_tools/rest_client.py | 136,137 | 125,253 | query | RESTServiceClient | 139,148 | 137,148 | class RESTServiceClient:
"""A thin client for the REST Service."""
def __init__(self, service_client):
self.service_client = service_client
self.query_timeout = None
def get_info(self):
"""Returns the /info"""
return self.service_client.GET("info")
def query(self, name... | class RESTServiceClient:
"""A thin client for the REST Service."""
def __init__(self, service_client):
self.service_client = service_client
self.query_timeout = None
def get_info(self):
"""Returns the /info"""
return self.service_client.GET("info")
def query(self, name... | if args and kwargs:
raise ValueError(
"Mixing of keyword arguments and positional arguments when "
"querying an endpoint is not supported."
)
return self.service_client.POST(
"query/" + name, data={"data": args or kwargs}, timeout=self.... | """Performs a query. Either specify *args or **kwargs, not both.
Respects query_timeout."""
if args and kwargs:
raise ValueError(
"Mixing of keyword arguments and positional arguments when "
"querying an endpoint is not supported."
)
... | 33 | 874 | 93 | 967 | from .rest import RESTObject, RESTProperty
from datetime import datetime
def from_epoch(value):
if isinstance(value, datetime):
return value
else:
return datetime.utcfromtimestamp(value)
def to_epoch(value):
return (value - datetime(1970, 1, 1)).total_seconds()
class Endpoint(RESTObjec... | from .rest import RESTObject, RESTProperty
from datetime import datetime
def from_epoch(value):
if isinstance(value, datetime):
return value
else:
return datetime.utcfromtimestamp(value)
def to_epoch(value):
return (value - datetime(1970, 1, 1)).total_seconds()
class Endpoint(RESTObjec... |
50,291 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/tabpy_tools/schema.py | 9,10 | 1,109 | _generate_schema_from_example_and_description | 15,53 | 10,53 | import logging
import genson
import jsonschema
logger = logging.getLogger(__name__)
def _generate_schema_from_example_and_description(input, description):
FILL_FUNC_BODYdef generate_schema(input, output, input_description=None, output_description=None):
"""
Generate schema from a given sample input and outp... | import logging
import genson
import jsonschema
logger = logging.getLogger(__name__)
def _generate_schema_from_example_and_description(input, description):
"""
With an example input, a schema is automatically generated that conforms
to the example in json-schema.org. The description given by the users
... | s = genson.SchemaBuilder(None)
s.add_object(input)
input_schema = s.to_schema()
if description is not None:
if "properties" in input_schema:
# Case for input = {'x':1}, input_description='not a dict'
if not isinstance(description, dict):
msg = f"{input} a... | """
With an example input, a schema is automatically generated that conforms
to the example in json-schema.org. The description given by the users
is then added to the schema.
"""
s = genson.SchemaBuilder(None)
s.add_object(input)
input_schema = s.to_schema()
if description is not N... | 119 | 707 | 390 | 1,097 | import logging
import genson
import jsonschema
logger = logging.getLogger(__name__)
def _generate_schema_from_example_and_description(input, description):
FILL_FUNC_BODYdef generate_schema(input, output, input_description=None, output_description=None):
"""
Generate schema from a given sample input and outp... | import logging
import genson
import jsonschema
logger = logging.getLogger(__name__)
def _generate_schema_from_example_and_description(input, description):
"""
With an example input, a schema is automatically generated that conforms
to the example in json-schema.org. The description given by the users
... | |
50,292 | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy | /home/hieuvd/dung_repo/raw/stars_03/tableau_TabPy/TabPy/tabpy/utils/tabpy_user.py | 90,91 | 1,135 | update_user | 91,107 | 91,107 | """
Utility for managing user names and passwords for TabPy.
For more information about how to configure and use authentication for
TabPy read the documentation at https://github.com/tableau/TabPy.
Usage:
tabpy-user add (-u NAME | --user <NAME>) [-p PWD | --password PWD] (-f FILE | --pwdfile FILE)
tabpy-user updat... | """
Utility for managing user names and passwords for TabPy.
For more information about how to configure and use authentication for
TabPy read the documentation at https://github.com/tableau/TabPy.
Usage:
tabpy-user add (-u NAME | --user <NAME>) [-p PWD | --password PWD] (-f FILE | --pwdfile FILE)
tabpy-user updat... | username = args["--username"].lower()
logger.info(f'Updating username "{username}"')
if username not in credentials:
logger.error(
f'Username "{username}" not found in passwords file. '
'Do you want to run "add" command instead?'
)
return False
password ... | username = args["--username"].lower()
logger.info(f'Updating username "{username}"')
if username not in credentials:
logger.error(
f'Username "{username}" not found in passwords file. '
'Do you want to run "add" command instead?'
)
return False
password ... | 47 | 1,146 | 168 | 1,314 | """
Utility for managing user names and passwords for TabPy.
For more information about how to configure and use authentication for
TabPy read the documentation at https://github.com/tableau/TabPy.
Usage:
tabpy-user add (-u NAME | --user <NAME>) [-p PWD | --password PWD] (-f FILE | --pwdfile FILE)
tabpy-user updat... | """
Utility for managing user names and passwords for TabPy.
For more information about how to configure and use authentication for
TabPy read the documentation at https://github.com/tableau/TabPy.
Usage:
tabpy-user add (-u NAME | --user <NAME>) [-p PWD | --password PWD] (-f FILE | --pwdfile FILE)
tabpy-user updat... | |
50,390 | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/tasks/specs.py | 39,40 | 1,51 | generate_spectask | 40,47 | 40,47 | import invoke
import os
class Rubyspecs:
def __init__(self, files, options, untranslated=False):
self.exe = "`pwd`/bin/%s" % (
"topaz_untranslated.py" if untranslated else "topaz")
self.files = files
self.options = options
def mspec(self, args):
invoke.run(
... | import invoke
import os
class Rubyspecs:
def __init__(self, files, options, untranslated=False):
self.exe = "`pwd`/bin/%s" % (
"topaz_untranslated.py" if untranslated else "topaz")
self.files = files
self.options = options
def mspec(self, args):
invoke.run(
... | def spectask(ctx, files="", options="", untranslated=False):
runner = Rubyspecs(files, options, untranslated=untranslated)
getattr(runner, taskname)()
spectask.__name__ = taskname
return invoke.task(spectask)
| def spectask(ctx, files="", options="", untranslated=False):
runner = Rubyspecs(files, options, untranslated=untranslated)
getattr(runner, taskname)()
spectask.__name__ = taskname
return invoke.task(spectask)
| 17 | 446 | 83 | 529 | import invoke
import os
class Rubyspecs:
def __init__(self, files, options, untranslated=False):
self.exe = "`pwd`/bin/%s" % (
"topaz_untranslated.py" if untranslated else "topaz")
self.files = files
self.options = options
def mspec(self, args):
invoke.run(
... | import invoke
import os
class Rubyspecs:
def __init__(self, files, options, untranslated=False):
self.exe = "`pwd`/bin/%s" % (
"topaz_untranslated.py" if untranslated else "topaz")
self.files = files
self.options = options
def mspec(self, args):
invoke.run(
... | |
50,391 | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/tasks/specs.py | 26,27 | 5,39 | retag | Rubyspecs | 27,39 | 27,39 | class Rubyspecs:
def __init__(self, files, options, untranslated=False):
self.exe = "`pwd`/bin/%s" % (
"topaz_untranslated.py" if untranslated else "topaz")
self.files = files
self.options = options
def mspec(self, args):
invoke.run(
"spec/mspec/bin/mspec... | class Rubyspecs:
def __init__(self, files, options, untranslated=False):
self.exe = "`pwd`/bin/%s" % (
"topaz_untranslated.py" if untranslated else "topaz")
self.files = files
self.options = options
def mspec(self, args):
invoke.run(
"spec/mspec/bin/mspec... | assert len(self.files) == 0, "retag task mustn't get a file list"
for d in ["core", "command_line", "language", "library"]:
for dirname, subdirlist, files in os.walk(
"spec/rubyspec/%s/" % d):
for f in files:
if f.endswith("_spec.rb"):
... | assert len(self.files) == 0, "retag task mustn't get a file list"
for d in ["core", "command_line", "language", "library"]:
for dirname, subdirlist, files in os.walk(
"spec/rubyspec/%s/" % d):
for f in files:
if f.endswith("_spec.rb"):
... | 39 | 260 | 136 | 396 | import invoke
import os
class Rubyspecs:
def __init__(self, files, options, untranslated=False):
self.exe = "`pwd`/bin/%s" % (
"topaz_untranslated.py" if untranslated else "topaz")
self.files = files
self.options = options
def mspec(self, args):
invoke.run(
... | import invoke
import os
class Rubyspecs:
def __init__(self, files, options, untranslated=False):
self.exe = "`pwd`/bin/%s" % (
"topaz_untranslated.py" if untranslated else "topaz")
self.files = files
self.options = options
def mspec(self, args):
invoke.run(
... |
50,392 | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/tasks/travis.py | 95,97 | 1,177 | untag_specs | 97,103 | 97,103 | import glob
import os
import struct
import sys
import invoke
import requests
if os.environ.get('TRAVIS_OS_NAME') == 'osx':
invoke.run = os.system
class Test:
def __init__(self, func, deps=[], needs_rpython=True, create_build=False):
self.func = func
self.deps = deps
self.needs_rpytho... | import glob
import os
import struct
import sys
import invoke
import requests
if os.environ.get('TRAVIS_OS_NAME') == 'osx':
invoke.run = os.system
class Test:
def __init__(self, func, deps=[], needs_rpython=True, create_build=False):
self.func = func
self.deps = deps
self.needs_rpytho... | invoke.run("""\
spec/mspec/bin/mspec tag --del fails -t {} -f spec\
--config=topaz.mspec {}\
""".format("`pwd`/bin/topaz", files))
| invoke.run("""\
spec/mspec/bin/mspec tag --del fails -t {} -f spec\
--config=topaz.mspec {}\
""".format("`pwd`/bin/topaz", files))
| 13 | 1,872 | 68 | 1,940 | import glob
import os
import struct
import sys
import invoke
import requests
if os.environ.get('TRAVIS_OS_NAME') == 'osx':
invoke.run = os.system
class Test:
def __init__(self, func, deps=[], needs_rpython=True, create_build=False):
self.func = func
self.deps = deps
self.needs_rpytho... | import glob
import os
import struct
import sys
import invoke
import requests
if os.environ.get('TRAVIS_OS_NAME') == 'osx':
invoke.run = os.system
class Test:
def __init__(self, func, deps=[], needs_rpython=True, create_build=False):
self.func = func
self.deps = deps
self.needs_rpytho... | |
50,393 | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/tasks/travis.py | 23,24 | 13,73 | download_rpython | Test | 24,36 | 24,36 | class Test:
def __init__(self, func, deps=[], needs_rpython=True, create_build=False):
self.func = func
self.deps = deps
self.needs_rpython = needs_rpython
self.create_build = create_build
def install_deps(self):
invoke.run("pip install {}".format(" ".join(self.deps)))
... | class Test:
def __init__(self, func, deps=[], needs_rpython=True, create_build=False):
self.func = func
self.deps = deps
self.needs_rpython = needs_rpython
self.create_build = create_build
def install_deps(self):
invoke.run("pip install {}".format(" ".join(self.deps)))
... | invoke.run(
"wget https://bitbucket.org/pypy/pypy/get/default.tar.bz2"
" -O `pwd`/../pypy.tar.bz2 ||"
"wget https://bitbucket.org/pypy/pypy/get/default.tar.bz2"
" -O `pwd`/../pypy.tar.bz2"
)
invoke.run("tar -xf `pwd`/../pypy.tar.bz2 -C `pwd`/../")
... | invoke.run(
"wget https://bitbucket.org/pypy/pypy/get/default.tar.bz2"
" -O `pwd`/../pypy.tar.bz2 ||"
"wget https://bitbucket.org/pypy/pypy/get/default.tar.bz2"
" -O `pwd`/../pypy.tar.bz2"
)
invoke.run("tar -xf `pwd`/../pypy.tar.bz2 -C `pwd`/../")
... | 30 | 550 | 227 | 777 | import glob
import os
import struct
import sys
import invoke
import requests
if os.environ.get('TRAVIS_OS_NAME') == 'osx':
invoke.run = os.system
class Test:
def __init__(self, func, deps=[], needs_rpython=True, create_build=False):
self.func = func
self.deps = deps
self.needs_rpytho... | import glob
import os
import struct
import sys
import invoke
import requests
if os.environ.get('TRAVIS_OS_NAME') == 'osx':
invoke.run = os.system
class Test:
def __init__(self, func, deps=[], needs_rpython=True, create_build=False):
self.func = func
self.deps = deps
self.needs_rpytho... |
50,394 | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/closure.py | 35,36 | 25,39 | upgrade_to_closure | ClosureCell | 36,39 | 36,39 | class ClosureCell(BaseCell):
def __init__(self, w_value):
self.w_value = w_value
def get(self, space, frame, pos):
return self.w_value
def set(self, space, frame, pos, w_value):
self.w_value = w_value
def upgrade_to_closure(self, space, frame, pos):
FILL_FUNC_BODY | class ClosureCell(BaseCell):
def __init__(self, w_value):
self.w_value = w_value
def get(self, space, frame, pos):
return self.w_value
def set(self, space, frame, pos, w_value):
self.w_value = w_value
def upgrade_to_closure(self, space, frame, pos):
FILL_FUNC_BODY | return self
| return self
| 2 | 112 | 9 | 121 | from topaz.objects.objectobject import W_Root
from topaz.objects.intobject import W_FixnumObject, W_MutableFixnumObject
class BaseCell(W_Root):
pass
class LocalCell(BaseCell):
def get(self, space, frame, pos):
return frame.localsstack_w[pos]
def set(self, space, frame, pos, w_value):
fr... | from topaz.objects.objectobject import W_Root
from topaz.objects.intobject import W_FixnumObject, W_MutableFixnumObject
class BaseCell(W_Root):
pass
class LocalCell(BaseCell):
def get(self, space, frame, pos):
return frame.localsstack_w[pos]
def set(self, space, frame, pos, w_value):
fr... |
50,395 | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/closure.py | 43,44 | 39,55 | set | IntCell | 44,49 | 44,49 | class IntCell(ClosureCell):
def __init__(self, intvalue):
ClosureCell.__init__(self, W_MutableFixnumObject(None, intvalue))
def set(self, space, frame, pos, w_value):
FILL_FUNC_BODY def get(self, space, frame, pos):
w_value = self.w_value
if isinstance(w_value, W_MutableFixnumObject)... | class IntCell(ClosureCell):
def __init__(self, intvalue):
ClosureCell.__init__(self, W_MutableFixnumObject(None, intvalue))
def set(self, space, frame, pos, w_value):
FILL_FUNC_BODY def get(self, space, frame, pos):
w_value = self.w_value
if isinstance(w_value, W_MutableFixnumObject)... | if isinstance(w_value, W_FixnumObject):
self.w_value.set_intvalue(w_value.intvalue)
else:
ClosureCell.set(self, space, frame, pos, w_value)
| if isinstance(w_value, W_FixnumObject):
self.w_value.set_intvalue(w_value.intvalue)
else:
ClosureCell.set(self, space, frame, pos, w_value)
| 10 | 143 | 67 | 210 | from topaz.objects.objectobject import W_Root
from topaz.objects.intobject import W_FixnumObject, W_MutableFixnumObject
class BaseCell(W_Root):
pass
class LocalCell(BaseCell):
def get(self, space, frame, pos):
return frame.localsstack_w[pos]
def set(self, space, frame, pos, w_value):
fr... | from topaz.objects.objectobject import W_Root
from topaz.objects.intobject import W_FixnumObject, W_MutableFixnumObject
class BaseCell(W_Root):
pass
class LocalCell(BaseCell):
def get(self, space, frame, pos):
return frame.localsstack_w[pos]
def set(self, space, frame, pos, w_value):
fr... |
50,396 | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz | /home/hieuvd/dung_repo/raw/stars_03/topazproject_topaz/topaz/topaz/closure.py | 16,17 | 9,25 | upgrade_to_closure | LocalCell | 17,25 | 17,25 | class LocalCell(BaseCell):
def get(self, space, frame, pos):
return frame.localsstack_w[pos]
def set(self, space, frame, pos, w_value):
frame.localsstack_w[pos] = w_value
def upgrade_to_closure(self, space, frame, pos):
FILL_FUNC_BODY | class LocalCell(BaseCell):
def get(self, space, frame, pos):
return frame.localsstack_w[pos]
def set(self, space, frame, pos, w_value):
frame.localsstack_w[pos] = w_value
def upgrade_to_closure(self, space, frame, pos):
FILL_FUNC_BODY | w_obj = self.get(space, frame, pos)
if isinstance(w_obj, W_FixnumObject):
frame.cells[pos] = result = IntCell(space.int_w(w_obj))
else:
frame.cells[pos] = result = ClosureCell(w_obj)
return result
| w_obj = self.get(space, frame, pos)
if isinstance(w_obj, W_FixnumObject):
frame.cells[pos] = result = IntCell(space.int_w(w_obj))
else:
frame.cells[pos] = result = ClosureCell(w_obj)
return result
| 21 | 96 | 96 | 192 | from topaz.objects.objectobject import W_Root
from topaz.objects.intobject import W_FixnumObject, W_MutableFixnumObject
class BaseCell(W_Root):
pass
class LocalCell(BaseCell):
def get(self, space, frame, pos):
return frame.localsstack_w[pos]
def set(self, space, frame, pos, w_value):
fr... | from topaz.objects.objectobject import W_Root
from topaz.objects.intobject import W_FixnumObject, W_MutableFixnumObject
class BaseCell(W_Root):
pass
class LocalCell(BaseCell):
def get(self, space, frame, pos):
return frame.localsstack_w[pos]
def set(self, space, frame, pos, w_value):
fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.