Search is not available for this dataset
text stringlengths 75 104k |
|---|
def write(self, data, mode='w'):
"""
Write data to the file.
`data` is the data to write
`mode` is the mode argument to pass to `open()`
"""
with open(self.path, mode) as f:
f.write(data) |
def configure(self):
"""
Configure the Python logging module for this file.
"""
# build a file handler for this file
handler = logging.FileHandler(self.path, delay=True)
# if we got a format string, create a formatter with it
if self._format:
handler.... |
def create(self):
"""
Create the file.
If the file already exists an exception will be raised
"""
if not os.path.exists(self.path):
open(self.path, 'a').close()
else:
raise Exception("File exists: {}".format(self.path)) |
def apply_config(self, applicator):
"""
Replace any config tokens with values from the config.
"""
if type(self._path) == str:
self._path = applicator.apply(self._path)
for key in self._children:
self._children[key].apply_config(applicator) |
def path(self):
"""
Return the path to this directory.
"""
p = ''
if self._parent and self._parent.path:
p = os.path.join(p, self._parent.path)
if self._base:
p = os.path.join(p, self._base)
if self._path:
p = os.path.join(p, s... |
def remove(self, recursive=True, ignore_error=True):
"""
Remove the directory.
"""
try:
if recursive or self._cleanup == 'recursive':
shutil.rmtree(self.path)
else:
os.rmdir(self.path)
except Exception as e:
if n... |
def prepare(self):
"""
Prepare the Directory for use in an Environment.
This will create the directory if the create flag is set.
"""
if self._create:
self.create()
for k in self._children:
self._children[k]._env = self._env
self._chil... |
def cleanup(self):
"""
Clean up children and remove the directory.
Directory will only be removed if the cleanup flag is set.
"""
for k in self._children:
self._children[k].cleanup()
if self._cleanup:
self.remove(True) |
def path_to(self, path):
"""
Find the path to something inside this directory.
"""
return os.path.join(self.path, str(path)) |
def list(self):
"""
List the contents of the directory.
"""
return [File(f, parent=self) for f in os.listdir(self.path)] |
def write(self, filename, data, mode='w'):
"""
Write to a file in the directory.
"""
with open(self.path_to(str(filename)), mode) as f:
f.write(data) |
def read(self, filename):
"""
Read a file from the directory.
"""
with open(self.path_to(str(filename))) as f:
d = f.read()
return d |
def add(self, *args, **kwargs):
"""
Add objects to the directory.
"""
for key in kwargs:
if isinstance(kwargs[key], str):
self._children[key] = File(kwargs[key])
else:
self._children[key] = kwargs[key]
self._children[key... |
def save(self):
"""
Save the state to a file.
"""
with open(self.path, 'w') as f:
f.write(yaml.dump(dict(self.d))) |
def load(self):
"""
Load a saved state file.
"""
if os.path.exists(self.path):
with open(self.path, 'r') as f:
self.d = yaml.safe_load(f.read().replace('\t', ' '*4)) |
def cleanup(self):
"""
Clean up the saved state.
"""
if os.path.exists(self.path):
os.remove(self.path) |
def load_plugins(self, directory):
"""
Loads plugins from the specified directory.
`directory` is the full path to a directory containing python modules
which each contain a subclass of the Plugin class.
There is no criteria for a valid plugin at this level - any python
... |
def update_dict(target, source):
"""
Recursively merge values from a nested dictionary into another nested
dictionary.
For example:
>>> target = {
... 'thing': 123,
... 'thang': {
... 'a': 1,
... 'b': 2
... }
... }
>>> source = {
... ... |
def _child(self, path):
"""
Return a ConfigNode object representing a child node with the specified
relative path.
"""
if self._path:
path = '{}.{}'.format(self._path, path)
return ConfigNode(root=self._root, path=path) |
def _resolve_path(self, create=False):
"""
Returns a tuple of a reference to the last container in the path, and
the last component in the key path.
For example, with a self._value like this:
{
'thing': {
'another': {
'some_leaf':... |
def _get_value(self):
"""
Get the value represented by this node.
"""
if self._path:
try:
container, last = self._resolve_path()
return container[last]
except KeyError:
return None
except IndexError:
... |
def update(self, data={}, options={}):
"""
Update the configuration with new data.
This can be passed either or both `data` and `options`.
`options` is a dict of keypath/value pairs like this (similar to
CherryPy's config mechanism:
>>> c.update(options={
... |
def load(self, reload=False):
"""
Load the config and defaults from files.
"""
if reload or not self._loaded:
# load defaults
if self._defaults_file and type(self._defaults_file) == str:
self._defaults_file = File(self._defaults_file, parent=self._... |
def apply_to_str(self, obj):
"""
Apply the config to a string.
"""
toks = re.split('({config:|})', obj)
newtoks = []
try:
while len(toks):
tok = toks.pop(0)
if tok == '{config:':
# pop the config variable, lo... |
def validate_twilio_signature(func=None, backend_name='twilio-backend'):
"""View decorator to validate requests from Twilio per http://www.twilio.com/docs/security."""
def _dec(view_func):
@functools.wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwarg... |
def build_callback_url(request, urlname, message):
"""
Build Twilio callback url for confirming message delivery status
:type message: OutgoingSMS
"""
location = reverse(urlname, kwargs={"pk": message.pk})
callback_domain = getattr(settings, "TWILIO_CALLBACK_DOMAIN", None)
if callback_doma... |
def send_sms(request, to_number, body, callback_urlname="sms_status_callback"):
"""
Create :class:`OutgoingSMS` object and send SMS using Twilio.
"""
client = TwilioRestClient(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
from_number = settings.TWILIO_PHONE_NUMBER
message = OutgoingS... |
def main(port, export, css, files):
"""
\b
Examples:
$ moo README.md # live preview README.md
$ moo -e *.md # export all markdown files
$ moo --no-css -e README.md # export README.md without CSS
$ cat README.md | moo -e - | less # export ST... |
def process_input(self):
"""Called when socket is read-ready"""
try:
pyngus.read_socket_input(self.connection, self.socket)
except Exception as e:
LOG.error("Exception on socket read: %s", str(e))
self.connection.close_input()
self.connection.close... |
def send_output(self):
"""Called when socket is write-ready"""
try:
pyngus.write_socket_output(self.connection,
self.socket)
except Exception as e:
LOG.error("Exception on socket write: %s", str(e))
self.connection.close_... |
def process(self):
""" Do connection-based processing (I/O and timers) """
readfd = []
writefd = []
if self.connection.needs_input > 0:
readfd = [self.socket]
if self.connection.has_output > 0:
writefd = [self.socket]
timeout = None
deadli... |
def create_caller(self, method_map, source_addr, target_addr,
receiver_properties, sender_properties):
""" Caller factory
"""
if self.caller:
self.caller.destroy()
self.caller = MyCaller(method_map, self, source_addr, target_addr,
... |
def _send_request(self):
"""Send a message containing the RPC method call
"""
msg = Message()
msg.subject = "An RPC call!"
msg.address = self._to
msg.reply_to = self._reply_to
msg.body = self._method
msg.correlation_id = 5 # whatever...
print("se... |
def read_socket_input(connection, socket_obj):
"""Read from the network layer and processes all data read. Can
support both blocking and non-blocking sockets.
Returns the number of input bytes processed, or EOS if input processing
is done. Any exceptions raised by the socket are re-raised.
"""
... |
def write_socket_output(connection, socket_obj):
"""Write data to the network layer. Can support both blocking and
non-blocking sockets.
Returns the number of output bytes sent, or EOS if output processing
is done. Any exceptions raised by the socket are re-raised.
"""
count = connection.has_o... |
def _not_reentrant(func):
"""Decorator that prevents callbacks from calling into link methods that
are not reentrant """
def wrap(*args, **kws):
link = args[0]
if link._callback_lock.in_callback:
m = "Link %s cannot be invoked from a callback!" % func
raise RuntimeErr... |
def _get_remote_settle_modes(pn_link):
"""Return a map containing the settle modes as provided by the remote.
Skip any default value.
"""
modes = {}
snd = pn_link.remote_snd_settle_mode
if snd == proton.Link.SND_UNSETTLED:
modes['snd-settle-mode'] = 'unsettled'
elif snd == proton.Lin... |
def configure(self, target_address, source_address, handler, properties):
"""Assign addresses, properties, etc."""
self._handler = handler
self._properties = properties
dynamic_props = None
if properties:
dynamic_props = properties.get("dynamic-node-properties")
... |
def source_address(self):
"""Return the authorative source of the link."""
# If link is a sender, source is determined by the local
# value, else use the remote.
if self._pn_link.is_sender:
return self._pn_link.source.address
else:
return self._pn_link.rem... |
def target_address(self):
"""Return the authorative target of the link."""
# If link is a receiver, target is determined by the local
# value, else use the remote.
if self._pn_link.is_receiver:
return self._pn_link.target.address
else:
return self._pn_link... |
def _session_closed(self):
"""Remote has closed the session used by this link."""
# if link not already closed:
if self._endpoint_state & proton.Endpoint.REMOTE_ACTIVE:
# simulate close received
self._process_remote_state()
elif self._endpoint_state & proton.Endpo... |
def reject(self, pn_condition=None):
"""See Link Reject, AMQP1.0 spec."""
self._pn_link.source.type = proton.Terminus.UNSPECIFIED
super(SenderLink, self).reject(pn_condition) |
def _process_delivery(self, pn_delivery):
"""Check if the delivery can be processed."""
if pn_delivery.tag in self._send_requests:
if pn_delivery.settled or pn_delivery.remote_state:
# remote has reached a 'terminal state'
outcome = pn_delivery.remote_state
... |
def reject(self, pn_condition=None):
"""See Link Reject, AMQP1.0 spec."""
self._pn_link.target.type = proton.Terminus.UNSPECIFIED
super(ReceiverLink, self).reject(pn_condition) |
def _process_delivery(self, pn_delivery):
"""Check if the delivery can be processed."""
if pn_delivery.readable and not pn_delivery.partial:
data = self._pn_link.recv(pn_delivery.pending)
msg = proton.Message()
msg.decode(data)
self._pn_link.advance()
... |
def new_sender(self, name):
"""Create a new sender link."""
pn_link = self._pn_session.sender(name)
return self.request_sender(pn_link) |
def request_sender(self, pn_link):
"""Create link from request for a sender."""
sl = SenderLink(self._connection, pn_link)
self._links.add(sl)
return sl |
def new_receiver(self, name):
"""Create a new receiver link."""
pn_link = self._pn_session.receiver(name)
return self.request_receiver(pn_link) |
def request_receiver(self, pn_link):
"""Create link from request for a receiver."""
rl = ReceiverLink(self._connection, pn_link)
self._links.add(rl)
return rl |
def link_destroyed(self, link):
"""Link has been destroyed."""
self._links.discard(link)
if not self._links:
# no more links
LOG.debug("destroying unneeded session")
self._pn_session.close()
self._pn_session.free()
self._pn_session = No... |
def _ep_need_close(self):
"""Peer has closed its end of the session."""
LOG.debug("Session %s close requested - closing...",
self._name)
links = self._links.copy() # may modify _links
for link in links:
link._session_closed() |
def _process_endpoint_event(self, event):
"""Called when the Proton Engine generates an endpoint state change
event.
"""
state_fsm = Endpoint._FSM[self._state]
entry = state_fsm.get(event)
if not entry:
# protocol error: invalid event for current state
... |
def extendMarkdown(self, md, md_globals):
"""Modifies inline patterns."""
mark_tag = SimpleTagPattern(MARK_RE, 'mark')
md.inlinePatterns.add('mark', mark_tag, '_begin') |
def receiver_remote_closed(self, receiver_link, pn_condition):
"""Peer has closed its end of the link."""
LOG.debug("receiver_remote_closed condition=%s", pn_condition)
receiver_link.close()
self.done = True |
def receiver_failed(self, receiver_link, error):
"""Protocol error occurred."""
LOG.warn("receiver_failed error=%s", error)
receiver_link.close()
self.done = True |
def get_host_port(server_address):
"""Parse the hostname and port out of the server_address."""
regex = re.compile(r"^amqp://([a-zA-Z0-9.]+)(:([\d]+))?$")
x = regex.match(server_address)
if not x:
raise Exception("Bad address syntax: %s" % server_address)
matches = x.groups()
host = matc... |
def connect_socket(host, port, blocking=True):
"""Create a TCP connection to the server."""
addr = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
if not addr:
raise Exception("Could not translate address '%s:%s'"
% (host, str(port)))
my_socket = socket... |
def server_socket(host, port, backlog=10):
"""Create a TCP listening socket for a server."""
addr = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
if not addr:
raise Exception("Could not translate address '%s:%s'"
% (host, str(port)))
my_socket = socke... |
def process_connection(connection, my_socket):
"""Handle I/O and Timers on a single Connection."""
if connection.closed:
return False
work = False
readfd = []
writefd = []
if connection.needs_input > 0:
readfd = [my_socket]
work = True
if connection.has_output > 0:
... |
def need_processing(self):
"""A utility to help determine which connections need
processing. Returns a triple of lists containing those connections that
0) need to read from the network, 1) need to write to the network, 2)
waiting for pending timers to expire. The timer list is sorted w... |
def _not_reentrant(func):
"""Decorator that prevents callbacks from calling into methods that are
not reentrant
"""
def wrap(self, *args, **kws):
if self._callback_lock and self._callback_lock.in_callback:
m = "Connection %s cannot be invoked from a callback!"... |
def process(self, now):
"""Perform connection state processing."""
if self._pn_connection is None:
LOG.error("Connection.process() called on destroyed connection!")
return 0
# do nothing until the connection has been opened
if self._pn_connection.state & proton.E... |
def output_data(self):
"""Get a buffer of data that needs to be written to the network.
"""
c = self.has_output
if c <= 0:
return None
try:
buf = self._pn_transport.peek(c)
except Exception as e:
self._connection_failed(str(e))
... |
def create_sender(self, source_address, target_address=None,
event_handler=None, name=None, properties=None):
"""Factory method for Sender links."""
ident = name or str(source_address)
if ident in self._sender_links:
raise KeyError("Sender %s already exists!" % ... |
def reject_sender(self, link_handle, pn_condition=None):
"""Rejects the SenderLink, and destroys the handle."""
link = self._sender_links.get(link_handle)
if not link:
raise Exception("Invalid link_handle: %s" % link_handle)
link.reject(pn_condition)
# note: normally,... |
def create_receiver(self, target_address, source_address=None,
event_handler=None, name=None, properties=None):
"""Factory method for creating Receive links."""
ident = name or str(target_address)
if ident in self._receiver_links:
raise KeyError("Receiver %s a... |
def _connection_failed(self, error="Error not specified!"):
"""Clean up after connection failure detected."""
if not self._error:
LOG.error("Connection failed: %s", str(error))
self._error = error |
def _ep_active(self):
"""Both ends of the Endpoint have become active."""
LOG.debug("Connection is up")
if self._handler:
with self._callback_lock:
self._handler.connection_active(self) |
def _ep_need_close(self):
"""The remote has closed its end of the endpoint."""
LOG.debug("Connection remotely closed")
if self._handler:
cond = self._pn_connection.remote_condition
with self._callback_lock:
self._handler.connection_remote_closed(self, cond... |
def _ep_error(self, error):
"""The endpoint state machine failed due to protocol error."""
super(Connection, self)._ep_error(error)
self._connection_failed("Protocol error occurred.") |
def twilio_view(f):
"""This decorator provides several helpful shortcuts for writing Twilio
views.
- It ensures that only requests from Twilio are passed through. This
helps protect you from forged requests.
- It ensures your view is exempt from CSRF checks via Django's
@cs... |
def _is_equal(self, test_color):
"""Equality test"""
if test_color is None:
ans = False
elif test_color.color_type != self.color_type:
ans = False
elif self.name is not None and self.name == test_color.name:
ans = True
elif (self.red ==... |
def _get_color_string(self):
"""Adobe output string for defining colors"""
s = ''
if self.color_type == 'd':
if self.name is "black":
s = '%.3f G' % 0
else:
s = '%.3f %.3f %.3f RG' % (
self.red / 255.0, self.gree... |
def _set_font(self, family=None, style=None, size=None):
"""Select a font; size given in points"""
if style is not None:
if 'B' in style:
family += '_bold'
if 'I' in style:
family += '_italic'
self._set_family(family)
self._get_dif... |
def _string_width(self, s):
"""Get width of a string in the current font"""
s = str(s)
w = 0
for char in s:
char = ord(char)
w += self.character_widths[char]
return w * self.font_size / 1000.0 |
def get_ttf(self):
""" Given a search path, find file with requested extension """
font_dict = {}
families = []
rootdirlist = string.split(self.search_path, os.pathsep)
#for rootdir in rootdirlist:
# rootdir = os.path.expanduser(rootdir)
for dirName, subdirLis... |
def _set_compression(self, value):
""" May be used to compress PDF files. Code is more readable
for testing and inspection if not compressed. Requires a boolean. """
if isinstance(value, bool):
self.compression = value
else:
raise Exception(
... |
def _create_placeholder_objects(self):
""" PDF objects #1 through #3 are typically saved for the
Zeroth, Catalog, and Pages Objects. This program will save
the numbers, but outputs the individual Page and Content objects
first. The actual Catalog and Pages objects are cal... |
def _add_object(self, flag=None):
""" The flag is a simple integer to force the placement
of the object into position in the object array.
Used for overwriting the placeholder objects.
"""
self.offset = len(self.buffer)
if flag is None:
objnum... |
def _out(self, stream, page=None):
""" Stores the pdf code in a buffer. If it is page related,
provide the page object.
"""
if page is not None:
page.buffer += str(stream) + "\n"
else:
self.buffer += str(stream) + "\n" |
def _put_stream(self, stream):
""" Creates a PDF text stream sandwich.
"""
self._out('stream')
self._out(stream)
self._out('endstream') |
def _add_page(self, text):
""" Helper function for PDFText, to have the document
add a page, and retry adding a large block of
text that would otherwise have been to long for the
page.
"""
save_cursor = self.parent.document.page.cursor.copy()
... |
def _set_color_scheme(self, draw_color=None, fill_color=None, text_color=None):
""" Default color object is black letters
& black lines."""
if draw_color is None:
draw_color = PDFColor()
draw_color._set_type('d')
if fill_color is None:
fill_... |
def _set_default_font(self):
""" Internal method to set the initial default font. Change
the font using set_font method."""
self.font = PDFFont(self.session)
self.font._set_index()
self.fonts.append(self.font)
self.fontkeys.append(self.font.font_key) |
def add_page(self, page=None):
""" May generate and add a PDFPage separately, or use this to generate
a default page."""
if page is None:
self.page = PDFPage(self.orientation_default, self.layout_default, self.margins)
else:
self.page = page
sel... |
def set_font(self, family=None, style='', size=None, font=None):
""" Set the document font object, size given in points. If family, style, and/or size is given, generates
a new Font object, checks to see if it is already in use, and selects it. """
if font:
testfont = font
... |
def set_font_size(self, size):
"""Convenience method for just changing font size."""
if self.font.font_size == size:
pass
else:
self.font._set_size(size) |
def add_text(self, text, cursor=None, justification=None):
""" Input text, short or long. Writes in order, within the defined page boundaries. Sequential add_text commands will print without
additional whitespace. """
if cursor is None:
cursor = self.page.cursor
te... |
def add_newline(self, number=1):
""" Starts over again at the new line. If number is specified,
it will leave multiple lines."""
if isinstance(number, int):
try:
self.page._add_newline(self.font, number, self.double_spacing)
except ValueError:
... |
def add_pie_chart(self, data, cursor, width, height, title=None, data_type="raw", fill_colors=None, labels=False, background=None, legend=None):
""" Data type may be "raw" or "percent" """
save_draw_color = self.draw_color
save_fill_color = self.fill_color
chart = PDFPieChart(self.... |
def _output_pages(self):
""" Called by the PDFLite object to prompt creating
the page objects."""
if not self.orientation_changes:
self._get_orientation_changes()
# Page
for page in self.pages:
obj = self.session._add_object()
sel... |
def _get_orientation_changes(self):
""" Returns a list of the pages that have
orientation changes."""
self.orientation_changes = []
for page in self.pages:
if page.orientation_change is True:
self.orientation_changes.append(page.index)
e... |
def _output_fonts(self):
""" Called by the PDFLite object to prompt creating
the font objects."""
self.session._save_object_number()
self._output_encoding_diffs()
self._output_font_files()
for font in self.fonts:
obj = self.session._add_object()
... |
def _output_images(self):
""" Creates reference images, that can be
drawn throughout the document."""
for image in self.images:
obj = self.session._add_object()
image._set_number(obj.id)
image._output() |
def _output(self):
""" Prompts the creating of image objects.
"""
self.session._out('<</Type /XObject')
self.session._out('/Subtype /Image')
self.session._out('/Width %s' % self.width)
self.session._out('/Height %s' % self.height)
if self.colorspace is 'Indexed'... |
def transform(self, a, b, c, d, e, f):
""" Adjust the current transformation state of the current graphics state
matrix. Not recommended for the faint of heart.
"""
a0, b0, c0, d0, e0, f0 = self._currentMatrix
self._currentMatrix = (a0 * a + c0 * b, b0 * a + d0 * b,
... |
def absolute_position(self, x, y):
"""return the absolute position of x,y in user space w.r.t. default user space"""
(a, b, c, d, e, f) = self._currentMatrix
xp = a * x + c * y + e
yp = b * x + d * y + f
return xp, yp |
def rotate(self, theta):
"""Rotate current graphic state by the angle theta (in degrees)."""
c = cos(theta * pi / 180)
s = sin(theta * pi / 180)
self.transform(c, s, -s, c, 0, 0) |
def _set_style(self, style=None):
""" Style should be a string, containing the letters 'B' for bold,
'U' for underline, or 'I' for italic, or should be '', for no style.
Symbol will not be underlined. The underline style can further be
modified by specifying the underline thickness a... |
def _set_font(self, family=None, style=None, size=None):
"""Select a font; size given in points"""
self._set_family(family)
self._set_style(style)
self._set_size(size)
self._set_font_key()
self._set_name()
self._set_character_widths() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.