text
stringlengths
81
112k
Return the literal representation of a numeric tag. def serialize_numeric(self, tag): """Return the literal representation of a numeric tag.""" str_func = int.__str__ if isinstance(tag, int) else float.__str__ return str_func(tag) + tag.suffix
Return the literal representation of an array tag. def serialize_array(self, tag): """Return the literal representation of an array tag.""" elements = self.comma.join(f'{el}{tag.item_suffix}' for el in tag) return f'[{tag.array_prefix}{self.semicolon}{elements}]'
Return the literal representation of a list tag. def serialize_list(self, tag): """Return the literal representation of a list tag.""" separator, fmt = self.comma, '[{}]' with self.depth(): if self.should_expand(tag): separator, fmt = self.expand(separator, fmt) ...
Return the literal representation of a compound tag. def serialize_compound(self, tag): """Return the literal representation of a compound tag.""" separator, fmt = self.comma, '{{{}}}' with self.depth(): if self.should_expand(tag): separator, fmt = self.expand(separ...
Return the _column_map without unused optional fields def populated_column_map(self): '''Return the _column_map without unused optional fields''' column_map = [] cls = self.model for csv_name, field_pattern in cls._column_map: # Separate the local field name from foreign col...
Return the objects in the target feed def in_feed(self, feed): '''Return the objects in the target feed''' kwargs = {self.model._rel_to_feed: feed} return self.filter(**kwargs)
Import from the GTFS text file def import_txt(cls, txt_file, feed, filter_func=None): '''Import from the GTFS text file''' # Setup the conversion from GTFS to Django Format # Conversion functions def no_convert(value): return value def date_convert(value): return datetime.strp...
Export records as a GTFS comma-separated file def export_txt(cls, feed): '''Export records as a GTFS comma-separated file''' objects = cls.objects.in_feed(feed) # If no records, return None if not objects.exists(): return # Get the columns used in the dataset ...
Turn an AndroidApi's method into a function that builds the request, sends it, then passes the response to the actual method. Should be used as a decorator. def make_android_api_method(req_method, secure=True, version=0): """Turn an AndroidApi's method into a function that builds the request, sends it,...
Get the params that will be included with every request def _get_base_params(self): """Get the params that will be included with every request """ base_params = { 'locale': self._get_locale(), 'device_id': ANDROID.DEVICE_ID, 'device_type': ANDROID.A...
Build a URL for a API method request def _build_request_url(self, secure, api_method, version): """Build a URL for a API method request """ if secure: proto = ANDROID.PROTOCOL_SECURE else: proto = ANDROID.PROTOCOL_INSECURE req_url = ANDROID.API_URL.format...
Get if the session is premium for a given media type @param str media_type Should be one of ANDROID.MEDIA_TYPE_* @return bool def is_premium(self, media_type): """Get if the session is premium for a given media type @param str media_type Should be one of ANDROID.MEDIA_TYPE...
Login using email/username and password, used to get the auth token @param str account @param str password @param int duration (optional) def login(self, response): """ Login using email/username and password, used to get the auth token @param str account @para...
Read a numeric value from a file-like object. def read_numeric(fmt, buff, byteorder='big'): """Read a numeric value from a file-like object.""" try: fmt = fmt[byteorder] return fmt.unpack(buff.read(fmt.size))[0] except StructError: return 0 except KeyError as exc: ...
Write a numeric value to a file-like object. def write_numeric(fmt, value, buff, byteorder='big'): """Write a numeric value to a file-like object.""" try: buff.write(fmt[byteorder].pack(value)) except KeyError as exc: raise ValueError('Invalid byte order') from exc
Read a string from a file-like object. def read_string(buff, byteorder='big'): """Read a string from a file-like object.""" length = read_numeric(USHORT, buff, byteorder) return buff.read(length).decode('utf-8')
Write a string to a file-like object. def write_string(value, buff, byteorder='big'): """Write a string to a file-like object.""" data = value.encode('utf-8') write_numeric(USHORT, len(data), buff, byteorder) buff.write(data)
Infer a list subtype from a collection of items. def infer_list_subtype(items): """Infer a list subtype from a collection of items.""" subtype = End for item in items: item_type = type(item) if not issubclass(item_type, Base): continue ...
Cast list item to the appropriate tag type. def cast_item(cls, item): """Cast list item to the appropriate tag type.""" if not isinstance(item, cls.subtype): incompatible = isinstance(item, Base) and not any( issubclass(cls.subtype, tag_type) and isinstance(item, tag_typ...
Recursively merge tags from another compound. def merge(self, other): """Recursively merge tags from another compound.""" for key, value in other.items(): if key in self and (isinstance(self[key], Compound) and isinstance(value, dict)): s...
Decrypt encrypted subtitle data in high level model object @param crunchyroll.models.Subtitle subtitle @return str def decrypt_subtitle(self, subtitle): """Decrypt encrypted subtitle data in high level model object @param crunchyroll.models.Subtitle subtitle @return str ...
Decrypt encrypted subtitle data @param int subtitle_id @param str iv @param str encrypted_data @return str def decrypt(self, encryption_key, iv, encrypted_data): """Decrypt encrypted subtitle data @param int subtitle_id @param str iv @param str encrypte...
Generate the encryption key for a given media item Encryption key is basically just sha1(<magic value based on subtitle_id> + '"#$&).6CXzPHw=2N_+isZK') then padded with 0s to 32 chars @param int subtitle_id @param int key_size @return str def _build_encryption_key(self...
Build the other half of the encryption key hash I have no idea what is going on here @param int subtitle_id @return str def _build_hash_magic(self, subtitle_id): """Build the other half of the encryption key hash I have no idea what is going on here @param int subtit...
Build a seed for the hash based on the Fibonacci sequence Take first `seq_len` + len(`seq_seed`) characters of Fibonacci sequence, starting with `seq_seed`, and applying e % `mod_value` + `HASH_SECRET_CHAR_OFFSET` to the resulting sequence, then return as a string @param tuple|...
Turn a string containing the subs xml document into the formatted subtitle string @param str|crunchyroll.models.StyledSubtitle sub_xml_text @return str def format(self, subtitles): """Turn a string containing the subs xml document into the formatted subtitle string @pa...
Check if API sessions are started and start them if not def require_session_started(func): """Check if API sessions are started and start them if not """ @functools.wraps(func) def inner_func(self, *pargs, **kwargs): if not self.session_started: logger.info('Starting session for req...
Check if andoid API is logged in and login if not, implies `require_session_started` def require_android_logged_in(func): """Check if andoid API is logged in and login if not, implies `require_session_started` """ @functools.wraps(func) @require_session_started def inner_func(self, *pargs, ...
Check if andoid manga API is logged in and login if credentials were provided, implies `require_session_started` def optional_manga_logged_in(func): """Check if andoid manga API is logged in and login if credentials were provided, implies `require_session_started` """ @functools.wraps(func) @re...
Check if ajax API is logged in and login if not def require_ajax_logged_in(func): """Check if ajax API is logged in and login if not """ @functools.wraps(func) def inner_func(self, *pargs, **kwargs): if not self._ajax_api.logged_in: logger.info('Logging into AJAX API for required me...
Start the underlying APIs sessions Calling this is not required, it will be called automatically if a method that needs a session is called @return bool def start_session(self): """Start the underlying APIs sessions Calling this is not required, it will be called automaticall...
Login with the given username/email and password Calling this method is not required if credentials were provided in the constructor, but it could be used to switch users or something maybe @return bool def login(self, username, password): """Login with the given username/email and pa...
Get a list of anime series @param str sort pick how results should be sorted, should be one of META.SORT_* @param int limit limit number of series to return, there doesn't seem to be an upper bound @param int offset list s...
Get a list of drama series @param str sort pick how results should be sorted, should be one of META.SORT_* @param int limit limit number of series to return, there doesn't seem to be an upper bound @param int offset list s...
Get a list of manga series def list_manga_series(self, filter=None, content_type='jp_manga'): """Get a list of manga series """ result = self._manga_api.list_series(filter, content_type) return result
Search anime series list by series name, case-sensitive @param str query_string string to search for, note that the search is very simplistic and only matches against the start of the series name, ex) search ...
Search drama series list by series name, case-sensitive @param str query_string string to search for, note that the search is very simplistic and only matches against the start of the series name, ex) search ...
Search the manga series list by name, case-insensitive @param str query_string @return list<crunchyroll.models.Series> def search_manga_series(self, query_string): """Search the manga series list by name, case-insensitive @param str query_string @return list<crunchyroll.mode...
List media for a given series or collection @param crunchyroll.models.Series series the series to search for @param str sort choose the ordering of the results, only META.SORT_DESC ...
Search for media from a series starting with query_string, case-sensitive @param crunchyroll.models.Series series the series to search in @param str query_string the search query, same restrictions as `search_anime_series` ...
Get the stream data for a given media item @param crunchyroll.models.Media media_item @param int format @param int quality @return crunchyroll.models.MediaStream def get_media_stream(self, media_item, format, quality): """Get the stream data for a given media item @par...
Turn a SubtitleStub into a full Subtitle object @param crunchyroll.models.SubtitleStub subtitle_stub @return crunchyroll.models.Subtitle def unfold_subtitle_stub(self, subtitle_stub): """Turn a SubtitleStub into a full Subtitle object @param crunchyroll.models.SubtitleStub subtitle_st...
Get the available media formats for a given media item @param crunchyroll.models.Media @return dict def get_stream_formats(self, media_item): """Get the available media formats for a given media item @param crunchyroll.models.Media @return dict """ scraper = Sc...
List the series in the queue, optionally filtering by type of media @param list<str> media_types a list of media types to filter the queue with, should be of META.TYPE_* @return list<crunchyroll.models.Series> def list_queue(self, media_types=[META.TYPE_A...
Add a series to the queue @param crunchyroll.models.Series series @return bool def add_to_queue(self, series): """Add a series to the queue @param crunchyroll.models.Series series @return bool """ result = self._android_api.add_to_queue(series_id=series.series_...
Remove a series from the queue @param crunchyroll.models.Series series @return bool def remove_from_queue(self, series): """Remove a series from the queue @param crunchyroll.models.Series series @return bool """ result = self._android_api.remove_from_queue(seri...
Create a compound tag schema. This function is a short convenience function that makes it easy to subclass the base `CompoundSchema` class. The `name` argument is the name of the class and `dct` should be a dictionnary containing the actual schema. The schema should map keys to tag types or...
Cast schema item to the appropriate tag type. def cast_item(cls, key, value): """Cast schema item to the appropriate tag type.""" schema_type = cls.schema.get(key) if schema_type is None: if cls.strict: raise TypeError(f'Invalid key {key!r}') elif not i...
Simple obsolete/removed method decorator Parameters ---------- oldname : str The name of the old obsolete name newfunc : FunctionType Replacement unbound member function. def obsolete_rename(oldname, newfunc): """ Simple obsolete/removed method decorator Parameters ---...
Runs a bash command safely, with shell=false, catches any non-zero return codes. Raises slightly modified CalledProcessError exceptions on failures. Note: command is a string and cannot include pipes. def call(command, silent=False): """ Runs a bash command safely, with shell=false, catche...
Tars and bzips a directory, preserving as much metadata as possible. Adds '.tbz' to the provided output file name. def tarbz(source_directory_path, output_file_full_path, silent=False): """ Tars and bzips a directory, preserving as much metadata as possible. Adds '.tbz' to the provided output file ...
Restores your mongo database backup from a .tbz created using this library. This function will ensure that a directory is created at the file path if one does not exist already. If used in conjunction with this library's mongodump operation, the backup data will be extracted directly into the provi...
Determine if any of the items in the value list for the given attribute contain value. def value_contains(self, value, attribute): """ Determine if any of the items in the value list for the given attribute contain value. """ for item in self[attribute]: if v...
Clear all search defaults specified by the list of parameter names given as ``args``. If ``args`` is not given, then clear all existing search defaults. Examples:: conn.set_search_defaults(scope=ldap.SCOPE_BASE, attrs=['cn']) conn.clear_search_defaults(['scope']) ...
Search the directory. def search(self, filter, base_dn=None, attrs=None, scope=None, timeout=None, limit=None): """ Search the directory. """ if base_dn is None: base_dn = self._search_defaults.get('base_dn', '') if attrs is None: attrs = s...
Get a single object. This is a convenience wrapper for the search method that checks that only one object was returned, and returns that single object instead of a list. This method takes the exact same arguments as search. def get(self, *args, **kwargs): """ Get a single obje...
Attempt to authenticate given dn and password using a bind operation. Return True if the bind is successful, and return False there was an exception raised that is contained in self.failed_authentication_exceptions. def authenticate(self, dn='', password=''): """ Attempt to auth...
Compare the ``attr`` of the entry ``dn`` with given ``value``. This is a convenience wrapper for the ldap library's ``compare`` function that returns a boolean value instead of 1 or 0. def compare(self, dn, attr, value): """ Compare the ``attr`` of the entry ``dn`` with given ``value``...
Get the accessor function for an instance to look for `key`. Look for it as an attribute, and if that does not work, look to see if it is a tag. def get_property_func(key): """ Get the accessor function for an instance to look for `key`. Look for it as an attribute, and if that does not work, loo...
List available billing metrics def list_billing(region, filter_by_kwargs): """List available billing metrics""" conn = boto.ec2.cloudwatch.connect_to_region(region) metrics = conn.list_metrics(metric_name='EstimatedCharges') # Filtering is based on metric Dimensions. Only really valuable one is # ...
List running ec2 instances. def list_cloudfront(region, filter_by_kwargs): """List running ec2 instances.""" conn = boto.connect_cloudfront() instances = conn.get_all_distributions() return lookup(instances, filter_by=filter_by_kwargs)
List running ec2 instances. def list_ec2(region, filter_by_kwargs): """List running ec2 instances.""" conn = boto.ec2.connect_to_region(region) instances = conn.get_only_instances() return lookup(instances, filter_by=filter_by_kwargs)
List running ebs volumes. def list_ebs(region, filter_by_kwargs): """List running ebs volumes.""" conn = boto.ec2.connect_to_region(region) instances = conn.get_all_volumes() return lookup(instances, filter_by=filter_by_kwargs)
List all load balancers. def list_elb(region, filter_by_kwargs): """List all load balancers.""" conn = boto.ec2.elb.connect_to_region(region) instances = conn.get_all_load_balancers() return lookup(instances, filter_by=filter_by_kwargs)
List all RDS thingys. def list_rds(region, filter_by_kwargs): """List all RDS thingys.""" conn = boto.rds.connect_to_region(region) instances = conn.get_all_dbinstances() return lookup(instances, filter_by=filter_by_kwargs)
List all ElastiCache Clusters. def list_elasticache(region, filter_by_kwargs): """List all ElastiCache Clusters.""" conn = boto.elasticache.connect_to_region(region) req = conn.describe_cache_clusters() data = req["DescribeCacheClustersResponse"]["DescribeCacheClustersResult"]["CacheClusters"] if f...
List all Auto Scaling Groups. def list_autoscaling_group(region, filter_by_kwargs): """List all Auto Scaling Groups.""" conn = boto.ec2.autoscale.connect_to_region(region) groups = conn.get_all_groups() return lookup(groups, filter_by=filter_by_kwargs)
List all SQS Queues. def list_sqs(region, filter_by_kwargs): """List all SQS Queues.""" conn = boto.sqs.connect_to_region(region) queues = conn.get_all_queues() return lookup(queues, filter_by=filter_by_kwargs)
List all the kinesis applications along with the shards for each stream def list_kinesis_applications(region, filter_by_kwargs): """List all the kinesis applications along with the shards for each stream""" conn = boto.kinesis.connect_to_region(region) streams = conn.list_streams()['StreamNames'] kines...
List all DynamoDB tables. def list_dynamodb(region, filter_by_kwargs): """List all DynamoDB tables.""" conn = boto.dynamodb.connect_to_region(region) tables = conn.list_tables() return lookup(tables, filter_by=filter_by_kwargs)
Register a new handler for a specific :class:`slack.actions.Action` `callback_id`. Optional routing based on the action name too. The name argument is useful for actions of type `interactive_message` to provide a different handler for each individual action. Args: callback_...
Yields handlers matching the incoming :class:`slack.actions.Action` `callback_id`. Args: action: :class:`slack.actions.Action` Yields: handler def dispatch(self, action: Action) -> Any: """ Yields handlers matching the incoming :class:`slack.actions.Action` `ca...
Commit to the use of specified Qt api. Raise an error if another Qt api is already loaded in sys.modules def comittoapi(api): """ Commit to the use of specified Qt api. Raise an error if another Qt api is already loaded in sys.modules """ global USED_API assert USED_API is None, "committ...
Return dictionary of metadata for given dist @param dist: distribution @type dist: pkg_resources Distribution object @returns: dict of metadata or None def get_metadata(dist): """ Return dictionary of metadata for given dist @param dist: distribution @type dist: pkg_resources Distributio...
Add command-line options for this plugin. The base plugin class adds --with-$name by default, used to enable the plugin. def add_options(self, parser): """Add command-line options for this plugin. The base plugin class adds --with-$name by default, used to enable the plugin. ...
Configure the plugin and system, based on selected options. The base plugin class sets the plugin to enabled if the enable option for the plugin (self.enable_opt) is true. def configure(self, options, conf): """Configure the plugin and system, based on selected options. The base plugi...
Return help for this plugin. This will be output as the help section of the --with-$name option that enables the plugin. def help(self): """Return help for this plugin. This will be output as the help section of the --with-$name option that enables the plugin. """ if self.__clas...
Check request response status Args: status: Response status headers: Response headers data: Response data Raises: :class:`slack.exceptions.RateLimited`: For 429 status code :class:`slack.exceptions:HTTPException`: def raise_for_status( status: int, headers: Mutable...
Check request response for Slack API error Args: headers: Response headers data: Response data Raises: :class:`slack.exceptions.SlackAPIError` def raise_for_api_error(headers: MutableMapping, data: MutableMapping) -> None: """ Check request response for Slack API error Ar...
Decode the response body For 'application/json' content-type load the body as a dictionary Args: headers: Response headers body: Response body Returns: decoded body def decode_body(headers: MutableMapping, body: bytes) -> dict: """ Decode the response body For 'appli...
Find content-type and encoding of the response Args: headers: Response headers Returns: :py:class:`tuple` (content-type, encoding) def parse_content_type(headers: MutableMapping) -> Tuple[Optional[str], str]: """ Find content-type and encoding of the response Args: header...
Prepare outgoing request Create url, headers, add token to the body and if needed json encode it Args: url: :class:`slack.methods` item or string of url data: Outgoing data headers: Custom headers global_headers: Global headers token: Slack API token as_json: Po...
Decode incoming response Args: status: Response status headers: Response headers body: Response body Returns: Response data def decode_response(status: int, headers: MutableMapping, body: bytes) -> dict: """ Decode incoming response Args: status: Response ...
Find iteration mode and iteration key for a given :class:`slack.methods` Args: url: :class:`slack.methods` or string url itermode: Custom iteration mode iterkey: Custom iteration key Returns: :py:class:`tuple` (itermode, iterkey) def find_iteration( url: Union[methods, str...
Prepare outgoing iteration request Args: url: :class:`slack.methods` item or string of url data: Outgoing data limit: Maximum number of results to return per call. iterkey: Key in response data to iterate over (required for url string). itermode: Iteration mode (required for...
Decode incoming response from an iteration request Args: data: Response data Returns: Next itervalue def decode_iter_request(data: dict) -> Optional[Union[str, int]]: """ Decode incoming response from an iteration request Args: data: Response data Returns: Ne...
Check if the incoming event needs to be discarded Args: event: Incoming :class:`slack.events.Event` bot_id: Id of connected bot Returns: boolean def discard_event(event: events.Event, bot_id: str = None) -> bool: """ Check if the incoming event needs to be discarded Args:...
Validate incoming request signature using the application signing secret. Contrary to the ``team_id`` and ``verification_token`` verification this method is not called by ``slack-sansio`` when creating object from incoming HTTP request. Because the body of the request needs to be provided as text and not decoded a...
Runs a backup operation to At Least a local directory. You must provide mongodb credentials along with a a directory for a dump operation and a directory to contain your compressed backup. backup_prefix: optionally provide a prefix to be prepended to your backups, by default the pr...
Runs mongorestore with source data from the provided .tbz backup, using the provided username and password. The contents of the .tbz will be dumped into the provided backup directory, and that folder will be deleted after a successful mongodb restore unless cleanup is set to False. Note: ...
Runs mongodump using the provided credentials on the running mongod process. WARNING: This function will delete the contents of the provided directory before it runs. def mongodump(mongo_user, mongo_password, mongo_dump_directory_path, database=None, silent=False): """ Runs mo...
Warning: Setting drop_database to True will drop the ENTIRE CURRENTLY RUNNING DATABASE before restoring. Mongorestore requires a running mongod process, in addition the provided user must have restore permissions for the database. A mongolia superuser will have more than a...
Returns a datetime object computed from a file name string, with formatting based on DATETIME_FORMAT. def get_backup_file_time_tag(file_name, custom_prefix="backup"): """ Returns a datetime object computed from a file name string, with formatting based on DATETIME_FORMAT.""" name_string = f...
Takes a datetime object and a directory path, runs through files in the directory and deletes those tagged with a date from before the provided datetime. If your backups have a custom_prefix that is not the default ("backup"), provide it with the "custom_prefix" kwarg. def purge_old...
Use setuptools to search for a package's URI @returns: URI string def get_download_uri(package_name, version, source, index_url=None): """ Use setuptools to search for a package's URI @returns: URI string """ tmpdir = None force_scan = True develop_ok = False if not index_url: ...
Return list of all installed packages Note: It returns one project name per pkg no matter how many versions of a particular package is installed @returns: list of project name strings for every installed pkg def get_pkglist(): """ Return list of all installed packages Note: It returns one pr...
Register a new handler for a specific slash command Args: command: Slash command handler: Callback def register(self, command: str, handler: Any): """ Register a new handler for a specific slash command Args: command: Slash command handl...
Yields handlers matching the incoming :class:`slack.actions.Command`. Args: command: :class:`slack.actions.Command` Yields: handler def dispatch(self, command: Command) -> Iterator[Any]: """ Yields handlers matching the incoming :class:`slack.actions.Command`. ...
Set the preferred Qt API. Will raise a RuntimeError if a Qt API was already selected. Note that QT_API environment variable (if set) will take precedence. def setpreferredapi(api): """ Set the preferred Qt API. Will raise a RuntimeError if a Qt API was already selected. Note that QT_API env...
Select an Qt API to use. This can only be set once and before any of the Qt modules are explicitly imported. def selectapi(api): """ Select an Qt API to use. This can only be set once and before any of the Qt modules are explicitly imported. """ global __SELECTED_API, USED_API if ...