id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
230,600
StanfordVL/robosuite
robosuite/wrappers/ik_wrapper.py
IKWrapper.set_robot_joint_positions
def set_robot_joint_positions(self, positions): """ Overrides the function to set the joint positions directly, since we need to notify the IK controller of the change. """ self.env.set_robot_joint_positions(positions) self.controller.sync_state()
python
def set_robot_joint_positions(self, positions): self.env.set_robot_joint_positions(positions) self.controller.sync_state()
[ "def", "set_robot_joint_positions", "(", "self", ",", "positions", ")", ":", "self", ".", "env", ".", "set_robot_joint_positions", "(", "positions", ")", "self", ".", "controller", ".", "sync_state", "(", ")" ]
Overrides the function to set the joint positions directly, since we need to notify the IK controller of the change.
[ "Overrides", "the", "function", "to", "set", "the", "joint", "positions", "directly", "since", "we", "need", "to", "notify", "the", "IK", "controller", "of", "the", "change", "." ]
65cd16810e2ed647e3ec88746af3412065b7f278
https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/wrappers/ik_wrapper.py#L53-L59
230,601
StanfordVL/robosuite
robosuite/wrappers/ik_wrapper.py
IKWrapper._make_input
def _make_input(self, action, old_quat): """ Helper function that returns a dictionary with keys dpos, rotation from a raw input array. The first three elements are taken to be displacement in position, and a quaternion indicating the change in rotation with respect to @old_quat. """ return { "dpos": action[:3], # IK controller takes an absolute orientation in robot base frame "rotation": T.quat2mat(T.quat_multiply(old_quat, action[3:7])), }
python
def _make_input(self, action, old_quat): return { "dpos": action[:3], # IK controller takes an absolute orientation in robot base frame "rotation": T.quat2mat(T.quat_multiply(old_quat, action[3:7])), }
[ "def", "_make_input", "(", "self", ",", "action", ",", "old_quat", ")", ":", "return", "{", "\"dpos\"", ":", "action", "[", ":", "3", "]", ",", "# IK controller takes an absolute orientation in robot base frame", "\"rotation\"", ":", "T", ".", "quat2mat", "(", "...
Helper function that returns a dictionary with keys dpos, rotation from a raw input array. The first three elements are taken to be displacement in position, and a quaternion indicating the change in rotation with respect to @old_quat.
[ "Helper", "function", "that", "returns", "a", "dictionary", "with", "keys", "dpos", "rotation", "from", "a", "raw", "input", "array", ".", "The", "first", "three", "elements", "are", "taken", "to", "be", "displacement", "in", "position", "and", "a", "quatern...
65cd16810e2ed647e3ec88746af3412065b7f278
https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/wrappers/ik_wrapper.py#L116-L126
230,602
jrief/django-websocket-redis
ws4redis/publisher.py
RedisPublisher.fetch_message
def fetch_message(self, request, facility, audience='any'): """ Fetch the first message available for the given ``facility`` and ``audience``, if it has been persisted in the Redis datastore. The current HTTP ``request`` is used to determine to whom the message belongs. A unique string is used to identify the bucket's ``facility``. Determines the ``audience`` to check for the message. Must be one of ``broadcast``, ``group``, ``user``, ``session`` or ``any``. The default is ``any``, which means to check for all possible audiences. """ prefix = self.get_prefix() channels = [] if audience in ('session', 'any',): if request and request.session: channels.append('{prefix}session:{0}:{facility}'.format(request.session.session_key, prefix=prefix, facility=facility)) if audience in ('user', 'any',): if is_authenticated(request): channels.append('{prefix}user:{0}:{facility}'.format(request.user.get_username(), prefix=prefix, facility=facility)) if audience in ('group', 'any',): try: if is_authenticated(request): groups = request.session['ws4redis:memberof'] channels.extend('{prefix}group:{0}:{facility}'.format(g, prefix=prefix, facility=facility) for g in groups) except (KeyError, AttributeError): pass if audience in ('broadcast', 'any',): channels.append('{prefix}broadcast:{facility}'.format(prefix=prefix, facility=facility)) for channel in channels: message = self._connection.get(channel) if message: return message
python
def fetch_message(self, request, facility, audience='any'): prefix = self.get_prefix() channels = [] if audience in ('session', 'any',): if request and request.session: channels.append('{prefix}session:{0}:{facility}'.format(request.session.session_key, prefix=prefix, facility=facility)) if audience in ('user', 'any',): if is_authenticated(request): channels.append('{prefix}user:{0}:{facility}'.format(request.user.get_username(), prefix=prefix, facility=facility)) if audience in ('group', 'any',): try: if is_authenticated(request): groups = request.session['ws4redis:memberof'] channels.extend('{prefix}group:{0}:{facility}'.format(g, prefix=prefix, facility=facility) for g in groups) except (KeyError, AttributeError): pass if audience in ('broadcast', 'any',): channels.append('{prefix}broadcast:{facility}'.format(prefix=prefix, facility=facility)) for channel in channels: message = self._connection.get(channel) if message: return message
[ "def", "fetch_message", "(", "self", ",", "request", ",", "facility", ",", "audience", "=", "'any'", ")", ":", "prefix", "=", "self", ".", "get_prefix", "(", ")", "channels", "=", "[", "]", "if", "audience", "in", "(", "'session'", ",", "'any'", ",", ...
Fetch the first message available for the given ``facility`` and ``audience``, if it has been persisted in the Redis datastore. The current HTTP ``request`` is used to determine to whom the message belongs. A unique string is used to identify the bucket's ``facility``. Determines the ``audience`` to check for the message. Must be one of ``broadcast``, ``group``, ``user``, ``session`` or ``any``. The default is ``any``, which means to check for all possible audiences.
[ "Fetch", "the", "first", "message", "available", "for", "the", "given", "facility", "and", "audience", "if", "it", "has", "been", "persisted", "in", "the", "Redis", "datastore", ".", "The", "current", "HTTP", "request", "is", "used", "to", "determine", "to",...
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/publisher.py#L27-L58
230,603
jrief/django-websocket-redis
ws4redis/subscriber.py
RedisSubscriber.set_pubsub_channels
def set_pubsub_channels(self, request, channels): """ Initialize the channels used for publishing and subscribing messages through the message queue. """ facility = request.path_info.replace(settings.WEBSOCKET_URL, '', 1) # initialize publishers audience = { 'users': 'publish-user' in channels and [SELF] or [], 'groups': 'publish-group' in channels and [SELF] or [], 'sessions': 'publish-session' in channels and [SELF] or [], 'broadcast': 'publish-broadcast' in channels, } self._publishers = set() for key in self._get_message_channels(request=request, facility=facility, **audience): self._publishers.add(key) # initialize subscribers audience = { 'users': 'subscribe-user' in channels and [SELF] or [], 'groups': 'subscribe-group' in channels and [SELF] or [], 'sessions': 'subscribe-session' in channels and [SELF] or [], 'broadcast': 'subscribe-broadcast' in channels, } self._subscription = self._connection.pubsub() for key in self._get_message_channels(request=request, facility=facility, **audience): self._subscription.subscribe(key)
python
def set_pubsub_channels(self, request, channels): facility = request.path_info.replace(settings.WEBSOCKET_URL, '', 1) # initialize publishers audience = { 'users': 'publish-user' in channels and [SELF] or [], 'groups': 'publish-group' in channels and [SELF] or [], 'sessions': 'publish-session' in channels and [SELF] or [], 'broadcast': 'publish-broadcast' in channels, } self._publishers = set() for key in self._get_message_channels(request=request, facility=facility, **audience): self._publishers.add(key) # initialize subscribers audience = { 'users': 'subscribe-user' in channels and [SELF] or [], 'groups': 'subscribe-group' in channels and [SELF] or [], 'sessions': 'subscribe-session' in channels and [SELF] or [], 'broadcast': 'subscribe-broadcast' in channels, } self._subscription = self._connection.pubsub() for key in self._get_message_channels(request=request, facility=facility, **audience): self._subscription.subscribe(key)
[ "def", "set_pubsub_channels", "(", "self", ",", "request", ",", "channels", ")", ":", "facility", "=", "request", ".", "path_info", ".", "replace", "(", "settings", ".", "WEBSOCKET_URL", ",", "''", ",", "1", ")", "# initialize publishers", "audience", "=", "...
Initialize the channels used for publishing and subscribing messages through the message queue.
[ "Initialize", "the", "channels", "used", "for", "publishing", "and", "subscribing", "messages", "through", "the", "message", "queue", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/subscriber.py#L23-L49
230,604
jrief/django-websocket-redis
ws4redis/subscriber.py
RedisSubscriber.send_persisted_messages
def send_persisted_messages(self, websocket): """ This method is called immediately after a websocket is openend by the client, so that persisted messages can be sent back to the client upon connection. """ for channel in self._subscription.channels: message = self._connection.get(channel) if message: websocket.send(message)
python
def send_persisted_messages(self, websocket): for channel in self._subscription.channels: message = self._connection.get(channel) if message: websocket.send(message)
[ "def", "send_persisted_messages", "(", "self", ",", "websocket", ")", ":", "for", "channel", "in", "self", ".", "_subscription", ".", "channels", ":", "message", "=", "self", ".", "_connection", ".", "get", "(", "channel", ")", "if", "message", ":", "webso...
This method is called immediately after a websocket is openend by the client, so that persisted messages can be sent back to the client upon connection.
[ "This", "method", "is", "called", "immediately", "after", "a", "websocket", "is", "openend", "by", "the", "client", "so", "that", "persisted", "messages", "can", "be", "sent", "back", "to", "the", "client", "upon", "connection", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/subscriber.py#L51-L59
230,605
jrief/django-websocket-redis
ws4redis/subscriber.py
RedisSubscriber.get_file_descriptor
def get_file_descriptor(self): """ Returns the file descriptor used for passing to the select call when listening on the message queue. """ return self._subscription.connection and self._subscription.connection._sock.fileno()
python
def get_file_descriptor(self): return self._subscription.connection and self._subscription.connection._sock.fileno()
[ "def", "get_file_descriptor", "(", "self", ")", ":", "return", "self", ".", "_subscription", ".", "connection", "and", "self", ".", "_subscription", ".", "connection", ".", "_sock", ".", "fileno", "(", ")" ]
Returns the file descriptor used for passing to the select call when listening on the message queue.
[ "Returns", "the", "file", "descriptor", "used", "for", "passing", "to", "the", "select", "call", "when", "listening", "on", "the", "message", "queue", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/subscriber.py#L64-L69
230,606
jrief/django-websocket-redis
ws4redis/subscriber.py
RedisSubscriber.release
def release(self): """ New implementation to free up Redis subscriptions when websockets close. This prevents memory sap when Redis Output Buffer and Output Lists build when websockets are abandoned. """ if self._subscription and self._subscription.subscribed: self._subscription.unsubscribe() self._subscription.reset()
python
def release(self): if self._subscription and self._subscription.subscribed: self._subscription.unsubscribe() self._subscription.reset()
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "_subscription", "and", "self", ".", "_subscription", ".", "subscribed", ":", "self", ".", "_subscription", ".", "unsubscribe", "(", ")", "self", ".", "_subscription", ".", "reset", "(", ")" ]
New implementation to free up Redis subscriptions when websockets close. This prevents memory sap when Redis Output Buffer and Output Lists build when websockets are abandoned.
[ "New", "implementation", "to", "free", "up", "Redis", "subscriptions", "when", "websockets", "close", ".", "This", "prevents", "memory", "sap", "when", "Redis", "Output", "Buffer", "and", "Output", "Lists", "build", "when", "websockets", "are", "abandoned", "." ...
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/subscriber.py#L71-L78
230,607
jrief/django-websocket-redis
ws4redis/context_processors.py
default
def default(request): """ Adds additional context variables to the default context. """ protocol = request.is_secure() and 'wss://' or 'ws://' heartbeat_msg = settings.WS4REDIS_HEARTBEAT and '"{0}"'.format(settings.WS4REDIS_HEARTBEAT) or 'null' context = { 'WEBSOCKET_URI': protocol + request.get_host() + settings.WEBSOCKET_URL, 'WS4REDIS_HEARTBEAT': mark_safe(heartbeat_msg), } return context
python
def default(request): protocol = request.is_secure() and 'wss://' or 'ws://' heartbeat_msg = settings.WS4REDIS_HEARTBEAT and '"{0}"'.format(settings.WS4REDIS_HEARTBEAT) or 'null' context = { 'WEBSOCKET_URI': protocol + request.get_host() + settings.WEBSOCKET_URL, 'WS4REDIS_HEARTBEAT': mark_safe(heartbeat_msg), } return context
[ "def", "default", "(", "request", ")", ":", "protocol", "=", "request", ".", "is_secure", "(", ")", "and", "'wss://'", "or", "'ws://'", "heartbeat_msg", "=", "settings", ".", "WS4REDIS_HEARTBEAT", "and", "'\"{0}\"'", ".", "format", "(", "settings", ".", "WS4...
Adds additional context variables to the default context.
[ "Adds", "additional", "context", "variables", "to", "the", "default", "context", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/context_processors.py#L6-L16
230,608
jrief/django-websocket-redis
ws4redis/websocket.py
WebSocket._decode_bytes
def _decode_bytes(self, bytestring): """ Internal method used to convert the utf-8 encoded bytestring into unicode. If the conversion fails, the socket will be closed. """ if not bytestring: return u'' try: return bytestring.decode('utf-8') except UnicodeDecodeError: self.close(1007) raise
python
def _decode_bytes(self, bytestring): if not bytestring: return u'' try: return bytestring.decode('utf-8') except UnicodeDecodeError: self.close(1007) raise
[ "def", "_decode_bytes", "(", "self", ",", "bytestring", ")", ":", "if", "not", "bytestring", ":", "return", "u''", "try", ":", "return", "bytestring", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeDecodeError", ":", "self", ".", "close", "(", "1007...
Internal method used to convert the utf-8 encoded bytestring into unicode. If the conversion fails, the socket will be closed.
[ "Internal", "method", "used", "to", "convert", "the", "utf", "-", "8", "encoded", "bytestring", "into", "unicode", ".", "If", "the", "conversion", "fails", "the", "socket", "will", "be", "closed", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/websocket.py#L40-L51
230,609
jrief/django-websocket-redis
ws4redis/websocket.py
WebSocket.handle_close
def handle_close(self, header, payload): """ Called when a close frame has been decoded from the stream. :param header: The decoded `Header`. :param payload: The bytestring payload associated with the close frame. """ if not payload: self.close(1000, None) return if len(payload) < 2: raise WebSocketError('Invalid close frame: {0} {1}'.format(header, payload)) rv = payload[:2] if six.PY2: code = struct.unpack('!H', str(rv))[0] else: code = struct.unpack('!H', bytes(rv))[0] payload = payload[2:] if payload: validator = Utf8Validator() val = validator.validate(payload) if not val[0]: raise UnicodeError if not self._is_valid_close_code(code): raise WebSocketError('Invalid close code {0}'.format(code)) self.close(code, payload)
python
def handle_close(self, header, payload): if not payload: self.close(1000, None) return if len(payload) < 2: raise WebSocketError('Invalid close frame: {0} {1}'.format(header, payload)) rv = payload[:2] if six.PY2: code = struct.unpack('!H', str(rv))[0] else: code = struct.unpack('!H', bytes(rv))[0] payload = payload[2:] if payload: validator = Utf8Validator() val = validator.validate(payload) if not val[0]: raise UnicodeError if not self._is_valid_close_code(code): raise WebSocketError('Invalid close code {0}'.format(code)) self.close(code, payload)
[ "def", "handle_close", "(", "self", ",", "header", ",", "payload", ")", ":", "if", "not", "payload", ":", "self", ".", "close", "(", "1000", ",", "None", ")", "return", "if", "len", "(", "payload", ")", "<", "2", ":", "raise", "WebSocketError", "(", ...
Called when a close frame has been decoded from the stream. :param header: The decoded `Header`. :param payload: The bytestring payload associated with the close frame.
[ "Called", "when", "a", "close", "frame", "has", "been", "decoded", "from", "the", "stream", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/websocket.py#L88-L113
230,610
jrief/django-websocket-redis
ws4redis/websocket.py
WebSocket.read_frame
def read_frame(self): """ Block until a full frame has been read from the socket. This is an internal method as calling this will not cleanup correctly if an exception is called. Use `receive` instead. :return: The header and payload as a tuple. """ header = Header.decode_header(self.stream) if header.flags: raise WebSocketError if not header.length: return header, '' try: payload = self.stream.read(header.length) except socket_error: payload = '' except Exception: logger.debug("{}: {}".format(type(e), six.text_type(e))) payload = '' if len(payload) != header.length: raise WebSocketError('Unexpected EOF reading frame payload') if header.mask: payload = header.unmask_payload(payload) return header, payload
python
def read_frame(self): header = Header.decode_header(self.stream) if header.flags: raise WebSocketError if not header.length: return header, '' try: payload = self.stream.read(header.length) except socket_error: payload = '' except Exception: logger.debug("{}: {}".format(type(e), six.text_type(e))) payload = '' if len(payload) != header.length: raise WebSocketError('Unexpected EOF reading frame payload') if header.mask: payload = header.unmask_payload(payload) return header, payload
[ "def", "read_frame", "(", "self", ")", ":", "header", "=", "Header", ".", "decode_header", "(", "self", ".", "stream", ")", "if", "header", ".", "flags", ":", "raise", "WebSocketError", "if", "not", "header", ".", "length", ":", "return", "header", ",", ...
Block until a full frame has been read from the socket. This is an internal method as calling this will not cleanup correctly if an exception is called. Use `receive` instead. :return: The header and payload as a tuple.
[ "Block", "until", "a", "full", "frame", "has", "been", "read", "from", "the", "socket", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/websocket.py#L121-L146
230,611
jrief/django-websocket-redis
ws4redis/websocket.py
WebSocket.read_message
def read_message(self): """ Return the next text or binary message from the socket. This is an internal method as calling this will not cleanup correctly if an exception is called. Use `receive` instead. """ opcode = None message = None while True: header, payload = self.read_frame() f_opcode = header.opcode if f_opcode in (self.OPCODE_TEXT, self.OPCODE_BINARY): # a new frame if opcode: raise WebSocketError("The opcode in non-fin frame is expected to be zero, got {0!r}".format(f_opcode)) # Start reading a new message, reset the validator self.utf8validator.reset() self.utf8validate_last = (True, True, 0, 0) opcode = f_opcode elif f_opcode == self.OPCODE_CONTINUATION: if not opcode: raise WebSocketError("Unexpected frame with opcode=0") elif f_opcode == self.OPCODE_PING: self.handle_ping(header, payload) continue elif f_opcode == self.OPCODE_PONG: self.handle_pong(header, payload) continue elif f_opcode == self.OPCODE_CLOSE: self.handle_close(header, payload) return else: raise WebSocketError("Unexpected opcode={0!r}".format(f_opcode)) if opcode == self.OPCODE_TEXT: self.validate_utf8(payload) if six.PY3: payload = payload.decode() if message is None: message = six.text_type() if opcode == self.OPCODE_TEXT else six.binary_type() message += payload if header.fin: break if opcode == self.OPCODE_TEXT: if six.PY2: self.validate_utf8(message) else: self.validate_utf8(message.encode()) return message else: return bytearray(message)
python
def read_message(self): opcode = None message = None while True: header, payload = self.read_frame() f_opcode = header.opcode if f_opcode in (self.OPCODE_TEXT, self.OPCODE_BINARY): # a new frame if opcode: raise WebSocketError("The opcode in non-fin frame is expected to be zero, got {0!r}".format(f_opcode)) # Start reading a new message, reset the validator self.utf8validator.reset() self.utf8validate_last = (True, True, 0, 0) opcode = f_opcode elif f_opcode == self.OPCODE_CONTINUATION: if not opcode: raise WebSocketError("Unexpected frame with opcode=0") elif f_opcode == self.OPCODE_PING: self.handle_ping(header, payload) continue elif f_opcode == self.OPCODE_PONG: self.handle_pong(header, payload) continue elif f_opcode == self.OPCODE_CLOSE: self.handle_close(header, payload) return else: raise WebSocketError("Unexpected opcode={0!r}".format(f_opcode)) if opcode == self.OPCODE_TEXT: self.validate_utf8(payload) if six.PY3: payload = payload.decode() if message is None: message = six.text_type() if opcode == self.OPCODE_TEXT else six.binary_type() message += payload if header.fin: break if opcode == self.OPCODE_TEXT: if six.PY2: self.validate_utf8(message) else: self.validate_utf8(message.encode()) return message else: return bytearray(message)
[ "def", "read_message", "(", "self", ")", ":", "opcode", "=", "None", "message", "=", "None", "while", "True", ":", "header", ",", "payload", "=", "self", ".", "read_frame", "(", ")", "f_opcode", "=", "header", ".", "opcode", "if", "f_opcode", "in", "("...
Return the next text or binary message from the socket. This is an internal method as calling this will not cleanup correctly if an exception is called. Use `receive` instead.
[ "Return", "the", "next", "text", "or", "binary", "message", "from", "the", "socket", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/websocket.py#L157-L207
230,612
jrief/django-websocket-redis
ws4redis/websocket.py
WebSocket.close
def close(self, code=1000, message=''): """ Close the websocket and connection, sending the specified code and message. The underlying socket object is _not_ closed, that is the responsibility of the initiator. """ try: message = self._encode_bytes(message) self.send_frame( struct.pack('!H%ds' % len(message), code, message), opcode=self.OPCODE_CLOSE) except WebSocketError: # Failed to write the closing frame but it's ok because we're # closing the socket anyway. logger.debug("Failed to write closing frame -> closing socket") finally: logger.debug("Closed WebSocket") self._closed = True self.stream = None
python
def close(self, code=1000, message=''): try: message = self._encode_bytes(message) self.send_frame( struct.pack('!H%ds' % len(message), code, message), opcode=self.OPCODE_CLOSE) except WebSocketError: # Failed to write the closing frame but it's ok because we're # closing the socket anyway. logger.debug("Failed to write closing frame -> closing socket") finally: logger.debug("Closed WebSocket") self._closed = True self.stream = None
[ "def", "close", "(", "self", ",", "code", "=", "1000", ",", "message", "=", "''", ")", ":", "try", ":", "message", "=", "self", ".", "_encode_bytes", "(", "message", ")", "self", ".", "send_frame", "(", "struct", ".", "pack", "(", "'!H%ds'", "%", "...
Close the websocket and connection, sending the specified code and message. The underlying socket object is _not_ closed, that is the responsibility of the initiator.
[ "Close", "the", "websocket", "and", "connection", "sending", "the", "specified", "code", "and", "message", ".", "The", "underlying", "socket", "object", "is", "_not_", "closed", "that", "is", "the", "responsibility", "of", "the", "initiator", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/websocket.py#L262-L280
230,613
jrief/django-websocket-redis
ws4redis/websocket.py
Header.decode_header
def decode_header(cls, stream): """ Decode a WebSocket header. :param stream: A file like object that can be 'read' from. :returns: A `Header` instance. """ read = stream.read data = read(2) if len(data) != 2: raise WebSocketError("Unexpected EOF while decoding header") first_byte, second_byte = struct.unpack('!BB', data) header = cls( fin=first_byte & cls.FIN_MASK == cls.FIN_MASK, opcode=first_byte & cls.OPCODE_MASK, flags=first_byte & cls.HEADER_FLAG_MASK, length=second_byte & cls.LENGTH_MASK) has_mask = second_byte & cls.MASK_MASK == cls.MASK_MASK if header.opcode > 0x07: if not header.fin: raise WebSocketError('Received fragmented control frame: {0!r}'.format(data)) # Control frames MUST have a payload length of 125 bytes or less if header.length > 125: raise FrameTooLargeException('Control frame cannot be larger than 125 bytes: {0!r}'.format(data)) if header.length == 126: # 16 bit length data = read(2) if len(data) != 2: raise WebSocketError('Unexpected EOF while decoding header') header.length = struct.unpack('!H', data)[0] elif header.length == 127: # 64 bit length data = read(8) if len(data) != 8: raise WebSocketError('Unexpected EOF while decoding header') header.length = struct.unpack('!Q', data)[0] if has_mask: mask = read(4) if len(mask) != 4: raise WebSocketError('Unexpected EOF while decoding header') header.mask = mask return header
python
def decode_header(cls, stream): read = stream.read data = read(2) if len(data) != 2: raise WebSocketError("Unexpected EOF while decoding header") first_byte, second_byte = struct.unpack('!BB', data) header = cls( fin=first_byte & cls.FIN_MASK == cls.FIN_MASK, opcode=first_byte & cls.OPCODE_MASK, flags=first_byte & cls.HEADER_FLAG_MASK, length=second_byte & cls.LENGTH_MASK) has_mask = second_byte & cls.MASK_MASK == cls.MASK_MASK if header.opcode > 0x07: if not header.fin: raise WebSocketError('Received fragmented control frame: {0!r}'.format(data)) # Control frames MUST have a payload length of 125 bytes or less if header.length > 125: raise FrameTooLargeException('Control frame cannot be larger than 125 bytes: {0!r}'.format(data)) if header.length == 126: # 16 bit length data = read(2) if len(data) != 2: raise WebSocketError('Unexpected EOF while decoding header') header.length = struct.unpack('!H', data)[0] elif header.length == 127: # 64 bit length data = read(8) if len(data) != 8: raise WebSocketError('Unexpected EOF while decoding header') header.length = struct.unpack('!Q', data)[0] if has_mask: mask = read(4) if len(mask) != 4: raise WebSocketError('Unexpected EOF while decoding header') header.mask = mask return header
[ "def", "decode_header", "(", "cls", ",", "stream", ")", ":", "read", "=", "stream", ".", "read", "data", "=", "read", "(", "2", ")", "if", "len", "(", "data", ")", "!=", "2", ":", "raise", "WebSocketError", "(", "\"Unexpected EOF while decoding header\"", ...
Decode a WebSocket header. :param stream: A file like object that can be 'read' from. :returns: A `Header` instance.
[ "Decode", "a", "WebSocket", "header", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/websocket.py#L340-L381
230,614
jrief/django-websocket-redis
ws4redis/websocket.py
Header.encode_header
def encode_header(cls, fin, opcode, mask, length, flags): """ Encodes a WebSocket header. :param fin: Whether this is the final frame for this opcode. :param opcode: The opcode of the payload, see `OPCODE_*` :param mask: Whether the payload is masked. :param length: The length of the frame. :param flags: The RSV* flags. :return: A bytestring encoded header. """ first_byte = opcode second_byte = 0 if six.PY2: extra = '' else: extra = b'' if fin: first_byte |= cls.FIN_MASK if flags & cls.RSV0_MASK: first_byte |= cls.RSV0_MASK if flags & cls.RSV1_MASK: first_byte |= cls.RSV1_MASK if flags & cls.RSV2_MASK: first_byte |= cls.RSV2_MASK # now deal with length complexities if length < 126: second_byte += length elif length <= 0xffff: second_byte += 126 extra = struct.pack('!H', length) elif length <= 0xffffffffffffffff: second_byte += 127 extra = struct.pack('!Q', length) else: raise FrameTooLargeException if mask: second_byte |= cls.MASK_MASK extra += mask if six.PY3: return bytes([first_byte, second_byte]) + extra return chr(first_byte) + chr(second_byte) + extra
python
def encode_header(cls, fin, opcode, mask, length, flags): first_byte = opcode second_byte = 0 if six.PY2: extra = '' else: extra = b'' if fin: first_byte |= cls.FIN_MASK if flags & cls.RSV0_MASK: first_byte |= cls.RSV0_MASK if flags & cls.RSV1_MASK: first_byte |= cls.RSV1_MASK if flags & cls.RSV2_MASK: first_byte |= cls.RSV2_MASK # now deal with length complexities if length < 126: second_byte += length elif length <= 0xffff: second_byte += 126 extra = struct.pack('!H', length) elif length <= 0xffffffffffffffff: second_byte += 127 extra = struct.pack('!Q', length) else: raise FrameTooLargeException if mask: second_byte |= cls.MASK_MASK extra += mask if six.PY3: return bytes([first_byte, second_byte]) + extra return chr(first_byte) + chr(second_byte) + extra
[ "def", "encode_header", "(", "cls", ",", "fin", ",", "opcode", ",", "mask", ",", "length", ",", "flags", ")", ":", "first_byte", "=", "opcode", "second_byte", "=", "0", "if", "six", ".", "PY2", ":", "extra", "=", "''", "else", ":", "extra", "=", "b...
Encodes a WebSocket header. :param fin: Whether this is the final frame for this opcode. :param opcode: The opcode of the payload, see `OPCODE_*` :param mask: Whether the payload is masked. :param length: The length of the frame. :param flags: The RSV* flags. :return: A bytestring encoded header.
[ "Encodes", "a", "WebSocket", "header", "." ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/websocket.py#L384-L425
230,615
jrief/django-websocket-redis
ws4redis/models.py
store_groups_in_session
def store_groups_in_session(sender, user, request, **kwargs): """ When a user logs in, fetch its groups and store them in the users session. This is required by ws4redis, since fetching groups accesses the database, which is a blocking operation and thus not allowed from within the websocket loop. """ if hasattr(user, 'groups'): request.session['ws4redis:memberof'] = [g.name for g in user.groups.all()]
python
def store_groups_in_session(sender, user, request, **kwargs): if hasattr(user, 'groups'): request.session['ws4redis:memberof'] = [g.name for g in user.groups.all()]
[ "def", "store_groups_in_session", "(", "sender", ",", "user", ",", "request", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "user", ",", "'groups'", ")", ":", "request", ".", "session", "[", "'ws4redis:memberof'", "]", "=", "[", "g", ".", "n...
When a user logs in, fetch its groups and store them in the users session. This is required by ws4redis, since fetching groups accesses the database, which is a blocking operation and thus not allowed from within the websocket loop.
[ "When", "a", "user", "logs", "in", "fetch", "its", "groups", "and", "store", "them", "in", "the", "users", "session", ".", "This", "is", "required", "by", "ws4redis", "since", "fetching", "groups", "accesses", "the", "database", "which", "is", "a", "blocki...
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/models.py#L7-L14
230,616
jrief/django-websocket-redis
ws4redis/redis_store.py
RedisStore.publish_message
def publish_message(self, message, expire=None): """ Publish a ``message`` on the subscribed channel on the Redis datastore. ``expire`` sets the time in seconds, on how long the message shall additionally of being published, also be persisted in the Redis datastore. If unset, it defaults to the configuration settings ``WS4REDIS_EXPIRE``. """ if expire is None: expire = self._expire if not isinstance(message, RedisMessage): raise ValueError('message object is not of type RedisMessage') for channel in self._publishers: self._connection.publish(channel, message) if expire > 0: self._connection.setex(channel, expire, message)
python
def publish_message(self, message, expire=None): if expire is None: expire = self._expire if not isinstance(message, RedisMessage): raise ValueError('message object is not of type RedisMessage') for channel in self._publishers: self._connection.publish(channel, message) if expire > 0: self._connection.setex(channel, expire, message)
[ "def", "publish_message", "(", "self", ",", "message", ",", "expire", "=", "None", ")", ":", "if", "expire", "is", "None", ":", "expire", "=", "self", ".", "_expire", "if", "not", "isinstance", "(", "message", ",", "RedisMessage", ")", ":", "raise", "V...
Publish a ``message`` on the subscribed channel on the Redis datastore. ``expire`` sets the time in seconds, on how long the message shall additionally of being published, also be persisted in the Redis datastore. If unset, it defaults to the configuration settings ``WS4REDIS_EXPIRE``.
[ "Publish", "a", "message", "on", "the", "subscribed", "channel", "on", "the", "Redis", "datastore", ".", "expire", "sets", "the", "time", "in", "seconds", "on", "how", "long", "the", "message", "shall", "additionally", "of", "being", "published", "also", "be...
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/redis_store.py#L100-L114
230,617
jrief/django-websocket-redis
ws4redis/uwsgi_runserver.py
uWSGIWebsocket.get_file_descriptor
def get_file_descriptor(self): """Return the file descriptor for the given websocket""" try: return uwsgi.connection_fd() except IOError as e: self.close() raise WebSocketError(e)
python
def get_file_descriptor(self): try: return uwsgi.connection_fd() except IOError as e: self.close() raise WebSocketError(e)
[ "def", "get_file_descriptor", "(", "self", ")", ":", "try", ":", "return", "uwsgi", ".", "connection_fd", "(", ")", "except", "IOError", "as", "e", ":", "self", ".", "close", "(", ")", "raise", "WebSocketError", "(", "e", ")" ]
Return the file descriptor for the given websocket
[ "Return", "the", "file", "descriptor", "for", "the", "given", "websocket" ]
abcddaad2f579d71dbf375e5e34bc35eef795a81
https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/uwsgi_runserver.py#L12-L18
230,618
erget/StereoVision
stereovision/stereo_cameras.py
StereoPair.get_frames_singleimage
def get_frames_singleimage(self): """ Get current left and right frames from a single image, by splitting the image in half. """ frame = self.captures[0].read()[1] height, width, colors = frame.shape left_frame = frame[:, :width/2, :] right_frame = frame[:, width/2:, :] return [left_frame, right_frame]
python
def get_frames_singleimage(self): frame = self.captures[0].read()[1] height, width, colors = frame.shape left_frame = frame[:, :width/2, :] right_frame = frame[:, width/2:, :] return [left_frame, right_frame]
[ "def", "get_frames_singleimage", "(", "self", ")", ":", "frame", "=", "self", ".", "captures", "[", "0", "]", ".", "read", "(", ")", "[", "1", "]", "height", ",", "width", ",", "colors", "=", "frame", ".", "shape", "left_frame", "=", "frame", "[", ...
Get current left and right frames from a single image, by splitting the image in half.
[ "Get", "current", "left", "and", "right", "frames", "from", "a", "single", "image", "by", "splitting", "the", "image", "in", "half", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/stereo_cameras.py#L79-L88
230,619
erget/StereoVision
stereovision/stereo_cameras.py
StereoPair.show_frames
def show_frames(self, wait=0): """ Show current frames from cameras. ``wait`` is the wait interval in milliseconds before the window closes. """ for window, frame in zip(self.windows, self.get_frames()): cv2.imshow(window, frame) cv2.waitKey(wait)
python
def show_frames(self, wait=0): for window, frame in zip(self.windows, self.get_frames()): cv2.imshow(window, frame) cv2.waitKey(wait)
[ "def", "show_frames", "(", "self", ",", "wait", "=", "0", ")", ":", "for", "window", ",", "frame", "in", "zip", "(", "self", ".", "windows", ",", "self", ".", "get_frames", "(", ")", ")", ":", "cv2", ".", "imshow", "(", "window", ",", "frame", ")...
Show current frames from cameras. ``wait`` is the wait interval in milliseconds before the window closes.
[ "Show", "current", "frames", "from", "cameras", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/stereo_cameras.py#L90-L98
230,620
erget/StereoVision
stereovision/stereo_cameras.py
ChessboardFinder.get_chessboard
def get_chessboard(self, columns, rows, show=False): """ Take a picture with a chessboard visible in both captures. ``columns`` and ``rows`` should be the number of inside corners in the chessboard's columns and rows. ``show`` determines whether the frames are shown while the cameras search for a chessboard. """ found_chessboard = [False, False] while not all(found_chessboard): frames = self.get_frames() if show: self.show_frames(1) for i, frame in enumerate(frames): (found_chessboard[i], corners) = cv2.findChessboardCorners(frame, (columns, rows), flags=cv2.CALIB_CB_FAST_CHECK) return frames
python
def get_chessboard(self, columns, rows, show=False): found_chessboard = [False, False] while not all(found_chessboard): frames = self.get_frames() if show: self.show_frames(1) for i, frame in enumerate(frames): (found_chessboard[i], corners) = cv2.findChessboardCorners(frame, (columns, rows), flags=cv2.CALIB_CB_FAST_CHECK) return frames
[ "def", "get_chessboard", "(", "self", ",", "columns", ",", "rows", ",", "show", "=", "False", ")", ":", "found_chessboard", "=", "[", "False", ",", "False", "]", "while", "not", "all", "(", "found_chessboard", ")", ":", "frames", "=", "self", ".", "get...
Take a picture with a chessboard visible in both captures. ``columns`` and ``rows`` should be the number of inside corners in the chessboard's columns and rows. ``show`` determines whether the frames are shown while the cameras search for a chessboard.
[ "Take", "a", "picture", "with", "a", "chessboard", "visible", "in", "both", "captures", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/stereo_cameras.py#L112-L129
230,621
erget/StereoVision
stereovision/stereo_cameras.py
CalibratedPair.get_frames
def get_frames(self): """Rectify and return current frames from cameras.""" frames = super(CalibratedPair, self).get_frames() return self.calibration.rectify(frames)
python
def get_frames(self): frames = super(CalibratedPair, self).get_frames() return self.calibration.rectify(frames)
[ "def", "get_frames", "(", "self", ")", ":", "frames", "=", "super", "(", "CalibratedPair", ",", "self", ")", ".", "get_frames", "(", ")", "return", "self", ".", "calibration", ".", "rectify", "(", "frames", ")" ]
Rectify and return current frames from cameras.
[ "Rectify", "and", "return", "current", "frames", "from", "cameras", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/stereo_cameras.py#L154-L157
230,622
erget/StereoVision
stereovision/stereo_cameras.py
CalibratedPair.get_point_cloud
def get_point_cloud(self, pair): """Get 3D point cloud from image pair.""" disparity = self.block_matcher.get_disparity(pair) points = self.block_matcher.get_3d(disparity, self.calibration.disp_to_depth_mat) colors = cv2.cvtColor(pair[0], cv2.COLOR_BGR2RGB) return PointCloud(points, colors)
python
def get_point_cloud(self, pair): disparity = self.block_matcher.get_disparity(pair) points = self.block_matcher.get_3d(disparity, self.calibration.disp_to_depth_mat) colors = cv2.cvtColor(pair[0], cv2.COLOR_BGR2RGB) return PointCloud(points, colors)
[ "def", "get_point_cloud", "(", "self", ",", "pair", ")", ":", "disparity", "=", "self", ".", "block_matcher", ".", "get_disparity", "(", "pair", ")", "points", "=", "self", ".", "block_matcher", ".", "get_3d", "(", "disparity", ",", "self", ".", "calibrati...
Get 3D point cloud from image pair.
[ "Get", "3D", "point", "cloud", "from", "image", "pair", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/stereo_cameras.py#L159-L165
230,623
erget/StereoVision
stereovision/blockmatchers.py
BlockMatcher.load_settings
def load_settings(self, settings): """Load settings from file""" with open(settings) as settings_file: settings_dict = simplejson.load(settings_file) for key, value in settings_dict.items(): self.__setattr__(key, value)
python
def load_settings(self, settings): with open(settings) as settings_file: settings_dict = simplejson.load(settings_file) for key, value in settings_dict.items(): self.__setattr__(key, value)
[ "def", "load_settings", "(", "self", ",", "settings", ")", ":", "with", "open", "(", "settings", ")", "as", "settings_file", ":", "settings_dict", "=", "simplejson", ".", "load", "(", "settings_file", ")", "for", "key", ",", "value", "in", "settings_dict", ...
Load settings from file
[ "Load", "settings", "from", "file" ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L82-L87
230,624
erget/StereoVision
stereovision/blockmatchers.py
BlockMatcher.save_settings
def save_settings(self, settings_file): """Save block matcher settings to a file object""" settings = {} for parameter in self.parameter_maxima: settings[parameter] = self.__getattribute__(parameter) with open(settings_file, "w") as settings_file: simplejson.dump(settings, settings_file)
python
def save_settings(self, settings_file): settings = {} for parameter in self.parameter_maxima: settings[parameter] = self.__getattribute__(parameter) with open(settings_file, "w") as settings_file: simplejson.dump(settings, settings_file)
[ "def", "save_settings", "(", "self", ",", "settings_file", ")", ":", "settings", "=", "{", "}", "for", "parameter", "in", "self", ".", "parameter_maxima", ":", "settings", "[", "parameter", "]", "=", "self", ".", "__getattribute__", "(", "parameter", ")", ...
Save block matcher settings to a file object
[ "Save", "block", "matcher", "settings", "to", "a", "file", "object" ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L89-L95
230,625
erget/StereoVision
stereovision/blockmatchers.py
StereoBM.search_range
def search_range(self, value): """Set private ``_search_range`` and reset ``_block_matcher``.""" if value == 0 or not value % 16: self._search_range = value else: raise InvalidSearchRangeError("Search range must be a multiple of " "16.") self._replace_bm()
python
def search_range(self, value): if value == 0 or not value % 16: self._search_range = value else: raise InvalidSearchRangeError("Search range must be a multiple of " "16.") self._replace_bm()
[ "def", "search_range", "(", "self", ",", "value", ")", ":", "if", "value", "==", "0", "or", "not", "value", "%", "16", ":", "self", ".", "_search_range", "=", "value", "else", ":", "raise", "InvalidSearchRangeError", "(", "\"Search range must be a multiple of ...
Set private ``_search_range`` and reset ``_block_matcher``.
[ "Set", "private", "_search_range", "and", "reset", "_block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L125-L132
230,626
erget/StereoVision
stereovision/blockmatchers.py
StereoBM.window_size
def window_size(self, value): """Set private ``_window_size`` and reset ``_block_matcher``.""" if (value > 4 and value < self.parameter_maxima["window_size"] and value % 2): self._window_size = value else: raise InvalidWindowSizeError("Window size must be an odd number " "between 0 and {}.".format( self.parameter_maxima["window_size"] + 1)) self._replace_bm()
python
def window_size(self, value): if (value > 4 and value < self.parameter_maxima["window_size"] and value % 2): self._window_size = value else: raise InvalidWindowSizeError("Window size must be an odd number " "between 0 and {}.".format( self.parameter_maxima["window_size"] + 1)) self._replace_bm()
[ "def", "window_size", "(", "self", ",", "value", ")", ":", "if", "(", "value", ">", "4", "and", "value", "<", "self", ".", "parameter_maxima", "[", "\"window_size\"", "]", "and", "value", "%", "2", ")", ":", "self", ".", "_window_size", "=", "value", ...
Set private ``_window_size`` and reset ``_block_matcher``.
[ "Set", "private", "_window_size", "and", "reset", "_block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L140-L150
230,627
erget/StereoVision
stereovision/blockmatchers.py
StereoBM.stereo_bm_preset
def stereo_bm_preset(self, value): """Set private ``_stereo_bm_preset`` and reset ``_block_matcher``.""" if value in (cv2.STEREO_BM_BASIC_PRESET, cv2.STEREO_BM_FISH_EYE_PRESET, cv2.STEREO_BM_NARROW_PRESET): self._bm_preset = value else: raise InvalidBMPresetError("Stereo BM preset must be defined as " "cv2.STEREO_BM_*_PRESET.") self._replace_bm()
python
def stereo_bm_preset(self, value): if value in (cv2.STEREO_BM_BASIC_PRESET, cv2.STEREO_BM_FISH_EYE_PRESET, cv2.STEREO_BM_NARROW_PRESET): self._bm_preset = value else: raise InvalidBMPresetError("Stereo BM preset must be defined as " "cv2.STEREO_BM_*_PRESET.") self._replace_bm()
[ "def", "stereo_bm_preset", "(", "self", ",", "value", ")", ":", "if", "value", "in", "(", "cv2", ".", "STEREO_BM_BASIC_PRESET", ",", "cv2", ".", "STEREO_BM_FISH_EYE_PRESET", ",", "cv2", ".", "STEREO_BM_NARROW_PRESET", ")", ":", "self", ".", "_bm_preset", "=", ...
Set private ``_stereo_bm_preset`` and reset ``_block_matcher``.
[ "Set", "private", "_stereo_bm_preset", "and", "reset", "_block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L158-L167
230,628
erget/StereoVision
stereovision/blockmatchers.py
StereoSGBM.numDisparities
def numDisparities(self, value): """Set private ``_num_disp`` and reset ``_block_matcher``.""" if value > 0 and value % 16 == 0: self._num_disp = value else: raise InvalidNumDisparitiesError("numDisparities must be a " "positive integer evenly " "divisible by 16.") self._replace_bm()
python
def numDisparities(self, value): if value > 0 and value % 16 == 0: self._num_disp = value else: raise InvalidNumDisparitiesError("numDisparities must be a " "positive integer evenly " "divisible by 16.") self._replace_bm()
[ "def", "numDisparities", "(", "self", ",", "value", ")", ":", "if", "value", ">", "0", "and", "value", "%", "16", "==", "0", ":", "self", ".", "_num_disp", "=", "value", "else", ":", "raise", "InvalidNumDisparitiesError", "(", "\"numDisparities must be a \""...
Set private ``_num_disp`` and reset ``_block_matcher``.
[ "Set", "private", "_num_disp", "and", "reset", "_block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L239-L247
230,629
erget/StereoVision
stereovision/blockmatchers.py
StereoSGBM.SADWindowSize
def SADWindowSize(self, value): """Set private ``_sad_window_size`` and reset ``_block_matcher``.""" if value >= 1 and value <= 11 and value % 2: self._sad_window_size = value else: raise InvalidSADWindowSizeError("SADWindowSize must be odd and " "between 1 and 11.") self._replace_bm()
python
def SADWindowSize(self, value): if value >= 1 and value <= 11 and value % 2: self._sad_window_size = value else: raise InvalidSADWindowSizeError("SADWindowSize must be odd and " "between 1 and 11.") self._replace_bm()
[ "def", "SADWindowSize", "(", "self", ",", "value", ")", ":", "if", "value", ">=", "1", "and", "value", "<=", "11", "and", "value", "%", "2", ":", "self", ".", "_sad_window_size", "=", "value", "else", ":", "raise", "InvalidSADWindowSizeError", "(", "\"SA...
Set private ``_sad_window_size`` and reset ``_block_matcher``.
[ "Set", "private", "_sad_window_size", "and", "reset", "_block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L255-L262
230,630
erget/StereoVision
stereovision/blockmatchers.py
StereoSGBM.uniquenessRatio
def uniquenessRatio(self, value): """Set private ``_uniqueness`` and reset ``_block_matcher``.""" if value >= 5 and value <= 15: self._uniqueness = value else: raise InvalidUniquenessRatioError("Uniqueness ratio must be " "between 5 and 15.") self._replace_bm()
python
def uniquenessRatio(self, value): if value >= 5 and value <= 15: self._uniqueness = value else: raise InvalidUniquenessRatioError("Uniqueness ratio must be " "between 5 and 15.") self._replace_bm()
[ "def", "uniquenessRatio", "(", "self", ",", "value", ")", ":", "if", "value", ">=", "5", "and", "value", "<=", "15", ":", "self", ".", "_uniqueness", "=", "value", "else", ":", "raise", "InvalidUniquenessRatioError", "(", "\"Uniqueness ratio must be \"", "\"be...
Set private ``_uniqueness`` and reset ``_block_matcher``.
[ "Set", "private", "_uniqueness", "and", "reset", "_block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L270-L277
230,631
erget/StereoVision
stereovision/blockmatchers.py
StereoSGBM.speckleWindowSize
def speckleWindowSize(self, value): """Set private ``_speckle_window_size`` and reset ``_block_matcher``.""" if value >= 0 and value <= 200: self._speckle_window_size = value else: raise InvalidSpeckleWindowSizeError("Speckle window size must be 0 " "for disabled checks or " "between 50 and 200.") self._replace_bm()
python
def speckleWindowSize(self, value): if value >= 0 and value <= 200: self._speckle_window_size = value else: raise InvalidSpeckleWindowSizeError("Speckle window size must be 0 " "for disabled checks or " "between 50 and 200.") self._replace_bm()
[ "def", "speckleWindowSize", "(", "self", ",", "value", ")", ":", "if", "value", ">=", "0", "and", "value", "<=", "200", ":", "self", ".", "_speckle_window_size", "=", "value", "else", ":", "raise", "InvalidSpeckleWindowSizeError", "(", "\"Speckle window size mus...
Set private ``_speckle_window_size`` and reset ``_block_matcher``.
[ "Set", "private", "_speckle_window_size", "and", "reset", "_block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L285-L293
230,632
erget/StereoVision
stereovision/blockmatchers.py
StereoSGBM.speckleRange
def speckleRange(self, value): """Set private ``_speckle_range`` and reset ``_block_matcher``.""" if value >= 0: self._speckle_range = value else: raise InvalidSpeckleRangeError("Speckle range cannot be negative.") self._replace_bm()
python
def speckleRange(self, value): if value >= 0: self._speckle_range = value else: raise InvalidSpeckleRangeError("Speckle range cannot be negative.") self._replace_bm()
[ "def", "speckleRange", "(", "self", ",", "value", ")", ":", "if", "value", ">=", "0", ":", "self", ".", "_speckle_range", "=", "value", "else", ":", "raise", "InvalidSpeckleRangeError", "(", "\"Speckle range cannot be negative.\"", ")", "self", ".", "_replace_bm...
Set private ``_speckle_range`` and reset ``_block_matcher``.
[ "Set", "private", "_speckle_range", "and", "reset", "_block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L301-L307
230,633
erget/StereoVision
stereovision/blockmatchers.py
StereoSGBM.P1
def P1(self, value): """Set private ``_P1`` and reset ``_block_matcher``.""" if value < self.P2: self._P1 = value else: raise InvalidFirstDisparityChangePenaltyError("P1 must be less " "than P2.") self._replace_bm()
python
def P1(self, value): if value < self.P2: self._P1 = value else: raise InvalidFirstDisparityChangePenaltyError("P1 must be less " "than P2.") self._replace_bm()
[ "def", "P1", "(", "self", ",", "value", ")", ":", "if", "value", "<", "self", ".", "P2", ":", "self", ".", "_P1", "=", "value", "else", ":", "raise", "InvalidFirstDisparityChangePenaltyError", "(", "\"P1 must be less \"", "\"than P2.\"", ")", "self", ".", ...
Set private ``_P1`` and reset ``_block_matcher``.
[ "Set", "private", "_P1", "and", "reset", "_block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L326-L333
230,634
erget/StereoVision
stereovision/blockmatchers.py
StereoSGBM.P2
def P2(self, value): """Set private ``_P2`` and reset ``_block_matcher``.""" if value > self.P1: self._P2 = value else: raise InvalidSecondDisparityChangePenaltyError("P2 must be greater " "than P1.") self._replace_bm()
python
def P2(self, value): if value > self.P1: self._P2 = value else: raise InvalidSecondDisparityChangePenaltyError("P2 must be greater " "than P1.") self._replace_bm()
[ "def", "P2", "(", "self", ",", "value", ")", ":", "if", "value", ">", "self", ".", "P1", ":", "self", ".", "_P2", "=", "value", "else", ":", "raise", "InvalidSecondDisparityChangePenaltyError", "(", "\"P2 must be greater \"", "\"than P1.\"", ")", "self", "."...
Set private ``_P2`` and reset ``_block_matcher``.
[ "Set", "private", "_P2", "and", "reset", "_block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L341-L348
230,635
erget/StereoVision
stereovision/calibration.py
StereoCalibration._copy_calibration
def _copy_calibration(self, calibration): """Copy another ``StereoCalibration`` object's values.""" for key, item in calibration.__dict__.items(): self.__dict__[key] = item
python
def _copy_calibration(self, calibration): for key, item in calibration.__dict__.items(): self.__dict__[key] = item
[ "def", "_copy_calibration", "(", "self", ",", "calibration", ")", ":", "for", "key", ",", "item", "in", "calibration", ".", "__dict__", ".", "items", "(", ")", ":", "self", ".", "__dict__", "[", "key", "]", "=", "item" ]
Copy another ``StereoCalibration`` object's values.
[ "Copy", "another", "StereoCalibration", "object", "s", "values", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/calibration.py#L53-L56
230,636
erget/StereoVision
stereovision/calibration.py
StereoCalibrator._get_corners
def _get_corners(self, image): """Find subpixel chessboard corners in image.""" temp = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ret, corners = cv2.findChessboardCorners(temp, (self.rows, self.columns)) if not ret: raise ChessboardNotFoundError("No chessboard could be found.") cv2.cornerSubPix(temp, corners, (11, 11), (-1, -1), (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 30, 0.01)) return corners
python
def _get_corners(self, image): temp = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ret, corners = cv2.findChessboardCorners(temp, (self.rows, self.columns)) if not ret: raise ChessboardNotFoundError("No chessboard could be found.") cv2.cornerSubPix(temp, corners, (11, 11), (-1, -1), (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 30, 0.01)) return corners
[ "def", "_get_corners", "(", "self", ",", "image", ")", ":", "temp", "=", "cv2", ".", "cvtColor", "(", "image", ",", "cv2", ".", "COLOR_BGR2GRAY", ")", "ret", ",", "corners", "=", "cv2", ".", "findChessboardCorners", "(", "temp", ",", "(", "self", ".", ...
Find subpixel chessboard corners in image.
[ "Find", "subpixel", "chessboard", "corners", "in", "image", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/calibration.py#L149-L159
230,637
erget/StereoVision
stereovision/calibration.py
StereoCalibrator._show_corners
def _show_corners(self, image, corners): """Show chessboard corners found in image.""" temp = image cv2.drawChessboardCorners(temp, (self.rows, self.columns), corners, True) window_name = "Chessboard" cv2.imshow(window_name, temp) if cv2.waitKey(0): cv2.destroyWindow(window_name)
python
def _show_corners(self, image, corners): temp = image cv2.drawChessboardCorners(temp, (self.rows, self.columns), corners, True) window_name = "Chessboard" cv2.imshow(window_name, temp) if cv2.waitKey(0): cv2.destroyWindow(window_name)
[ "def", "_show_corners", "(", "self", ",", "image", ",", "corners", ")", ":", "temp", "=", "image", "cv2", ".", "drawChessboardCorners", "(", "temp", ",", "(", "self", ".", "rows", ",", "self", ".", "columns", ")", ",", "corners", ",", "True", ")", "w...
Show chessboard corners found in image.
[ "Show", "chessboard", "corners", "found", "in", "image", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/calibration.py#L161-L169
230,638
erget/StereoVision
stereovision/calibration.py
StereoCalibrator.add_corners
def add_corners(self, image_pair, show_results=False): """ Record chessboard corners found in an image pair. The image pair should be an iterable composed of two CvMats ordered (left, right). """ side = "left" self.object_points.append(self.corner_coordinates) for image in image_pair: corners = self._get_corners(image) if show_results: self._show_corners(image, corners) self.image_points[side].append(corners.reshape(-1, 2)) side = "right" self.image_count += 1
python
def add_corners(self, image_pair, show_results=False): side = "left" self.object_points.append(self.corner_coordinates) for image in image_pair: corners = self._get_corners(image) if show_results: self._show_corners(image, corners) self.image_points[side].append(corners.reshape(-1, 2)) side = "right" self.image_count += 1
[ "def", "add_corners", "(", "self", ",", "image_pair", ",", "show_results", "=", "False", ")", ":", "side", "=", "\"left\"", "self", ".", "object_points", ".", "append", "(", "self", ".", "corner_coordinates", ")", "for", "image", "in", "image_pair", ":", "...
Record chessboard corners found in an image pair. The image pair should be an iterable composed of two CvMats ordered (left, right).
[ "Record", "chessboard", "corners", "found", "in", "an", "image", "pair", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/calibration.py#L201-L216
230,639
erget/StereoVision
stereovision/calibration.py
StereoCalibrator.calibrate_cameras
def calibrate_cameras(self): """Calibrate cameras based on found chessboard corners.""" criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 100, 1e-5) flags = (cv2.CALIB_FIX_ASPECT_RATIO + cv2.CALIB_ZERO_TANGENT_DIST + cv2.CALIB_SAME_FOCAL_LENGTH) calib = StereoCalibration() (calib.cam_mats["left"], calib.dist_coefs["left"], calib.cam_mats["right"], calib.dist_coefs["right"], calib.rot_mat, calib.trans_vec, calib.e_mat, calib.f_mat) = cv2.stereoCalibrate(self.object_points, self.image_points["left"], self.image_points["right"], self.image_size, calib.cam_mats["left"], calib.dist_coefs["left"], calib.cam_mats["right"], calib.dist_coefs["right"], calib.rot_mat, calib.trans_vec, calib.e_mat, calib.f_mat, criteria=criteria, flags=flags)[1:] (calib.rect_trans["left"], calib.rect_trans["right"], calib.proj_mats["left"], calib.proj_mats["right"], calib.disp_to_depth_mat, calib.valid_boxes["left"], calib.valid_boxes["right"]) = cv2.stereoRectify(calib.cam_mats["left"], calib.dist_coefs["left"], calib.cam_mats["right"], calib.dist_coefs["right"], self.image_size, calib.rot_mat, calib.trans_vec, flags=0) for side in ("left", "right"): (calib.undistortion_map[side], calib.rectification_map[side]) = cv2.initUndistortRectifyMap( calib.cam_mats[side], calib.dist_coefs[side], calib.rect_trans[side], calib.proj_mats[side], self.image_size, cv2.CV_32FC1) # This is replaced because my results were always bad. Estimates are # taken from the OpenCV samples. width, height = self.image_size focal_length = 0.8 * width calib.disp_to_depth_mat = np.float32([[1, 0, 0, -0.5 * width], [0, -1, 0, 0.5 * height], [0, 0, 0, -focal_length], [0, 0, 1, 0]]) return calib
python
def calibrate_cameras(self): criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 100, 1e-5) flags = (cv2.CALIB_FIX_ASPECT_RATIO + cv2.CALIB_ZERO_TANGENT_DIST + cv2.CALIB_SAME_FOCAL_LENGTH) calib = StereoCalibration() (calib.cam_mats["left"], calib.dist_coefs["left"], calib.cam_mats["right"], calib.dist_coefs["right"], calib.rot_mat, calib.trans_vec, calib.e_mat, calib.f_mat) = cv2.stereoCalibrate(self.object_points, self.image_points["left"], self.image_points["right"], self.image_size, calib.cam_mats["left"], calib.dist_coefs["left"], calib.cam_mats["right"], calib.dist_coefs["right"], calib.rot_mat, calib.trans_vec, calib.e_mat, calib.f_mat, criteria=criteria, flags=flags)[1:] (calib.rect_trans["left"], calib.rect_trans["right"], calib.proj_mats["left"], calib.proj_mats["right"], calib.disp_to_depth_mat, calib.valid_boxes["left"], calib.valid_boxes["right"]) = cv2.stereoRectify(calib.cam_mats["left"], calib.dist_coefs["left"], calib.cam_mats["right"], calib.dist_coefs["right"], self.image_size, calib.rot_mat, calib.trans_vec, flags=0) for side in ("left", "right"): (calib.undistortion_map[side], calib.rectification_map[side]) = cv2.initUndistortRectifyMap( calib.cam_mats[side], calib.dist_coefs[side], calib.rect_trans[side], calib.proj_mats[side], self.image_size, cv2.CV_32FC1) # This is replaced because my results were always bad. Estimates are # taken from the OpenCV samples. width, height = self.image_size focal_length = 0.8 * width calib.disp_to_depth_mat = np.float32([[1, 0, 0, -0.5 * width], [0, -1, 0, 0.5 * height], [0, 0, 0, -focal_length], [0, 0, 1, 0]]) return calib
[ "def", "calibrate_cameras", "(", "self", ")", ":", "criteria", "=", "(", "cv2", ".", "TERM_CRITERIA_MAX_ITER", "+", "cv2", ".", "TERM_CRITERIA_EPS", ",", "100", ",", "1e-5", ")", "flags", "=", "(", "cv2", ".", "CALIB_FIX_ASPECT_RATIO", "+", "cv2", ".", "CA...
Calibrate cameras based on found chessboard corners.
[ "Calibrate", "cameras", "based", "on", "found", "chessboard", "corners", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/calibration.py#L218-L270
230,640
erget/StereoVision
stereovision/calibration.py
StereoCalibrator.check_calibration
def check_calibration(self, calibration): """ Check calibration quality by computing average reprojection error. First, undistort detected points and compute epilines for each side. Then compute the error between the computed epipolar lines and the position of the points detected on the other side for each point and return the average error. """ sides = "left", "right" which_image = {sides[0]: 1, sides[1]: 2} undistorted, lines = {}, {} for side in sides: undistorted[side] = cv2.undistortPoints( np.concatenate(self.image_points[side]).reshape(-1, 1, 2), calibration.cam_mats[side], calibration.dist_coefs[side], P=calibration.cam_mats[side]) lines[side] = cv2.computeCorrespondEpilines(undistorted[side], which_image[side], calibration.f_mat) total_error = 0 this_side, other_side = sides for side in sides: for i in range(len(undistorted[side])): total_error += abs(undistorted[this_side][i][0][0] * lines[other_side][i][0][0] + undistorted[this_side][i][0][1] * lines[other_side][i][0][1] + lines[other_side][i][0][2]) other_side, this_side = sides total_points = self.image_count * len(self.object_points) return total_error / total_points
python
def check_calibration(self, calibration): sides = "left", "right" which_image = {sides[0]: 1, sides[1]: 2} undistorted, lines = {}, {} for side in sides: undistorted[side] = cv2.undistortPoints( np.concatenate(self.image_points[side]).reshape(-1, 1, 2), calibration.cam_mats[side], calibration.dist_coefs[side], P=calibration.cam_mats[side]) lines[side] = cv2.computeCorrespondEpilines(undistorted[side], which_image[side], calibration.f_mat) total_error = 0 this_side, other_side = sides for side in sides: for i in range(len(undistorted[side])): total_error += abs(undistorted[this_side][i][0][0] * lines[other_side][i][0][0] + undistorted[this_side][i][0][1] * lines[other_side][i][0][1] + lines[other_side][i][0][2]) other_side, this_side = sides total_points = self.image_count * len(self.object_points) return total_error / total_points
[ "def", "check_calibration", "(", "self", ",", "calibration", ")", ":", "sides", "=", "\"left\"", ",", "\"right\"", "which_image", "=", "{", "sides", "[", "0", "]", ":", "1", ",", "sides", "[", "1", "]", ":", "2", "}", "undistorted", ",", "lines", "="...
Check calibration quality by computing average reprojection error. First, undistort detected points and compute epilines for each side. Then compute the error between the computed epipolar lines and the position of the points detected on the other side for each point and return the average error.
[ "Check", "calibration", "quality", "by", "computing", "average", "reprojection", "error", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/calibration.py#L272-L305
230,641
erget/StereoVision
stereovision/ui_utils.py
find_files
def find_files(folder): """Discover stereo photos and return them as a pairwise sorted list.""" files = [i for i in os.listdir(folder) if i.startswith("left")] files.sort() for i in range(len(files)): insert_string = "right{}".format(files[i * 2][4:]) files.insert(i * 2 + 1, insert_string) files = [os.path.join(folder, filename) for filename in files] return files
python
def find_files(folder): files = [i for i in os.listdir(folder) if i.startswith("left")] files.sort() for i in range(len(files)): insert_string = "right{}".format(files[i * 2][4:]) files.insert(i * 2 + 1, insert_string) files = [os.path.join(folder, filename) for filename in files] return files
[ "def", "find_files", "(", "folder", ")", ":", "files", "=", "[", "i", "for", "i", "in", "os", ".", "listdir", "(", "folder", ")", "if", "i", ".", "startswith", "(", "\"left\"", ")", "]", "files", ".", "sort", "(", ")", "for", "i", "in", "range", ...
Discover stereo photos and return them as a pairwise sorted list.
[ "Discover", "stereo", "photos", "and", "return", "them", "as", "a", "pairwise", "sorted", "list", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/ui_utils.py#L66-L74
230,642
erget/StereoVision
stereovision/ui_utils.py
calibrate_folder
def calibrate_folder(args): """ Calibrate camera based on chessboard images, write results to output folder. All images are read from disk. Chessboard points are found and used to calibrate the stereo pair. Finally, the calibration is written to the folder specified in ``args``. ``args`` needs to contain the following fields: input_files: List of paths to input files rows: Number of rows in chessboard columns: Number of columns in chessboard square_size: Size of chessboard squares in cm output_folder: Folder to write calibration to """ height, width = cv2.imread(args.input_files[0]).shape[:2] calibrator = StereoCalibrator(args.rows, args.columns, args.square_size, (width, height)) progress = ProgressBar(maxval=len(args.input_files), widgets=[Bar("=", "[", "]"), " ", Percentage()]) print("Reading input files...") progress.start() while args.input_files: left, right = args.input_files[:2] img_left, im_right = cv2.imread(left), cv2.imread(right) calibrator.add_corners((img_left, im_right), show_results=args.show_chessboards) args.input_files = args.input_files[2:] progress.update(progress.maxval - len(args.input_files)) progress.finish() print("Calibrating cameras. This can take a while.") calibration = calibrator.calibrate_cameras() avg_error = calibrator.check_calibration(calibration) print("The average error between chessboard points and their epipolar " "lines is \n" "{} pixels. This should be as small as possible.".format(avg_error)) calibration.export(args.output_folder)
python
def calibrate_folder(args): height, width = cv2.imread(args.input_files[0]).shape[:2] calibrator = StereoCalibrator(args.rows, args.columns, args.square_size, (width, height)) progress = ProgressBar(maxval=len(args.input_files), widgets=[Bar("=", "[", "]"), " ", Percentage()]) print("Reading input files...") progress.start() while args.input_files: left, right = args.input_files[:2] img_left, im_right = cv2.imread(left), cv2.imread(right) calibrator.add_corners((img_left, im_right), show_results=args.show_chessboards) args.input_files = args.input_files[2:] progress.update(progress.maxval - len(args.input_files)) progress.finish() print("Calibrating cameras. This can take a while.") calibration = calibrator.calibrate_cameras() avg_error = calibrator.check_calibration(calibration) print("The average error between chessboard points and their epipolar " "lines is \n" "{} pixels. This should be as small as possible.".format(avg_error)) calibration.export(args.output_folder)
[ "def", "calibrate_folder", "(", "args", ")", ":", "height", ",", "width", "=", "cv2", ".", "imread", "(", "args", ".", "input_files", "[", "0", "]", ")", ".", "shape", "[", ":", "2", "]", "calibrator", "=", "StereoCalibrator", "(", "args", ".", "rows...
Calibrate camera based on chessboard images, write results to output folder. All images are read from disk. Chessboard points are found and used to calibrate the stereo pair. Finally, the calibration is written to the folder specified in ``args``. ``args`` needs to contain the following fields: input_files: List of paths to input files rows: Number of rows in chessboard columns: Number of columns in chessboard square_size: Size of chessboard squares in cm output_folder: Folder to write calibration to
[ "Calibrate", "camera", "based", "on", "chessboard", "images", "write", "results", "to", "output", "folder", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/ui_utils.py#L77-L115
230,643
erget/StereoVision
stereovision/ui_utils.py
BMTuner._set_value
def _set_value(self, parameter, new_value): """Try setting new parameter on ``block_matcher`` and update map.""" try: self.block_matcher.__setattr__(parameter, new_value) except BadBlockMatcherArgumentError: return self.update_disparity_map()
python
def _set_value(self, parameter, new_value): try: self.block_matcher.__setattr__(parameter, new_value) except BadBlockMatcherArgumentError: return self.update_disparity_map()
[ "def", "_set_value", "(", "self", ",", "parameter", ",", "new_value", ")", ":", "try", ":", "self", ".", "block_matcher", ".", "__setattr__", "(", "parameter", ",", "new_value", ")", "except", "BadBlockMatcherArgumentError", ":", "return", "self", ".", "update...
Try setting new parameter on ``block_matcher`` and update map.
[ "Try", "setting", "new", "parameter", "on", "block_matcher", "and", "update", "map", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/ui_utils.py#L134-L140
230,644
erget/StereoVision
stereovision/ui_utils.py
BMTuner._initialize_trackbars
def _initialize_trackbars(self): """ Initialize trackbars by discovering ``block_matcher``'s parameters. """ for parameter in self.block_matcher.parameter_maxima.keys(): maximum = self.block_matcher.parameter_maxima[parameter] if not maximum: maximum = self.shortest_dimension cv2.createTrackbar(parameter, self.window_name, self.block_matcher.__getattribute__(parameter), maximum, partial(self._set_value, parameter))
python
def _initialize_trackbars(self): for parameter in self.block_matcher.parameter_maxima.keys(): maximum = self.block_matcher.parameter_maxima[parameter] if not maximum: maximum = self.shortest_dimension cv2.createTrackbar(parameter, self.window_name, self.block_matcher.__getattribute__(parameter), maximum, partial(self._set_value, parameter))
[ "def", "_initialize_trackbars", "(", "self", ")", ":", "for", "parameter", "in", "self", ".", "block_matcher", ".", "parameter_maxima", ".", "keys", "(", ")", ":", "maximum", "=", "self", ".", "block_matcher", ".", "parameter_maxima", "[", "parameter", "]", ...
Initialize trackbars by discovering ``block_matcher``'s parameters.
[ "Initialize", "trackbars", "by", "discovering", "block_matcher", "s", "parameters", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/ui_utils.py#L142-L153
230,645
erget/StereoVision
stereovision/ui_utils.py
BMTuner._save_bm_state
def _save_bm_state(self): """Save current state of ``block_matcher``.""" for parameter in self.block_matcher.parameter_maxima.keys(): self.bm_settings[parameter].append( self.block_matcher.__getattribute__(parameter))
python
def _save_bm_state(self): for parameter in self.block_matcher.parameter_maxima.keys(): self.bm_settings[parameter].append( self.block_matcher.__getattribute__(parameter))
[ "def", "_save_bm_state", "(", "self", ")", ":", "for", "parameter", "in", "self", ".", "block_matcher", ".", "parameter_maxima", ".", "keys", "(", ")", ":", "self", ".", "bm_settings", "[", "parameter", "]", ".", "append", "(", "self", ".", "block_matcher"...
Save current state of ``block_matcher``.
[ "Save", "current", "state", "of", "block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/ui_utils.py#L155-L159
230,646
erget/StereoVision
stereovision/ui_utils.py
BMTuner.update_disparity_map
def update_disparity_map(self): """ Update disparity map in GUI. The disparity image is normalized to the range 0-255 and then divided by 255, because OpenCV multiplies it by 255 when displaying. This is because the pixels are stored as floating points. """ disparity = self.block_matcher.get_disparity(self.pair) norm_coeff = 255 / disparity.max() cv2.imshow(self.window_name, disparity * norm_coeff / 255) cv2.waitKey()
python
def update_disparity_map(self): disparity = self.block_matcher.get_disparity(self.pair) norm_coeff = 255 / disparity.max() cv2.imshow(self.window_name, disparity * norm_coeff / 255) cv2.waitKey()
[ "def", "update_disparity_map", "(", "self", ")", ":", "disparity", "=", "self", ".", "block_matcher", ".", "get_disparity", "(", "self", ".", "pair", ")", "norm_coeff", "=", "255", "/", "disparity", ".", "max", "(", ")", "cv2", ".", "imshow", "(", "self"...
Update disparity map in GUI. The disparity image is normalized to the range 0-255 and then divided by 255, because OpenCV multiplies it by 255 when displaying. This is because the pixels are stored as floating points.
[ "Update", "disparity", "map", "in", "GUI", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/ui_utils.py#L184-L195
230,647
erget/StereoVision
stereovision/ui_utils.py
BMTuner.tune_pair
def tune_pair(self, pair): """Tune a pair of images.""" self._save_bm_state() self.pair = pair self.update_disparity_map()
python
def tune_pair(self, pair): self._save_bm_state() self.pair = pair self.update_disparity_map()
[ "def", "tune_pair", "(", "self", ",", "pair", ")", ":", "self", ".", "_save_bm_state", "(", ")", "self", ".", "pair", "=", "pair", "self", ".", "update_disparity_map", "(", ")" ]
Tune a pair of images.
[ "Tune", "a", "pair", "of", "images", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/ui_utils.py#L197-L201
230,648
erget/StereoVision
stereovision/ui_utils.py
BMTuner.report_settings
def report_settings(self, parameter): """ Report chosen settings for ``parameter`` in ``block_matcher``. ``bm_settings`` is updated to include the latest state before work is begun. This state is removed at the end so that the method has no side effects. All settings are reported except for the first one on record, which is ``block_matcher``'s default setting. """ self._save_bm_state() report = [] settings_list = self.bm_settings[parameter][1:] unique_values = list(set(settings_list)) value_frequency = {} for value in unique_values: value_frequency[settings_list.count(value)] = value frequencies = value_frequency.keys() frequencies.sort(reverse=True) header = "{} value | Selection frequency".format(parameter) left_column_width = len(header[:-21]) right_column_width = 21 report.append(header) report.append("{}|{}".format("-" * left_column_width, "-" * right_column_width)) for frequency in frequencies: left_column = str(value_frequency[frequency]).center( left_column_width) right_column = str(frequency).center(right_column_width) report.append("{}|{}".format(left_column, right_column)) # Remove newest settings for param in self.block_matcher.parameter_maxima.keys(): self.bm_settings[param].pop(-1) return "\n".join(report)
python
def report_settings(self, parameter): self._save_bm_state() report = [] settings_list = self.bm_settings[parameter][1:] unique_values = list(set(settings_list)) value_frequency = {} for value in unique_values: value_frequency[settings_list.count(value)] = value frequencies = value_frequency.keys() frequencies.sort(reverse=True) header = "{} value | Selection frequency".format(parameter) left_column_width = len(header[:-21]) right_column_width = 21 report.append(header) report.append("{}|{}".format("-" * left_column_width, "-" * right_column_width)) for frequency in frequencies: left_column = str(value_frequency[frequency]).center( left_column_width) right_column = str(frequency).center(right_column_width) report.append("{}|{}".format(left_column, right_column)) # Remove newest settings for param in self.block_matcher.parameter_maxima.keys(): self.bm_settings[param].pop(-1) return "\n".join(report)
[ "def", "report_settings", "(", "self", ",", "parameter", ")", ":", "self", ".", "_save_bm_state", "(", ")", "report", "=", "[", "]", "settings_list", "=", "self", ".", "bm_settings", "[", "parameter", "]", "[", "1", ":", "]", "unique_values", "=", "list"...
Report chosen settings for ``parameter`` in ``block_matcher``. ``bm_settings`` is updated to include the latest state before work is begun. This state is removed at the end so that the method has no side effects. All settings are reported except for the first one on record, which is ``block_matcher``'s default setting.
[ "Report", "chosen", "settings", "for", "parameter", "in", "block_matcher", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/ui_utils.py#L203-L235
230,649
erget/StereoVision
stereovision/point_cloud.py
PointCloud.write_ply
def write_ply(self, output_file): """Export ``PointCloud`` to PLY file for viewing in MeshLab.""" points = np.hstack([self.coordinates, self.colors]) with open(output_file, 'w') as outfile: outfile.write(self.ply_header.format( vertex_count=len(self.coordinates))) np.savetxt(outfile, points, '%f %f %f %d %d %d')
python
def write_ply(self, output_file): points = np.hstack([self.coordinates, self.colors]) with open(output_file, 'w') as outfile: outfile.write(self.ply_header.format( vertex_count=len(self.coordinates))) np.savetxt(outfile, points, '%f %f %f %d %d %d')
[ "def", "write_ply", "(", "self", ",", "output_file", ")", ":", "points", "=", "np", ".", "hstack", "(", "[", "self", ".", "coordinates", ",", "self", ".", "colors", "]", ")", "with", "open", "(", "output_file", ",", "'w'", ")", "as", "outfile", ":", ...
Export ``PointCloud`` to PLY file for viewing in MeshLab.
[ "Export", "PointCloud", "to", "PLY", "file", "for", "viewing", "in", "MeshLab", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/point_cloud.py#L61-L67
230,650
erget/StereoVision
stereovision/point_cloud.py
PointCloud.filter_infinity
def filter_infinity(self): """Filter infinite distances from ``PointCloud.``""" mask = self.coordinates[:, 2] > self.coordinates[:, 2].min() coords = self.coordinates[mask] colors = self.colors[mask] return PointCloud(coords, colors)
python
def filter_infinity(self): mask = self.coordinates[:, 2] > self.coordinates[:, 2].min() coords = self.coordinates[mask] colors = self.colors[mask] return PointCloud(coords, colors)
[ "def", "filter_infinity", "(", "self", ")", ":", "mask", "=", "self", ".", "coordinates", "[", ":", ",", "2", "]", ">", "self", ".", "coordinates", "[", ":", ",", "2", "]", ".", "min", "(", ")", "coords", "=", "self", ".", "coordinates", "[", "ma...
Filter infinite distances from ``PointCloud.``
[ "Filter", "infinite", "distances", "from", "PointCloud", "." ]
1adff45e291362f52188e0fd0211265845a4461a
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/point_cloud.py#L69-L74
230,651
webrecorder/pywb
pywb/utils/loaders.py
BlockLoader._get_loader_for_url
def _get_loader_for_url(self, url): """ Determine loading method based on uri """ parts = url.split('://', 1) if len(parts) < 2: type_ = 'file' else: type_ = parts[0] if '+' in type_: profile_name, scheme = type_.split('+', 1) if len(parts) == 2: url = scheme + '://' + parts[1] else: profile_name = '' scheme = type_ loader = self.cached.get(type_) if loader: return loader, url loader_cls = self._get_loader_class_for_type(scheme) if not loader_cls: raise IOError('No Loader for type: ' + scheme) profile = self.kwargs if self.profile_loader: profile = self.profile_loader(profile_name, scheme) loader = loader_cls(**profile) self.cached[type_] = loader return loader, url
python
def _get_loader_for_url(self, url): parts = url.split('://', 1) if len(parts) < 2: type_ = 'file' else: type_ = parts[0] if '+' in type_: profile_name, scheme = type_.split('+', 1) if len(parts) == 2: url = scheme + '://' + parts[1] else: profile_name = '' scheme = type_ loader = self.cached.get(type_) if loader: return loader, url loader_cls = self._get_loader_class_for_type(scheme) if not loader_cls: raise IOError('No Loader for type: ' + scheme) profile = self.kwargs if self.profile_loader: profile = self.profile_loader(profile_name, scheme) loader = loader_cls(**profile) self.cached[type_] = loader return loader, url
[ "def", "_get_loader_for_url", "(", "self", ",", "url", ")", ":", "parts", "=", "url", ".", "split", "(", "'://'", ",", "1", ")", "if", "len", "(", "parts", ")", "<", "2", ":", "type_", "=", "'file'", "else", ":", "type_", "=", "parts", "[", "0", ...
Determine loading method based on uri
[ "Determine", "loading", "method", "based", "on", "uri" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/utils/loaders.py#L181-L216
230,652
webrecorder/pywb
pywb/utils/loaders.py
LocalFileLoader.load
def load(self, url, offset=0, length=-1): """ Load a file-like reader from the local file system """ # if starting with . or /, can only be a file path.. file_only = url.startswith(('/', '.')) # convert to filename filename = from_file_url(url) if filename != url: file_only = True url = filename try: # first, try as file afile = open(url, 'rb') except IOError: if file_only: raise return super(LocalFileLoader, self).load(url, offset, length) if offset > 0: afile.seek(offset) if length >= 0: return LimitReader(afile, length) else: return afile
python
def load(self, url, offset=0, length=-1): # if starting with . or /, can only be a file path.. file_only = url.startswith(('/', '.')) # convert to filename filename = from_file_url(url) if filename != url: file_only = True url = filename try: # first, try as file afile = open(url, 'rb') except IOError: if file_only: raise return super(LocalFileLoader, self).load(url, offset, length) if offset > 0: afile.seek(offset) if length >= 0: return LimitReader(afile, length) else: return afile
[ "def", "load", "(", "self", ",", "url", ",", "offset", "=", "0", ",", "length", "=", "-", "1", ")", ":", "# if starting with . or /, can only be a file path..", "file_only", "=", "url", ".", "startswith", "(", "(", "'/'", ",", "'.'", ")", ")", "# convert t...
Load a file-like reader from the local file system
[ "Load", "a", "file", "-", "like", "reader", "from", "the", "local", "file", "system" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/utils/loaders.py#L272-L302
230,653
webrecorder/pywb
pywb/utils/loaders.py
HttpLoader.load
def load(self, url, offset, length): """ Load a file-like reader over http using range requests and an optional cookie created via a cookie_maker """ headers = {} if offset != 0 or length != -1: headers['Range'] = BlockLoader._make_range_header(offset, length) if self.cookie_maker: if isinstance(self.cookie_maker, six.string_types): headers['Cookie'] = self.cookie_maker else: headers['Cookie'] = self.cookie_maker.make() if not self.session: self.session = requests.Session() r = self.session.get(url, headers=headers, stream=True) r.raise_for_status() return r.raw
python
def load(self, url, offset, length): headers = {} if offset != 0 or length != -1: headers['Range'] = BlockLoader._make_range_header(offset, length) if self.cookie_maker: if isinstance(self.cookie_maker, six.string_types): headers['Cookie'] = self.cookie_maker else: headers['Cookie'] = self.cookie_maker.make() if not self.session: self.session = requests.Session() r = self.session.get(url, headers=headers, stream=True) r.raise_for_status() return r.raw
[ "def", "load", "(", "self", ",", "url", ",", "offset", ",", "length", ")", ":", "headers", "=", "{", "}", "if", "offset", "!=", "0", "or", "length", "!=", "-", "1", ":", "headers", "[", "'Range'", "]", "=", "BlockLoader", ".", "_make_range_header", ...
Load a file-like reader over http using range requests and an optional cookie created via a cookie_maker
[ "Load", "a", "file", "-", "like", "reader", "over", "http", "using", "range", "requests", "and", "an", "optional", "cookie", "created", "via", "a", "cookie_maker" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/utils/loaders.py#L313-L333
230,654
webrecorder/pywb
pywb/warcserver/resource/responseloader.py
BaseLoader.raise_on_self_redirect
def raise_on_self_redirect(self, params, cdx, status_code, location_url): """ Check if response is a 3xx redirect to the same url If so, reject this capture to avoid causing redirect loop """ if cdx.get('is_live'): return if not status_code.startswith('3') or status_code == '304': return request_url = params['url'].lower() if not location_url: return location_url = location_url.lower() if location_url.startswith('/'): host = urlsplit(cdx['url']).netloc location_url = host + location_url location_url = location_url.split('://', 1)[-1].rstrip('/') request_url = request_url.split('://', 1)[-1].rstrip('/') self_redir = False if request_url == location_url: self_redir = True elif params.get('sr-urlkey'): # if new location canonicalized matches old key, also self-redirect if canonicalize(location_url) == params.get('sr-urlkey'): self_redir = True if self_redir: msg = 'Self Redirect {0} -> {1}' msg = msg.format(request_url, location_url) params['sr-urlkey'] = cdx['urlkey'] raise LiveResourceException(msg)
python
def raise_on_self_redirect(self, params, cdx, status_code, location_url): if cdx.get('is_live'): return if not status_code.startswith('3') or status_code == '304': return request_url = params['url'].lower() if not location_url: return location_url = location_url.lower() if location_url.startswith('/'): host = urlsplit(cdx['url']).netloc location_url = host + location_url location_url = location_url.split('://', 1)[-1].rstrip('/') request_url = request_url.split('://', 1)[-1].rstrip('/') self_redir = False if request_url == location_url: self_redir = True elif params.get('sr-urlkey'): # if new location canonicalized matches old key, also self-redirect if canonicalize(location_url) == params.get('sr-urlkey'): self_redir = True if self_redir: msg = 'Self Redirect {0} -> {1}' msg = msg.format(request_url, location_url) params['sr-urlkey'] = cdx['urlkey'] raise LiveResourceException(msg)
[ "def", "raise_on_self_redirect", "(", "self", ",", "params", ",", "cdx", ",", "status_code", ",", "location_url", ")", ":", "if", "cdx", ".", "get", "(", "'is_live'", ")", ":", "return", "if", "not", "status_code", ".", "startswith", "(", "'3'", ")", "or...
Check if response is a 3xx redirect to the same url If so, reject this capture to avoid causing redirect loop
[ "Check", "if", "response", "is", "a", "3xx", "redirect", "to", "the", "same", "url", "If", "so", "reject", "this", "capture", "to", "avoid", "causing", "redirect", "loop" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/resource/responseloader.py#L121-L158
230,655
webrecorder/pywb
pywb/warcserver/resource/blockrecordloader.py
BlockArcWarcRecordLoader.load
def load(self, url, offset, length, no_record_parse=False): """ Load a single record from given url at offset with length and parse as either warc or arc record """ try: length = int(length) except: length = -1 stream = self.loader.load(url, int(offset), length) decomp_type = 'gzip' # Create decompressing stream stream = DecompressingBufferedReader(stream=stream, decomp_type=decomp_type, block_size=self.block_size) return self.parse_record_stream(stream, no_record_parse=no_record_parse)
python
def load(self, url, offset, length, no_record_parse=False): try: length = int(length) except: length = -1 stream = self.loader.load(url, int(offset), length) decomp_type = 'gzip' # Create decompressing stream stream = DecompressingBufferedReader(stream=stream, decomp_type=decomp_type, block_size=self.block_size) return self.parse_record_stream(stream, no_record_parse=no_record_parse)
[ "def", "load", "(", "self", ",", "url", ",", "offset", ",", "length", ",", "no_record_parse", "=", "False", ")", ":", "try", ":", "length", "=", "int", "(", "length", ")", "except", ":", "length", "=", "-", "1", "stream", "=", "self", ".", "loader"...
Load a single record from given url at offset with length and parse as either warc or arc record
[ "Load", "a", "single", "record", "from", "given", "url", "at", "offset", "with", "length", "and", "parse", "as", "either", "warc", "or", "arc", "record" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/resource/blockrecordloader.py#L18-L35
230,656
webrecorder/pywb
pywb/warcserver/index/cdxobject.py
CDXObject.conv_to_json
def conv_to_json(obj, fields=None): """ return cdx as json dictionary string if ``fields`` is ``None``, output will include all fields in order stored, otherwise only specified fields will be included :param fields: list of field names to output """ if fields is None: return json_encode(OrderedDict(((x, obj[x]) for x in obj if not x.startswith('_')))) + '\n' result = json_encode(OrderedDict([(x, obj[x]) for x in fields if x in obj])) + '\n' return result
python
def conv_to_json(obj, fields=None): if fields is None: return json_encode(OrderedDict(((x, obj[x]) for x in obj if not x.startswith('_')))) + '\n' result = json_encode(OrderedDict([(x, obj[x]) for x in fields if x in obj])) + '\n' return result
[ "def", "conv_to_json", "(", "obj", ",", "fields", "=", "None", ")", ":", "if", "fields", "is", "None", ":", "return", "json_encode", "(", "OrderedDict", "(", "(", "(", "x", ",", "obj", "[", "x", "]", ")", "for", "x", "in", "obj", "if", "not", "x"...
return cdx as json dictionary string if ``fields`` is ``None``, output will include all fields in order stored, otherwise only specified fields will be included :param fields: list of field names to output
[ "return", "cdx", "as", "json", "dictionary", "string", "if", "fields", "is", "None", "output", "will", "include", "all", "fields", "in", "order", "stored", "otherwise", "only", "specified", "fields", "will", "be", "included" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/cdxobject.py#L198-L212
230,657
webrecorder/pywb
pywb/rewrite/content_rewriter.py
StreamingRewriter.rewrite_text_stream_to_gen
def rewrite_text_stream_to_gen(self, stream, rwinfo): """ Convert stream to generator using applying rewriting func to each portion of the stream. Align to line boundaries if needed. """ try: buff = self.first_buff # for html rewriting: # if charset is utf-8, use that, otherwise default to encode to ascii-compatible encoding # encoding only used for url rewriting, encoding back to bytes after rewriting if rwinfo.charset == 'utf-8' and rwinfo.text_type == 'html': charset = 'utf-8' else: charset = 'iso-8859-1' if buff: yield buff.encode(charset) decoder = codecs.getincrementaldecoder(charset)() while True: buff = stream.read(BUFF_SIZE) if not buff: break if self.align_to_line: buff += stream.readline() try: buff = decoder.decode(buff) except UnicodeDecodeError: if charset == 'utf-8': rwinfo.charset = 'iso-8859-1' charset = rwinfo.charset decoder = codecs.getincrementaldecoder(charset)() buff = decoder.decode(buff) buff = self.rewrite(buff) yield buff.encode(charset) # For adding a tail/handling final buffer buff = self.final_read() # ensure decoder is marked as finished (final buffer already decoded) decoder.decode(b'', final=True) if buff: yield buff.encode(charset) finally: stream.close()
python
def rewrite_text_stream_to_gen(self, stream, rwinfo): try: buff = self.first_buff # for html rewriting: # if charset is utf-8, use that, otherwise default to encode to ascii-compatible encoding # encoding only used for url rewriting, encoding back to bytes after rewriting if rwinfo.charset == 'utf-8' and rwinfo.text_type == 'html': charset = 'utf-8' else: charset = 'iso-8859-1' if buff: yield buff.encode(charset) decoder = codecs.getincrementaldecoder(charset)() while True: buff = stream.read(BUFF_SIZE) if not buff: break if self.align_to_line: buff += stream.readline() try: buff = decoder.decode(buff) except UnicodeDecodeError: if charset == 'utf-8': rwinfo.charset = 'iso-8859-1' charset = rwinfo.charset decoder = codecs.getincrementaldecoder(charset)() buff = decoder.decode(buff) buff = self.rewrite(buff) yield buff.encode(charset) # For adding a tail/handling final buffer buff = self.final_read() # ensure decoder is marked as finished (final buffer already decoded) decoder.decode(b'', final=True) if buff: yield buff.encode(charset) finally: stream.close()
[ "def", "rewrite_text_stream_to_gen", "(", "self", ",", "stream", ",", "rwinfo", ")", ":", "try", ":", "buff", "=", "self", ".", "first_buff", "# for html rewriting:", "# if charset is utf-8, use that, otherwise default to encode to ascii-compatible encoding", "# encoding only u...
Convert stream to generator using applying rewriting func to each portion of the stream. Align to line boundaries if needed.
[ "Convert", "stream", "to", "generator", "using", "applying", "rewriting", "func", "to", "each", "portion", "of", "the", "stream", ".", "Align", "to", "line", "boundaries", "if", "needed", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/rewrite/content_rewriter.py#L292-L345
230,658
webrecorder/pywb
pywb/warcserver/index/cdxops.py
cdx_load
def cdx_load(sources, query, process=True): """ merge text CDX lines from sources, return an iterator for filtered and access-checked sequence of CDX objects. :param sources: iterable for text CDX sources. :param process: bool, perform processing sorting/filtering/grouping ops """ cdx_iter = create_merged_cdx_gen(sources, query) # page count is a special case, no further processing if query.page_count: return cdx_iter cdx_iter = make_obj_iter(cdx_iter, query) if process and not query.secondary_index_only: cdx_iter = process_cdx(cdx_iter, query) custom_ops = query.custom_ops for op in custom_ops: cdx_iter = op(cdx_iter, query) if query.output == 'text': cdx_iter = cdx_to_text(cdx_iter, query.fields) elif query.output == 'json': cdx_iter = cdx_to_json(cdx_iter, query.fields) return cdx_iter
python
def cdx_load(sources, query, process=True): cdx_iter = create_merged_cdx_gen(sources, query) # page count is a special case, no further processing if query.page_count: return cdx_iter cdx_iter = make_obj_iter(cdx_iter, query) if process and not query.secondary_index_only: cdx_iter = process_cdx(cdx_iter, query) custom_ops = query.custom_ops for op in custom_ops: cdx_iter = op(cdx_iter, query) if query.output == 'text': cdx_iter = cdx_to_text(cdx_iter, query.fields) elif query.output == 'json': cdx_iter = cdx_to_json(cdx_iter, query.fields) return cdx_iter
[ "def", "cdx_load", "(", "sources", ",", "query", ",", "process", "=", "True", ")", ":", "cdx_iter", "=", "create_merged_cdx_gen", "(", "sources", ",", "query", ")", "# page count is a special case, no further processing", "if", "query", ".", "page_count", ":", "re...
merge text CDX lines from sources, return an iterator for filtered and access-checked sequence of CDX objects. :param sources: iterable for text CDX sources. :param process: bool, perform processing sorting/filtering/grouping ops
[ "merge", "text", "CDX", "lines", "from", "sources", "return", "an", "iterator", "for", "filtered", "and", "access", "-", "checked", "sequence", "of", "CDX", "objects", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/cdxops.py#L20-L48
230,659
webrecorder/pywb
pywb/warcserver/index/cdxops.py
create_merged_cdx_gen
def create_merged_cdx_gen(sources, query): """ create a generator which loads and merges cdx streams ensures cdxs are lazy loaded """ # Optimize: no need to merge if just one input if len(sources) == 1: cdx_iter = sources[0].load_cdx(query) else: source_iters = map(lambda src: src.load_cdx(query), sources) cdx_iter = merge(*(source_iters)) for cdx in cdx_iter: yield cdx
python
def create_merged_cdx_gen(sources, query): # Optimize: no need to merge if just one input if len(sources) == 1: cdx_iter = sources[0].load_cdx(query) else: source_iters = map(lambda src: src.load_cdx(query), sources) cdx_iter = merge(*(source_iters)) for cdx in cdx_iter: yield cdx
[ "def", "create_merged_cdx_gen", "(", "sources", ",", "query", ")", ":", "# Optimize: no need to merge if just one input", "if", "len", "(", "sources", ")", "==", "1", ":", "cdx_iter", "=", "sources", "[", "0", "]", ".", "load_cdx", "(", "query", ")", "else", ...
create a generator which loads and merges cdx streams ensures cdxs are lazy loaded
[ "create", "a", "generator", "which", "loads", "and", "merges", "cdx", "streams", "ensures", "cdxs", "are", "lazy", "loaded" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/cdxops.py#L96-L109
230,660
webrecorder/pywb
pywb/warcserver/index/cdxops.py
cdx_limit
def cdx_limit(cdx_iter, limit): """ limit cdx to at most `limit`. """ # for cdx, _ in itertools.izip(cdx_iter, xrange(limit)): # yield cdx return (cdx for cdx, _ in zip(cdx_iter, range(limit)))
python
def cdx_limit(cdx_iter, limit): # for cdx, _ in itertools.izip(cdx_iter, xrange(limit)): # yield cdx return (cdx for cdx, _ in zip(cdx_iter, range(limit)))
[ "def", "cdx_limit", "(", "cdx_iter", ",", "limit", ")", ":", "# for cdx, _ in itertools.izip(cdx_iter, xrange(limit)):", "# yield cdx", "return", "(", "cdx", "for", "cdx", ",", "_", "in", "zip", "(", "cdx_iter", ",", "range", "(", "limit", ")", ")", ")...
limit cdx to at most `limit`.
[ "limit", "cdx", "to", "at", "most", "limit", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/cdxops.py#L126-L132
230,661
webrecorder/pywb
pywb/warcserver/index/cdxops.py
cdx_reverse
def cdx_reverse(cdx_iter, limit): """ return cdx records in reverse order. """ # optimize for single last if limit == 1: last = None for cdx in cdx_iter: last = cdx if not last: return yield last reverse_cdxs = deque(maxlen=limit) for cdx in cdx_iter: reverse_cdxs.appendleft(cdx) for cdx in reverse_cdxs: yield cdx
python
def cdx_reverse(cdx_iter, limit): # optimize for single last if limit == 1: last = None for cdx in cdx_iter: last = cdx if not last: return yield last reverse_cdxs = deque(maxlen=limit) for cdx in cdx_iter: reverse_cdxs.appendleft(cdx) for cdx in reverse_cdxs: yield cdx
[ "def", "cdx_reverse", "(", "cdx_iter", ",", "limit", ")", ":", "# optimize for single last", "if", "limit", "==", "1", ":", "last", "=", "None", "for", "cdx", "in", "cdx_iter", ":", "last", "=", "cdx", "if", "not", "last", ":", "return", "yield", "last",...
return cdx records in reverse order.
[ "return", "cdx", "records", "in", "reverse", "order", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/cdxops.py#L136-L157
230,662
webrecorder/pywb
pywb/warcserver/index/cdxops.py
cdx_clamp
def cdx_clamp(cdx_iter, from_ts, to_ts): """ Clamp by start and end ts """ if from_ts and len(from_ts) < 14: from_ts = pad_timestamp(from_ts, PAD_14_DOWN) if to_ts and len(to_ts) < 14: to_ts = pad_timestamp(to_ts, PAD_14_UP) for cdx in cdx_iter: if from_ts and cdx[TIMESTAMP] < from_ts: continue if to_ts and cdx[TIMESTAMP] > to_ts: continue yield cdx
python
def cdx_clamp(cdx_iter, from_ts, to_ts): if from_ts and len(from_ts) < 14: from_ts = pad_timestamp(from_ts, PAD_14_DOWN) if to_ts and len(to_ts) < 14: to_ts = pad_timestamp(to_ts, PAD_14_UP) for cdx in cdx_iter: if from_ts and cdx[TIMESTAMP] < from_ts: continue if to_ts and cdx[TIMESTAMP] > to_ts: continue yield cdx
[ "def", "cdx_clamp", "(", "cdx_iter", ",", "from_ts", ",", "to_ts", ")", ":", "if", "from_ts", "and", "len", "(", "from_ts", ")", "<", "14", ":", "from_ts", "=", "pad_timestamp", "(", "from_ts", ",", "PAD_14_DOWN", ")", "if", "to_ts", "and", "len", "(",...
Clamp by start and end ts
[ "Clamp", "by", "start", "and", "end", "ts" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/cdxops.py#L236-L253
230,663
webrecorder/pywb
pywb/warcserver/index/cdxops.py
cdx_collapse_time_status
def cdx_collapse_time_status(cdx_iter, timelen=10): """ collapse by timestamp and status code. """ timelen = int(timelen) last_token = None for cdx in cdx_iter: curr_token = (cdx[TIMESTAMP][:timelen], cdx.get(STATUSCODE, '')) # yield if last_dedup_time is diff, otherwise skip if curr_token != last_token: last_token = curr_token yield cdx
python
def cdx_collapse_time_status(cdx_iter, timelen=10): timelen = int(timelen) last_token = None for cdx in cdx_iter: curr_token = (cdx[TIMESTAMP][:timelen], cdx.get(STATUSCODE, '')) # yield if last_dedup_time is diff, otherwise skip if curr_token != last_token: last_token = curr_token yield cdx
[ "def", "cdx_collapse_time_status", "(", "cdx_iter", ",", "timelen", "=", "10", ")", ":", "timelen", "=", "int", "(", "timelen", ")", "last_token", "=", "None", "for", "cdx", "in", "cdx_iter", ":", "curr_token", "=", "(", "cdx", "[", "TIMESTAMP", "]", "["...
collapse by timestamp and status code.
[ "collapse", "by", "timestamp", "and", "status", "code", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/cdxops.py#L257-L271
230,664
webrecorder/pywb
pywb/warcserver/index/cdxops.py
cdx_sort_closest
def cdx_sort_closest(closest, cdx_iter, limit=10): """ sort CDXCaptureResult by closest to timestamp. """ closest_cdx = [] closest_keys = [] closest_sec = timestamp_to_sec(closest) for cdx in cdx_iter: sec = timestamp_to_sec(cdx[TIMESTAMP]) key = abs(closest_sec - sec) # create tuple to sort by key #bisect.insort(closest_cdx, (key, cdx)) i = bisect.bisect_right(closest_keys, key) closest_keys.insert(i, key) closest_cdx.insert(i, cdx) if len(closest_cdx) == limit: # assuming cdx in ascending order and keys have started increasing if key > closest_keys[-1]: break if len(closest_cdx) > limit: closest_cdx.pop() for cdx in closest_cdx: yield cdx
python
def cdx_sort_closest(closest, cdx_iter, limit=10): closest_cdx = [] closest_keys = [] closest_sec = timestamp_to_sec(closest) for cdx in cdx_iter: sec = timestamp_to_sec(cdx[TIMESTAMP]) key = abs(closest_sec - sec) # create tuple to sort by key #bisect.insort(closest_cdx, (key, cdx)) i = bisect.bisect_right(closest_keys, key) closest_keys.insert(i, key) closest_cdx.insert(i, cdx) if len(closest_cdx) == limit: # assuming cdx in ascending order and keys have started increasing if key > closest_keys[-1]: break if len(closest_cdx) > limit: closest_cdx.pop() for cdx in closest_cdx: yield cdx
[ "def", "cdx_sort_closest", "(", "closest", ",", "cdx_iter", ",", "limit", "=", "10", ")", ":", "closest_cdx", "=", "[", "]", "closest_keys", "=", "[", "]", "closest_sec", "=", "timestamp_to_sec", "(", "closest", ")", "for", "cdx", "in", "cdx_iter", ":", ...
sort CDXCaptureResult by closest to timestamp.
[ "sort", "CDXCaptureResult", "by", "closest", "to", "timestamp", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/cdxops.py#L275-L303
230,665
webrecorder/pywb
pywb/warcserver/index/cdxops.py
cdx_resolve_revisits
def cdx_resolve_revisits(cdx_iter): """ resolve revisits. this filter adds three fields to CDX: ``orig.length``, ``orig.offset``, and ``orig.filename``. for revisit records, these fields have corresponding field values in previous non-revisit (original) CDX record. They are all ``"-"`` for non-revisit records. """ originals = {} for cdx in cdx_iter: is_revisit = cdx.is_revisit() digest = cdx.get(DIGEST) original_cdx = None # only set if digest is valid, otherwise no way to resolve if digest: original_cdx = originals.get(digest) if not original_cdx and not is_revisit: originals[digest] = cdx if original_cdx and is_revisit: fill_orig = lambda field: original_cdx.get(field, '-') # Transfer mimetype and statuscode if MIMETYPE in cdx: cdx[MIMETYPE] = original_cdx.get(MIMETYPE, '') if STATUSCODE in cdx: cdx[STATUSCODE] = original_cdx.get(STATUSCODE, '') else: fill_orig = lambda field: '-' # Always add either the original or empty '- - -' for field in ORIG_TUPLE: cdx['orig.' + field] = fill_orig(field) yield cdx
python
def cdx_resolve_revisits(cdx_iter): originals = {} for cdx in cdx_iter: is_revisit = cdx.is_revisit() digest = cdx.get(DIGEST) original_cdx = None # only set if digest is valid, otherwise no way to resolve if digest: original_cdx = originals.get(digest) if not original_cdx and not is_revisit: originals[digest] = cdx if original_cdx and is_revisit: fill_orig = lambda field: original_cdx.get(field, '-') # Transfer mimetype and statuscode if MIMETYPE in cdx: cdx[MIMETYPE] = original_cdx.get(MIMETYPE, '') if STATUSCODE in cdx: cdx[STATUSCODE] = original_cdx.get(STATUSCODE, '') else: fill_orig = lambda field: '-' # Always add either the original or empty '- - -' for field in ORIG_TUPLE: cdx['orig.' + field] = fill_orig(field) yield cdx
[ "def", "cdx_resolve_revisits", "(", "cdx_iter", ")", ":", "originals", "=", "{", "}", "for", "cdx", "in", "cdx_iter", ":", "is_revisit", "=", "cdx", ".", "is_revisit", "(", ")", "digest", "=", "cdx", ".", "get", "(", "DIGEST", ")", "original_cdx", "=", ...
resolve revisits. this filter adds three fields to CDX: ``orig.length``, ``orig.offset``, and ``orig.filename``. for revisit records, these fields have corresponding field values in previous non-revisit (original) CDX record. They are all ``"-"`` for non-revisit records.
[ "resolve", "revisits", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/cdxops.py#L316-L355
230,666
webrecorder/pywb
pywb/apps/cli.py
BaseCli.load
def load(self): """This method is called to load the application. Subclasses must return a application that can be used by used by pywb.utils.geventserver.GeventServer.""" if self.r.live: self.extra_config['collections'] = {'live': {'index': '$live'}} if self.r.debug: self.extra_config['debug'] = True if self.r.record: self.extra_config['recorder'] = 'live'
python
def load(self): if self.r.live: self.extra_config['collections'] = {'live': {'index': '$live'}} if self.r.debug: self.extra_config['debug'] = True if self.r.record: self.extra_config['recorder'] = 'live'
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "r", ".", "live", ":", "self", ".", "extra_config", "[", "'collections'", "]", "=", "{", "'live'", ":", "{", "'index'", ":", "'$live'", "}", "}", "if", "self", ".", "r", ".", "debug", ":", ...
This method is called to load the application. Subclasses must return a application that can be used by used by pywb.utils.geventserver.GeventServer.
[ "This", "method", "is", "called", "to", "load", "the", "application", ".", "Subclasses", "must", "return", "a", "application", "that", "can", "be", "used", "by", "used", "by", "pywb", ".", "utils", ".", "geventserver", ".", "GeventServer", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/cli.py#L102-L113
230,667
webrecorder/pywb
pywb/apps/cli.py
BaseCli.run_gevent
def run_gevent(self): """Created the server that runs the application supplied a subclass""" from pywb.utils.geventserver import GeventServer, RequestURIWSGIHandler logging.info('Starting Gevent Server on ' + str(self.r.port)) ge = GeventServer(self.application, port=self.r.port, hostname=self.r.bind, handler_class=RequestURIWSGIHandler, direct=True)
python
def run_gevent(self): from pywb.utils.geventserver import GeventServer, RequestURIWSGIHandler logging.info('Starting Gevent Server on ' + str(self.r.port)) ge = GeventServer(self.application, port=self.r.port, hostname=self.r.bind, handler_class=RequestURIWSGIHandler, direct=True)
[ "def", "run_gevent", "(", "self", ")", ":", "from", "pywb", ".", "utils", ".", "geventserver", "import", "GeventServer", ",", "RequestURIWSGIHandler", "logging", ".", "info", "(", "'Starting Gevent Server on '", "+", "str", "(", "self", ".", "r", ".", "port", ...
Created the server that runs the application supplied a subclass
[ "Created", "the", "server", "that", "runs", "the", "application", "supplied", "a", "subclass" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/cli.py#L120-L128
230,668
webrecorder/pywb
pywb/rewrite/templateview.py
JinjaEnv._make_loaders
def _make_loaders(self, paths, packages): """Initialize the template loaders based on the supplied paths and packages. :param list[str] paths: List of paths to search for templates :param list[str] packages: List of assets package names :return: A list of loaders to be used for loading the template assets :rtype: list[FileSystemLoader|PackageLoader] """ loaders = [] # add loaders for paths for path in paths: loaders.append(FileSystemLoader(path)) # add loaders for all specified packages for package in packages: loaders.append(PackageLoader(package)) return loaders
python
def _make_loaders(self, paths, packages): loaders = [] # add loaders for paths for path in paths: loaders.append(FileSystemLoader(path)) # add loaders for all specified packages for package in packages: loaders.append(PackageLoader(package)) return loaders
[ "def", "_make_loaders", "(", "self", ",", "paths", ",", "packages", ")", ":", "loaders", "=", "[", "]", "# add loaders for paths", "for", "path", "in", "paths", ":", "loaders", ".", "append", "(", "FileSystemLoader", "(", "path", ")", ")", "# add loaders for...
Initialize the template loaders based on the supplied paths and packages. :param list[str] paths: List of paths to search for templates :param list[str] packages: List of assets package names :return: A list of loaders to be used for loading the template assets :rtype: list[FileSystemLoader|PackageLoader]
[ "Initialize", "the", "template", "loaders", "based", "on", "the", "supplied", "paths", "and", "packages", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/rewrite/templateview.py#L99-L116
230,669
webrecorder/pywb
pywb/rewrite/templateview.py
JinjaEnv.template_filter
def template_filter(self, param=None): """Returns a decorator that adds the wrapped function to dictionary of template filters. The wrapped function is keyed by either the supplied param (if supplied) or by the wrapped functions name. :param param: Optional name to use instead of the name of the function to be wrapped :return: A decorator to wrap a template filter function :rtype: callable """ def deco(func): name = param or func.__name__ self.filters[name] = func return func return deco
python
def template_filter(self, param=None): def deco(func): name = param or func.__name__ self.filters[name] = func return func return deco
[ "def", "template_filter", "(", "self", ",", "param", "=", "None", ")", ":", "def", "deco", "(", "func", ")", ":", "name", "=", "param", "or", "func", ".", "__name__", "self", ".", "filters", "[", "name", "]", "=", "func", "return", "func", "return", ...
Returns a decorator that adds the wrapped function to dictionary of template filters. The wrapped function is keyed by either the supplied param (if supplied) or by the wrapped functions name. :param param: Optional name to use instead of the name of the function to be wrapped :return: A decorator to wrap a template filter function :rtype: callable
[ "Returns", "a", "decorator", "that", "adds", "the", "wrapped", "function", "to", "dictionary", "of", "template", "filters", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/rewrite/templateview.py#L118-L133
230,670
webrecorder/pywb
pywb/rewrite/templateview.py
JinjaEnv._init_filters
def _init_filters(self): """Initialize the default pywb provided Jninja filters available during template rendering""" self.filters = {} @self.template_filter() def format_ts(value, format_='%a, %b %d %Y %H:%M:%S'): """Formats the supplied timestamp using format_ :param str value: The timestamp to be formatted :param str format_: The format string :return: The correctly formatted timestamp as determined by format_ :rtype: str """ if format_ == '%s': return timestamp_to_sec(value) else: value = timestamp_to_datetime(value) return value.strftime(format_) @self.template_filter('urlsplit') def get_urlsplit(url): """Splits the supplied URL :param str url: The url to be split :return: The split url :rtype: urllib.parse.SplitResult """ split = urlsplit(url) return split @self.template_filter() def tojson(obj): """Converts the supplied object/array/any to a JSON string if it can be JSONified :param any obj: The value to be converted to a JSON string :return: The JSON string representation of the supplied value :rtype: str """ return json.dumps(obj) @self.template_filter() def tobool(bool_val): """Converts a python boolean to a JS "true" or "false" string :param any obj: A value to be evaluated as a boolean :return: The string "true" or "false" to be inserted into JS """ return 'true' if bool_val else 'false'
python
def _init_filters(self): self.filters = {} @self.template_filter() def format_ts(value, format_='%a, %b %d %Y %H:%M:%S'): """Formats the supplied timestamp using format_ :param str value: The timestamp to be formatted :param str format_: The format string :return: The correctly formatted timestamp as determined by format_ :rtype: str """ if format_ == '%s': return timestamp_to_sec(value) else: value = timestamp_to_datetime(value) return value.strftime(format_) @self.template_filter('urlsplit') def get_urlsplit(url): """Splits the supplied URL :param str url: The url to be split :return: The split url :rtype: urllib.parse.SplitResult """ split = urlsplit(url) return split @self.template_filter() def tojson(obj): """Converts the supplied object/array/any to a JSON string if it can be JSONified :param any obj: The value to be converted to a JSON string :return: The JSON string representation of the supplied value :rtype: str """ return json.dumps(obj) @self.template_filter() def tobool(bool_val): """Converts a python boolean to a JS "true" or "false" string :param any obj: A value to be evaluated as a boolean :return: The string "true" or "false" to be inserted into JS """ return 'true' if bool_val else 'false'
[ "def", "_init_filters", "(", "self", ")", ":", "self", ".", "filters", "=", "{", "}", "@", "self", ".", "template_filter", "(", ")", "def", "format_ts", "(", "value", ",", "format_", "=", "'%a, %b %d %Y %H:%M:%S'", ")", ":", "\"\"\"Formats the supplied timesta...
Initialize the default pywb provided Jninja filters available during template rendering
[ "Initialize", "the", "default", "pywb", "provided", "Jninja", "filters", "available", "during", "template", "rendering" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/rewrite/templateview.py#L135-L182
230,671
webrecorder/pywb
pywb/rewrite/templateview.py
BaseInsertView.render_to_string
def render_to_string(self, env, **kwargs): """Render this template. :param dict env: The WSGI environment associated with the request causing this template to be rendered :param any kwargs: The keyword arguments to be supplied to the Jninja template render method :return: The rendered template :rtype: str """ template = None template_path = env.get(self.jenv.env_template_dir_key) if template_path: # jinja paths are not os paths, always use '/' as separator # https://github.com/pallets/jinja/issues/411 template_path = template_path + '/' + self.insert_file try: template = self.jenv.jinja_env.get_template(template_path) except TemplateNotFound as te: pass if not template: template = self.jenv.jinja_env.get_template(self.insert_file) params = env.get(self.jenv.env_template_params_key) if params: kwargs.update(params) kwargs['env'] = env kwargs['static_prefix'] = env.get('pywb.host_prefix', '') + env.get('pywb.app_prefix', '') + '/static' return template.render(**kwargs)
python
def render_to_string(self, env, **kwargs): template = None template_path = env.get(self.jenv.env_template_dir_key) if template_path: # jinja paths are not os paths, always use '/' as separator # https://github.com/pallets/jinja/issues/411 template_path = template_path + '/' + self.insert_file try: template = self.jenv.jinja_env.get_template(template_path) except TemplateNotFound as te: pass if not template: template = self.jenv.jinja_env.get_template(self.insert_file) params = env.get(self.jenv.env_template_params_key) if params: kwargs.update(params) kwargs['env'] = env kwargs['static_prefix'] = env.get('pywb.host_prefix', '') + env.get('pywb.app_prefix', '') + '/static' return template.render(**kwargs)
[ "def", "render_to_string", "(", "self", ",", "env", ",", "*", "*", "kwargs", ")", ":", "template", "=", "None", "template_path", "=", "env", ".", "get", "(", "self", ".", "jenv", ".", "env_template_dir_key", ")", "if", "template_path", ":", "# jinja paths ...
Render this template. :param dict env: The WSGI environment associated with the request causing this template to be rendered :param any kwargs: The keyword arguments to be supplied to the Jninja template render method :return: The rendered template :rtype: str
[ "Render", "this", "template", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/rewrite/templateview.py#L200-L232
230,672
webrecorder/pywb
pywb/rewrite/templateview.py
HeadInsertView.create_insert_func
def create_insert_func(self, wb_url, wb_prefix, host_prefix, top_url, env, is_framed, coll='', include_ts=True, **kwargs): """Create the function used to render the header insert template for the current request. :param rewrite.wburl.WbUrl wb_url: The WbUrl for the request this template is being rendered for :param str wb_prefix: The URL prefix pywb is serving the content using (e.g. http://localhost:8080/live/) :param str host_prefix: The host URL prefix pywb is running on (e.g. http://localhost:8080) :param str top_url: The full URL for this request (e.g. http://localhost:8080/live/http://example.com) :param dict env: The WSGI environment dictionary for this request :param bool is_framed: Is pywb or a specific collection running in framed mode :param str coll: The name of the collection this request is associated with :param bool include_ts: Should a timestamp be included in the rendered template :param kwargs: Additional keyword arguments to be supplied to the Jninja template render method :return: A function to be used to render the header insert for the request this template is being rendered for :rtype: callable """ params = kwargs params['host_prefix'] = host_prefix params['wb_prefix'] = wb_prefix params['wb_url'] = wb_url params['top_url'] = top_url params['coll'] = coll params['is_framed'] = is_framed def make_head_insert(rule, cdx): params['wombat_ts'] = cdx['timestamp'] if include_ts else '' params['wombat_sec'] = timestamp_to_sec(cdx['timestamp']) params['is_live'] = cdx.get('is_live') if self.banner_view: banner_html = self.banner_view.render_to_string(env, cdx=cdx, **params) params['banner_html'] = banner_html return self.render_to_string(env, cdx=cdx, **params) return make_head_insert
python
def create_insert_func(self, wb_url, wb_prefix, host_prefix, top_url, env, is_framed, coll='', include_ts=True, **kwargs): params = kwargs params['host_prefix'] = host_prefix params['wb_prefix'] = wb_prefix params['wb_url'] = wb_url params['top_url'] = top_url params['coll'] = coll params['is_framed'] = is_framed def make_head_insert(rule, cdx): params['wombat_ts'] = cdx['timestamp'] if include_ts else '' params['wombat_sec'] = timestamp_to_sec(cdx['timestamp']) params['is_live'] = cdx.get('is_live') if self.banner_view: banner_html = self.banner_view.render_to_string(env, cdx=cdx, **params) params['banner_html'] = banner_html return self.render_to_string(env, cdx=cdx, **params) return make_head_insert
[ "def", "create_insert_func", "(", "self", ",", "wb_url", ",", "wb_prefix", ",", "host_prefix", ",", "top_url", ",", "env", ",", "is_framed", ",", "coll", "=", "''", ",", "include_ts", "=", "True", ",", "*", "*", "kwargs", ")", ":", "params", "=", "kwar...
Create the function used to render the header insert template for the current request. :param rewrite.wburl.WbUrl wb_url: The WbUrl for the request this template is being rendered for :param str wb_prefix: The URL prefix pywb is serving the content using (e.g. http://localhost:8080/live/) :param str host_prefix: The host URL prefix pywb is running on (e.g. http://localhost:8080) :param str top_url: The full URL for this request (e.g. http://localhost:8080/live/http://example.com) :param dict env: The WSGI environment dictionary for this request :param bool is_framed: Is pywb or a specific collection running in framed mode :param str coll: The name of the collection this request is associated with :param bool include_ts: Should a timestamp be included in the rendered template :param kwargs: Additional keyword arguments to be supplied to the Jninja template render method :return: A function to be used to render the header insert for the request this template is being rendered for :rtype: callable
[ "Create", "the", "function", "used", "to", "render", "the", "header", "insert", "template", "for", "the", "current", "request", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/rewrite/templateview.py#L240-L282
230,673
webrecorder/pywb
pywb/rewrite/templateview.py
PkgResResolver.get_pkg_path
def get_pkg_path(self, item): """Get the package path for the :param str item: A resources full package path :return: The netloc and path from the items package path :rtype: tuple[str, str] """ if not isinstance(item, str): return None parts = urlsplit(item) if parts.scheme == 'pkg' and parts.netloc: return (parts.netloc, parts.path) return None
python
def get_pkg_path(self, item): if not isinstance(item, str): return None parts = urlsplit(item) if parts.scheme == 'pkg' and parts.netloc: return (parts.netloc, parts.path) return None
[ "def", "get_pkg_path", "(", "self", ",", "item", ")", ":", "if", "not", "isinstance", "(", "item", ",", "str", ")", ":", "return", "None", "parts", "=", "urlsplit", "(", "item", ")", "if", "parts", ".", "scheme", "==", "'pkg'", "and", "parts", ".", ...
Get the package path for the :param str item: A resources full package path :return: The netloc and path from the items package path :rtype: tuple[str, str]
[ "Get", "the", "package", "path", "for", "the" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/rewrite/templateview.py#L347-L361
230,674
webrecorder/pywb
pywb/apps/wbrequestresponse.py
WbResponse.text_stream
def text_stream(stream, content_type='text/plain; charset=utf-8', status='200 OK'): """Utility method for constructing a streaming text response. :param Any stream: The response body stream :param str content_type: The content-type of the response :param str status: The HTTP status line :return: WbResponse that is a text stream :rtype WbResponse: """ if 'charset' not in content_type: content_type += '; charset=utf-8' return WbResponse.bin_stream(WbResponse.encode_stream(stream), content_type, status)
python
def text_stream(stream, content_type='text/plain; charset=utf-8', status='200 OK'): if 'charset' not in content_type: content_type += '; charset=utf-8' return WbResponse.bin_stream(WbResponse.encode_stream(stream), content_type, status)
[ "def", "text_stream", "(", "stream", ",", "content_type", "=", "'text/plain; charset=utf-8'", ",", "status", "=", "'200 OK'", ")", ":", "if", "'charset'", "not", "in", "content_type", ":", "content_type", "+=", "'; charset=utf-8'", "return", "WbResponse", ".", "bi...
Utility method for constructing a streaming text response. :param Any stream: The response body stream :param str content_type: The content-type of the response :param str status: The HTTP status line :return: WbResponse that is a text stream :rtype WbResponse:
[ "Utility", "method", "for", "constructing", "a", "streaming", "text", "response", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/wbrequestresponse.py#L38-L50
230,675
webrecorder/pywb
pywb/apps/wbrequestresponse.py
WbResponse.bin_stream
def bin_stream(stream, content_type, status='200 OK', headers=None): """Utility method for constructing a binary response. :param Any stream: The response body stream :param str content_type: The content-type of the response :param str status: The HTTP status line :param list[tuple[str, str]] headers: Additional headers for this response :return: WbResponse that is a binary stream :rtype: WbResponse """ def_headers = [('Content-Type', content_type)] if headers: def_headers += headers status_headers = StatusAndHeaders(status, def_headers) return WbResponse(status_headers, value=stream)
python
def bin_stream(stream, content_type, status='200 OK', headers=None): def_headers = [('Content-Type', content_type)] if headers: def_headers += headers status_headers = StatusAndHeaders(status, def_headers) return WbResponse(status_headers, value=stream)
[ "def", "bin_stream", "(", "stream", ",", "content_type", ",", "status", "=", "'200 OK'", ",", "headers", "=", "None", ")", ":", "def_headers", "=", "[", "(", "'Content-Type'", ",", "content_type", ")", "]", "if", "headers", ":", "def_headers", "+=", "heade...
Utility method for constructing a binary response. :param Any stream: The response body stream :param str content_type: The content-type of the response :param str status: The HTTP status line :param list[tuple[str, str]] headers: Additional headers for this response :return: WbResponse that is a binary stream :rtype: WbResponse
[ "Utility", "method", "for", "constructing", "a", "binary", "response", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/wbrequestresponse.py#L63-L80
230,676
webrecorder/pywb
pywb/apps/wbrequestresponse.py
WbResponse.text_response
def text_response(text, status='200 OK', content_type='text/plain; charset=utf-8'): """Utility method for constructing a text response. :param str text: The text response body :param str content_type: The content-type of the response :param str status: The HTTP status line :return: WbResponse text response :rtype: WbResponse """ encoded_text = text.encode('utf-8') status_headers = StatusAndHeaders(status, [('Content-Type', content_type), ('Content-Length', str(len(encoded_text)))]) return WbResponse(status_headers, value=[encoded_text])
python
def text_response(text, status='200 OK', content_type='text/plain; charset=utf-8'): encoded_text = text.encode('utf-8') status_headers = StatusAndHeaders(status, [('Content-Type', content_type), ('Content-Length', str(len(encoded_text)))]) return WbResponse(status_headers, value=[encoded_text])
[ "def", "text_response", "(", "text", ",", "status", "=", "'200 OK'", ",", "content_type", "=", "'text/plain; charset=utf-8'", ")", ":", "encoded_text", "=", "text", ".", "encode", "(", "'utf-8'", ")", "status_headers", "=", "StatusAndHeaders", "(", "status", ","...
Utility method for constructing a text response. :param str text: The text response body :param str content_type: The content-type of the response :param str status: The HTTP status line :return: WbResponse text response :rtype: WbResponse
[ "Utility", "method", "for", "constructing", "a", "text", "response", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/wbrequestresponse.py#L83-L97
230,677
webrecorder/pywb
pywb/apps/wbrequestresponse.py
WbResponse.json_response
def json_response(obj, status='200 OK', content_type='application/json; charset=utf-8'): """Utility method for constructing a JSON response. :param dict obj: The dictionary to be serialized in JSON format :param str content_type: The content-type of the response :param str status: The HTTP status line :return: WbResponse JSON response :rtype: WbResponse """ return WbResponse.text_response(json.dumps(obj), status, content_type)
python
def json_response(obj, status='200 OK', content_type='application/json; charset=utf-8'): return WbResponse.text_response(json.dumps(obj), status, content_type)
[ "def", "json_response", "(", "obj", ",", "status", "=", "'200 OK'", ",", "content_type", "=", "'application/json; charset=utf-8'", ")", ":", "return", "WbResponse", ".", "text_response", "(", "json", ".", "dumps", "(", "obj", ")", ",", "status", ",", "content_...
Utility method for constructing a JSON response. :param dict obj: The dictionary to be serialized in JSON format :param str content_type: The content-type of the response :param str status: The HTTP status line :return: WbResponse JSON response :rtype: WbResponse
[ "Utility", "method", "for", "constructing", "a", "JSON", "response", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/wbrequestresponse.py#L100-L109
230,678
webrecorder/pywb
pywb/apps/wbrequestresponse.py
WbResponse.redir_response
def redir_response(location, status='302 Redirect', headers=None): """Utility method for constructing redirection response. :param str location: The location of the resource redirecting to :param str status: The HTTP status line :param list[tuple[str, str]] headers: Additional headers for this response :return: WbResponse redirection response :rtype: WbResponse """ redir_headers = [('Location', location), ('Content-Length', '0')] if headers: redir_headers += headers return WbResponse(StatusAndHeaders(status, redir_headers))
python
def redir_response(location, status='302 Redirect', headers=None): redir_headers = [('Location', location), ('Content-Length', '0')] if headers: redir_headers += headers return WbResponse(StatusAndHeaders(status, redir_headers))
[ "def", "redir_response", "(", "location", ",", "status", "=", "'302 Redirect'", ",", "headers", "=", "None", ")", ":", "redir_headers", "=", "[", "(", "'Location'", ",", "location", ")", ",", "(", "'Content-Length'", ",", "'0'", ")", "]", "if", "headers", ...
Utility method for constructing redirection response. :param str location: The location of the resource redirecting to :param str status: The HTTP status line :param list[tuple[str, str]] headers: Additional headers for this response :return: WbResponse redirection response :rtype: WbResponse
[ "Utility", "method", "for", "constructing", "redirection", "response", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/wbrequestresponse.py#L112-L125
230,679
webrecorder/pywb
pywb/apps/wbrequestresponse.py
WbResponse.options_response
def options_response(env): """Construct WbResponse for OPTIONS based on the WSGI env dictionary :param dict env: The WSGI environment dictionary :return: The WBResponse for the options request :rtype: WbResponse """ status_headers = StatusAndHeaders('200 Ok', [ ('Content-Type', 'text/plain'), ('Content-Length', '0'), ]) response = WbResponse(status_headers) response.add_access_control_headers(env=env) return response
python
def options_response(env): status_headers = StatusAndHeaders('200 Ok', [ ('Content-Type', 'text/plain'), ('Content-Length', '0'), ]) response = WbResponse(status_headers) response.add_access_control_headers(env=env) return response
[ "def", "options_response", "(", "env", ")", ":", "status_headers", "=", "StatusAndHeaders", "(", "'200 Ok'", ",", "[", "(", "'Content-Type'", ",", "'text/plain'", ")", ",", "(", "'Content-Length'", ",", "'0'", ")", ",", "]", ")", "response", "=", "WbResponse...
Construct WbResponse for OPTIONS based on the WSGI env dictionary :param dict env: The WSGI environment dictionary :return: The WBResponse for the options request :rtype: WbResponse
[ "Construct", "WbResponse", "for", "OPTIONS", "based", "on", "the", "WSGI", "env", "dictionary" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/wbrequestresponse.py#L128-L141
230,680
webrecorder/pywb
pywb/utils/canonicalize.py
canonicalize
def canonicalize(url, surt_ordered=True): """ Canonicalize url and convert to surt If not in surt ordered mode, convert back to url form as surt conversion is currently part of canonicalization >>> canonicalize('http://example.com/path/file.html', surt_ordered=True) 'com,example)/path/file.html' >>> canonicalize('http://example.com/path/file.html', surt_ordered=False) 'example.com/path/file.html' >>> canonicalize('urn:some:id') 'urn:some:id' """ try: key = surt.surt(url) except Exception as e: #pragma: no cover # doesn't happen with surt from 0.3b # urn is already canonical, so just use as-is if url.startswith('urn:'): return url raise UrlCanonicalizeException('Invalid Url: ' + url) # if not surt, unsurt the surt to get canonicalized non-surt url if not surt_ordered: key = unsurt(key) return key
python
def canonicalize(url, surt_ordered=True): try: key = surt.surt(url) except Exception as e: #pragma: no cover # doesn't happen with surt from 0.3b # urn is already canonical, so just use as-is if url.startswith('urn:'): return url raise UrlCanonicalizeException('Invalid Url: ' + url) # if not surt, unsurt the surt to get canonicalized non-surt url if not surt_ordered: key = unsurt(key) return key
[ "def", "canonicalize", "(", "url", ",", "surt_ordered", "=", "True", ")", ":", "try", ":", "key", "=", "surt", ".", "surt", "(", "url", ")", "except", "Exception", "as", "e", ":", "#pragma: no cover", "# doesn't happen with surt from 0.3b", "# urn is already can...
Canonicalize url and convert to surt If not in surt ordered mode, convert back to url form as surt conversion is currently part of canonicalization >>> canonicalize('http://example.com/path/file.html', surt_ordered=True) 'com,example)/path/file.html' >>> canonicalize('http://example.com/path/file.html', surt_ordered=False) 'example.com/path/file.html' >>> canonicalize('urn:some:id') 'urn:some:id'
[ "Canonicalize", "url", "and", "convert", "to", "surt", "If", "not", "in", "surt", "ordered", "mode", "convert", "back", "to", "url", "form", "as", "surt", "conversion", "is", "currently", "part", "of", "canonicalization" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/utils/canonicalize.py#L25-L54
230,681
webrecorder/pywb
pywb/warcserver/index/fuzzymatcher.py
FuzzyMatcher.parse_fuzzy_rule
def parse_fuzzy_rule(self, rule): """ Parse rules using all the different supported forms """ url_prefix = rule.get('url_prefix') config = rule.get('fuzzy_lookup') if not config: return if not isinstance(url_prefix, list): url_prefix = [url_prefix] if not isinstance(config, dict): regex = self.make_regex(config) replace_after = self.DEFAULT_REPLACE_AFTER filter_str = self.DEFAULT_FILTER match_type = self.DEFAULT_MATCH_TYPE find_all = False else: regex = self.make_regex(config.get('match')) replace_after = config.get('replace', self.DEFAULT_REPLACE_AFTER) filter_str = config.get('filter', self.DEFAULT_FILTER) match_type = config.get('type', self.DEFAULT_MATCH_TYPE) find_all = config.get('find_all', False) return FuzzyRule(url_prefix, regex, replace_after, filter_str, match_type, find_all)
python
def parse_fuzzy_rule(self, rule): url_prefix = rule.get('url_prefix') config = rule.get('fuzzy_lookup') if not config: return if not isinstance(url_prefix, list): url_prefix = [url_prefix] if not isinstance(config, dict): regex = self.make_regex(config) replace_after = self.DEFAULT_REPLACE_AFTER filter_str = self.DEFAULT_FILTER match_type = self.DEFAULT_MATCH_TYPE find_all = False else: regex = self.make_regex(config.get('match')) replace_after = config.get('replace', self.DEFAULT_REPLACE_AFTER) filter_str = config.get('filter', self.DEFAULT_FILTER) match_type = config.get('type', self.DEFAULT_MATCH_TYPE) find_all = config.get('find_all', False) return FuzzyRule(url_prefix, regex, replace_after, filter_str, match_type, find_all)
[ "def", "parse_fuzzy_rule", "(", "self", ",", "rule", ")", ":", "url_prefix", "=", "rule", ".", "get", "(", "'url_prefix'", ")", "config", "=", "rule", ".", "get", "(", "'fuzzy_lookup'", ")", "if", "not", "config", ":", "return", "if", "not", "isinstance"...
Parse rules using all the different supported forms
[ "Parse", "rules", "using", "all", "the", "different", "supported", "forms" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/index/fuzzymatcher.py#L43-L68
230,682
webrecorder/pywb
pywb/warcserver/resource/resolvingloader.py
ResolvingLoader.load_headers_and_payload
def load_headers_and_payload(self, cdx, failed_files, cdx_loader): """ Resolve headers and payload for a given capture In the simple case, headers and payload are in the same record. In the case of revisit records, the payload and headers may be in different records. If the original has already been found, lookup original using orig. fields in cdx dict. Otherwise, call _load_different_url_payload() to get cdx index from a different url to find the original record. """ has_curr = (cdx['filename'] != '-') #has_orig = (cdx.get('orig.filename', '-') != '-') orig_f = cdx.get('orig.filename') has_orig = orig_f and orig_f != '-' # load headers record from cdx['filename'] unless it is '-' (rare) headers_record = None if has_curr: headers_record = self._resolve_path_load(cdx, False, failed_files) # two index lookups # Case 1: if mimetype is still warc/revisit if cdx.get('mime') == 'warc/revisit' and headers_record: payload_record = self._load_different_url_payload(cdx, headers_record, failed_files, cdx_loader) # single lookup cases # case 2: non-revisit elif (has_curr and not has_orig): payload_record = headers_record # case 3: identical url revisit, load payload from orig.filename elif (has_orig): payload_record = self._resolve_path_load(cdx, True, failed_files) return headers_record, payload_record
python
def load_headers_and_payload(self, cdx, failed_files, cdx_loader): has_curr = (cdx['filename'] != '-') #has_orig = (cdx.get('orig.filename', '-') != '-') orig_f = cdx.get('orig.filename') has_orig = orig_f and orig_f != '-' # load headers record from cdx['filename'] unless it is '-' (rare) headers_record = None if has_curr: headers_record = self._resolve_path_load(cdx, False, failed_files) # two index lookups # Case 1: if mimetype is still warc/revisit if cdx.get('mime') == 'warc/revisit' and headers_record: payload_record = self._load_different_url_payload(cdx, headers_record, failed_files, cdx_loader) # single lookup cases # case 2: non-revisit elif (has_curr and not has_orig): payload_record = headers_record # case 3: identical url revisit, load payload from orig.filename elif (has_orig): payload_record = self._resolve_path_load(cdx, True, failed_files) return headers_record, payload_record
[ "def", "load_headers_and_payload", "(", "self", ",", "cdx", ",", "failed_files", ",", "cdx_loader", ")", ":", "has_curr", "=", "(", "cdx", "[", "'filename'", "]", "!=", "'-'", ")", "#has_orig = (cdx.get('orig.filename', '-') != '-')", "orig_f", "=", "cdx", ".", ...
Resolve headers and payload for a given capture In the simple case, headers and payload are in the same record. In the case of revisit records, the payload and headers may be in different records. If the original has already been found, lookup original using orig. fields in cdx dict. Otherwise, call _load_different_url_payload() to get cdx index from a different url to find the original record.
[ "Resolve", "headers", "and", "payload", "for", "a", "given", "capture", "In", "the", "simple", "case", "headers", "and", "payload", "are", "in", "the", "same", "record", ".", "In", "the", "case", "of", "revisit", "records", "the", "payload", "and", "header...
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/resource/resolvingloader.py#L47-L86
230,683
webrecorder/pywb
pywb/warcserver/resource/resolvingloader.py
ResolvingLoader._load_different_url_payload
def _load_different_url_payload(self, cdx, headers_record, failed_files, cdx_loader): """ Handle the case where a duplicate of a capture with same digest exists at a different url. If a cdx_server is provided, a query is made for matching url, timestamp and digest. Raise exception if no matches found. """ ref_target_uri = (headers_record.rec_headers. get_header('WARC-Refers-To-Target-URI')) target_uri = headers_record.rec_headers.get_header('WARC-Target-URI') # if no target uri, no way to find the original if not ref_target_uri: raise ArchiveLoadFailed(self.MISSING_REVISIT_MSG) ref_target_date = (headers_record.rec_headers. get_header('WARC-Refers-To-Date')) if not ref_target_date: ref_target_date = cdx['timestamp'] else: ref_target_date = iso_date_to_timestamp(ref_target_date) digest = cdx.get('digest', '-') try: orig_cdx_lines = self.load_cdx_for_dupe(ref_target_uri, ref_target_date, digest, cdx_loader) except NotFoundException: raise ArchiveLoadFailed(self.MISSING_REVISIT_MSG) for orig_cdx in orig_cdx_lines: try: payload_record = self._resolve_path_load(orig_cdx, False, failed_files) return payload_record except ArchiveLoadFailed as e: pass raise ArchiveLoadFailed(self.MISSING_REVISIT_MSG)
python
def _load_different_url_payload(self, cdx, headers_record, failed_files, cdx_loader): ref_target_uri = (headers_record.rec_headers. get_header('WARC-Refers-To-Target-URI')) target_uri = headers_record.rec_headers.get_header('WARC-Target-URI') # if no target uri, no way to find the original if not ref_target_uri: raise ArchiveLoadFailed(self.MISSING_REVISIT_MSG) ref_target_date = (headers_record.rec_headers. get_header('WARC-Refers-To-Date')) if not ref_target_date: ref_target_date = cdx['timestamp'] else: ref_target_date = iso_date_to_timestamp(ref_target_date) digest = cdx.get('digest', '-') try: orig_cdx_lines = self.load_cdx_for_dupe(ref_target_uri, ref_target_date, digest, cdx_loader) except NotFoundException: raise ArchiveLoadFailed(self.MISSING_REVISIT_MSG) for orig_cdx in orig_cdx_lines: try: payload_record = self._resolve_path_load(orig_cdx, False, failed_files) return payload_record except ArchiveLoadFailed as e: pass raise ArchiveLoadFailed(self.MISSING_REVISIT_MSG)
[ "def", "_load_different_url_payload", "(", "self", ",", "cdx", ",", "headers_record", ",", "failed_files", ",", "cdx_loader", ")", ":", "ref_target_uri", "=", "(", "headers_record", ".", "rec_headers", ".", "get_header", "(", "'WARC-Refers-To-Target-URI'", ")", ")",...
Handle the case where a duplicate of a capture with same digest exists at a different url. If a cdx_server is provided, a query is made for matching url, timestamp and digest. Raise exception if no matches found.
[ "Handle", "the", "case", "where", "a", "duplicate", "of", "a", "capture", "with", "same", "digest", "exists", "at", "a", "different", "url", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/resource/resolvingloader.py#L151-L199
230,684
webrecorder/pywb
pywb/warcserver/resource/resolvingloader.py
ResolvingLoader.load_cdx_for_dupe
def load_cdx_for_dupe(self, url, timestamp, digest, cdx_loader): """ If a cdx_server is available, return response from server, otherwise empty list """ if not cdx_loader: return iter([]) filters = [] filters.append('!mime:warc/revisit') if digest and digest != '-': filters.append('digest:' + digest) params = dict(url=url, closest=timestamp, filter=filters) return cdx_loader(params)
python
def load_cdx_for_dupe(self, url, timestamp, digest, cdx_loader): if not cdx_loader: return iter([]) filters = [] filters.append('!mime:warc/revisit') if digest and digest != '-': filters.append('digest:' + digest) params = dict(url=url, closest=timestamp, filter=filters) return cdx_loader(params)
[ "def", "load_cdx_for_dupe", "(", "self", ",", "url", ",", "timestamp", ",", "digest", ",", "cdx_loader", ")", ":", "if", "not", "cdx_loader", ":", "return", "iter", "(", "[", "]", ")", "filters", "=", "[", "]", "filters", ".", "append", "(", "'!mime:wa...
If a cdx_server is available, return response from server, otherwise empty list
[ "If", "a", "cdx_server", "is", "available", "return", "response", "from", "server", "otherwise", "empty", "list" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/warcserver/resource/resolvingloader.py#L201-L220
230,685
webrecorder/pywb
pywb/utils/binsearch.py
binsearch_offset
def binsearch_offset(reader, key, compare_func=cmp, block_size=8192): """ Find offset of the line which matches a given 'key' using binary search If key is not found, the offset is of the line after the key File is subdivided into block_size (default 8192) sized blocks Optional compare_func may be specified """ min_ = 0 reader.seek(0, 2) max_ = int(reader.tell() / block_size) while max_ - min_ > 1: mid = int(min_ + ((max_ - min_) / 2)) reader.seek(mid * block_size) if mid > 0: reader.readline() # skip partial line line = reader.readline() if compare_func(key, line) > 0: min_ = mid else: max_ = mid return min_ * block_size
python
def binsearch_offset(reader, key, compare_func=cmp, block_size=8192): min_ = 0 reader.seek(0, 2) max_ = int(reader.tell() / block_size) while max_ - min_ > 1: mid = int(min_ + ((max_ - min_) / 2)) reader.seek(mid * block_size) if mid > 0: reader.readline() # skip partial line line = reader.readline() if compare_func(key, line) > 0: min_ = mid else: max_ = mid return min_ * block_size
[ "def", "binsearch_offset", "(", "reader", ",", "key", ",", "compare_func", "=", "cmp", ",", "block_size", "=", "8192", ")", ":", "min_", "=", "0", "reader", ".", "seek", "(", "0", ",", "2", ")", "max_", "=", "int", "(", "reader", ".", "tell", "(", ...
Find offset of the line which matches a given 'key' using binary search If key is not found, the offset is of the line after the key File is subdivided into block_size (default 8192) sized blocks Optional compare_func may be specified
[ "Find", "offset", "of", "the", "line", "which", "matches", "a", "given", "key", "using", "binary", "search", "If", "key", "is", "not", "found", "the", "offset", "is", "of", "the", "line", "after", "the", "key" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/utils/binsearch.py#L17-L44
230,686
webrecorder/pywb
pywb/utils/binsearch.py
linearsearch
def linearsearch(iter_, key, prev_size=0, compare_func=cmp): """ Perform a linear search over iterator until current_line >= key optionally also tracking upto N previous lines, which are returned before the first matched line. if end of stream is reached before a match is found, nothing is returned (prev lines discarded also) """ prev_deque = deque(maxlen=prev_size + 1) matched = False for line in iter_: prev_deque.append(line) if compare_func(line, key) >= 0: matched = True break # no matches, so return empty iterator if not matched: return iter([]) return itertools.chain(prev_deque, iter_)
python
def linearsearch(iter_, key, prev_size=0, compare_func=cmp): prev_deque = deque(maxlen=prev_size + 1) matched = False for line in iter_: prev_deque.append(line) if compare_func(line, key) >= 0: matched = True break # no matches, so return empty iterator if not matched: return iter([]) return itertools.chain(prev_deque, iter_)
[ "def", "linearsearch", "(", "iter_", ",", "key", ",", "prev_size", "=", "0", ",", "compare_func", "=", "cmp", ")", ":", "prev_deque", "=", "deque", "(", "maxlen", "=", "prev_size", "+", "1", ")", "matched", "=", "False", "for", "line", "in", "iter_", ...
Perform a linear search over iterator until current_line >= key optionally also tracking upto N previous lines, which are returned before the first matched line. if end of stream is reached before a match is found, nothing is returned (prev lines discarded also)
[ "Perform", "a", "linear", "search", "over", "iterator", "until", "current_line", ">", "=", "key" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/utils/binsearch.py#L70-L96
230,687
webrecorder/pywb
pywb/utils/binsearch.py
iter_prefix
def iter_prefix(reader, key): """ Creates an iterator which iterates over lines that start with prefix 'key' in a sorted text file. """ return itertools.takewhile( lambda line: line.startswith(key), search(reader, key))
python
def iter_prefix(reader, key): return itertools.takewhile( lambda line: line.startswith(key), search(reader, key))
[ "def", "iter_prefix", "(", "reader", ",", "key", ")", ":", "return", "itertools", ".", "takewhile", "(", "lambda", "line", ":", "line", ".", "startswith", "(", "key", ")", ",", "search", "(", "reader", ",", "key", ")", ")" ]
Creates an iterator which iterates over lines that start with prefix 'key' in a sorted text file.
[ "Creates", "an", "iterator", "which", "iterates", "over", "lines", "that", "start", "with", "prefix", "key", "in", "a", "sorted", "text", "file", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/utils/binsearch.py#L133-L141
230,688
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.get_upstream_paths
def get_upstream_paths(self, port): """Retrieve a dictionary containing the full URLs of the upstream apps :param int port: The port used by the replay and cdx servers :return: A dictionary containing the upstream paths (replay, cdx-server, record [if enabled]) :rtype: dict[str, str] """ base_paths = { 'replay': self.REPLAY_API % port, 'cdx-server': self.CDX_API % port, } if self.recorder_path: base_paths['record'] = self.recorder_path return base_paths
python
def get_upstream_paths(self, port): base_paths = { 'replay': self.REPLAY_API % port, 'cdx-server': self.CDX_API % port, } if self.recorder_path: base_paths['record'] = self.recorder_path return base_paths
[ "def", "get_upstream_paths", "(", "self", ",", "port", ")", ":", "base_paths", "=", "{", "'replay'", ":", "self", ".", "REPLAY_API", "%", "port", ",", "'cdx-server'", ":", "self", ".", "CDX_API", "%", "port", ",", "}", "if", "self", ".", "recorder_path",...
Retrieve a dictionary containing the full URLs of the upstream apps :param int port: The port used by the replay and cdx servers :return: A dictionary containing the upstream paths (replay, cdx-server, record [if enabled]) :rtype: dict[str, str]
[ "Retrieve", "a", "dictionary", "containing", "the", "full", "URLs", "of", "the", "upstream", "apps" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L132-L147
230,689
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.init_recorder
def init_recorder(self, recorder_config): """Initialize the recording functionality of pywb. If recording_config is None this function is a no op""" if not recorder_config: self.recorder = None self.recorder_path = None return if isinstance(recorder_config, str): recorder_coll = recorder_config recorder_config = {} else: recorder_coll = recorder_config['source_coll'] # TODO: support dedup dedup_index = None warc_writer = MultiFileWARCWriter(self.warcserver.archive_paths, max_size=int(recorder_config.get('rollover_size', 1000000000)), max_idle_secs=int(recorder_config.get('rollover_idle_secs', 600)), filename_template=recorder_config.get('filename_template'), dedup_index=dedup_index) self.recorder = RecorderApp(self.RECORD_SERVER % str(self.warcserver_server.port), warc_writer, accept_colls=recorder_config.get('source_filter')) recorder_server = GeventServer(self.recorder, port=0) self.recorder_path = self.RECORD_API % (recorder_server.port, recorder_coll)
python
def init_recorder(self, recorder_config): if not recorder_config: self.recorder = None self.recorder_path = None return if isinstance(recorder_config, str): recorder_coll = recorder_config recorder_config = {} else: recorder_coll = recorder_config['source_coll'] # TODO: support dedup dedup_index = None warc_writer = MultiFileWARCWriter(self.warcserver.archive_paths, max_size=int(recorder_config.get('rollover_size', 1000000000)), max_idle_secs=int(recorder_config.get('rollover_idle_secs', 600)), filename_template=recorder_config.get('filename_template'), dedup_index=dedup_index) self.recorder = RecorderApp(self.RECORD_SERVER % str(self.warcserver_server.port), warc_writer, accept_colls=recorder_config.get('source_filter')) recorder_server = GeventServer(self.recorder, port=0) self.recorder_path = self.RECORD_API % (recorder_server.port, recorder_coll)
[ "def", "init_recorder", "(", "self", ",", "recorder_config", ")", ":", "if", "not", "recorder_config", ":", "self", ".", "recorder", "=", "None", "self", ".", "recorder_path", "=", "None", "return", "if", "isinstance", "(", "recorder_config", ",", "str", ")"...
Initialize the recording functionality of pywb. If recording_config is None this function is a no op
[ "Initialize", "the", "recording", "functionality", "of", "pywb", ".", "If", "recording_config", "is", "None", "this", "function", "is", "a", "no", "op" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L149-L176
230,690
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.init_autoindex
def init_autoindex(self, auto_interval): """Initialize and start the auto-indexing of the collections. If auto_interval is None this is a no op. :param str|int auto_interval: The auto-indexing interval from the configuration file or CLI argument """ if not auto_interval: return from pywb.manager.autoindex import AutoIndexer colls_dir = self.warcserver.root_dir if self.warcserver.root_dir else None indexer = AutoIndexer(colls_dir=colls_dir, interval=int(auto_interval)) if not os.path.isdir(indexer.root_path): msg = 'No managed directory "{0}" for auto-indexing' logging.error(msg.format(indexer.root_path)) import sys sys.exit(2) msg = 'Auto-Indexing Enabled on "{0}", checking every {1} secs' logging.info(msg.format(indexer.root_path, auto_interval)) indexer.start()
python
def init_autoindex(self, auto_interval): if not auto_interval: return from pywb.manager.autoindex import AutoIndexer colls_dir = self.warcserver.root_dir if self.warcserver.root_dir else None indexer = AutoIndexer(colls_dir=colls_dir, interval=int(auto_interval)) if not os.path.isdir(indexer.root_path): msg = 'No managed directory "{0}" for auto-indexing' logging.error(msg.format(indexer.root_path)) import sys sys.exit(2) msg = 'Auto-Indexing Enabled on "{0}", checking every {1} secs' logging.info(msg.format(indexer.root_path, auto_interval)) indexer.start()
[ "def", "init_autoindex", "(", "self", ",", "auto_interval", ")", ":", "if", "not", "auto_interval", ":", "return", "from", "pywb", ".", "manager", ".", "autoindex", "import", "AutoIndexer", "colls_dir", "=", "self", ".", "warcserver", ".", "root_dir", "if", ...
Initialize and start the auto-indexing of the collections. If auto_interval is None this is a no op. :param str|int auto_interval: The auto-indexing interval from the configuration file or CLI argument
[ "Initialize", "and", "start", "the", "auto", "-", "indexing", "of", "the", "collections", ".", "If", "auto_interval", "is", "None", "this", "is", "a", "no", "op", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L178-L200
230,691
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.serve_static
def serve_static(self, environ, coll='', filepath=''): """Serve a static file associated with a specific collection or one of pywb's own static assets :param dict environ: The WSGI environment dictionary for the request :param str coll: The collection the static file is associated with :param str filepath: The file path (relative to the collection) for the static assest :return: The WbResponse for the static asset :rtype: WbResponse """ proxy_enabled = self.is_proxy_enabled(environ) if proxy_enabled and environ.get('REQUEST_METHOD') == 'OPTIONS': return WbResponse.options_response(environ) if coll: path = os.path.join(self.warcserver.root_dir, coll, self.static_dir) else: path = self.static_dir environ['pywb.static_dir'] = path try: response = self.static_handler(environ, filepath) if proxy_enabled: response.add_access_control_headers(env=environ) return response except: self.raise_not_found(environ, 'Static File Not Found: {0}'.format(filepath))
python
def serve_static(self, environ, coll='', filepath=''): proxy_enabled = self.is_proxy_enabled(environ) if proxy_enabled and environ.get('REQUEST_METHOD') == 'OPTIONS': return WbResponse.options_response(environ) if coll: path = os.path.join(self.warcserver.root_dir, coll, self.static_dir) else: path = self.static_dir environ['pywb.static_dir'] = path try: response = self.static_handler(environ, filepath) if proxy_enabled: response.add_access_control_headers(env=environ) return response except: self.raise_not_found(environ, 'Static File Not Found: {0}'.format(filepath))
[ "def", "serve_static", "(", "self", ",", "environ", ",", "coll", "=", "''", ",", "filepath", "=", "''", ")", ":", "proxy_enabled", "=", "self", ".", "is_proxy_enabled", "(", "environ", ")", "if", "proxy_enabled", "and", "environ", ".", "get", "(", "'REQU...
Serve a static file associated with a specific collection or one of pywb's own static assets :param dict environ: The WSGI environment dictionary for the request :param str coll: The collection the static file is associated with :param str filepath: The file path (relative to the collection) for the static assest :return: The WbResponse for the static asset :rtype: WbResponse
[ "Serve", "a", "static", "file", "associated", "with", "a", "specific", "collection", "or", "one", "of", "pywb", "s", "own", "static", "assets" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L226-L250
230,692
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.get_metadata
def get_metadata(self, coll): """Retrieve the metadata associated with a collection :param str coll: The name of the collection to receive metadata for :return: The collections metadata if it exists :rtype: dict """ #if coll == self.all_coll: # coll = '*' metadata = {'coll': coll, 'type': 'replay'} if coll in self.warcserver.list_fixed_routes(): metadata.update(self.warcserver.get_coll_config(coll)) else: metadata.update(self.metadata_cache.load(coll)) return metadata
python
def get_metadata(self, coll): #if coll == self.all_coll: # coll = '*' metadata = {'coll': coll, 'type': 'replay'} if coll in self.warcserver.list_fixed_routes(): metadata.update(self.warcserver.get_coll_config(coll)) else: metadata.update(self.metadata_cache.load(coll)) return metadata
[ "def", "get_metadata", "(", "self", ",", "coll", ")", ":", "#if coll == self.all_coll:", "# coll = '*'", "metadata", "=", "{", "'coll'", ":", "coll", ",", "'type'", ":", "'replay'", "}", "if", "coll", "in", "self", ".", "warcserver", ".", "list_fixed_routes...
Retrieve the metadata associated with a collection :param str coll: The name of the collection to receive metadata for :return: The collections metadata if it exists :rtype: dict
[ "Retrieve", "the", "metadata", "associated", "with", "a", "collection" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L252-L270
230,693
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.serve_cdx
def serve_cdx(self, environ, coll='$root'): """Make the upstream CDX query for a collection and response with the results of the query :param dict environ: The WSGI environment dictionary for the request :param str coll: The name of the collection this CDX query is for :return: The WbResponse containing the results of the CDX query :rtype: WbResponse """ base_url = self.rewriterapp.paths['cdx-server'] #if coll == self.all_coll: # coll = '*' cdx_url = base_url.format(coll=coll) if environ.get('QUERY_STRING'): cdx_url += '&' if '?' in cdx_url else '?' cdx_url += environ.get('QUERY_STRING') try: res = requests.get(cdx_url, stream=True) content_type = res.headers.get('Content-Type') return WbResponse.bin_stream(StreamIter(res.raw), content_type=content_type) except Exception as e: return WbResponse.text_response('Error: ' + str(e), status='400 Bad Request')
python
def serve_cdx(self, environ, coll='$root'): base_url = self.rewriterapp.paths['cdx-server'] #if coll == self.all_coll: # coll = '*' cdx_url = base_url.format(coll=coll) if environ.get('QUERY_STRING'): cdx_url += '&' if '?' in cdx_url else '?' cdx_url += environ.get('QUERY_STRING') try: res = requests.get(cdx_url, stream=True) content_type = res.headers.get('Content-Type') return WbResponse.bin_stream(StreamIter(res.raw), content_type=content_type) except Exception as e: return WbResponse.text_response('Error: ' + str(e), status='400 Bad Request')
[ "def", "serve_cdx", "(", "self", ",", "environ", ",", "coll", "=", "'$root'", ")", ":", "base_url", "=", "self", ".", "rewriterapp", ".", "paths", "[", "'cdx-server'", "]", "#if coll == self.all_coll:", "# coll = '*'", "cdx_url", "=", "base_url", ".", "form...
Make the upstream CDX query for a collection and response with the results of the query :param dict environ: The WSGI environment dictionary for the request :param str coll: The name of the collection this CDX query is for :return: The WbResponse containing the results of the CDX query :rtype: WbResponse
[ "Make", "the", "upstream", "CDX", "query", "for", "a", "collection", "and", "response", "with", "the", "results", "of", "the", "query" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L300-L328
230,694
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.setup_paths
def setup_paths(self, environ, coll, record=False): """Populates the WSGI environment dictionary with the path information necessary to perform a response for content or record. :param dict environ: The WSGI environment dictionary for the request :param str coll: The name of the collection the record is to be served from :param bool record: Should the content being served by recorded (save to a warc). Only valid in record mode """ if not coll or not self.warcserver.root_dir: return if coll != '$root': pop_path_info(environ) if record: pop_path_info(environ) paths = [self.warcserver.root_dir] if coll != '$root': paths.append(coll) paths.append(self.templates_dir) # jinja2 template paths always use '/' as separator environ['pywb.templates_dir'] = '/'.join(paths)
python
def setup_paths(self, environ, coll, record=False): if not coll or not self.warcserver.root_dir: return if coll != '$root': pop_path_info(environ) if record: pop_path_info(environ) paths = [self.warcserver.root_dir] if coll != '$root': paths.append(coll) paths.append(self.templates_dir) # jinja2 template paths always use '/' as separator environ['pywb.templates_dir'] = '/'.join(paths)
[ "def", "setup_paths", "(", "self", ",", "environ", ",", "coll", ",", "record", "=", "False", ")", ":", "if", "not", "coll", "or", "not", "self", ".", "warcserver", ".", "root_dir", ":", "return", "if", "coll", "!=", "'$root'", ":", "pop_path_info", "("...
Populates the WSGI environment dictionary with the path information necessary to perform a response for content or record. :param dict environ: The WSGI environment dictionary for the request :param str coll: The name of the collection the record is to be served from :param bool record: Should the content being served by recorded (save to a warc). Only valid in record mode
[ "Populates", "the", "WSGI", "environment", "dictionary", "with", "the", "path", "information", "necessary", "to", "perform", "a", "response", "for", "content", "or", "record", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L387-L411
230,695
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.raise_not_found
def raise_not_found(self, environ, msg): """Utility function for raising a werkzeug.exceptions.NotFound execption with the supplied WSGI environment and message. :param dict environ: The WSGI environment dictionary for the request :param str msg: The error message """ raise NotFound(response=self.rewriterapp._error_response(environ, msg))
python
def raise_not_found(self, environ, msg): raise NotFound(response=self.rewriterapp._error_response(environ, msg))
[ "def", "raise_not_found", "(", "self", ",", "environ", ",", "msg", ")", ":", "raise", "NotFound", "(", "response", "=", "self", ".", "rewriterapp", ".", "_error_response", "(", "environ", ",", "msg", ")", ")" ]
Utility function for raising a werkzeug.exceptions.NotFound execption with the supplied WSGI environment and message. :param dict environ: The WSGI environment dictionary for the request :param str msg: The error message
[ "Utility", "function", "for", "raising", "a", "werkzeug", ".", "exceptions", ".", "NotFound", "execption", "with", "the", "supplied", "WSGI", "environment", "and", "message", "." ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L439-L446
230,696
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp._check_refer_redirect
def _check_refer_redirect(self, environ): """Returns a WbResponse for a HTTP 307 redirection if the HTTP referer header is the same as the HTTP host header :param dict environ: The WSGI environment dictionary for the request :return: WbResponse HTTP 307 redirection :rtype: WbResponse """ referer = environ.get('HTTP_REFERER') if not referer: return host = environ.get('HTTP_HOST') if host not in referer: return inx = referer[1:].find('http') if not inx: inx = referer[1:].find('///') if inx > 0: inx + 1 if inx < 0: return url = referer[inx + 1:] host = referer[:inx + 1] orig_url = environ['PATH_INFO'] if environ.get('QUERY_STRING'): orig_url += '?' + environ['QUERY_STRING'] full_url = host + urljoin(url, orig_url) return WbResponse.redir_response(full_url, '307 Redirect')
python
def _check_refer_redirect(self, environ): referer = environ.get('HTTP_REFERER') if not referer: return host = environ.get('HTTP_HOST') if host not in referer: return inx = referer[1:].find('http') if not inx: inx = referer[1:].find('///') if inx > 0: inx + 1 if inx < 0: return url = referer[inx + 1:] host = referer[:inx + 1] orig_url = environ['PATH_INFO'] if environ.get('QUERY_STRING'): orig_url += '?' + environ['QUERY_STRING'] full_url = host + urljoin(url, orig_url) return WbResponse.redir_response(full_url, '307 Redirect')
[ "def", "_check_refer_redirect", "(", "self", ",", "environ", ")", ":", "referer", "=", "environ", ".", "get", "(", "'HTTP_REFERER'", ")", "if", "not", "referer", ":", "return", "host", "=", "environ", ".", "get", "(", "'HTTP_HOST'", ")", "if", "host", "n...
Returns a WbResponse for a HTTP 307 redirection if the HTTP referer header is the same as the HTTP host header :param dict environ: The WSGI environment dictionary for the request :return: WbResponse HTTP 307 redirection :rtype: WbResponse
[ "Returns", "a", "WbResponse", "for", "a", "HTTP", "307", "redirection", "if", "the", "HTTP", "referer", "header", "is", "the", "same", "as", "the", "HTTP", "host", "header" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L448-L480
230,697
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.handle_request
def handle_request(self, environ, start_response): """Retrieves the route handler and calls the handler returning its the response :param dict environ: The WSGI environment dictionary for the request :param start_response: :return: The WbResponse for the request :rtype: WbResponse """ urls = self.url_map.bind_to_environ(environ) try: endpoint, args = urls.match() # store original script_name (original prefix) before modifications are made environ['pywb.app_prefix'] = environ.get('SCRIPT_NAME') response = endpoint(environ, **args) return response(environ, start_response) except HTTPException as e: redir = self._check_refer_redirect(environ) if redir: return redir(environ, start_response) return e(environ, start_response) except Exception as e: if self.debug: traceback.print_exc() response = self.rewriterapp._error_response(environ, 'Internal Error: ' + str(e), '500 Server Error') return response(environ, start_response)
python
def handle_request(self, environ, start_response): urls = self.url_map.bind_to_environ(environ) try: endpoint, args = urls.match() # store original script_name (original prefix) before modifications are made environ['pywb.app_prefix'] = environ.get('SCRIPT_NAME') response = endpoint(environ, **args) return response(environ, start_response) except HTTPException as e: redir = self._check_refer_redirect(environ) if redir: return redir(environ, start_response) return e(environ, start_response) except Exception as e: if self.debug: traceback.print_exc() response = self.rewriterapp._error_response(environ, 'Internal Error: ' + str(e), '500 Server Error') return response(environ, start_response)
[ "def", "handle_request", "(", "self", ",", "environ", ",", "start_response", ")", ":", "urls", "=", "self", ".", "url_map", ".", "bind_to_environ", "(", "environ", ")", "try", ":", "endpoint", ",", "args", "=", "urls", ".", "match", "(", ")", "# store or...
Retrieves the route handler and calls the handler returning its the response :param dict environ: The WSGI environment dictionary for the request :param start_response: :return: The WbResponse for the request :rtype: WbResponse
[ "Retrieves", "the", "route", "handler", "and", "calls", "the", "handler", "returning", "its", "the", "response" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L485-L514
230,698
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.create_app
def create_app(cls, port): """Create a new instance of FrontEndApp that listens on port with a hostname of 0.0.0.0 :param int port: The port FrontEndApp is to listen on :return: A new instance of FrontEndApp wrapped in GeventServer :rtype: GeventServer """ app = FrontEndApp() app_server = GeventServer(app, port=port, hostname='0.0.0.0') return app_server
python
def create_app(cls, port): app = FrontEndApp() app_server = GeventServer(app, port=port, hostname='0.0.0.0') return app_server
[ "def", "create_app", "(", "cls", ",", "port", ")", ":", "app", "=", "FrontEndApp", "(", ")", "app_server", "=", "GeventServer", "(", "app", ",", "port", "=", "port", ",", "hostname", "=", "'0.0.0.0'", ")", "return", "app_server" ]
Create a new instance of FrontEndApp that listens on port with a hostname of 0.0.0.0 :param int port: The port FrontEndApp is to listen on :return: A new instance of FrontEndApp wrapped in GeventServer :rtype: GeventServer
[ "Create", "a", "new", "instance", "of", "FrontEndApp", "that", "listens", "on", "port", "with", "a", "hostname", "of", "0", ".", "0", ".", "0", ".", "0" ]
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L517-L526
230,699
webrecorder/pywb
pywb/apps/frontendapp.py
FrontEndApp.init_proxy
def init_proxy(self, config): """Initialize and start proxy mode. If proxy configuration entry is not contained in the config this is a no op. Causes handler to become an instance of WSGIProxMiddleware. :param dict config: The configuration object used to configure this instance of FrontEndApp """ proxy_config = config.get('proxy') if not proxy_config: return if isinstance(proxy_config, str): proxy_coll = proxy_config proxy_config = {} else: proxy_coll = proxy_config['coll'] if '/' in proxy_coll: raise Exception('Proxy collection can not contain "/"') proxy_config['ca_name'] = proxy_config.get('ca_name', self.PROXY_CA_NAME) proxy_config['ca_file_cache'] = proxy_config.get('ca_file_cache', self.PROXY_CA_PATH) if proxy_config.get('recording'): logging.info('Proxy recording into collection "{0}"'.format(proxy_coll)) if proxy_coll in self.warcserver.list_fixed_routes(): raise Exception('Can not record into fixed collection') proxy_coll += self.RECORD_ROUTE if not config.get('recorder'): config['recorder'] = 'live' else: logging.info('Proxy enabled for collection "{0}"'.format(proxy_coll)) if proxy_config.get('enable_content_rewrite', True): self.proxy_prefix = '/{0}/bn_/'.format(proxy_coll) else: self.proxy_prefix = '/{0}/id_/'.format(proxy_coll) self.proxy_default_timestamp = proxy_config.get('default_timestamp') if self.proxy_default_timestamp: if not self.ALL_DIGITS.match(self.proxy_default_timestamp): try: self.proxy_default_timestamp = iso_date_to_timestamp(self.proxy_default_timestamp) except: raise Exception('Invalid Proxy Timestamp: Must Be All-Digit Timestamp or ISO Date Format') self.proxy_coll = proxy_coll self.handler = WSGIProxMiddleware(self.handle_request, self.proxy_route_request, proxy_host=proxy_config.get('host', 'pywb.proxy'), proxy_options=proxy_config)
python
def init_proxy(self, config): proxy_config = config.get('proxy') if not proxy_config: return if isinstance(proxy_config, str): proxy_coll = proxy_config proxy_config = {} else: proxy_coll = proxy_config['coll'] if '/' in proxy_coll: raise Exception('Proxy collection can not contain "/"') proxy_config['ca_name'] = proxy_config.get('ca_name', self.PROXY_CA_NAME) proxy_config['ca_file_cache'] = proxy_config.get('ca_file_cache', self.PROXY_CA_PATH) if proxy_config.get('recording'): logging.info('Proxy recording into collection "{0}"'.format(proxy_coll)) if proxy_coll in self.warcserver.list_fixed_routes(): raise Exception('Can not record into fixed collection') proxy_coll += self.RECORD_ROUTE if not config.get('recorder'): config['recorder'] = 'live' else: logging.info('Proxy enabled for collection "{0}"'.format(proxy_coll)) if proxy_config.get('enable_content_rewrite', True): self.proxy_prefix = '/{0}/bn_/'.format(proxy_coll) else: self.proxy_prefix = '/{0}/id_/'.format(proxy_coll) self.proxy_default_timestamp = proxy_config.get('default_timestamp') if self.proxy_default_timestamp: if not self.ALL_DIGITS.match(self.proxy_default_timestamp): try: self.proxy_default_timestamp = iso_date_to_timestamp(self.proxy_default_timestamp) except: raise Exception('Invalid Proxy Timestamp: Must Be All-Digit Timestamp or ISO Date Format') self.proxy_coll = proxy_coll self.handler = WSGIProxMiddleware(self.handle_request, self.proxy_route_request, proxy_host=proxy_config.get('host', 'pywb.proxy'), proxy_options=proxy_config)
[ "def", "init_proxy", "(", "self", ",", "config", ")", ":", "proxy_config", "=", "config", ".", "get", "(", "'proxy'", ")", "if", "not", "proxy_config", ":", "return", "if", "isinstance", "(", "proxy_config", ",", "str", ")", ":", "proxy_coll", "=", "prox...
Initialize and start proxy mode. If proxy configuration entry is not contained in the config this is a no op. Causes handler to become an instance of WSGIProxMiddleware. :param dict config: The configuration object used to configure this instance of FrontEndApp
[ "Initialize", "and", "start", "proxy", "mode", ".", "If", "proxy", "configuration", "entry", "is", "not", "contained", "in", "the", "config", "this", "is", "a", "no", "op", ".", "Causes", "handler", "to", "become", "an", "instance", "of", "WSGIProxMiddleware...
77f8bb647639dd66f6b92b7a9174c28810e4b1d9
https://github.com/webrecorder/pywb/blob/77f8bb647639dd66f6b92b7a9174c28810e4b1d9/pywb/apps/frontendapp.py#L528-L580