_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q264600
Room.get_users
validation
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...
python
{ "resource": "" }
q264601
Room.set_name
validation
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}}) ...
python
{ "resource": "" }
q264602
Room.set_topic
validation
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...
python
{ "resource": "" }
q264603
Room.speak
validation
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) ...
python
{ "resource": "" }
q264604
Config.get_xdg_dirs
validation
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...
python
{ "resource": "" }
q264605
Config.get_xdg_home
validation
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...
python
{ "resource": "" }
q264606
Config._effective_filename
validation
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 ...
python
{ "resource": "" }
q264607
Config.check_file
validation
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...
python
{ "resource": "" }
q264608
Config.load
validation
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...
python
{ "resource": "" }
q264609
StylesResource.get
validation
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) ...
python
{ "resource": "" }
q264610
Connection.create_from_settings
validation
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_...
python
{ "resource": "" }
q264611
Connection.delete
validation
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...
python
{ "resource": "" }
q264612
Connection.post
validation
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 ...
python
{ "resource": "" }
q264613
Connection.get
validation
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...
python
{ "resource": "" }
q264614
Connection.get_headers
validation
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...
python
{ "resource": "" }
q264615
Connection._get_password_url
validation
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"] ...
python
{ "resource": "" }
q264616
Connection.parse
validation
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...
python
{ "resource": "" }
q264617
Connection.build_twisted_request
validation
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...
python
{ "resource": "" }
q264618
Connection._fetch
validation
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: ...
python
{ "resource": "" }
q264619
Connection._url
validation
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...
python
{ "resource": "" }
q264620
Message.is_text
validation
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 ]
python
{ "resource": "" }
q264621
Campfire.get_rooms
validation
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...
python
{ "resource": "" }
q264622
Campfire.get_room_by_name
validation
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...
python
{ "resource": "" }
q264623
Campfire.get_room
validation
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]
python
{ "resource": "" }
q264624
Campfire.get_user
validation
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]
python
{ "resource": "" }
q264625
Campfire.search
validation
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...
python
{ "resource": "" }
q264626
Stream.attach
validation
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...
python
{ "resource": "" }
q264627
Stream.incoming
validation
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...
python
{ "resource": "" }
q264628
StreamProcess.fetch
validation
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...
python
{ "resource": "" }
q264629
StreamProcess.received
validation
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)
python
{ "resource": "" }
q264630
LiveStreamProtocol.connectionMade
validation
def connectionMade(self): """ Called when a connection is made, and used to send out headers """ headers = [ "GET %s HTTP/1.1" % ("/room/%s/live.json" % self.factory.get_stream().get_room_id()) ] connection_headers = self.factory.get_stream().get_connection().get_headers() ...
python
{ "resource": "" }
q264631
LiveStreamProtocol.lineReceived
validation
def lineReceived(self, line): """ Callback issued by twisted when new line arrives. Args: line (str): Incoming line """ while self._in_header: if line: self._headers.append(line) else: http, status, message = self._head...
python
{ "resource": "" }
q264632
LiveStreamProtocol.rawDataReceived
validation
def rawDataReceived(self, data): """ Process data. Args: data (str): Incoming data """ if self._len_expected is not None: data, extra = data[:self._len_expected], data[self._len_expected:] self._len_expected -= len(data) else: extr...
python
{ "resource": "" }
q264633
_InvenioCSLRESTState.styles
validation
def styles(self): """Get a dictionary of CSL styles.""" styles = get_all_styles() whitelist = self.app.config.get('CSL_STYLES_WHITELIST') if whitelist: return {k: v for k, v in styles.items() if k in whitelist} return styles
python
{ "resource": "" }
q264634
MultiPartProducer.startProducing
validation
def startProducing(self, consumer): """ Start producing. Args: consumer: Consumer """ self._consumer = consumer self._current_deferred = defer.Deferred() self._sent = 0 self._paused = False if not hasattr(self, "_chunk_headers"): ...
python
{ "resource": "" }
q264635
MultiPartProducer._finish
validation
def _finish(self, forced=False): """ Cleanup code after asked to stop producing. Kwargs: forced (bool): If True, we were forced to stop """ if hasattr(self, "_current_file_handle") and self._current_file_handle: self._current_file_handle.close() ...
python
{ "resource": "" }
q264636
MultiPartProducer._send_to_consumer
validation
def _send_to_consumer(self, block): """ Send a block of bytes to the consumer. Args: block (str): Block of bytes """ self._consumer.write(block) self._sent += len(block) if self._callback: self._callback(self._sent, self.length)
python
{ "resource": "" }
q264637
MultiPartProducer._length
validation
def _length(self): """ Returns total length for this request. Returns: int. Length """ self._build_chunk_headers() length = 0 if self._data: for field in self._data: length += len(self._chunk_headers[field]) lengt...
python
{ "resource": "" }
q264638
MultiPartProducer._build_chunk_headers
validation
def _build_chunk_headers(self): """ Build headers for each field. """ if hasattr(self, "_chunk_headers") and self._chunk_headers: return self._chunk_headers = {} for field in self._files: self._chunk_headers[field] = self._headers(field, True) for field i...
python
{ "resource": "" }
q264639
MultiPartProducer._file_size
validation
def _file_size(self, field): """ Returns the file size for given file field. Args: field (str): File field Returns: int. File size """ size = 0 try: handle = open(self._files[field], "r") size = os.fstat(handle.fileno()).s...
python
{ "resource": "" }
q264640
_filename
validation
def _filename(draw, result_type=None): """Generate a path value of type result_type. result_type can either be bytes or text_type """ # Various ASCII chars have a special meaning for the operating system, # so make them more common ascii_char = characters(min_codepoint=0x01, max_codepoint=0x7f...
python
{ "resource": "" }
q264641
_str_to_path
validation
def _str_to_path(s, result_type): """Given an ASCII str, returns a path of the given type.""" assert isinstance(s, str) if isinstance(s, bytes) and result_type is text_type: return s.decode('ascii') elif isinstance(s, text_type) and result_type is bytes: return s.encode('ascii') ret...
python
{ "resource": "" }
q264642
_path_root
validation
def _path_root(draw, result_type): """Generates a root component for a path.""" # Based on https://en.wikipedia.org/wiki/Path_(computing) def tp(s=''): return _str_to_path(s, result_type) if os.name != 'nt': return tp(os.sep) sep = sampled_from([os.sep, os.altsep or os.sep]).map(...
python
{ "resource": "" }
q264643
fspaths
validation
def fspaths(draw, allow_pathlike=None): """A strategy which generates filesystem path values. The generated values include everything which the builtin :func:`python:open` function accepts i.e. which won't lead to :exc:`ValueError` or :exc:`TypeError` being raised. Note that the range of the retur...
python
{ "resource": "" }
q264644
CodeBuilder._exec
validation
def _exec(self, globals_dict=None): """exec compiled code""" globals_dict = globals_dict or {} globals_dict.setdefault('__builtins__', {}) exec(self._code, globals_dict) return globals_dict
python
{ "resource": "" }
q264645
Template.handle_extends
validation
def handle_extends(self, text): """replace all blocks in extends with current blocks""" match = self.re_extends.match(text) if match: extra_text = self.re_extends.sub('', text, count=1) blocks = self.get_blocks(extra_text) path = os.path.join(self.base_dir, ma...
python
{ "resource": "" }
q264646
Template.flush_buffer
validation
def flush_buffer(self): """flush all buffered string into code""" self.code_builder.add_line('{0}.extend([{1}])', self.result_var, ','.join(self.buffered)) self.buffered = []
python
{ "resource": "" }
q264647
UploadProcess.add_data
validation
def add_data(self, data): """ Add POST data. Args: data (dict): key => value dictionary """ if not self._data: self._data = {} self._data.update(data)
python
{ "resource": "" }
q264648
API.log_error
validation
def log_error(self, text: str) -> None: ''' Given some error text it will log the text if self.log_errors is True :param text: Error text to log ''' if self.log_errors: with self._log_fp.open('a+') as log_file: log_file.write(f'{text}\n')
python
{ "resource": "" }
q264649
API.parse_conll
validation
def parse_conll(self, texts: List[str], retry_count: int = 0) -> List[str]: ''' Processes the texts using TweeboParse and returns them in CoNLL format. :param texts: The List of Strings to be processed by TweeboParse. :param retry_count: The number of times it has retried for. Default ...
python
{ "resource": "" }
q264650
CampfireEntity.set_data
validation
def set_data(self, data={}, datetime_fields=[]): """ Set entity data Args: data (dict): Entity data datetime_fields (array): Fields that should be parsed as datetimes """ if datetime_fields: for field in datetime_fields: if field in da...
python
{ "resource": "" }
q264651
validate_xml_text
validation
def validate_xml_text(text): """validates XML text""" bad_chars = __INVALID_XML_CHARS & set(text) if bad_chars: for offset,c in enumerate(text): if c in bad_chars: raise RuntimeError('invalid XML character: ' + repr(c) + ' at offset ' + str(offset))
python
{ "resource": "" }
q264652
validate_xml_name
validation
def validate_xml_name(name): """validates XML name""" if len(name) == 0: raise RuntimeError('empty XML name') if __INVALID_NAME_CHARS & set(name): raise RuntimeError('XML name contains invalid character') if name[0] in __INVALID_NAME_START_CHARS: raise RuntimeError('XML name st...
python
{ "resource": "" }
q264653
GameStage.on_enter_stage
validation
def on_enter_stage(self): """ Prepare the actors, the world, and the messaging system to begin playing the game. This method is guaranteed to be called exactly once upon entering the game stage. """ with self.world._unlock_temporarily(): sel...
python
{ "resource": "" }
q264654
GameStage.on_update_stage
validation
def on_update_stage(self, dt): """ Sequentially update the actors, the world, and the messaging system. The theater terminates once all of the actors indicate that they are done. """ for actor in self.actors: actor.on_update_game(dt) self.forum.on_update_g...
python
{ "resource": "" }
q264655
GameStage.on_exit_stage
validation
def on_exit_stage(self): """ Give the actors, the world, and the messaging system a chance to react to the end of the game. """ # 1. Let the forum react to the end of the game. Local forums don't # react to this, but remote forums take the opportunity to stop ...
python
{ "resource": "" }
q264656
DebugPanel.render_vars
validation
def render_vars(self): """Template variables.""" return { 'records': [ { 'message': record.getMessage(), 'time': dt.datetime.fromtimestamp(record.created).strftime('%H:%M:%S'), } for record in self.handler.records ...
python
{ "resource": "" }
q264657
AIODatabase.init_async
validation
def init_async(self, loop=None): """Use when application is starting.""" self._loop = loop or asyncio.get_event_loop() self._async_lock = asyncio.Lock(loop=loop) # FIX: SQLITE in memory database if not self.database == ':memory:': self._state = ConnectionLocal()
python
{ "resource": "" }
q264658
AIODatabase.async_connect
validation
async def async_connect(self): """Catch a connection asyncrounosly.""" if self._async_lock is None: raise Exception('Error, database not properly initialized before async connection') async with self._async_lock: self.connect(True) return self._state.conn
python
{ "resource": "" }
q264659
PooledAIODatabase.init_async
validation
def init_async(self, loop): """Initialize self.""" super(PooledAIODatabase, self).init_async(loop) self._waiters = collections.deque()
python
{ "resource": "" }
q264660
PooledAIODatabase.async_connect
validation
async def async_connect(self): """Asyncronously wait for a connection from the pool.""" if self._waiters is None: raise Exception('Error, database not properly initialized before async connection') if self._waiters or self.max_connections and (len(self._in_use) >= self.max_connectio...
python
{ "resource": "" }
q264661
PooledAIODatabase._close
validation
def _close(self, conn): """Release waiters.""" super(PooledAIODatabase, self)._close(conn) for waiter in self._waiters: if not waiter.done(): logger.debug('Release a waiter') waiter.set_result(True) break
python
{ "resource": "" }
q264662
ClientForum.receive_id_from_server
validation
def receive_id_from_server(self): """ Listen for an id from the server. At the beginning of a game, each client receives an IdFactory from the server. This factory are used to give id numbers that are guaranteed to be unique to tokens that created locally. This method checks...
python
{ "resource": "" }
q264663
ClientForum.execute_sync
validation
def execute_sync(self, message): """ Respond when the server indicates that the client is out of sync. The server can request a sync when this client sends a message that fails the check() on the server. If the reason for the failure isn't very serious, then the server can de...
python
{ "resource": "" }
q264664
ClientForum.execute_undo
validation
def execute_undo(self, message): """ Manage the response when the server rejects a message. An undo is when required this client sends a message that the server refuses to pass on to the other clients playing the game. When this happens, the client must undo the changes that ...
python
{ "resource": "" }
q264665
ServerActor._relay_message
validation
def _relay_message(self, message): """ Relay messages from the forum on the server to the client represented by this actor. """ info("relaying message: {message}") if not message.was_sent_by(self._id_factory): self.pipe.send(message) self.pipe.de...
python
{ "resource": "" }
q264666
generate
validation
def generate(request): """ Create a new DataItem. """ models.DataItem.create( content=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20)) ) return muffin.HTTPFound('/')
python
{ "resource": "" }
q264667
require_active_token
validation
def require_active_token(object): """ Raise an ApiUsageError if the given object is not a token that is currently participating in the game. To be participating in the game, the given token must have an id number and be associated with the world. """ require_token(object) token = object ...
python
{ "resource": "" }
q264668
TokenSafetyChecks.add_safety_checks
validation
def add_safety_checks(meta, members): """ Iterate through each member of the class being created and add a safety check to every method that isn't marked as read-only. """ for member_name, member_value in members.items(): members[member_name] = meta.add_safety_check(...
python
{ "resource": "" }
q264669
Token.watch_method
validation
def watch_method(self, method_name, callback): """ Register the given callback to be called whenever the method with the given name is called. You can easily take advantage of this feature in token extensions by using the @watch_token decorator. """ # Make sure a toke...
python
{ "resource": "" }
q264670
Token._remove_from_world
validation
def _remove_from_world(self): """ Clear all the internal data the token needed while it was part of the world. Note that this method doesn't actually remove the token from the world. That's what World._remove_token() does. This method is just responsible for setting...
python
{ "resource": "" }
q264671
World._unlock_temporarily
validation
def _unlock_temporarily(self): """ Allow tokens to modify the world for the duration of a with-block. It's important that tokens only modify the world at appropriate times, otherwise the changes they make may not be communicated across the network to other clients. To help ca...
python
{ "resource": "" }
q264672
scan
validation
def scan(xml): """Converts XML tree to event generator""" if xml.tag is et.Comment: yield {'type': COMMENT, 'text': xml.text} return if xml.tag is et.PI: if xml.text: yield {'type': PI, 'target': xml.target, 'text': xml.text} else: yield {'type': PI,...
python
{ "resource": "" }
q264673
unscan
validation
def unscan(events, nsmap=None): """Converts events stream into lXML tree""" root = None last_closed_elt = None stack = [] for obj in events: if obj['type'] == ENTER: elt = _obj2elt(obj, nsmap=nsmap) if stack: stack[-1].append(elt) elif ro...
python
{ "resource": "" }
q264674
parse
validation
def parse(filename): """Parses file content into events stream""" for event, elt in et.iterparse(filename, events= ('start', 'end', 'comment', 'pi'), huge_tree=True): if event == 'start': obj = _elt2obj(elt) obj['type'] = ENTER yield obj if elt.text: ...
python
{ "resource": "" }
q264675
subtree
validation
def subtree(events): """selects sub-tree events""" stack = 0 for obj in events: if obj['type'] == ENTER: stack += 1 elif obj['type'] == EXIT: if stack == 0: break stack -= 1 yield obj
python
{ "resource": "" }
q264676
merge_text
validation
def merge_text(events): """merges each run of successive text events into one text event""" text = [] for obj in events: if obj['type'] == TEXT: text.append(obj['text']) else: if text: yield {'type': TEXT, 'text': ''.join(text)} text.cl...
python
{ "resource": "" }
q264677
with_peer
validation
def with_peer(events): """locates ENTER peer for each EXIT object. Convenient when selectively filtering out XML markup""" stack = [] for obj in events: if obj['type'] == ENTER: stack.append(obj) yield obj, None elif obj['type'] == EXIT: yield obj, st...
python
{ "resource": "" }
q264678
BusinessDate.from_date
validation
def from_date(datetime_date): """ construct BusinessDate instance from datetime.date instance, raise ValueError exception if not possible :param datetime.date datetime_date: calendar day :return bool: """ return BusinessDate.from_ymd(datetime_date.year, datetime_...
python
{ "resource": "" }
q264679
BusinessDate.to_date
validation
def to_date(self): """ construct datetime.date instance represented calendar date of BusinessDate instance :return datetime.date: """ y, m, d = self.to_ymd() return date(y, m, d)
python
{ "resource": "" }
q264680
BusinessDate.add_period
validation
def add_period(self, p, holiday_obj=None): """ addition of a period object :param BusinessDate d: :param p: :type p: BusinessPeriod or str :param list holiday_obj: :return bankdate: """ if isinstance(p, (list, tuple)): return [Busines...
python
{ "resource": "" }
q264681
BusinessDate.add_months
validation
def add_months(self, month_int): """ addition of a number of months :param BusinessDate d: :param int month_int: :return bankdate: """ month_int += self.month while month_int > 12: self = BusinessDate.add_years(self, 1) month_int ...
python
{ "resource": "" }
q264682
BusinessDate.add_business_days
validation
def add_business_days(self, days_int, holiday_obj=None): """ private method for the addition of business days, used in the addition of a BusinessPeriod only :param BusinessDate d: :param int days_int: :param list holiday_obj: :return: BusinessDate """ re...
python
{ "resource": "" }
q264683
quoted
validation
def quoted(parser=any_token): """Parses as much as possible until it encounters a matching closing quote. By default matches any_token, but can be provided with a more specific parser if required. Returns a string """ quote_char = quote() value, _ = many_until(parser, partial(one_of, quote_...
python
{ "resource": "" }
q264684
days_in_month
validation
def days_in_month(year, month): """ returns number of days for the given year and month :param int year: calendar year :param int month: calendar month :return int: """ eom = _days_per_month[month - 1] if is_leap_year(year) and month == 2: eom += 1 return eom
python
{ "resource": "" }
q264685
Plugin.setup
validation
def setup(self, app): # noqa """Initialize the application.""" super().setup(app) # Setup Database self.database.initialize(connect(self.cfg.connection, **self.cfg.connection_params)) # Fix SQLite in-memory database if self.database.database == ':memory:': ...
python
{ "resource": "" }
q264686
Plugin.startup
validation
def startup(self, app): """Register connection's middleware and prepare self database.""" self.database.init_async(app.loop) if not self.cfg.connection_manual: app.middlewares.insert(0, self._middleware)
python
{ "resource": "" }
q264687
Plugin.cleanup
validation
def cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()
python
{ "resource": "" }
q264688
Plugin.register
validation
def register(self, model): """Register a model in self.""" self.models[model._meta.table_name] = model model._meta.database = self.database return model
python
{ "resource": "" }
q264689
Plugin.manage
validation
async def manage(self): """Manage a database connection.""" cm = _ContextManager(self.database) if isinstance(self.database.obj, AIODatabase): cm.connection = await self.database.async_connect() else: cm.connection = self.database.connect() return cm
python
{ "resource": "" }
q264690
migrate
validation
def migrate(migrator, database, **kwargs): """ Write your migrations here. > Model = migrator.orm['name'] > migrator.sql(sql) > migrator.create_table(Model) > migrator.drop_table(Model, cascade=True) > migrator.add_columns(Model, **fields) > migrator.change_columns(Model, **fields) > m...
python
{ "resource": "" }
q264691
chain
validation
def chain(*args): """Runs a series of parsers in sequence passing the result of each parser to the next. The result of the last parser is returned. """ def chain_block(*args, **kwargs): v = args[0](*args, **kwargs) for p in args[1:]: v = p(v) return v return chain...
python
{ "resource": "" }
q264692
one_of
validation
def one_of(these): """Returns the current token if is found in the collection provided. Fails otherwise. """ ch = peek() try: if (ch is EndOfFile) or (ch not in these): fail(list(these)) except TypeError: if ch != these: fail([these]) next() r...
python
{ "resource": "" }
q264693
not_one_of
validation
def not_one_of(these): """Returns the current token if it is not found in the collection provided. The negative of one_of. """ ch = peek() desc = "not_one_of" + repr(these) try: if (ch is EndOfFile) or (ch in these): fail([desc]) except TypeError: if ch != t...
python
{ "resource": "" }
q264694
satisfies
validation
def satisfies(guard): """Returns the current token if it satisfies the guard function provided. Fails otherwise. This is the a generalisation of one_of. """ i = peek() if (i is EndOfFile) or (not guard(i)): fail(["<satisfies predicate " + _fun_to_str(guard) + ">"]) next() re...
python
{ "resource": "" }
q264695
not_followed_by
validation
def not_followed_by(parser): """Succeeds if the given parser cannot consume input""" @tri def not_followed_by_block(): failed = object() result = optional(tri(parser), failed) if result != failed: fail(["not " + _fun_to_str(parser)]) choice(not_followed_by_block)
python
{ "resource": "" }
q264696
many
validation
def many(parser): """Applies the parser to input zero or more times. Returns a list of parser results. """ results = [] terminate = object() while local_ps.value: result = optional(parser, terminate) if result == terminate: break results.append(result) ...
python
{ "resource": "" }
q264697
many_until
validation
def many_until(these, term): """Consumes as many of these as it can until it term is encountered. Returns a tuple of the list of these results and the term result """ results = [] while True: stop, result = choice(_tag(True, term), _tag(False, these)) ...
python
{ "resource": "" }
q264698
many_until1
validation
def many_until1(these, term): """Like many_until but must consume at least one of these. """ first = [these()] these_results, term_result = many_until(these, term) return (first + these_results, term_result)
python
{ "resource": "" }
q264699
sep1
validation
def sep1(parser, separator): """Like sep but must consume at least one of parser. """ first = [parser()] def inner(): separator() return parser() return first + many(tri(inner))
python
{ "resource": "" }