Search is not available for this dataset
text
stringlengths
75
104k
def send_payload(self, params): """Performs the actual sending action and returns the result """ data = json.dumps({ 'jsonrpc': self.version, 'method': self.service_name, 'params': params, 'id': text_type(uuid.uuid4()) }) data_binar...
def make_response(self, rv): """Converts the return value from a view function to a real response object that is an instance of :attr:`response_class`. """ status_or_headers = headers = None if isinstance(rv, tuple): rv, status_or_headers, headers = rv + (None,) * (3 ...
def json_rpc_format(self): """Return the Exception data in a format for JSON-RPC """ error = { 'name': text_type(self.__class__.__name__), 'code': self.code, 'message': '{0}'.format(text_type(self.message)), 'data': self.data } if...
def from_file(cls, file): """Try loading given config file. :param str file: full path to the config file to load """ if not os.path.exists(file): raise ValueError("Config file not found.") try: config_parser = configparser.ConfigParser() con...
def discover(cls): """Make a guess about the config file location an try loading it.""" file = os.path.join(Config.config_dir, Config.config_name) return cls.from_file(file)
def create_config(cls, cfgfile, nick, twtfile, twturl, disclose_identity, add_news): """Create a new config file at the default location. :param str cfgfile: path to the config file :param str nick: nickname to use for own tweets :param str twtfile: path to the local twtxt file ...
def write_config(self): """Writes `self.cfg` to `self.config_file`.""" with open(self.config_file, "w") as config_file: self.cfg.write(config_file)
def following(self): """A :class:`list` of all :class:`Source` objects.""" following = [] try: for (nick, url) in self.cfg.items("following"): source = Source(nick, url) following.append(source) except configparser.NoSectionError as e: ...
def options(self): """A :class:`dict` of all config options.""" try: return dict(self.cfg.items("twtxt")) except configparser.NoSectionError as e: logger.debug(e) return {}
def add_source(self, source): """Adds a new :class:`Source` to the config’s following section.""" if not self.cfg.has_section("following"): self.cfg.add_section("following") self.cfg.set("following", source.nick, source.url) self.write_config()
def get_source_by_nick(self, nick): """Returns the :class:`Source` of the given nick. :param str nick: nickname for which will be searched in the config """ url = self.cfg.get("following", nick, fallback=None) return Source(nick, url) if url else None
def remove_source_by_nick(self, nick): """Removes a :class:`Source` form the config’s following section. :param str nick: nickname for which will be searched in the config """ if not self.cfg.has_section("following"): return False ret_val = self.cfg.remove_option("f...
def build_default_map(self): """Maps config options to the default values used by click, returns :class:`dict`.""" default_map = { "following": { "check": self.check_following, "timeout": self.timeout, "porcelain": self.porcelain, }...
def check_config_sanity(self): """Checks if the given values in the config file are sane.""" is_sane = True # This extracts some properties which cannot be checked like "nick", # but it is definitely better than writing the property names as a # string literal. propertie...
def validate_config_key(ctx, param, value): """Validate a configuration key according to `section.item`.""" if not value: return value try: section, item = value.split(".", 1) except ValueError: raise click.BadArgumentUsage("Given key does not contain a section name.") else:...
def expand_mentions(text, embed_names=True): """Searches the given text for mentions and expands them. For example: "@source.nick" will be expanded to "@<source.nick source.url>". """ if embed_names: mention_format = "@<{name} {url}>" else: mention_format = "@<{url}>" def h...
def format_mentions(text, format_callback=format_mention): """Searches the given text for mentions generated by `expand_mention()` and returns a human-readable form. For example: "@<bob http://example.org/twtxt.txt>" will result in "@bob" If you follow a source: source.nick will be bold If you are...
def make_aware(dt): """Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.""" return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
def parse_tweets(raw_tweets, source, now=None): """ Parses a list of raw tweet lines from a twtxt file and returns a list of :class:`Tweet` objects. :param list raw_tweets: list of raw tweet lines :param Source source: the source of the given tweets :param Datetime now: the ...
def parse_tweet(raw_tweet, source, now=None): """ Parses a single raw tweet line from a twtxt file and returns a :class:`Tweet` object. :param str raw_tweet: a single raw tweet line :param Source source: the source of the given tweet :param Datetime now: the current datetime...
def from_file(cls, file, *args, **kwargs): """Try loading given cache file.""" try: cache = shelve.open(file) return cls(file, cache, *args, **kwargs) except OSError as e: logger.debug("Loading {0} failed".format(file)) raise e
def discover(cls, *args, **kwargs): """Make a guess about the cache file location an try loading it.""" file = os.path.join(Cache.cache_dir, Cache.cache_name) return cls.from_file(file, *args, **kwargs)
def is_cached(self, url): """Checks if specified URL is cached.""" try: return True if url in self.cache else False except TypeError: return False
def add_tweets(self, url, last_modified, tweets): """Adds new tweets to the cache.""" try: self.cache[url] = {"last_modified": last_modified, "tweets": tweets} self.mark_updated() return True except TypeError: return False
def get_tweets(self, url, limit=None): """Retrieves tweets from the cache.""" try: tweets = self.cache[url]["tweets"] self.mark_updated() return sorted(tweets, reverse=True)[:limit] except KeyError: return []
def remove_tweets(self, url): """Tries to remove cached tweets.""" try: del self.cache[url] self.mark_updated() return True except KeyError: return False
def cli(ctx, config, verbose): """Decentralised, minimalist microblogging service for hackers.""" init_logging(debug=verbose) if ctx.invoked_subcommand == "quickstart": return # Skip initializing config file try: if config: conf = Config.from_file(config) else: ...
def tweet(ctx, created_at, twtfile, text): """Append a new tweet to your twtxt file.""" text = expand_mentions(text) tweet = Tweet(text, created_at) if created_at else Tweet(text) pre_tweet_hook = ctx.obj["conf"].pre_tweet_hook if pre_tweet_hook: run_pre_tweet_hook(pre_tweet_hook, ctx.obj["...
def timeline(ctx, pager, limit, twtfile, sorting, timeout, porcelain, source, cache, force_update): """Retrieve your personal timeline.""" if source: source_obj = ctx.obj["conf"].get_source_by_nick(source) if not source_obj: logger.debug("Not following {0}, trying as URL".format(sour...
def following(ctx, check, timeout, porcelain): """Return the list of sources you’re following.""" sources = ctx.obj['conf'].following if check: sources = get_remote_status(sources, timeout) for (source, status) in sources: click.echo(style_source_with_status(source, status, porc...
def follow(ctx, nick, url, force): """Add a new source to your followings.""" source = Source(nick, url) sources = ctx.obj['conf'].following if not force: if source.nick in (source.nick for source in sources): click.confirm("➤ You’re already following {0}. Overwrite?".format( ...
def unfollow(ctx, nick): """Remove an existing source from your followings.""" source = ctx.obj['conf'].get_source_by_nick(nick) try: with Cache.discover() as cache: cache.remove_tweets(source.url) except OSError as e: logger.debug(e) ret_val = ctx.obj['conf'].remove_so...
def quickstart(): """Quickstart wizard for setting up twtxt.""" width = click.get_terminal_size()[0] width = width if width <= 79 else 79 click.secho("twtxt - quickstart", fg="cyan") click.secho("==================", fg="cyan") click.echo() help_text = "This wizard will generate a basic co...
def config(ctx, key, value, remove, edit): """Get or set config item.""" conf = ctx.obj["conf"] if not edit and not key: raise click.BadArgumentUsage("You have to specify either a key or use --edit.") if edit: return click.edit(filename=conf.config_file) if remove: try: ...
def relative_datetime(self): """Return human-readable relative time string.""" now = datetime.now(timezone.utc) tense = "from now" if self.created_at > now else "ago" return "{0} {1}".format(humanize.naturaldelta(now - self.created_at), tense)
def save(url, *args, **kwargs): """ Parse the options, set defaults and then fire up PhantomJS. """ device = heimdallDevice(kwargs.get('device', None)) kwargs['width'] = kwargs.get('width', None) or device.width kwargs['height'] = kwargs.get('height', None) or device.height kwargs['user_agent'] = ...
def screenshot(url, *args, **kwargs): """ Call PhantomJS with the specified flags and options. """ phantomscript = os.path.join(os.path.dirname(__file__), 'take_screenshot.js') directory = kwargs.get('save_dir', '/tmp') image_name = kwargs.get('image_name', None) or _i...
def _image_name_from_url(url): """ Create a nice image name from the url. """ find = r'https?://|[^\w]' replace = '_' return re.sub(find, replace, url).strip('_')
def worker(f): """ Decorator. Abortable worker. If wrapped task will be cancelled by dispatcher, decorator will send ftp codes of successful interrupt. :: >>> @worker ... async def worker(self, connection, rest): ... ... """ @functools.wraps(f) async def wrappe...
def get_permissions(self, path): """ Return nearest parent permission for `path`. :param path: path which permission you want to know :type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath` :rtype: :py:class:`aioftp.Permission` """ path = pathlib.PurePo...
def release(self): """ Release, incrementing the internal counter by one. """ if self.value is not None: self.value += 1 if self.value > self.maximum_value: raise ValueError("Too many releases")
async def start(self, host=None, port=0, **kwargs): """ :py:func:`asyncio.coroutine` Start server. :param host: ip address to bind for listening. :type host: :py:class:`str` :param port: port number to bind for listening. :type port: :py:class:`int` :p...
async def close(self): """ :py:func:`asyncio.coroutine` Shutdown the server and close all connections. """ self.server.close() tasks = [self.server.wait_closed()] for connection in self.connections.values(): connection._dispatcher.cancel() ...
async def write_response(self, stream, code, lines="", list=False): """ :py:func:`asyncio.coroutine` Complex method for sending response. :param stream: command connection stream :type stream: :py:class:`aioftp.StreamIO` :param code: server response code :type ...
async def parse_command(self, stream): """ :py:func:`asyncio.coroutine` Complex method for getting command. :param stream: connection steram :type stream: :py:class:`asyncio.StreamIO` :return: (code, rest) :rtype: (:py:class:`str`, :py:class:`str`) """ ...
async def response_writer(self, stream, response_queue): """ :py:func:`asyncio.coroutine` Worker for write_response with current connection. Get data to response from queue, this is for right order of responses. Exits if received :py:class:`None`. :param stream: command...
def get_paths(self, connection, path): """ Return *real* and *virtual* paths, resolves ".." with "up" action. *Real* path is path for path_io, when *virtual* deals with "user-view" and user requests :param connection: internal options for current connected user :type con...
def bytes2human(n, format="%(value).1f%(symbol)s"): """ >>> bytes2human(10000) '9K' >>> bytes2human(100001221) '95M' """ symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols[1:]): prefix[s] = 1 << (i + 1) * 10 for symbol in rev...
def human2bytes(s): """ >>> human2bytes('1M') 1048576 >>> human2bytes('1G') 1073741824 """ symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') letter = s[-1:].strip().upper() num = s[:-1] assert num.isdigit() and letter in symbols, s num = float(num) prefix = {symbols...
def register_memory(): """Register an approximation of memory used by FTP server process and all of its children. """ # XXX How to get a reliable representation of memory being used is # not clear. (rss - shared) seems kind of ok but we might also use # the private working set via get_memory_map...
def timethis(what): """"Utility function for making simple benchmarks (calculates time calls). It can be used either as a context manager or as a decorator. """ @contextlib.contextmanager def benchmark(): timer = time.clock if sys.platform == "win32" else time.time start = timer() ...
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
def retr(ftp): """Same as ftplib's retrbinary() but discard the received data.""" ftp.voidcmd('TYPE I') with contextlib.closing(ftp.transfercmd("RETR " + TESTFN)) as conn: recv_bytes = 0 while True: data = conn.recv(BUFFER_LEN) if not data: break ...
def stor(ftp=None): """Same as ftplib's storbinary() but just sends dummy data instead of reading it from a real file. """ if ftp is None: ftp = connect() quit = True else: quit = False ftp.voidcmd('TYPE I') with contextlib.closing(ftp.transfercmd("STOR " + TESTFN)) a...
def bytes_per_second(ftp, retr=True): """Return the number of bytes transmitted in 1 second.""" tot_bytes = 0 if retr: def request_file(): ftp.voidcmd('TYPE I') conn = ftp.transfercmd("retr " + TESTFN) return conn with contextlib.closing(request_file()) a...
def universal_exception(coro): """ Decorator. Reraising any exception (except `CancelledError` and `NotImplementedError`) with universal exception :py:class:`aioftp.PathIOError` """ @functools.wraps(coro) async def wrapper(*args, **kwargs): try: return await coro(*args, *...
def defend_file_methods(coro): """ Decorator. Raises exception when file methods called with wrapped by :py:class:`aioftp.AsyncPathIOContext` file object. """ @functools.wraps(coro) async def wrapper(self, file, *args, **kwargs): if isinstance(file, AsyncPathIOContext): raise...
def async_enterable(f): """ Decorator. Bring coroutine result up, so it can be used as async context :: >>> async def foo(): ... ... ... ... return AsyncContextInstance(...) ... ... ctx = await foo() ... async with ctx: ... .....
def setlocale(name): """ Context manager with threading lock for set locale on enter, and set it back to original state on exit. :: >>> with setlocale("C"): ... ... """ with LOCALE_LOCK: old_locale = locale.setlocale(locale.LC_ALL) try: yield loc...
async def wait(self): """ :py:func:`asyncio.coroutine` Wait until can do IO """ if self._limit is not None and self._limit > 0 and \ self._start is not None: now = _now() end = self._start + self._sum / self._limit await asynci...
def append(self, data, start): """ Count `data` for throttle :param data: bytes of data for count :type data: :py:class:`bytes` :param start: start of read/write time from :py:meth:`asyncio.BaseEventLoop.time` :type start: :py:class:`float` """ ...
def limit(self, value): """ Set throttle limit :param value: bytes per second :type value: :py:class:`int` or :py:class:`None` """ self._limit = value self._start = None self._sum = 0
def clone(self): """ Clone throttles without memory """ return StreamThrottle( read=self.read.clone(), write=self.write.clone() )
def from_limits(cls, read_speed_limit=None, write_speed_limit=None): """ Simple wrapper for creation :py:class:`aioftp.StreamThrottle` :param read_speed_limit: stream read speed limit in bytes or :py:class:`None` for unlimited :type read_speed_limit: :py:class:`int` or :py:c...
async def wait(self, name): """ :py:func:`asyncio.coroutine` Wait for all throttles :param name: name of throttle to acquire ("read" or "write") :type name: :py:class:`str` """ waiters = [] for throttle in self.throttles.values(): curr_thrott...
def append(self, name, data, start): """ Update timeout for all throttles :param name: name of throttle to append to ("read" or "write") :type name: :py:class:`str` :param data: bytes of data for count :type data: :py:class:`bytes` :param start: start of read/w...
async def read(self, count=-1): """ :py:func:`asyncio.coroutine` :py:meth:`aioftp.StreamIO.read` proxy """ await self.wait("read") start = _now() data = await super().read(count) self.append("read", data, start) return data
async def readline(self): """ :py:func:`asyncio.coroutine` :py:meth:`aioftp.StreamIO.readline` proxy """ await self.wait("read") start = _now() data = await super().readline() self.append("read", data, start) return data
async def write(self, data): """ :py:func:`asyncio.coroutine` :py:meth:`aioftp.StreamIO.write` proxy """ await self.wait("write") start = _now() await super().write(data) self.append("write", data, start)
def matches(self, mask): """ :param mask: Template for comparision. If mask symbol is not digit then it passes. :type mask: :py:class:`str` :: >>> Code("123").matches("1") True >>> Code("123").matches("1x3") True """ ...
async def finish(self, expected_codes="2xx", wait_codes="1xx"): """ :py:func:`asyncio.coroutine` Close connection and wait for `expected_codes` response from server passing `wait_codes`. :param expected_codes: tuple of expected codes or expected code :type expected_code...
async def parse_line(self): """ :py:func:`asyncio.coroutine` Parsing server response line. :return: (code, line) :rtype: (:py:class:`aioftp.Code`, :py:class:`str`) :raises ConnectionResetError: if received data is empty (this means, that connection is close...
async def parse_response(self): """ :py:func:`asyncio.coroutine` Parsing full server response (all lines). :return: (code, lines) :rtype: (:py:class:`aioftp.Code`, :py:class:`list` of :py:class:`str`) :raises aioftp.StatusCodeError: if received code does not matches al...
def check_codes(self, expected_codes, received_code, info): """ Checks if any of expected matches received. :param expected_codes: tuple of expected codes :type expected_codes: :py:class:`tuple` :param received_code: received code for matching :type received_code: :py:c...
async def command(self, command=None, expected_codes=(), wait_codes=()): """ :py:func:`asyncio.coroutine` Basic command logic. 1. Send command if not omitted. 2. Yield response until no wait code matches. 3. Check code for expected. :param command: command line...
def parse_epsv_response(s): """ Parsing `EPSV` (`message (|||port|)`) response. :param s: response line :type s: :py:class:`str` :return: (ip, port) :rtype: (:py:class:`None`, :py:class:`int`) """ matches = tuple(re.finditer(r"\((.)\1\1\d+\1\)", s)) ...
def parse_pasv_response(s): """ Parsing `PASV` server response. :param s: response line :type s: :py:class:`str` :return: (ip, port) :rtype: (:py:class:`str`, :py:class:`int`) """ sub, *_ = re.findall(r"[^(]*\(([^)]*)", s) nums = tuple(map(int, s...
def parse_directory_response(s): """ Parsing directory server response. :param s: response line :type s: :py:class:`str` :rtype: :py:class:`pathlib.PurePosixPath` """ seq_quotes = 0 start = False directory = "" for ch in s: if...
def parse_unix_mode(s): """ Parsing unix mode strings ("rwxr-x--t") into hexacimal notation. :param s: mode string :type s: :py:class:`str` :return mode: :rtype: :py:class:`int` """ parse_rw = {"rw": 6, "r-": 4, "-w": 2, "--": 0} mode = 0 ...
def parse_ls_date(self, s, *, now=None): """ Parsing dates from the ls unix utility. For example, "Nov 18 1958" and "Nov 18 12:29". :param s: ls date :type s: :py:class:`str` :rtype: :py:class:`str` """ with setlocale("C"): try: ...
def parse_list_line_unix(self, b): """ Attempt to parse a LIST line (similar to unix ls utility). :param b: response line :type b: :py:class:`bytes` or :py:class:`str` :return: (path, info) :rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`) """ ...
def parse_list_line_windows(self, b): """ Parsing Microsoft Windows `dir` output :param b: response line :type b: :py:class:`bytes` or :py:class:`str` :return: (path, info) :rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`) """ line = b.decode...
def parse_list_line(self, b): """ Parse LIST response with both Microsoft Windows® parser and UNIX parser :param b: response line :type b: :py:class:`bytes` or :py:class:`str` :return: (path, info) :rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`) ...
def parse_mlsx_line(self, b): """ Parsing MLS(T|D) response. :param b: response line :type b: :py:class:`bytes` or :py:class:`str` :return: (path, info) :rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`) """ if isinstance(b, bytes): ...
async def connect(self, host, port=DEFAULT_PORT): """ :py:func:`asyncio.coroutine` Connect to server. :param host: host name for connection :type host: :py:class:`str` :param port: port number for connection :type port: :py:class:`int` """ await...
async def login(self, user=DEFAULT_USER, password=DEFAULT_PASSWORD, account=DEFAULT_ACCOUNT): """ :py:func:`asyncio.coroutine` Server authentication. :param user: username :type user: :py:class:`str` :param password: password :type password:...
async def get_current_directory(self): """ :py:func:`asyncio.coroutine` Getting current working directory. :rtype: :py:class:`pathlib.PurePosixPath` """ code, info = await self.command("PWD", "257") directory = self.parse_directory_response(info[-1]) ret...
async def change_directory(self, path=".."): """ :py:func:`asyncio.coroutine` Change current directory. Goes «up» if no parameters passed. :param path: new directory, goes «up» if omitted :type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath` """ path ...
async def make_directory(self, path, *, parents=True): """ :py:func:`asyncio.coroutine` Make directory. :param path: path to directory to create :type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath` :param parents: create parents if does not exists :...
def list(self, path="", *, recursive=False, raw_command=None): """ :py:func:`asyncio.coroutine` List all files and directories in "path". :param path: directory or file path :type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath` :param recursive: list recursi...
async def stat(self, path): """ :py:func:`asyncio.coroutine` Getting path stats. :param path: path for getting info :type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath` :return: path info :rtype: :py:class:`dict` """ path = pathlib.P...
async def exists(self, path): """ :py:func:`asyncio.coroutine` Check path for existence. :param path: path to check :type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath` :rtype: :py:class:`bool` """ try: await self.stat(path) ...
async def rename(self, source, destination): """ :py:func:`asyncio.coroutine` Rename (move) file or directory. :param source: path to rename :type source: :py:class:`str` or :py:class:`pathlib.PurePosixPath` :param destination: path new name :type destination: ...
async def remove(self, path): """ :py:func:`asyncio.coroutine` High level remove method for removing path recursively (file or directory). :param path: path to remove :type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath` """ if await self.exis...
def upload_stream(self, destination, *, offset=0): """ Create stream for write data to `destination` file. :param destination: destination path of file on server side :type destination: :py:class:`str` or :py:class:`pathlib.PurePosixPath` :param offset: byte offset for stream s...
def append_stream(self, destination, *, offset=0): """ Create stream for append (write) data to `destination` file. :param destination: destination path of file on server side :type destination: :py:class:`str` or :py:class:`pathlib.PurePosixPath` :param offset: byte offset for...
async def upload(self, source, destination="", *, write_into=False, block_size=DEFAULT_BLOCK_SIZE): """ :py:func:`asyncio.coroutine` High level upload method for uploading files and directories recursively from file system. :param source: source path of fil...
def download_stream(self, source, *, offset=0): """ :py:func:`asyncio.coroutine` Create stream for read data from `source` file. :param source: source path of file on server side :type source: :py:class:`str` or :py:class:`pathlib.PurePosixPath` :param offset: byte off...
async def download(self, source, destination="", *, write_into=False, block_size=DEFAULT_BLOCK_SIZE): """ :py:func:`asyncio.coroutine` High level download method for downloading files and directories recursively and save them to the file system. :param so...
async def get_passive_connection(self, conn_type="I", commands=("epsv", "pasv")): """ :py:func:`asyncio.coroutine` Getting pair of reader, writer for passive connection with server. :param conn_type: connection type ("I", "A", "E", "L") :typ...