repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
eight04/pyAPNG
apng/__init__.py
read_file
python
def read_file(file): if hasattr(file, "read"): return file.read() if hasattr(file, "read_bytes"): return file.read_bytes() with open(file, "rb") as f: return f.read()
Read ``file`` into ``bytes``. :arg file type: path-like or file-like :rtype: bytes
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L113-L124
null
#! python3 """This is an APNG module, which can create apng file from pngs Reference: http://littlesvr.ca/apng/ http://wiki.mozilla.org/APNG_Specification https://www.w3.org/TR/PNG/ """ import struct import binascii import io import zlib from collections import namedtuple __version__ = "0.3.3" PNG_SIGN = b"\x89\x5...
eight04/pyAPNG
apng/__init__.py
write_file
python
def write_file(file, b): if hasattr(file, "write_bytes"): file.write_bytes(b) elif hasattr(file, "write"): file.write(b) else: with open(file, "wb") as f: f.write(b)
Write ``b`` to file ``file``. :arg file type: path-like or file-like object. :arg bytes b: The content.
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L126-L138
null
#! python3 """This is an APNG module, which can create apng file from pngs Reference: http://littlesvr.ca/apng/ http://wiki.mozilla.org/APNG_Specification https://www.w3.org/TR/PNG/ """ import struct import binascii import io import zlib from collections import namedtuple __version__ = "0.3.3" PNG_SIGN = b"\x89\x5...
eight04/pyAPNG
apng/__init__.py
open_file
python
def open_file(file, mode): if hasattr(file, "read"): return file if hasattr(file, "open"): return file.open(mode) return open(file, mode)
Open a file. :arg file: file-like or path-like object. :arg str mode: ``mode`` argument for :func:`open`.
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L140-L150
null
#! python3 """This is an APNG module, which can create apng file from pngs Reference: http://littlesvr.ca/apng/ http://wiki.mozilla.org/APNG_Specification https://www.w3.org/TR/PNG/ """ import struct import binascii import io import zlib from collections import namedtuple __version__ = "0.3.3" PNG_SIGN = b"\x89\x5...
eight04/pyAPNG
apng/__init__.py
file_to_png
python
def file_to_png(fp): import PIL.Image # pylint: disable=import-error with io.BytesIO() as dest: PIL.Image.open(fp).save(dest, "PNG", optimize=True) return dest.getvalue()
Convert an image to PNG format with Pillow. :arg file-like fp: The image file. :rtype: bytes
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L152-L161
null
#! python3 """This is an APNG module, which can create apng file from pngs Reference: http://littlesvr.ca/apng/ http://wiki.mozilla.org/APNG_Specification https://www.w3.org/TR/PNG/ """ import struct import binascii import io import zlib from collections import namedtuple __version__ = "0.3.3" PNG_SIGN = b"\x89\x5...
eight04/pyAPNG
apng/__init__.py
PNG.init
python
def init(self): for type_, data in self.chunks: if type_ == "IHDR": self.hdr = data elif type_ == "IEND": self.end = data if self.hdr: # grab w, h info self.width, self.height = struct.unpack("!II", self.hdr[8:16])
Extract some info from chunks
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L185-L195
null
class PNG: """Represent a PNG image. """ def __init__(self): self.hdr = None self.end = None self.width = None self.height = None self.chunks = [] """A list of :class:`Chunk`. After reading a PNG file, the bytes are parsed into multiple chunks. You can remove/add chunks into this array before calling...
eight04/pyAPNG
apng/__init__.py
PNG.open_any
python
def open_any(cls, file): with open_file(file, "rb") as f: header = f.read(8) f.seek(0) if header != PNG_SIGN: b = file_to_png(f) else: b = f.read() return cls.from_bytes(b)
Open an image file. If the image is not PNG format, it would convert the image into PNG with Pillow module. If the module is not installed, :class:`ImportError` would be raised. :arg file: Input file. :type file: path-like or file-like :rtype: :class:`PNG`
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L208-L224
[ "def open_file(file, mode):\n\t\"\"\"Open a file.\n\n\t:arg file: file-like or path-like object.\n\t:arg str mode: ``mode`` argument for :func:`open`.\n\t\"\"\"\n\tif hasattr(file, \"read\"):\n\t\treturn file\n\tif hasattr(file, \"open\"):\n\t\treturn file.open(mode)\n\treturn open(file, mode)\n", "def from_bytes...
class PNG: """Represent a PNG image. """ def __init__(self): self.hdr = None self.end = None self.width = None self.height = None self.chunks = [] """A list of :class:`Chunk`. After reading a PNG file, the bytes are parsed into multiple chunks. You can remove/add chunks into this array before calling...
eight04/pyAPNG
apng/__init__.py
PNG.from_bytes
python
def from_bytes(cls, b): im = cls() im.chunks = list(parse_chunks(b)) im.init() return im
Create :class:`PNG` from raw bytes. :arg bytes b: The raw bytes of the PNG file. :rtype: :class:`PNG`
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L227-L236
[ "def parse_chunks(b):\n\t\"\"\"Parse PNG bytes into multiple chunks. \n\n\t:arg bytes b: The raw bytes of the PNG file.\n\t:return: A generator yielding :class:`Chunk`.\n\t:rtype: Iterator[Chunk]\n\t\"\"\"\n\t# skip signature\n\ti = 8\n\t# yield chunks\n\twhile i < len(b):\n\t\tdata_len, = struct.unpack(\"!I\", b[i...
class PNG: """Represent a PNG image. """ def __init__(self): self.hdr = None self.end = None self.width = None self.height = None self.chunks = [] """A list of :class:`Chunk`. After reading a PNG file, the bytes are parsed into multiple chunks. You can remove/add chunks into this array before calling...
eight04/pyAPNG
apng/__init__.py
PNG.from_chunks
python
def from_chunks(cls, chunks): im = cls() im.chunks = chunks im.init() return im
Construct PNG from raw chunks. :arg chunks: A list of ``(chunk_type, chunk_raw_data)``. Also see :func:`chunks`. :type chunks: list[tuple(str, bytes)]
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L239-L249
null
class PNG: """Represent a PNG image. """ def __init__(self): self.hdr = None self.end = None self.width = None self.height = None self.chunks = [] """A list of :class:`Chunk`. After reading a PNG file, the bytes are parsed into multiple chunks. You can remove/add chunks into this array before calling...
eight04/pyAPNG
apng/__init__.py
PNG.to_bytes
python
def to_bytes(self): chunks = [PNG_SIGN] chunks.extend(c[1] for c in self.chunks) return b"".join(chunks)
Convert the entire image to bytes. :rtype: bytes
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L252-L259
null
class PNG: """Represent a PNG image. """ def __init__(self): self.hdr = None self.end = None self.width = None self.height = None self.chunks = [] """A list of :class:`Chunk`. After reading a PNG file, the bytes are parsed into multiple chunks. You can remove/add chunks into this array before calling...
eight04/pyAPNG
apng/__init__.py
FrameControl.to_bytes
python
def to_bytes(self): return struct.pack( "!IIIIHHbb", self.width, self.height, self.x_offset, self.y_offset, self.delay, self.delay_den, self.depose_op, self.blend_op )
Convert to bytes. :rtype: bytes
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L287-L295
null
class FrameControl: """A data class holding fcTL info.""" def __init__(self, width=None, height=None, x_offset=0, y_offset=0, delay=100, delay_den=1000, depose_op=1, blend_op=0): """Parameters are assigned as object members. See `https://wiki.mozilla.org/APNG_Specification <https://wiki.mozilla.org/APNG_Spe...
eight04/pyAPNG
apng/__init__.py
APNG.append
python
def append(self, png, **options): if not isinstance(png, PNG): raise TypeError("Expect an instance of `PNG` but got `{}`".format(png)) control = FrameControl(**options) if control.width is None: control.width = png.width if control.height is None: control.height = png.height self.frames.append((png, ...
Append one frame. :arg PNG png: Append a :class:`PNG` as a frame. :arg dict options: The options for :class:`FrameControl`.
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L321-L334
null
class APNG: """Represent an APNG image.""" def __init__(self, num_plays=0): """An :class:`APNG` is composed by multiple :class:`PNG` s and :class:`FrameControl`, which can be inserted with :meth:`append`. :arg int num_plays: Number of times to loop. 0 = infinite. :var frames: The frames of APNG. :vartype ...
eight04/pyAPNG
apng/__init__.py
APNG.append_file
python
def append_file(self, file, **options): self.append(PNG.open_any(file), **options)
Create a PNG from file and append the PNG as a frame. :arg file: Input file. :type file: path-like or file-like. :arg dict options: The options for :class:`FrameControl`.
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L336-L343
[ "def open_any(cls, file):\n\t\"\"\"Open an image file. If the image is not PNG format, it would convert\n\tthe image into PNG with Pillow module. If the module is not\n\tinstalled, :class:`ImportError` would be raised.\n\n\t:arg file: Input file.\n\t:type file: path-like or file-like\n\t:rtype: :class:`PNG`\n\t\"\"...
class APNG: """Represent an APNG image.""" def __init__(self, num_plays=0): """An :class:`APNG` is composed by multiple :class:`PNG` s and :class:`FrameControl`, which can be inserted with :meth:`append`. :arg int num_plays: Number of times to loop. 0 = infinite. :var frames: The frames of APNG. :vartype ...
eight04/pyAPNG
apng/__init__.py
APNG.to_bytes
python
def to_bytes(self): # grab the chunks we needs out = [PNG_SIGN] # FIXME: it's tricky to define "other_chunks". HoneyView stop the # animation if it sees chunks other than fctl or idat, so we put other # chunks to the end of the file other_chunks = [] seq = 0 # for first frame png, control = sel...
Convert the entire image to bytes. :rtype: bytes
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L345-L411
[ "def make_chunk(chunk_type, chunk_data):\n\t\"\"\"Create a raw chunk by composing chunk type and data. It\n\tcalculates chunk length and CRC for you.\n\n\t:arg str chunk_type: PNG chunk type.\n\t:arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**.\n\t:rtype: bytes\n\t\"\"\"\n\tout = str...
class APNG: """Represent an APNG image.""" def __init__(self, num_plays=0): """An :class:`APNG` is composed by multiple :class:`PNG` s and :class:`FrameControl`, which can be inserted with :meth:`append`. :arg int num_plays: Number of times to loop. 0 = infinite. :var frames: The frames of APNG. :vartype ...
eight04/pyAPNG
apng/__init__.py
APNG.from_files
python
def from_files(cls, files, **options): im = cls() for file in files: im.append_file(file, **options) return im
Create an APNG from multiple files. This is a shortcut of:: im = APNG() for file in files: im.append_file(file, **options) :arg list files: A list of filename. See :meth:`PNG.open`. :arg dict options: Options for :class:`FrameControl`. :rtype: APNG
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L414-L430
null
class APNG: """Represent an APNG image.""" def __init__(self, num_plays=0): """An :class:`APNG` is composed by multiple :class:`PNG` s and :class:`FrameControl`, which can be inserted with :meth:`append`. :arg int num_plays: Number of times to loop. 0 = infinite. :var frames: The frames of APNG. :vartype ...
eight04/pyAPNG
apng/__init__.py
APNG.from_bytes
python
def from_bytes(cls, b): hdr = None head_chunks = [] end = ("IEND", make_chunk("IEND", b"")) frame_chunks = [] frames = [] num_plays = 0 frame_has_head_chunks = False control = None for type_, data in parse_chunks(b): if type_ == "IHDR": hdr = data frame_chunks.append((type_, data))...
Create an APNG from raw bytes. :arg bytes b: The raw bytes of the APNG file. :rtype: APNG
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L433-L494
[ "def parse_chunks(b):\n\t\"\"\"Parse PNG bytes into multiple chunks. \n\n\t:arg bytes b: The raw bytes of the PNG file.\n\t:return: A generator yielding :class:`Chunk`.\n\t:rtype: Iterator[Chunk]\n\t\"\"\"\n\t# skip signature\n\ti = 8\n\t# yield chunks\n\twhile i < len(b):\n\t\tdata_len, = struct.unpack(\"!I\", b[i...
class APNG: """Represent an APNG image.""" def __init__(self, num_plays=0): """An :class:`APNG` is composed by multiple :class:`PNG` s and :class:`FrameControl`, which can be inserted with :meth:`append`. :arg int num_plays: Number of times to loop. 0 = infinite. :var frames: The frames of APNG. :vartype ...
eight04/pyAPNG
cute.py
readme
python
def readme(): from livereload import Server server = Server() server.watch("README.rst", "py cute.py readme_build") server.serve(open_url_delay=1, root="build/readme")
Live reload readme
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/cute.py#L6-L11
null
# https://github.com/PyCQA/pylint/issues/1368 # pylint: disable=bad-whitespace import sys from xcute import cute, Skip IS_LATEST = sys.version_info[:2] == (3, 6) cute( pkg_name = "apng", lint = Skip("pylint cute.py test apng", sys.version_info < (3, )), test = [ "lint", "pytest -x test", "readme_build" ], ...
ui/django-post_office
post_office/models.py
get_upload_path
python
def get_upload_path(instance, filename): if not instance.name: instance.name = filename # set original filename date = timezone.now().date() filename = '{name}.{ext}'.format(name=uuid4().hex, ext=filename.split('.')[-1]) return os.path.join('post_office_att...
Overriding to store the original filename
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/models.py#L274-L283
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from collections import namedtuple from uuid import uuid4 from email.mime.nonmultipart import MIMENonMultipart from django.core.mail import EmailMessage, EmailMultiAlternatives from django.db import models from django.utils.encoding import pyt...
ui/django-post_office
post_office/fields.py
CommaSeparatedEmailField.get_prep_value
python
def get_prep_value(self, value): if isinstance(value, six.string_types): return value else: return ', '.join(map(lambda s: s.strip(), value))
We need to accomodate queries where a single email, or list of email addresses is supplied as arguments. For example: - Email.objects.filter(to='mail@example.com') - Email.objects.filter(to=['one@example.com', 'two@example.com'])
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/fields.py#L28-L39
null
class CommaSeparatedEmailField(TextField): default_validators = [validate_comma_separated_emails] description = _("Comma-separated emails") def __init__(self, *args, **kwargs): kwargs['blank'] = True super(CommaSeparatedEmailField, self).__init__(*args, **kwargs) def formfield(self, **...
ui/django-post_office
post_office/mail.py
create
python
def create(sender, recipients=None, cc=None, bcc=None, subject='', message='', html_message='', context=None, scheduled_time=None, headers=None, template=None, priority=None, render_on_delivery=False, commit=True, backend=''): priority = parse_priority(priority) status = None if...
Creates an email from supplied keyword arguments. If template is specified, email subject and content will be rendered during delivery.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/mail.py#L23-L84
[ "def parse_priority(priority):\n if priority is None:\n priority = get_default_priority()\n # If priority is given as a string, returns the enum representation\n if isinstance(priority, string_types):\n priority = getattr(PRIORITY, priority, None)\n\n if priority is None:\n ...
from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool from django.conf import settings from django.core.exceptions import ValidationError from django.db import connection as db_connection from django.db.models import Q from django.template import Context, Template from django.utils.time...
ui/django-post_office
post_office/mail.py
send_many
python
def send_many(kwargs_list): emails = [] for kwargs in kwargs_list: emails.append(send(commit=False, **kwargs)) Email.objects.bulk_create(emails)
Similar to mail.send(), but this function accepts a list of kwargs. Internally, it uses Django's bulk_create command for efficiency reasons. Currently send_many() can't be used to send emails with priority = 'now'.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/mail.py#L157-L166
[ "def send(recipients=None, sender=None, template=None, context=None, subject='',\n message='', html_message='', scheduled_time=None, headers=None,\n priority=None, attachments=None, render_on_delivery=False,\n log_level=None, commit=True, cc=None, bcc=None, language='',\n backend='')...
from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool from django.conf import settings from django.core.exceptions import ValidationError from django.db import connection as db_connection from django.db.models import Q from django.template import Context, Template from django.utils.time...
ui/django-post_office
post_office/mail.py
get_queued
python
def get_queued(): return Email.objects.filter(status=STATUS.queued) \ .select_related('template') \ .filter(Q(scheduled_time__lte=now()) | Q(scheduled_time=None)) \ .order_by(*get_sending_order()).prefetch_related('attachments')[:get_batch_size()]
Returns a list of emails that should be sent: - Status is queued - Has scheduled_time lower than the current time or None
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/mail.py#L169-L178
[ "def get_batch_size():\n return get_config().get('BATCH_SIZE', 100)\n", "def get_sending_order():\n return get_config().get('SENDING_ORDER', ['-priority'])\n" ]
from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool from django.conf import settings from django.core.exceptions import ValidationError from django.db import connection as db_connection from django.db.models import Q from django.template import Context, Template from django.utils.time...
ui/django-post_office
post_office/mail.py
send_queued
python
def send_queued(processes=1, log_level=None): queued_emails = get_queued() total_sent, total_failed = 0, 0 total_email = len(queued_emails) logger.info('Started sending %s emails with %s processes.' % (total_email, processes)) if log_level is None: log_level = get_log_level...
Sends out all queued mails that has scheduled_time less than now or None
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/mail.py#L181-L220
[ "def get_log_level():\n return get_config().get('LOG_LEVEL', 2)\n", "def split_emails(emails, split_count=1):\n # Group emails into X sublists\n # taken from http://www.garyrobinson.net/2008/04/splitting-a-pyt.html\n # Strange bug, only return 100 email if we do not evaluate the list\n if list(emai...
from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool from django.conf import settings from django.core.exceptions import ValidationError from django.db import connection as db_connection from django.db.models import Q from django.template import Context, Template from django.utils.time...
ui/django-post_office
post_office/backends.py
EmailBackend.send_messages
python
def send_messages(self, email_messages): from .mail import create from .utils import create_attachments if not email_messages: return for email_message in email_messages: subject = email_message.subject from_email = email_message.from_email ...
Queue one or more EmailMessage objects and returns the number of email messages sent.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/backends.py#L17-L66
[ "def get_default_priority():\n return get_config().get('DEFAULT_PRIORITY', 'medium')\n", "def create(sender, recipients=None, cc=None, bcc=None, subject='', message='',\n html_message='', context=None, scheduled_time=None, headers=None,\n template=None, priority=None, render_on_delivery=Fal...
class EmailBackend(BaseEmailBackend): def open(self): pass def close(self): pass
ui/django-post_office
post_office/lockfile.py
FileLock.valid_lock
python
def valid_lock(self): lock_pid = self.get_lock_pid() # If we're unable to get lock_pid if lock_pid is None: return False # this is our process if self._pid == lock_pid: return True # it is/was another process # see if it is running ...
See if the lock exists and is left over from an old process.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/lockfile.py#L56-L80
[ "def get_lock_pid(self):\n try:\n return int(open(self.lock_filename).read())\n except IOError:\n # If we can't read symbolic link, there are two possibilities:\n # 1. The symbolic link is dead (point to non existing file)\n # 2. Symbolic link is not there\n # In either case...
class FileLock(object): def __init__(self, lock_filename, timeout=None, force=False): self.lock_filename = '%s.lock' % lock_filename self.timeout = timeout self.force = force self._pid = str(os.getpid()) # Store pid in a file in the same directory as desired lockname ...
ui/django-post_office
post_office/lockfile.py
FileLock.acquire
python
def acquire(self): pid_file = os.open(self.pid_filename, os.O_CREAT | os.O_EXCL | os.O_RDWR) os.write(pid_file, str(os.getpid()).encode('utf-8')) os.close(pid_file) if hasattr(os, 'symlink') and platform.system() != 'Windows': os.symlink(self.pid_filename, self.lock_filenam...
Create a pid filename and create a symlink (the actual lock file) across platforms that points to it. Symlink is used because it's an atomic operation across platforms.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/lockfile.py#L116-L130
null
class FileLock(object): def __init__(self, lock_filename, timeout=None, force=False): self.lock_filename = '%s.lock' % lock_filename self.timeout = timeout self.force = force self._pid = str(os.getpid()) # Store pid in a file in the same directory as desired lockname ...
ui/django-post_office
post_office/lockfile.py
FileLock.release
python
def release(self): if self.lock_filename != self.pid_filename: try: os.unlink(self.lock_filename) except OSError: pass try: os.remove(self.pid_filename) except OSError: pass
Try to delete the lock files. Doesn't matter if we fail
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/lockfile.py#L133-L144
null
class FileLock(object): def __init__(self, lock_filename, timeout=None, force=False): self.lock_filename = '%s.lock' % lock_filename self.timeout = timeout self.force = force self._pid = str(os.getpid()) # Store pid in a file in the same directory as desired lockname ...
ui/django-post_office
post_office/validators.py
validate_email_with_name
python
def validate_email_with_name(value): value = force_text(value) recipient = value if '<' and '>' in value: start = value.find('<') + 1 end = value.find('>') if start < end: recipient = value[start:end] validate_email(recipient)
Validate email address. Both "Recipient Name <email@example.com>" and "email@example.com" are valid.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/validators.py#L9-L24
null
from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.template import Template, TemplateSyntaxError, TemplateDoesNotExist from django.utils.encoding import force_text from .compat import text_type def validate_comma_separated_emails(value): """ Vali...
ui/django-post_office
post_office/validators.py
validate_comma_separated_emails
python
def validate_comma_separated_emails(value): if not isinstance(value, (tuple, list)): raise ValidationError('Email list must be a list/tuple.') for email in value: try: validate_email_with_name(email) except ValidationError: raise ValidationError('Invalid email: %...
Validate every email address in a comma separated list of emails.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/validators.py#L27-L38
[ "def validate_email_with_name(value):\n \"\"\"\n Validate email address.\n\n Both \"Recipient Name <email@example.com>\" and \"email@example.com\" are valid.\n \"\"\"\n value = force_text(value)\n\n recipient = value\n if '<' and '>' in value:\n start = value.find('<') + 1\n end =...
from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.template import Template, TemplateSyntaxError, TemplateDoesNotExist from django.utils.encoding import force_text from .compat import text_type def validate_email_with_name(value): """ Validate ema...
ui/django-post_office
post_office/validators.py
validate_template_syntax
python
def validate_template_syntax(source): try: Template(source) except (TemplateSyntaxError, TemplateDoesNotExist) as err: raise ValidationError(text_type(err))
Basic Django Template syntax validation. This allows for robuster template authoring.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/validators.py#L41-L49
null
from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.template import Template, TemplateSyntaxError, TemplateDoesNotExist from django.utils.encoding import force_text from .compat import text_type def validate_email_with_name(value): """ Validate ema...
ui/django-post_office
post_office/settings.py
get_available_backends
python
def get_available_backends(): backends = get_config().get('BACKENDS', {}) if backends: return backends # Try to get backend settings from old style # POST_OFFICE = { # 'EMAIL_BACKEND': 'mybackend' # } backend = get_config().get('EMAIL_BACKEND') if backend: warnings....
Returns a dictionary of defined backend classes. For example: { 'default': 'django.core.mail.backends.smtp.EmailBackend', 'locmem': 'django.core.mail.backends.locmem.EmailBackend', }
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/settings.py#L14-L48
[ "def get_config():\n \"\"\"\n Returns Post Office's configuration in dictionary format. e.g:\n POST_OFFICE = {\n 'BATCH_SIZE': 1000\n }\n \"\"\"\n return getattr(settings, 'POST_OFFICE', {})\n" ]
import warnings from django.conf import settings from django.core.cache.backends.base import InvalidCacheBackendError from django.template import engines as template_engines from .compat import import_attribute, get_cache def get_backend(alias='default'): return get_available_backends()[alias] def get_cache_...
ui/django-post_office
post_office/utils.py
send_mail
python
def send_mail(subject, message, from_email, recipient_list, html_message='', scheduled_time=None, headers=None, priority=PRIORITY.medium): subject = force_text(subject) status = None if priority == PRIORITY.now else STATUS.queued emails = [] for address in recipient_list: emails.a...
Add a new message to the mail queue. This is a replacement for Django's ``send_mail`` core email method.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/utils.py#L13-L34
null
from django.conf import settings from django.core.exceptions import ValidationError from django.core.files import File from django.utils.encoding import force_text from post_office import cache from .compat import string_types from .models import Email, PRIORITY, STATUS, EmailTemplate, Attachment from .settings import...
ui/django-post_office
post_office/utils.py
get_email_template
python
def get_email_template(name, language=''): use_cache = getattr(settings, 'POST_OFFICE_CACHE', True) if use_cache: use_cache = getattr(settings, 'POST_OFFICE_TEMPLATE_CACHE', True) if not use_cache: return EmailTemplate.objects.get(name=name, language=language) else: composite_nam...
Function that returns an email template instance, from cache or DB.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/utils.py#L37-L55
[ "def get(name):\n return cache_backend.get(get_cache_key(name))\n", "def set(name, content):\n return cache_backend.set(get_cache_key(name), content)\n" ]
from django.conf import settings from django.core.exceptions import ValidationError from django.core.files import File from django.utils.encoding import force_text from post_office import cache from .compat import string_types from .models import Email, PRIORITY, STATUS, EmailTemplate, Attachment from .settings import...
ui/django-post_office
post_office/utils.py
create_attachments
python
def create_attachments(attachment_files): attachments = [] for filename, filedata in attachment_files.items(): if isinstance(filedata, dict): content = filedata.get('file', None) mimetype = filedata.get('mimetype', None) headers = filedata.get('headers', None) ...
Create Attachment instances from files attachment_files is a dict of: * Key - the filename to be used for the attachment. * Value - file-like object, or a filename to open OR a dict of {'file': file-like-object, 'mimetype': string} Returns a list of Attachment objects
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/utils.py#L66-L106
null
from django.conf import settings from django.core.exceptions import ValidationError from django.core.files import File from django.utils.encoding import force_text from post_office import cache from .compat import string_types from .models import Email, PRIORITY, STATUS, EmailTemplate, Attachment from .settings import...
ui/django-post_office
post_office/utils.py
parse_emails
python
def parse_emails(emails): if isinstance(emails, string_types): emails = [emails] elif emails is None: emails = [] for email in emails: try: validate_email_with_name(email) except ValidationError: raise ValidationError('%s is not a valid email address...
A function that returns a list of valid email addresses. This function will also convert a single email address into a list of email addresses. None value is also converted into an empty list.
train
https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/utils.py#L122-L141
[ "def validate_email_with_name(value):\n \"\"\"\n Validate email address.\n\n Both \"Recipient Name <email@example.com>\" and \"email@example.com\" are valid.\n \"\"\"\n value = force_text(value)\n\n recipient = value\n if '<' and '>' in value:\n start = value.find('<') + 1\n end =...
from django.conf import settings from django.core.exceptions import ValidationError from django.core.files import File from django.utils.encoding import force_text from post_office import cache from .compat import string_types from .models import Email, PRIORITY, STATUS, EmailTemplate, Attachment from .settings import...
stefanfoulis/django-sendsms
sendsms/backends/smspubli.py
SmsBackend._send
python
def _send(self, message): params = { 'V': SMSPUBLI_API_VERSION, 'UN': SMSPUBLI_USERNAME, 'PWD': SMSPUBLI_PASSWORD, 'R': SMSPUBLI_ROUTE, 'SA': message.from_phone, 'DA': ','.join(message.to), 'M': message.body.encode('latin-1'...
Private method for send one message. :param SmsMessage message: SmsMessage class instance. :returns: True if message is sended else False :rtype: bool
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smspubli.py#L59-L113
null
class SmsBackend(BaseSmsBackend): """ SMS Backend smspubli.com provider. The methods "get_xxxxxx" serve to facilitate the inheritance. Thus if a private project in the access data are dynamic, and are stored in the database. A child class overrides the method "get_xxxx" to return data stored in ...
stefanfoulis/django-sendsms
sendsms/backends/filebased.py
SmsBackend._get_filename
python
def _get_filename(self): if self._fname is None: timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") fname = "%s-%s.log" % (timestamp, abs(id(self))) self._fname = os.path.join(self.file_path, fname) return self._fname
Return a unique file name.
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/filebased.py#L43-L49
null
class SmsBackend(ConsoleSmsBackend): def __init__(self, *args, **kwargs): self._fname = None if 'file_path' in kwargs: self.file_path = kwargs.pop('file_path') else: self.file_path = getattr(settings, 'SMS_FILE_PATH', None) # Make sure self.file_path is a ...
stefanfoulis/django-sendsms
sendsms/backends/smsglobal.py
SmsBackend.get_balance
python
def get_balance(self): if not SMSGLOBAL_CHECK_BALANCE_COUNTRY: raise Exception('SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.') params = { 'user' : self.get_username(), 'password' : self.get_password(), 'country' : SMSGLOBAL_CHEC...
Get balance with provider.
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smsglobal.py#L32-L52
[ "def get_username(self):\n return SMSGLOBAL_USERNAME\n", "def get_password(self):\n return SMSGLOBAL_PASSWORD\n" ]
class SmsBackend(BaseSmsBackend): """ A wrapper that manages the SMS Global network connection. Sending and parsing functionality borrowed from http://namingcrisis.net/code """ def get_username(self): return SMSGLOBAL_USERNAME def get_password(self): return SMSGLOBAL_PASSWORD ...
stefanfoulis/django-sendsms
sendsms/backends/smsglobal.py
SmsBackend.send_messages
python
def send_messages(self, sms_messages): if not sms_messages: return num_sent = 0 for message in sms_messages: if self._send(message): num_sent += 1 return num_sent
Sends one or more SmsMessage objects and returns the number of sms messages sent.
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smsglobal.py#L54-L66
[ "def _send(self, message):\n \"\"\"A helper method that does the actual sending.\"\"\"\n charset='UTF-8'\n params = {\n 'action' : 'sendsms',\n 'user' : self.get_username(),\n 'password' : self.get_password(),\n 'from' : message.from_phone,\n 'to' : \",\".join(message.to),\n '...
class SmsBackend(BaseSmsBackend): """ A wrapper that manages the SMS Global network connection. Sending and parsing functionality borrowed from http://namingcrisis.net/code """ def get_username(self): return SMSGLOBAL_USERNAME def get_password(self): return SMSGLOBAL_PASSWORD ...
stefanfoulis/django-sendsms
sendsms/backends/smsglobal.py
SmsBackend._send
python
def _send(self, message): charset='UTF-8' params = { 'action' : 'sendsms', 'user' : self.get_username(), 'password' : self.get_password(), 'from' : message.from_phone, 'to' : ",".join(message.to), 'text' : message.body, 'clientcharset...
A helper method that does the actual sending.
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smsglobal.py#L68-L107
[ "def get_username(self):\n return SMSGLOBAL_USERNAME\n", "def get_password(self):\n return SMSGLOBAL_PASSWORD\n", "def _parse_response(self, result_page):\n \"\"\"\n Takes a result page of sending the sms, returns an extracted tuple:\n ('numeric_err_code', '<sent_queued_message_id>', '<smsglo...
class SmsBackend(BaseSmsBackend): """ A wrapper that manages the SMS Global network connection. Sending and parsing functionality borrowed from http://namingcrisis.net/code """ def get_username(self): return SMSGLOBAL_USERNAME def get_password(self): return SMSGLOBAL_PASSWORD ...
stefanfoulis/django-sendsms
sendsms/backends/smsglobal.py
SmsBackend._parse_response
python
def _parse_response(self, result_page): # Sample result_page, single line -> "OK: 0; Sent queued message ID: 2063619577732703 SMSGlobalMsgID:6171799108850954" resultline = result_page.splitlines()[0] # get result line if resultline.startswith('ERROR:'): raise Exception(resultline.rep...
Takes a result page of sending the sms, returns an extracted tuple: ('numeric_err_code', '<sent_queued_message_id>', '<smsglobalmsgid>') Returns None if unable to extract info from result_page, it should be safe to assume that it was either a failed result or worse, the interface con...
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smsglobal.py#L109-L125
null
class SmsBackend(BaseSmsBackend): """ A wrapper that manages the SMS Global network connection. Sending and parsing functionality borrowed from http://namingcrisis.net/code """ def get_username(self): return SMSGLOBAL_USERNAME def get_password(self): return SMSGLOBAL_PASSWORD ...
stefanfoulis/django-sendsms
sendsms/api.py
send_sms
python
def send_sms(body, from_phone, to, flash=False, fail_silently=False, auth_user=None, auth_password=None, connection=None): from sendsms.message import SmsMessage connection = connection or get_connection( username = auth_user, password = auth_password, fail_silently = fail_s...
Easy wrapper for send a single SMS to a recipient list. :returns: the number of SMSs sent.
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/api.py#L14-L28
[ "def get_connection(path=None, fail_silently=False, **kwargs):\n \"\"\"\n Load an sms backend and return an instance of it.\n\n :param string path: backend python path. Default: sendsms.backends.console.SmsBackend\n :param bool fail_silently: Flag to not throw exceptions on error. Default: False\n :r...
#-*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured try: # Django versions >= 1.9 from django.utils.module_loading import import_module except ImportError: # Django versions < 1.9 from django.utils.importlib import import_module from sendsms.u...
stefanfoulis/django-sendsms
sendsms/api.py
send_mass_sms
python
def send_mass_sms(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None): from sendsms.message import SmsMessage connection = connection or get_connection( username = auth_user, password = auth_password, fail_silently = fail_silently ) ...
Given a datatuple of (message, from_phone, to, flash), sends each message to each recipient list. :returns: the number of SMSs sent.
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/api.py#L31-L48
[ "def get_connection(path=None, fail_silently=False, **kwargs):\n \"\"\"\n Load an sms backend and return an instance of it.\n\n :param string path: backend python path. Default: sendsms.backends.console.SmsBackend\n :param bool fail_silently: Flag to not throw exceptions on error. Default: False\n :r...
#-*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured try: # Django versions >= 1.9 from django.utils.module_loading import import_module except ImportError: # Django versions < 1.9 from django.utils.importlib import import_module from sendsms.u...
stefanfoulis/django-sendsms
sendsms/api.py
get_connection
python
def get_connection(path=None, fail_silently=False, **kwargs): path = path or getattr(settings, 'SENDSMS_BACKEND', 'sendsms.backends.locmem.SmsBackend') try: mod_name, klass_name = path.rsplit('.', 1) mod = import_module(mod_name) except AttributeError as e: raise ImproperlyConfigure...
Load an sms backend and return an instance of it. :param string path: backend python path. Default: sendsms.backends.console.SmsBackend :param bool fail_silently: Flag to not throw exceptions on error. Default: False :returns: backend class instance. :rtype: :py:class:`~sendsms.backends.base.BaseSmsBac...
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/api.py#L51-L73
null
#-*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured try: # Django versions >= 1.9 from django.utils.module_loading import import_module except ImportError: # Django versions < 1.9 from django.utils.importlib import import_module from sendsms.u...
stefanfoulis/django-sendsms
sendsms/backends/smssluzbacz.py
SmsBackend.open
python
def open(self): self.client = SmsGateApi(getattr(settings, 'SMS_SLUZBA_API_LOGIN', ''), getattr(settings, 'SMS_SLUZBA_API_PASSWORD', ''), getattr(settings, 'SMS_SLUZBA_API_TIMEOUT', 2), getattr(settings, 'SMS_SLUZ...
Initializes sms.sluzba.cz API library.
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smssluzbacz.py#L59-L64
null
class SmsBackend(BaseSmsBackend): """SmsBackend for sms.sluzba.cz API. settings.py configuration constants: SMS_SLUZBA_API_LOGIN - sms.sluzba.cz login SMS_SLUZBA_API_PASSWORD - sms.sluzba.cz password SMS_SLUZBA_API_TIMEOUT - connection timeout to sms.sluzba.cz in seconds SMS_SLUZBA_API_...
stefanfoulis/django-sendsms
sendsms/backends/smssluzbacz.py
SmsBackend.send_messages
python
def send_messages(self, messages): count = 0 for message in messages: message_body = unicodedata.normalize('NFKD', unicode(message.body)).encode('ascii', 'ignore') for tel_number in message.to: try: self.client.send(tel_number, message_body, ge...
Sending SMS messages via sms.sluzba.cz API. Note: This method returns number of actually sent sms messages not number of SmsMessage instances processed. :param messages: list of sms messages :type messages: list of sendsms.message.SmsMessage instances :returns: numb...
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smssluzbacz.py#L70-L97
null
class SmsBackend(BaseSmsBackend): """SmsBackend for sms.sluzba.cz API. settings.py configuration constants: SMS_SLUZBA_API_LOGIN - sms.sluzba.cz login SMS_SLUZBA_API_PASSWORD - sms.sluzba.cz password SMS_SLUZBA_API_TIMEOUT - connection timeout to sms.sluzba.cz in seconds SMS_SLUZBA_API_...
stefanfoulis/django-sendsms
sendsms/backends/console.py
SmsBackend.send_messages
python
def send_messages(self, messages): if not messages: return self._lock.acquire() try: # The try-except is nested to allow for # Python 2.4 support (Refs #12147) try: stream_created = self.open() for message in message...
Write all messages to the stream in a thread-safe way.
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/console.py#L18-L41
[ "def render_message(message):\n return u\"\"\"from: %(from)s\\nto: %(to)s\\nflash: %(flash)s\\n%(body)s\"\"\" % {\n 'from': message.from_phone,\n 'to': \", \".join(message.to),\n 'flash': message.flash,\n 'body': message.body,\n }\n", "def open(self):\n \"\"\"\n Open a netw...
class SmsBackend(BaseSmsBackend): def __init__(self, *args, **kwargs): self.stream = kwargs.pop('stream', sys.stdout) self._lock = threading.RLock() super(SmsBackend, self).__init__(*args, **kwargs)
stefanfoulis/django-sendsms
sendsms/backends/esendex.py
SmsBackend._parse_response
python
def _parse_response(self, response): response_dict = {} for line in response.splitlines(): key, value = response.split("=", 1) response_dict[key] = value return response_dict
Parse http raw respone into python dictionary object. :param str response: http response :returns: response dict :rtype: dict
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/esendex.py#L58-L72
null
class SmsBackend(BaseSmsBackend): """ SMS Backend for esendex.es provider. The methods "get_xxxxxx" serve to facilitate the inheritance. Thus if a private project in the access data are dynamic, and are stored in the database. A child class overrides the method "get_xxxx" to return data stored i...
stefanfoulis/django-sendsms
sendsms/backends/esendex.py
SmsBackend._send
python
def _send(self, message): params = { 'EsendexUsername': self.get_username(), 'EsendexPassword': self.get_password(), 'EsendexAccount': self.get_account(), 'EsendexOriginator': message.from_phone, 'EsendexRecipient': ",".join(message.to), ...
Private method to send one message. :param SmsMessage message: SmsMessage class instance. :returns: True if message is sent else False :rtype: bool
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/esendex.py#L74-L119
[ "def get_username(self):\n return ESENDEX_USERNAME\n", "def get_password(self):\n return ESENDEX_PASSWORD\n", "def get_account(self):\n return ESENDEX_ACCOUNT\n", "def _parse_response(self, response):\n \"\"\"\n Parse http raw respone into python\n dictionary object.\n\n :param str respon...
class SmsBackend(BaseSmsBackend): """ SMS Backend for esendex.es provider. The methods "get_xxxxxx" serve to facilitate the inheritance. Thus if a private project in the access data are dynamic, and are stored in the database. A child class overrides the method "get_xxxx" to return data stored i...
stefanfoulis/django-sendsms
sendsms/utils.py
load_object
python
def load_object(import_path): if '.' not in import_path: raise TypeError( "'import_path' argument to 'load_object' must " "contain at least one dot." ) module_name, object_name = import_path.rsplit('.', 1) module = import_module(module_name) return getattr(module,...
Shamelessly stolen from https://github.com/ojii/django-load Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the likes. Import paths should be: "mypackage.mymodule.MyObject". It then imports the module up until the last dot and tries to get the attribute after that dot fro...
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/utils.py#L8-L32
null
#-*- coding: utf-8 -*- try: from importlib import import_module except ImportError: from django.utils.importlib import import_module def load_object(import_path): """ Shamelessly stolen from https://github.com/ojii/django-load Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and ...
stefanfoulis/django-sendsms
sendsms/message.py
SmsMessage.send
python
def send(self, fail_silently=False): if not self.to: # Don't bother creating the connection if there's nobody to send to return 0 res = self.get_connection(fail_silently).send_messages([self]) sms_post_send.send(sender=self, to=self.to, from_phone=self.from_phone, body=se...
Sends the sms message
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/message.py#L30-L39
[ "def get_connection(self, fail_silently=False):\n if not self.connection:\n self.connection = get_connection(fail_silently=fail_silently)\n return self.connection\n" ]
class SmsMessage(object): """ A sms message """ def __init__(self, body, from_phone=None, to=None, flash=False, connection=None): """ Initialize a single SMS message (which can be sent to multiple recipients) """ if to: #assert not isinstance(to, basetring), '...
stefanfoulis/django-sendsms
sendsms/backends/nexmo.py
SmsBackend._send
python
def _send(self, message): params = { 'from': message.from_phone, 'to': ",".join(message.to), 'text': message.body, 'api_key': self.get_api_key(), 'api_secret': self.get_api_secret(), } print(params) logger.debug("POST to %r...
A helper method that does the actual sending :param SmsMessage message: SmsMessage class instance. :returns: True if message is sent else False :rtype: bool
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/nexmo.py#L120-L142
[ "def get_api_key(self):\n return NEXMO_API_KEY\n", "def get_api_secret(self):\n return NEXMO_API_SECRET\n", "def parse(self, host, response):\n if not response.status_code == 200:\n if self.fail_silently:\n logger.warning(\n \"Error: %s %r\", response.status_code, respo...
class SmsBackend(BaseSmsBackend): def get_api_key(self): return NEXMO_API_KEY def get_api_secret(self): return NEXMO_API_SECRET def _parse_response(self, response): """ Parse http raw respone into python dictionary object. :param str response: http respons...
stefanfoulis/django-sendsms
sendsms/backends/nexmo.py
SmsBackend.send_messages
python
def send_messages(self, messages): counter = 0 for message in messages: res, _ = self._send(message) if res: counter += 1 return counter
Send messages. :param list messages: List of SmsMessage instances. :returns: number of messages sended successful. :rtype: int
train
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/nexmo.py#L144-L158
[ "def _send(self, message):\n \"\"\"\n A helper method that does the actual sending\n\n :param SmsMessage message: SmsMessage class instance.\n :returns: True if message is sent else False\n :rtype: bool\n \"\"\"\n\n params = {\n 'from': message.from_phone, \n 'to': \",\".join(mess...
class SmsBackend(BaseSmsBackend): def get_api_key(self): return NEXMO_API_KEY def get_api_secret(self): return NEXMO_API_SECRET def _parse_response(self, response): """ Parse http raw respone into python dictionary object. :param str response: http respons...
TomAugspurger/engarde
engarde/checks.py
none_missing
python
def none_missing(df, columns=None): if columns is None: columns = df.columns try: assert not df[columns].isnull().any().any() except AssertionError as e: missing = df[columns].isnull() msg = generic.bad_locations(missing) e.args = msg raise return df
Asserts that there are no missing values (NaNs) in the DataFrame. Parameters ---------- df : DataFrame columns : list list of columns to restrict the check to Returns ------- df : DataFrame same as the original
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L20-L44
[ "def bad_locations(df):\n columns = df.columns\n all_locs = chain.from_iterable(zip(df.index, cycle([col])) for col in columns)\n bad = pd.Series(list(all_locs))[np.asarray(df).ravel(1)]\n msg = bad.values\n return msg\n" ]
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/checks.py
is_monotonic
python
def is_monotonic(df, items=None, increasing=None, strict=False): if items is None: items = {k: (increasing, strict) for k in df} for col, (increasing, strict) in items.items(): s = pd.Index(df[col]) if increasing: good = getattr(s, 'is_monotonic_increasing') elif inc...
Asserts that the DataFrame is monotonic. Parameters ========== df : Series or DataFrame items : dict mapping columns to conditions (increasing, strict) increasing : None or bool None is either increasing or decreasing. strict : whether the comparison should be strict Retur...
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L46-L85
null
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/checks.py
is_shape
python
def is_shape(df, shape): try: check = np.all(np.equal(df.shape, shape) | (np.equal(shape, [-1, -1]) | np.equal(shape, [None, None]))) assert check except AssertionError as e: msg = ("Expected shape: {}\n" "\t\tActual shap...
Asserts that the DataFrame is of a known shape. Parameters ========== df : DataFrame shape : tuple (n_rows, n_columns). Use None or -1 if you don't care about a dimension. Returns ======= df : DataFrame
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L87-L112
null
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/checks.py
unique
python
def unique(df, columns=None): if columns is None: columns = df.columns for col in columns: if not df[col].is_unique: raise AssertionError("Column {!r} contains non-unique values".format(col)) return df
Asserts that columns in the DataFrame only have unique values. Parameters ---------- df : DataFrame columns : list list of columns to restrict the check to. If None, check all columns. Returns ------- df : DataFrame same as the original
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L115-L135
null
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/checks.py
unique_index
python
def unique_index(df): try: assert df.index.is_unique except AssertionError as e: e.args = df.index.get_duplicates() raise return df
Assert that the index is unique Parameters ========== df : DataFrame Returns ======= df : DataFrame
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L138-L155
null
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/checks.py
within_set
python
def within_set(df, items=None): for k, v in items.items(): if not df[k].isin(v).all(): bad = df.loc[~df[k].isin(v), k] raise AssertionError('Not in set', bad) return df
Assert that df is a subset of items Parameters ========== df : DataFrame items : dict mapping of columns (k) to array-like of values (v) that ``df[k]`` is expected to be a subset of Returns ======= df : DataFrame
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L158-L177
null
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/checks.py
within_range
python
def within_range(df, items=None): for k, (lower, upper) in items.items(): if (lower > df[k]).any() or (upper < df[k]).any(): bad = (lower > df[k]) | (upper < df[k]) raise AssertionError("Outside range", bad) return df
Assert that a DataFrame is within a range. Parameters ========== df : DataFame items : dict mapping of columns (k) to a (low, high) tuple (v) that ``df[k]`` is expected to be between. Returns ======= df : DataFrame
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L179-L198
null
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/checks.py
within_n_std
python
def within_n_std(df, n=3): means = df.mean() stds = df.std() inliers = (np.abs(df[means.index] - means) < n * stds) if not np.all(inliers): msg = generic.bad_locations(~inliers) raise AssertionError(msg) return df
Assert that every value is within ``n`` standard deviations of its column's mean. Parameters ========== df : DataFame n : int number of standard deviations from the mean Returns ======= df : DataFrame
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L200-L221
[ "def bad_locations(df):\n columns = df.columns\n all_locs = chain.from_iterable(zip(df.index, cycle([col])) for col in columns)\n bad = pd.Series(list(all_locs))[np.asarray(df).ravel(1)]\n msg = bad.values\n return msg\n" ]
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/checks.py
has_dtypes
python
def has_dtypes(df, items): dtypes = df.dtypes for k, v in items.items(): if not dtypes[k] == v: raise AssertionError("{} has the wrong dtype. Should be ({}), is ({})".format(k, v,dtypes[k])) return df
Assert that a DataFrame has ``dtypes`` Parameters ========== df: DataFrame items: dict mapping of columns to dtype. Returns ======= df : DataFrame
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L223-L241
null
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/checks.py
one_to_many
python
def one_to_many(df, unitcol, manycol): subset = df[[manycol, unitcol]].drop_duplicates() for many in subset[manycol].unique(): if subset[subset[manycol] == many].shape[0] > 1: msg = "{} in {} has multiple values for {}".format(many, manycol, unitcol) raise AssertionError(msg) ...
Assert that a many-to-one relationship is preserved between two columns. For example, a retail store will have have distinct departments, each with several employees. If each employee may only work in a single department, then the relationship of the department to the employees is one to many. Para...
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L244-L272
null
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/checks.py
is_same_as
python
def is_same_as(df, df_to_compare, **kwargs): try: tm.assert_frame_equal(df, df_to_compare, **kwargs) except AssertionError as exc: six.raise_from(AssertionError("DataFrames are not equal"), exc) return df
Assert that two pandas dataframes are the equal Parameters ========== df : pandas DataFrame df_to_compare : pandas DataFrame **kwargs : dict keyword arguments passed through to panda's ``assert_frame_equal`` Returns ======= df : DataFrame
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/checks.py#L275-L295
null
# -*- coding: utf-8 -*- """ checks.py Each function in here should - Take a DataFrame as its first argument, maybe optional arguments - Makes its assert on the result - Return the original DataFrame """ import numpy as np import pandas as pd import pandas.util.testing as tm import six from engarde import generic fro...
TomAugspurger/engarde
engarde/generic.py
verify
python
def verify(df, check, *args, **kwargs): result = check(df, *args, **kwargs) try: assert result except AssertionError as e: msg = '{} is not true'.format(check.__name__) e.args = (msg, df) raise return df
Generic verify. Assert that ``check(df, *args, **kwargs)`` is true. Parameters ========== df : DataFrame check : function Should take DataFrame and **kwargs. Returns bool Returns ======= df : DataFrame same as the input.
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/generic.py#L15-L38
[ "f = lambda x, n: len(x) > n\n" ]
# -*- coding: utf-8 -*- """ Module for useful generic functions. """ from itertools import chain, cycle import numpy as np import pandas as pd # -------------- # Generic verify # -------------- def verify_all(df, check, *args, **kwargs): """ Verify that all the entries in ``check(df, *args, **kwargs)`` ...
TomAugspurger/engarde
engarde/generic.py
verify_all
python
def verify_all(df, check, *args, **kwargs): result = check(df, *args, **kwargs) try: assert np.all(result) except AssertionError as e: msg = "{} not true for all".format(check.__name__) e.args = (msg, df[~result]) raise return df
Verify that all the entries in ``check(df, *args, **kwargs)`` are true.
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/generic.py#L40-L52
[ "f = lambda x, n: x > n\n" ]
# -*- coding: utf-8 -*- """ Module for useful generic functions. """ from itertools import chain, cycle import numpy as np import pandas as pd # -------------- # Generic verify # -------------- def verify(df, check, *args, **kwargs): """ Generic verify. Assert that ``check(df, *args, **kwargs)`` is true...
TomAugspurger/engarde
engarde/generic.py
verify_any
python
def verify_any(df, check, *args, **kwargs): result = check(df, *args, **kwargs) try: assert np.any(result) except AssertionError as e: msg = '{} not true for any'.format(check.__name__) e.args = (msg, df) raise return df
Verify that any of the entries in ``check(df, *args, **kwargs)`` is true
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/engarde/generic.py#L54-L66
[ "f = lambda x, n: x > n\n" ]
# -*- coding: utf-8 -*- """ Module for useful generic functions. """ from itertools import chain, cycle import numpy as np import pandas as pd # -------------- # Generic verify # -------------- def verify(df, check, *args, **kwargs): """ Generic verify. Assert that ``check(df, *args, **kwargs)`` is true...
TomAugspurger/engarde
docs/sphinxext/ipython_directive.py
EmbeddedSphinxShell.process_input
python
def process_input(self, data, input_prompt, lineno): decorator, input, rest = data image_file = None image_directive = None is_verbatim = decorator=='@verbatim' or self.is_verbatim is_doctest = (decorator is not None and \ decorator.startswith('@doctest')) o...
Process data block for INPUT token.
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/docs/sphinxext/ipython_directive.py#L386-L499
null
class EmbeddedSphinxShell(object): """An embedded IPython instance to run inside Sphinx""" def __init__(self, exec_lines=None,state=None): self.cout = DecodingStringIO(u'') if exec_lines is None: exec_lines = [] self.state = state # Create config object for IPyth...
TomAugspurger/engarde
docs/sphinxext/ipython_directive.py
EmbeddedSphinxShell.process_output
python
def process_output(self, data, output_prompt, input_lines, output, is_doctest, decorator, image_file): TAB = ' ' * 4 if is_doctest and output is not None: found = output found = found.strip() submitted = data.strip() if self.direc...
Process data block for OUTPUT token.
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/docs/sphinxext/ipython_directive.py#L502-L552
[ "def custom_doctest(self, decorator, input_lines, found, submitted):\n \"\"\"\n Perform a specialized doctest.\n\n \"\"\"\n from .custom_doctests import doctests\n\n args = decorator.split()\n doctest_type = args[1]\n if doctest_type in doctests:\n doctests[doctest_type](self, args, inpu...
class EmbeddedSphinxShell(object): """An embedded IPython instance to run inside Sphinx""" def __init__(self, exec_lines=None,state=None): self.cout = DecodingStringIO(u'') if exec_lines is None: exec_lines = [] self.state = state # Create config object for IPyth...
TomAugspurger/engarde
docs/sphinxext/ipython_directive.py
EmbeddedSphinxShell.process_block
python
def process_block(self, block): ret = [] output = None input_lines = None lineno = self.IP.execution_count input_prompt = self.promptin % lineno output_prompt = self.promptout % lineno image_file = None image_directive = None for token, data in b...
process block from the block_parser and return a list of processed lines
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/docs/sphinxext/ipython_directive.py#L575-L608
[ "def process_input(self, data, input_prompt, lineno):\n \"\"\"\n Process data block for INPUT token.\n\n \"\"\"\n decorator, input, rest = data\n image_file = None\n image_directive = None\n\n is_verbatim = decorator=='@verbatim' or self.is_verbatim\n is_doctest = (decorator is not None and ...
class EmbeddedSphinxShell(object): """An embedded IPython instance to run inside Sphinx""" def __init__(self, exec_lines=None,state=None): self.cout = DecodingStringIO(u'') if exec_lines is None: exec_lines = [] self.state = state # Create config object for IPyth...
TomAugspurger/engarde
docs/sphinxext/ipython_directive.py
EmbeddedSphinxShell.ensure_pyplot
python
def ensure_pyplot(self): # We are here if the @figure pseudo decorator was used. Thus, it's # possible that we could be here even if python_mplbackend were set to # `None`. That's also strange and perhaps worthy of raising an # exception, but for now, we just set the backend to 'agg'. ...
Ensures that pyplot has been imported into the embedded IPython shell. Also, makes sure to set the backend appropriately if not set already.
train
https://github.com/TomAugspurger/engarde/blob/e7ea040cf0d20aee7ca4375b8c27caa2d9e43945/docs/sphinxext/ipython_directive.py#L610-L634
[ "def process_input_line(self, line, store_history=True):\n \"\"\"process the input, capturing stdout\"\"\"\n\n stdout = sys.stdout\n splitter = self.IP.input_splitter\n try:\n sys.stdout = self.cout\n splitter.push(line)\n more = splitter.push_accepts_more()\n if not more:\n ...
class EmbeddedSphinxShell(object): """An embedded IPython instance to run inside Sphinx""" def __init__(self, exec_lines=None,state=None): self.cout = DecodingStringIO(u'') if exec_lines is None: exec_lines = [] self.state = state # Create config object for IPyth...
TheHive-Project/TheHive4py
thehive4py/models.py
CaseHelper.create
python
def create(self, title, description, **kwargs): case = Case(title=title, description=description, **kwargs) response = self._thehive.create_case(case) # Check for failed authentication if response.status_code == requests.codes.unauthorized: raise TheHiveException("Authentica...
Create an instance of the Case class. :param title: Case title. :param description: Case description. :param kwargs: Additional arguments. :return: The created instance.
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/models.py#L154-L174
[ "def status_ok(status_code):\n \"\"\"Check whether a status code is OK\"\"\"\n OK_STATUS_CODES = [200, 201]\n return status_code in OK_STATUS_CODES\n" ]
class CaseHelper: """ Provides helper methods for interacting with instances of the Case class. """ def __init__(self, thehive): """ Initialize a CaseHelper instance. :param thehive: A TheHiveApi instance. """ self._thehive = thehive def __call__(self, id): ...
TheHive-Project/TheHive4py
thehive4py/models.py
CaseHelper.update
python
def update(self, case_id, **attributes): response = self._thehive.do_patch("/api/case/{}".format(case_id), **attributes) if response.status_code == requests.codes.unauthorized: raise TheHiveException("Authentication failed") if self.status_ok(response.status_code): ret...
Update a case. :param case_id: The ID of the case to update :param attributes: key=value pairs of case attributes to update (field=new_value) :return: The created instance.
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/models.py#L176-L193
[ "def status_ok(status_code):\n \"\"\"Check whether a status code is OK\"\"\"\n OK_STATUS_CODES = [200, 201]\n return status_code in OK_STATUS_CODES\n" ]
class CaseHelper: """ Provides helper methods for interacting with instances of the Case class. """ def __init__(self, thehive): """ Initialize a CaseHelper instance. :param thehive: A TheHiveApi instance. """ self._thehive = thehive def __call__(self, id): ...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.__find_rows
python
def __find_rows(self, find_url, **attributes): req = self.url + find_url # Add range and sort parameters params = { "range": attributes.get("range", "all"), "sort": attributes.get("sort", []) } # Add body data = { "query": attributes....
:param find_url: URL of the find api :type find_url: string :return: The Response returned by requests including the list of documents based on find_url :rtype: Response object
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L61-L84
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.create_case
python
def create_case(self, case): req = self.url + "/api/case" data = case.jsonify() try: return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert) except requests.exceptions.RequestException as e: ...
:param case: The case details :type case: Case defined in models.py :return: TheHive case :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L90-L104
[ "def jsonify(self):\n return json.dumps(self, sort_keys=True, indent=4, cls=CustomJsonEncoder)\n" ]
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.update_case
python
def update_case(self, case, fields=[]): req = self.url + "/api/case/{}".format(case.id) # Choose which attributes to send update_keys = [ 'title', 'description', 'severity', 'startDate', 'owner', 'flag', 'tlp', 'tags', 'status', 'resolutionStatus', 'impactStatus', 'summa...
Update a case. :param case: The case to update. The case's `id` determines which case to update. :param fields: Optional parameter, an array of fields names, the ones we want to update :return:
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L106-L124
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.create_case_task
python
def create_case_task(self, case_id, case_task): req = self.url + "/api/case/{}/task".format(case_id) data = case_task.jsonify() try: return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert) ex...
:param case_id: Case identifier :param case_task: TheHive task :type case_task: CaseTask defined in models.py :return: TheHive task :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L126-L143
[ "def jsonify(self):\n return json.dumps(self, sort_keys=True, indent=4, cls=CustomJsonEncoder)\n" ]
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.update_case_task
python
def update_case_task(self, task): req = self.url + "/api/case/task/{}".format(task.id) # Choose which attributes to send update_keys = [ 'title', 'description', 'status', 'order', 'user', 'owner', 'flag', 'endDate' ] data = {k: v for k, v in task.__dict__.items() if...
:Updates TheHive Task :param case: The task to update. The task's `id` determines which Task to update. :return:
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L145-L164
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.create_task_log
python
def create_task_log(self, task_id, case_task_log): req = self.url + "/api/case/task/{}/log".format(task_id) data = {'_json': json.dumps({"message":case_task_log.message})} if case_task_log.file: f = {'attachment': (os.path.basename(case_task_log.file), open(case_task_log.file, 'rb'...
:param task_id: Task identifier :param case_task_log: TheHive log :type case_task_log: CaseTaskLog defined in models.py :return: TheHive log :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L166-L189
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.create_case_observable
python
def create_case_observable(self, case_id, case_observable): req = self.url + "/api/case/{}/artifact".format(case_id) if case_observable.dataType == 'file': try: mesg = json.dumps({ "dataType": case_observable.dataType, "message": case_observable.message,...
:param case_id: Case identifier :param case_observable: TheHive observable :type case_observable: CaseObservable defined in models.py :return: TheHive observable :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L191-L219
[ "def jsonify(self):\n return json.dumps(self, sort_keys=True, indent=4, cls=CustomJsonEncoder)\n" ]
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.get_linked_cases
python
def get_linked_cases(self, case_id): req = self.url + "/api/case/{}/links".format(case_id) try: return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert) except requests.exceptions.RequestException as e: raise CaseException("Linked cases fetch erro...
:param case_id: Case identifier :return: TheHive case(s) :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L305-L316
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.get_case_template
python
def get_case_template(self, name): req = self.url + "/api/case/template/_search" data = { "query": And(Eq("name", name), Eq("status", "Ok")) } try: response = requests.post(req, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert) json_...
:param name: Case template name :return: TheHive case template :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L325-L348
[ "def And(*criteria):\n return {'_and': criteria}\n", "def Eq(field, value):\n return {'_field': field, '_value': value}\n" ]
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.get_task_logs
python
def get_task_logs(self, taskId): req = self.url + "/api/case/task/{}/log".format(taskId) try: return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert) except requests.exceptions.RequestException as e: raise CaseTaskException("Case task logs search...
:param taskId: Task identifier :type caseTaskLog: CaseTaskLog defined in models.py :return: TheHive logs :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L350-L363
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.create_alert
python
def create_alert(self, alert): req = self.url + "/api/alert" data = alert.jsonify() try: return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert) except requests.exceptions.RequestException as ...
:param alert: TheHive alert :type alert: Alert defined in models.py :return: TheHive alert :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L365-L379
[ "def jsonify(self):\n return json.dumps(self, sort_keys=True, indent=4, cls=CustomJsonEncoder)\n" ]
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.mark_alert_as_read
python
def mark_alert_as_read(self, alert_id): req = self.url + "/api/alert/{}/markAsRead".format(alert_id) try: return requests.post(req, headers={'Content-Type': 'application/json'}, proxies=self.proxies, auth=self.auth, verify=self.cert) except requests.exceptions.RequestException: ...
Mark an alert as read. :param alert_id: The ID of the alert to mark as read. :return:
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L381-L392
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.update_alert
python
def update_alert(self, alert_id, alert, fields=[]): req = self.url + "/api/alert/{}".format(alert_id) # update only the alert attributes that are not read-only update_keys = ['tlp', 'severity', 'tags', 'caseTemplate', 'title', 'description'] data = {k: v for k, v in alert.__dict__.item...
Update an alert. :param alert_id: The ID of the alert to update. :param data: The alert to update. :param fields: Optional parameter, an array of fields names, the ones we want to update :return:
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L407-L428
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.get_alert
python
def get_alert(self, alert_id): req = self.url + "/api/alert/{}".format(alert_id) try: return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert) except requests.exceptions.RequestException as e: raise AlertException("Alert fetch error: {}".format(e)...
:param alert_id: Alert identifier :return: TheHive Alert :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L430-L441
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.promote_alert_to_case
python
def promote_alert_to_case(self, alert_id): req = self.url + "/api/alert/{}/createCase".format(alert_id) try: return requests.post(req, headers={'Content-Type': 'application/json'}, proxies=self.proxies, auth=self.auth, verif...
This uses the TheHiveAPI to promote an alert to a case :param alert_id: Alert identifier :return: TheHive Case :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L451-L470
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
TheHive-Project/TheHive4py
thehive4py/api.py
TheHiveApi.run_analyzer
python
def run_analyzer(self, cortex_id, artifact_id, analyzer_id): req = self.url + "/api/connector/cortex/job" try: data = json.dumps({ "cortexId": cortex_id, "artifactId": artifact_id, "analyzerId": analyzer_id }) return requests.post...
:param cortex_id: identifier of the Cortex server :param artifact_id: identifier of the artifact as found with an artifact search :param analyzer_id: name of the analyzer used by the job :rtype: json
train
https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L472-L490
null
class TheHiveApi: """ Python API for TheHive :param url: thehive URL :param principal: The username or the API key :param password: The password for basic authentication or None. Defaults to None """ def __init__(self, url, principal, password=None, proxies={}, cert=True):...
kplindegaard/smbus2
smbus2/smbus2.py
i2c_msg.read
python
def read(address, length): arr = create_string_buffer(length) return i2c_msg( addr=address, flags=I2C_M_RD, len=length, buf=arr)
Prepares an i2c read transaction. :param address: Slave address. :type: address: int :param length: Number of bytes to read. :type: length: int :return: New :py:class:`i2c_msg` instance for read operation. :rtype: :py:class:`i2c_msg`
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L158-L172
null
class i2c_msg(Structure): """ As defined in ``i2c.h``. """ _fields_ = [ ('addr', c_uint16), ('flags', c_uint16), ('len', c_uint16), ('buf', POINTER(c_char))] def __iter__(self): return i2c_msg_iter(self) def __len__(self): return self.len de...
kplindegaard/smbus2
smbus2/smbus2.py
i2c_msg.write
python
def write(address, buf): if sys.version_info.major >= 3: if type(buf) is str: buf = bytes(map(ord, buf)) else: buf = bytes(buf) else: if type(buf) is not str: buf = ''.join([chr(x) for x in buf]) arr = create_str...
Prepares an i2c write transaction. :param address: Slave address. :type address: int :param buf: Bytes to write. Either list of values or str. :type buf: list :return: New :py:class:`i2c_msg` instance for write operation. :rtype: :py:class:`i2c_msg`
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L175-L197
null
class i2c_msg(Structure): """ As defined in ``i2c.h``. """ _fields_ = [ ('addr', c_uint16), ('flags', c_uint16), ('len', c_uint16), ('buf', POINTER(c_char))] def __iter__(self): return i2c_msg_iter(self) def __len__(self): return self.len de...
kplindegaard/smbus2
smbus2/smbus2.py
i2c_rdwr_ioctl_data.create
python
def create(*i2c_msg_instances): n_msg = len(i2c_msg_instances) msg_array = (i2c_msg * n_msg)(*i2c_msg_instances) return i2c_rdwr_ioctl_data( msgs=msg_array, nmsgs=n_msg )
Factory method for creating a i2c_rdwr_ioctl_data struct that can be called with ``ioctl(fd, I2C_RDWR, data)``. :param i2c_msg_instances: Up to 42 i2c_msg instances :rtype: i2c_rdwr_ioctl_data
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L211-L224
null
class i2c_rdwr_ioctl_data(Structure): """ As defined in ``i2c-dev.h``. """ _fields_ = [ ('msgs', POINTER(i2c_msg)), ('nmsgs', c_uint32) ] __slots__ = [name for name, type in _fields_] @staticmethod
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.open
python
def open(self, bus): self.fd = os.open("/dev/i2c-{}".format(bus), os.O_RDWR) self.funcs = self._get_funcs()
Open a given i2c bus. :param bus: i2c bus number (e.g. 0 or 1) :type bus: int
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L274-L282
[ "def _get_funcs(self):\n \"\"\"\n Returns a 32-bit value stating supported I2C functions.\n\n :rtype: int\n \"\"\"\n f = c_uint32()\n ioctl(self.fd, I2C_FUNCS, f)\n return f.value\n" ]
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.close
python
def close(self): if self.fd: os.close(self.fd) self.fd = None
Close the i2c connection.
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L284-L290
null
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus._set_address
python
def _set_address(self, address, force=None): force = force if force is not None else self.force if self.address != address or self._force_last != force: if force is True: ioctl(self.fd, I2C_SLAVE_FORCE, address) else: ioctl(self.fd, I2C_SLAVE, addr...
Set i2c slave address to use for subsequent calls. :param address: :type address: int :param force: :type force: Boolean
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L292-L308
null
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus._get_funcs
python
def _get_funcs(self): f = c_uint32() ioctl(self.fd, I2C_FUNCS, f) return f.value
Returns a 32-bit value stating supported I2C functions. :rtype: int
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L310-L318
null
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.write_quick
python
def write_quick(self, i2c_addr, force=None): self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_WRITE, command=0, size=I2C_SMBUS_QUICK) ioctl(self.fd, I2C_SMBUS, msg)
Perform quick transaction. Throws IOError if unsuccessful. :param i2c_addr: i2c address :type i2c_addr: int :param force: :type force: Boolean
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L320-L331
[ "def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA):\n u = union_i2c_smbus_data()\n return i2c_smbus_ioctl_data(\n read_write=read_write, command=command, size=size,\n data=union_pointer_type(u))\n", "def _set_address(self, address, force=None):\n \"\"\"\n Set i2c...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.read_byte
python
def read_byte(self, i2c_addr, force=None): self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE ) ioctl(self.fd, I2C_SMBUS, msg) return msg.data.contents.byte
Read a single byte from a device. :rtype: int :param i2c_addr: i2c address :type i2c_addr: int :param force: :type force: Boolean :return: Read byte value
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L333-L349
[ "def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA):\n u = union_i2c_smbus_data()\n return i2c_smbus_ioctl_data(\n read_write=read_write, command=command, size=size,\n data=union_pointer_type(u))\n", "def _set_address(self, address, force=None):\n \"\"\"\n Set i2c...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.write_byte
python
def write_byte(self, i2c_addr, value, force=None): self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_WRITE, command=value, size=I2C_SMBUS_BYTE ) ioctl(self.fd, I2C_SMBUS, msg)
Write a single byte to a device. :param i2c_addr: i2c address :type i2c_addr: int :param value: value to write :type value: int :param force: :type force: Boolean
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L351-L366
[ "def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA):\n u = union_i2c_smbus_data()\n return i2c_smbus_ioctl_data(\n read_write=read_write, command=command, size=size,\n data=union_pointer_type(u))\n", "def _set_address(self, address, force=None):\n \"\"\"\n Set i2c...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.read_byte_data
python
def read_byte_data(self, i2c_addr, register, force=None): self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_READ, command=register, size=I2C_SMBUS_BYTE_DATA ) ioctl(self.fd, I2C_SMBUS, msg) return msg.data.contents.byte
Read a single byte from a designated register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to read :type register: int :param force: :type force: Boolean :return: Read byte value :rtype: int
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L368-L386
[ "def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA):\n u = union_i2c_smbus_data()\n return i2c_smbus_ioctl_data(\n read_write=read_write, command=command, size=size,\n data=union_pointer_type(u))\n", "def _set_address(self, address, force=None):\n \"\"\"\n Set i2c...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...
kplindegaard/smbus2
smbus2/smbus2.py
SMBus.write_byte_data
python
def write_byte_data(self, i2c_addr, register, value, force=None): self._set_address(i2c_addr, force=force) msg = i2c_smbus_ioctl_data.create( read_write=I2C_SMBUS_WRITE, command=register, size=I2C_SMBUS_BYTE_DATA ) msg.data.contents.byte = value ioctl(self.fd, I2C_SMB...
Write a byte to a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to write to :type register: int :param value: Byte value to transmit :type value: int :param force: :type force: Boolean :rtype: None
train
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L388-L407
[ "def create(read_write=I2C_SMBUS_READ, command=0, size=I2C_SMBUS_BYTE_DATA):\n u = union_i2c_smbus_data()\n return i2c_smbus_ioctl_data(\n read_write=read_write, command=command, size=size,\n data=union_pointer_type(u))\n", "def _set_address(self, address, force=None):\n \"\"\"\n Set i2c...
class SMBus(object): def __init__(self, bus=None, force=False): """ Initialize and (optionally) open an i2c bus connection. :param bus: i2c bus number (e.g. 0 or 1). If not given, a subsequent call to ``open()`` is required. :type bus: int :param force: force us...