INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Parse persons from given datafield.
def _parse_persons(self, datafield, subfield, roles=["aut"]): """ Parse persons from given datafield. Args: datafield (str): code of datafield ("010", "730", etc..) subfield (char): code of subfield ("a", "z", "4", etc..) role (list of str): set to ["any"] f...
Args: undefined ( optional ): Argument which will be returned if the subname record is not found.
def get_subname(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `subname` record is not found. Returns: str: Subname of the book or `undefined` if `subname` is not \ found. """ ...
Args: undefined ( optional ): Argument which will be returned if the price record is not found.
def get_price(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `price` record is not found. Returns: str: Price of the book (with currency) or `undefined` if `price` \ is not found. ...
Args: undefined ( optional ): Argument which will be returned if the part record is not found.
def get_part(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `part` record is not found. Returns: str: Which part of the book series is this record or `undefined` \ if `part` is not found...
Args: undefined ( optional ): Argument which will be returned if the part_name record is not found.
def get_part_name(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `part_name` record is not found. Returns: str: Name of the part of the series. or `undefined` if `part_name`\ is not foun...
Args: undefined ( optional ): Argument which will be returned if the publisher record is not found.
def get_publisher(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `publisher` record is not found. Returns: str: Name of the publisher ("``Grada``" for example) or \ `undefined` if `publi...
Args: undefined ( optional ): Argument which will be returned if the pub_date record is not found.
def get_pub_date(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `pub_date` record is not found. Returns: str: Date of publication (month and year usually) or `undefined` \ if `pub_date` ...
Args: undefined ( optional ): Argument which will be returned if the pub_order record is not found.
def get_pub_order(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `pub_order` record is not found. Returns: str: Information about order in which was the book published or \ `undefined` i...
Args: undefined ( optional ): Argument which will be returned if the pub_place record is not found.
def get_pub_place(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `pub_place` record is not found. Returns: str: Name of city/country where the book was published or \ `undefined` if `pub...
Args: undefined ( optional ): Argument which will be returned if the format record is not found.
def get_format(self, undefined=""): """ Args: undefined (optional): Argument, which will be returned if the `format` record is not found. Returns: str: Dimensions of the book ('``23 cm``' for example) or `undefined` if `format` is n...
Returns: list: Authors represented as: class:. Person objects.
def get_authors(self): """ Returns: list: Authors represented as :class:`.Person` objects. """ authors = self._parse_persons("100", "a") authors += self._parse_persons("600", "a") authors += self._parse_persons("700", "a") authors += self._parse_person...
Args: roles ( list optional ): Specify which types of corporations you need. Set to [ any ] for any role [ dst ] for distributors etc..
def get_corporations(self, roles=["dst"]): """ Args: roles (list, optional): Specify which types of corporations you need. Set to ``["any"]`` for any role, ``["dst"]`` for distributors, etc.. Note: See http://www.loc.gov/marc/relators/...
Get list of VALID ISBN.
def get_ISBNs(self): """ Get list of VALID ISBN. Returns: list: List with *valid* ISBN strings. """ invalid_isbns = set(self.get_invalid_ISBNs()) valid_isbns = [ self._clean_isbn(isbn) for isbn in self["020a"] if self._cle...
Get list of VALID ISSNs ( 022a ).
def get_ISSNs(self): """ Get list of VALID ISSNs (``022a``). Returns: list: List with *valid* ISSN strings. """ invalid_issns = set(self.get_invalid_ISSNs()) return [ self._clean_isbn(issn) for issn in self["022a"] if self...
Filter binding from ISBN record. In MARC XML/ OAI the binding information is stored in same subrecord as ISBN.
def _filter_binding(self, binding): """ Filter binding from ISBN record. In MARC XML / OAI, the binding information is stored in same subrecord as ISBN. Example: ``<subfield code="a">80-251-0225-4 (brož.) :</subfield>`` -> ``brož.``. """ binding =...
Content of field 856u42. Typically URL pointing to producers homepage.
def get_urls(self): """ Content of field ``856u42``. Typically URL pointing to producers homepage. Returns: list: List of URLs defined by producer. """ urls = self.get_subfields("856", "u", i1="4", i2="2") return map(lambda x: x.replace("&amp;", "&")...
URL s which may point to edeposit aleph kramerius and so on.
def get_internal_urls(self): """ URL's, which may point to edeposit, aleph, kramerius and so on. Fields ``856u40``, ``998a`` and ``URLu``. Returns: list: List of internal URLs. """ internal_urls = self.get_subfields("856", "u", i1="4", i2="0") inter...
Returns: PublicationType:: class:. PublicationType enum ** value **.
def get_pub_type(self): """ Returns: PublicationType: :class:`.PublicationType` enum **value**. """ INFO_CHAR_INDEX = 6 SECOND_INFO_CHAR_I = 18 if not len(self.leader) >= INFO_CHAR_INDEX + 1: return PublicationType.monographic if self.con...
Standard dict - like. get () method.
def get(self, item, alt=None): """ Standard dict-like .get() method. Args: item (str): See :meth:`.__getitem__` for details. alt (default None): Alternative value, if item is not found. Returns: obj: `item` or `alt`, if item is not found. """...
r Create a callable that implements a PID controller.
def pid(kp=0., ki=0., kd=0., smooth=0.1): r'''Create a callable that implements a PID controller. A PID controller returns a control signal :math:`u(t)` given a history of error measurements :math:`e(0) \dots e(t)`, using proportional (P), integral (I), and derivative (D) terms, according to: .. m...
Given a sequence of sequences return a flat numpy array.
def as_flat_array(iterables): '''Given a sequence of sequences, return a flat numpy array. Parameters ---------- iterables : sequence of sequence of number A sequence of tuples or lists containing numbers. Typically these come from something that represents each joint in a skeleton, lik...
Load a skeleton definition from a file.
def load(self, source, **kwargs): '''Load a skeleton definition from a file. Parameters ---------- source : str or file A filename or file-like object that contains text information describing a skeleton. See :class:`pagoda.parser.Parser` for more inf...
Load a skeleton definition from a text file.
def load_skel(self, source, **kwargs): '''Load a skeleton definition from a text file. Parameters ---------- source : str or file A filename or file-like object that contains text information describing a skeleton. See :class:`pagoda.parser.BodyParser` for ...
Load a skeleton definition from an ASF text file.
def load_asf(self, source, **kwargs): '''Load a skeleton definition from an ASF text file. Parameters ---------- source : str or file A filename or file-like object that contains text information describing a skeleton, in ASF format. ''' if hasatt...
Set PID parameters for all joints in the skeleton.
def set_pid_params(self, *args, **kwargs): '''Set PID parameters for all joints in the skeleton. Parameters for this method are passed directly to the `pid` constructor. ''' for joint in self.joints: joint.target_angles = [None] * joint.ADOF joint.controllers = [...
Get a list of all current joint torques in the skeleton.
def joint_torques(self): '''Get a list of all current joint torques in the skeleton.''' return as_flat_array(getattr(j, 'amotor', j).feedback[-1][:j.ADOF] for j in self.joints)
Get a list of the indices for a specific joint.
def indices_for_joint(self, name): '''Get a list of the indices for a specific joint. Parameters ---------- name : str The name of the joint to look up. Returns ------- list of int : A list of the index values for quantities related to th...
Get a list of the indices for a specific body.
def indices_for_body(self, name, step=3): '''Get a list of the indices for a specific body. Parameters ---------- name : str The name of the body to look up. step : int, optional The number of numbers for each body. Defaults to 3, should be set ...
Get the current joint separations for the skeleton.
def joint_distances(self): '''Get the current joint separations for the skeleton. Returns ------- distances : list of float A list expressing the distance between the two joint anchor points, for each joint in the skeleton. These quantities describe how ...
Enable the joint motors in this skeleton.
def enable_motors(self, max_force): '''Enable the joint motors in this skeleton. This method sets the maximum force that can be applied by each joint to attain the desired target velocities. It also enables torque feedback for all joint motors. Parameters ---------- ...
Move each joint toward a target angle.
def set_target_angles(self, angles): '''Move each joint toward a target angle. This method uses a PID controller to set a target angular velocity for each degree of freedom in the skeleton, based on the difference between the current and the target angle for the respective DOF. ...
Add torques for each degree of freedom in the skeleton.
def add_torques(self, torques): '''Add torques for each degree of freedom in the skeleton. Parameters ---------- torques : list of float A list of the torques to add to each degree of freedom in the skeleton. ''' j = 0 for joint in self.jo...
Return the names of our marker labels in canonical order.
def labels(self): '''Return the names of our marker labels in canonical order.''' return sorted(self.channels, key=lambda c: self.channels[c])
Load marker data from a CSV file.
def load_csv(self, filename, start_frame=10, max_frames=int(1e300)): '''Load marker data from a CSV file. The file will be imported using Pandas, which must be installed to use this method. (``pip install pandas``) The first line of the CSV file will be used for header information. The...
Load marker data from a C3D file.
def load_c3d(self, filename, start_frame=0, max_frames=int(1e300)): '''Load marker data from a C3D file. The file will be imported using the c3d module, which must be installed to use this method. (``pip install c3d``) Parameters ---------- filename : str Na...
Process data to produce velocity and dropout information.
def process_data(self): '''Process data to produce velocity and dropout information.''' self.visibility = self.data[:, :, 3] self.positions = self.data[:, :, :3] self.velocities = np.zeros_like(self.positions) + 1000 for frame_no in range(1, len(self.data) - 1): prev ...
Create physics bodies corresponding to each marker in our data.
def create_bodies(self): '''Create physics bodies corresponding to each marker in our data.''' self.bodies = {} for label in self.channels: body = self.world.create_body( 'sphere', name='marker:{}'.format(label), radius=0.02) body.is_kinematic = True ...
Load attachment configuration from the given text source.
def load_attachments(self, source, skeleton): '''Load attachment configuration from the given text source. The attachment configuration file has a simple format. After discarding Unix-style comments (any part of a line that starts with the pound (#) character), each line in the file is ...
Attach marker bodies to the corresponding skeleton bodies.
def attach(self, frame_no): '''Attach marker bodies to the corresponding skeleton bodies. Attachments are only made for markers that are not in a dropout state in the given frame. Parameters ---------- frame_no : int The frame of data we will use for attachi...
Reposition markers to a specific frame of data.
def reposition(self, frame_no): '''Reposition markers to a specific frame of data. Parameters ---------- frame_no : int The frame of data where we should reposition marker bodies. Markers will be positioned in the appropriate places in world coordinates. ...
Get a list of the distances between markers and their attachments.
def distances(self): '''Get a list of the distances between markers and their attachments. Returns ------- distances : ndarray of shape (num-markers, 3) Array of distances for each marker joint in our attachment setup. If a marker does not currently have an assoc...
Return an array of the forces exerted by marker springs.
def forces(self, dx_tm1=None): '''Return an array of the forces exerted by marker springs. Notes ----- The forces exerted by the marker springs can be approximated by:: F = kp * dx where ``dx`` is the current array of marker distances. An even more accurate ...
Create and configure a skeleton in our model.
def load_skeleton(self, filename, pid_params=None): '''Create and configure a skeleton in our model. Parameters ---------- filename : str The name of a file containing skeleton configuration data. pid_params : dict, optional If given, use this dictionary ...
Load marker data and attachment preferences into the model.
def load_markers(self, filename, attachments, max_frames=1e100): '''Load marker data and attachment preferences into the model. Parameters ---------- filename : str The name of a file containing marker data. This currently needs to be either a .C3D or a .CSV file...
Advance the physics world by one step.
def step(self, substeps=2): '''Advance the physics world by one step. Typically this is called as part of a :class:`pagoda.viewer.Viewer`, but it can also be called manually (or some other stepping mechanism entirely can be used). ''' # by default we step by following ou...
Settle the skeleton to our marker data at a specific frame.
def settle_to_markers(self, frame_no=0, max_distance=0.05, max_iters=300, states=None): '''Settle the skeleton to our marker data at a specific frame. Parameters ---------- frame_no : int, optional Settle the skeleton to marker data at this frame. D...
Iterate over a set of marker data dragging its skeleton along.
def follow_markers(self, start=0, end=1e100, states=None): '''Iterate over a set of marker data, dragging its skeleton along. Parameters ---------- start : int, optional Start following marker data after this frame. Defaults to 0. end : int, optional Stop...
Update the simulator to a specific frame of marker data.
def _step_to_marker_frame(self, frame_no, dt=None): '''Update the simulator to a specific frame of marker data. This method returns a generator of body states for the skeleton! This generator must be exhausted (e.g., by consuming this call in a for loop) for the simulator to work proper...
Follow a set of marker data yielding kinematic joint angles.
def inverse_kinematics(self, start=0, end=1e100, states=None, max_force=20): '''Follow a set of marker data, yielding kinematic joint angles. Parameters ---------- start : int, optional Start following marker data after this frame. Defaults to 0. end : int, optional ...
Follow a set of angle data yielding dynamic joint torques.
def inverse_dynamics(self, angles, start=0, end=1e100, states=None, max_force=100): '''Follow a set of angle data, yielding dynamic joint torques. Parameters ---------- angles : ndarray (num-frames x num-dofs) Follow angle data provided by this array of angle values. ...
Move the body according to a set of torque data.
def forward_dynamics(self, torques, start=0, states=None): '''Move the body according to a set of torque data.''' if states is not None: self.skeleton.set_body_states(states) for frame_no, torque in enumerate(torques): if frame_no < start: continue ...
Sort values but put numbers after alphabetically sorted words.
def resorted(values): """ Sort values, but put numbers after alphabetically sorted words. This function is here to make outputs diff-compatible with Aleph. Example:: >>> sorted(["b", "1", "a"]) ['1', 'a', 'b'] >>> resorted(["b", "1", "a"]) ['a', 'b', '1'] Args: ...
Draw all bodies in the world.
def render(self, dt): '''Draw all bodies in the world.''' for frame in self._frozen: for body in frame: self.draw_body(body) for body in self.world.bodies: self.draw_body(body) if hasattr(self.world, 'markers'): # draw line between anc...
Get room stream to listen for messages.
def get_stream(self, error_callback=None, live=True): """ Get room stream to listen for messages. Kwargs: error_callback (func): Callback to call when an error occurred (parameters: exception) live (bool): If True, issue a live stream, otherwise an offline stream Return...
Get list of users in the room.
def get_users(self, sort=True): """ Get list of users in the room. Kwargs: sort (bool): If True, sort rooms by name Returns: array. List of users """ self._load() if sort: self.users.sort(key=operator.itemgetter("name")) retur...
Recent messages.
def recent(self, message_id=None, limit=None): """ Recent messages. Kwargs: message_id (int): If specified, return messages since the specified message ID limit (int): If specified, limit the number of messages Returns: array. Messages """ pa...
Set the room name.
def set_name(self, name): """ Set the room name. Args: name (str): Name Returns: bool. Success """ if not self._campfire.get_user().admin: return False result = self._connection.put("room/%s" % self.id, {"room": {"name": name}}) ...
Set the room topic.
def set_topic(self, topic): """ Set the room topic. Args: topic (str): Topic Returns: bool. Success """ if not topic: topic = '' result = self._connection.put("room/%s" % self.id, {"room": {"topic": topic}}) if result["success...
Post a message.
def speak(self, message): """ Post a message. Args: message (:class:`Message` or string): Message Returns: bool. Success """ campfire = self.get_campfire() if not isinstance(message, Message): message = Message(campfire, message) ...
Recent messages.
def transcript(self, for_date=None): """ Recent messages. Kwargs: for_date (date): If specified, get the transcript for this specific date Returns: array. Messages """ url = "room/%s/transcript" % self.id if for_date: url = "%s/%d/%d/...
Create a new thread to upload a file ( thread should be then started with start () to perform upload. )
def upload(self, path, progress_callback=None, finished_callback=None, error_callback=None): """ Create a new thread to upload a file (thread should be then started with start() to perform upload.) Args: path (str): Path to file Kwargs: progress_callback (func):...
Build a call to use the new get_config function from args passed to Config. __init__.
def get_new_call(group_name, app_name, search_path, filename, require_load, version, secure): # type: (str, str, Optional[str], str, bool, Optional[str], bool) -> str ''' Build a call to use the new ``get_config`` function from args passed to ``Config.__init__``. ''' new_call_kw...
Build a callable Python string for a function call. The output will be combined similar to this template::
def build_call_str(prefix, args, kwargs): # type: (str, Any, Any) -> str ''' Build a callable Python string for a function call. The output will be combined similar to this template:: <prefix>(<args>, <kwargs>) Example:: >>> build_call_str('foo', (1, 2), {'a': '10'}) "foo(...
Returns a list of paths specified by the XDG_CONFIG_DIRS environment variable or the appropriate default.
def get_xdg_dirs(self): # type: () -> List[str] """ Returns a list of paths specified by the XDG_CONFIG_DIRS environment variable or the appropriate default. The list is sorted by precedence, with the most important item coming *last* (required by the existing config_res...
Returns the value specified in the XDG_CONFIG_HOME environment variable or the appropriate default.
def get_xdg_home(self): # type: () -> str """ Returns the value specified in the XDG_CONFIG_HOME environment variable or the appropriate default. """ config_home = getenv('XDG_CONFIG_HOME', '') if config_home: self._log.debug('XDG_CONFIG_HOME is set to...
Returns the filename which is effectively used by the application. If overridden by an environment variable it will return that filename.
def _effective_filename(self): # type: () -> str """ Returns the filename which is effectively used by the application. If overridden by an environment variable, it will return that filename. """ # same logic for the configuration filename. First, check if we were ...
Returns a list of paths to search for config files in reverse order of precedence. In other words: the last path element will override the settings from the first one.
def _effective_path(self): # type: () -> List[str] """ Returns a list of paths to search for config files in reverse order of precedence. In other words: the last path element will override the settings from the first one. """ # default search path path =...
Check if filename can be read. Will return boolean which is True if the file can be read False otherwise.
def check_file(self, filename): # type: (str) -> bool """ Check if ``filename`` can be read. Will return boolean which is True if the file can be read, False otherwise. """ if not exists(filename): return False # Check if the file is version-compatibl...
Overrides: py: meth: configparser. ConfigParser. get.
def get(self, section, option, **kwargs): # type: ignore # type: (str, str, Any) -> Any """ Overrides :py:meth:`configparser.ConfigParser.get`. In addition to ``section`` and ``option``, this call takes an optional ``default`` value. This behaviour works in *addition* to the ...
Searches for an appropriate config file. If found loads the file into the current instance. This method can also be used to reload a configuration. Note that you may want to set reload to True to clear the configuration before loading in that case. Without doing that values will remain available even if they have been ...
def load(self, reload=False, require_load=False): # type: (bool, bool) -> None """ Searches for an appropriate config file. If found, loads the file into the current instance. This method can also be used to reload a configuration. Note that you may want to set ``reload`` to ``Tr...
Overrides: py: meth:. Config. check_file
def check_file(self, filename): # type: (str) -> bool """ Overrides :py:meth:`.Config.check_file` """ can_read = super(SecuredConfig, self).check_file(filename) if not can_read: return False mode = get_stat(filename).st_mode if (mode & stat.S_...
https:// www. python. org/ dev/ peps/ pep - 0333/ #environ - variables
def setup_environ(self): """https://www.python.org/dev/peps/pep-0333/#environ-variables""" # Set up base environment env = self.base_environ = {} env['SERVER_NAME'] = self.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PORT'] = str(self.server_port) ...
https:// www. python. org/ dev/ peps/ pep - 0333/ #environ - variables
def get_environ(self): """https://www.python.org/dev/peps/pep-0333/#environ-variables""" env = self.base_environ.copy() env['REQUEST_METHOD'] = self.request_method if '?' in self.path: path, query = self.path.split('?', 1) else: path, query = self.path, '...
Get styles.
def get(self, q=None, page=None): """Get styles.""" # Check cache to exit early if needed etag = generate_etag(current_ext.content_version.encode('utf8')) self.check_etag(etag, weak=True) # Build response res = jsonify(current_ext.styles) res.set_etag(etag) ...
Create a connection with given settings.
def create_from_settings(settings): """ Create a connection with given settings. Args: settings (dict): A dictionary of settings Returns: :class:`Connection`. The connection """ return Connection( settings["url"], settings["base_...
Issue a PUT request.
def delete(self, url=None, post_data={}, parse_data=False, key=None, parameters=None): """ Issue a PUT request. Kwargs: url (str): Destination URL post_data (dict): Dictionary of parameter and values parse_data (bool): If true, parse response data key (st...
Issue a POST request.
def post(self, url=None, post_data={}, parse_data=False, key=None, parameters=None, listener=None): """ Issue a POST request. Kwargs: url (str): Destination URL post_data (dict): Dictionary of parameter and values parse_data (bool): If true, parse response data ...
Issue a GET request.
def get(self, url=None, parse_data=True, key=None, parameters=None): """ Issue a GET request. Kwargs: url (str): Destination URL parse_data (bool): If true, parse response data key (string): If parse_data==True, look for this key when parsing data paramet...
Get headers.
def get_headers(self): """ Get headers. Returns: tuple: Headers """ headers = { "User-Agent": "kFlame 1.0" } password_url = self._get_password_url() if password_url and password_url in self._settings["authorizations"]: headers...
Get URL used for authentication
def _get_password_url(self): """ Get URL used for authentication Returns: string: URL """ password_url = None if self._settings["user"] or self._settings["authorization"]: if self._settings["url"]: password_url = self._settings["url"] ...
Parses a response.
def parse(self, text, key=None): """ Parses a response. Args: text (str): Text to parse Kwargs: key (str): Key to look for, if any Returns: Parsed value Raises: ValueError """ try: data = json.loads(t...
Build a request for twisted
def build_twisted_request(self, method, url, extra_headers={}, body_producer=None, full_url=False): """ Build a request for twisted Args: method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None url (str): Destination URL...
Issue a request.
def _fetch(self, method, url=None, post_data=None, parse_data=True, key=None, parameters=None, listener=None, full_return=False): """ Issue a request. Args: method (str): Request method (GET/POST/PUT/DELETE/etc.) If not specified, it will be POST if post_data is not None Kwargs: ...
Build destination URL.
def _url(self, url=None, parameters=None): """ Build destination URL. Kwargs: url (str): Destination URL parameters (dict): Additional GET parameters to append to the URL Returns: str. URL """ uri = url or self._settings["url"] if u...
Tells if this message is a text message.
def is_text(self): """ Tells if this message is a text message. Returns: bool. Success """ return self.type in [ self._TYPE_PASTE, self._TYPE_TEXT, self._TYPE_TWEET ]
Get rooms list.
def get_rooms(self, sort=True): """ Get rooms list. Kwargs: sort (bool): If True, sort rooms by name Returns: array. List of rooms (each room is a dict) """ rooms = self._connection.get("rooms") if sort: rooms.sort(key=operator.itemge...
Get a room by name.
def get_room_by_name(self, name): """ Get a room by name. Returns: :class:`Room`. Room Raises: RoomNotFoundException """ rooms = self.get_rooms() for room in rooms or []: if room["name"] == name: return self.get_room(r...
Get room.
def get_room(self, id): """ Get room. Returns: :class:`Room`. Room """ if id not in self._rooms: self._rooms[id] = Room(self, id) return self._rooms[id]
Get user.
def get_user(self, id = None): """ Get user. Returns: :class:`User`. User """ if not id: id = self._user.id if id not in self._users: self._users[id] = self._user if id == self._user.id else User(self, id) return self._users[id]
Search transcripts.
def search(self, terms): """ Search transcripts. Args: terms (str): Terms for search Returns: array. Messages """ messages = self._connection.get("search/%s" % urllib.quote_plus(terms), key="messages") if messages: messages = [Message...
: rtype: Cookie. SimpleCookie
def cookie_dump(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False): """ :rtype: ``Cookie.SimpleCookie`` """ cookie = SimpleCookie() cookie[key] = value for attr in ('max_age', 'expires', 'path', 'domain', 'secure', 'ht...
e. g. 200 OK
def response_status_string(code): """e.g. ``200 OK`` """ mean = HTTP_STATUS_CODES.get(code, 'unknown').upper() return '{code} {mean}'.format(code=code, mean=mean)
Request cookies
def cookies(self): """Request cookies :rtype: dict """ http_cookie = self.environ.get('HTTP_COOKIE', '') _cookies = { k: v.value for (k, v) in SimpleCookie(http_cookie).items() } return _cookies
Attach an observer.
def attach(self, observer): """ Attach an observer. Args: observer (func): A function to be called when new messages arrive Returns: :class:`Stream`. Current instance to allow chaining """ if not observer in self._observers: self._observers.a...
Called when incoming messages arrive.
def incoming(self, messages): """ Called when incoming messages arrive. Args: messages (tuple): Messages (each message is a dict) """ if self._observers: campfire = self._room.get_campfire() for message in messages: for observer in sel...
Called by the thread it runs the process.
def run(self): """ Called by the thread, it runs the process. NEVER call this method directly. Instead call start() to start the thread. To stop, call stop(), and then join() """ if self._live: self._use_process = True self._abort = False campfire ...
Called by the process it runs it.
def run(self): """ Called by the process, it runs it. NEVER call this method directly. Instead call start() to start the separate process. If you don't want to use a second process, then call fetch() directly on this istance. To stop, call terminate() """ if not self._q...
Fetch new messages.
def fetch(self): """ Fetch new messages. """ try: if not self._last_message_id: messages = self._connection.get("room/%s/recent" % self._room_id, key="messages", parameters={ "limit": 1 }) self._last_message_id = messages[-1...
Called when new messages arrive.
def received(self, messages): """ Called when new messages arrive. Args: messages (tuple): Messages """ if messages: if self._queue: self._queue.put_nowait(messages) if self._callback: self._callback(messages)
Called by the process it runs it.
def run(self): """ Called by the process, it runs it. NEVER call this method directly. Instead call start() to start the separate process. If you don't want to use a second process, then call fetch() directly on this istance. To stop, call terminate() """ if not self._q...