repo_name
stringclasses
4 values
method_name
stringlengths
3
72
method_code
stringlengths
87
3.59k
method_summary
stringlengths
12
196
original_method_code
stringlengths
129
8.98k
method_path
stringlengths
15
136
Azure/azure-sdk-for-python
WebsiteManagementService.restart_site
def restart_site(self, webspace_name, website_name): return self._perform_post( self._get_restart_path(webspace_name, website_name), None, as_async=True)
Restart a web site.
def restart_site(self, webspace_name, website_name): ''' Restart a web site. webspace_name: The name of the webspace. website_name: The name of the website. ''' return self._perform_post( self._get_restart_path(webspace_name, website_n...
azure-servicemanagement-legacy/azure/servicemanagement/websitemanagementservice.py
Azure/azure-sdk-for-python
WebsiteManagementService.get_historical_usage_metrics
def get_historical_usage_metrics(self, webspace_name, website_name, metrics = None, start_time=None, end_time=None, time_grain=None): metrics = ('names='+','.join(metrics)) if metrics else '' start_time = ('StartTime='+start_time) if start_time else '' end_ti...
Get historical usage metrics.
def get_historical_usage_metrics(self, webspace_name, website_name, metrics = None, start_time=None, end_time=None, time_grain=None): ''' Get historical usage metrics. webspace_name: The name of the webspace. website_name: The...
azure-servicemanagement-legacy/azure/servicemanagement/websitemanagementservice.py
Azure/azure-sdk-for-python
WebsiteManagementService.get_metric_definitions
def get_metric_definitions(self, webspace_name, website_name): return self._perform_get(self._get_metric_definitions_path(webspace_name, website_name), MetricDefinitions)
Get metric definitions of metrics available of this web site.
def get_metric_definitions(self, webspace_name, website_name): ''' Get metric definitions of metrics available of this web site. webspace_name: The name of the webspace. website_name: The name of the website. ''' return self._perform_get(self._get...
azure-servicemanagement-legacy/azure/servicemanagement/websitemanagementservice.py
Azure/azure-sdk-for-python
WebsiteManagementService.get_publish_profile_xml
def get_publish_profile_xml(self, webspace_name, website_name): return self._perform_get(self._get_publishxml_path(webspace_name, website_name), None).body.decode("utf-8")
Get a site's publish profile as a string
def get_publish_profile_xml(self, webspace_name, website_name): ''' Get a site's publish profile as a string webspace_name: The name of the webspace. website_name: The name of the website. ''' return self._perform_get(self._get_publishxml_path(web...
azure-servicemanagement-legacy/azure/servicemanagement/websitemanagementservice.py
Azure/azure-sdk-for-python
WebsiteManagementService.get_publish_profile
def get_publish_profile(self, webspace_name, website_name): return self._perform_get(self._get_publishxml_path(webspace_name, website_name), PublishData)
Get a site's publish profile as an object
def get_publish_profile(self, webspace_name, website_name): ''' Get a site's publish profile as an object webspace_name: The name of the webspace. website_name: The name of the website. ''' return self._perform_get(self._get_publishxml_path(webspa...
azure-servicemanagement-legacy/azure/servicemanagement/websitemanagementservice.py
Azure/azure-sdk-for-python
RegistriesOperations.update_policies
def update_policies( self, resource_group_name, registry_name, quarantine_policy=None, trust_policy=None, custom_headers=None, raw=False, polling=True, **operation_config): raw_result = self._update_policies_initial( resource_group_name=resource_group_name, registry_name=regi...
Updates the policies for the specified container registry.
def update_policies( self, resource_group_name, registry_name, quarantine_policy=None, trust_policy=None, custom_headers=None, raw=False, polling=True, **operation_config): """Updates the policies for the specified container registry. :param resource_group_name: The name of the resource gro...
azure-mgmt-containerregistry/azure/mgmt/containerregistry/v2018_02_01_preview/operations/registries_operations.py
Azure/azure-sdk-for-python
SchedulerManagementService.check_job_collection_name
def check_job_collection_name(self, cloud_service_id, job_collection_id): _validate_not_none('cloud_service_id', cloud_service_id) _validate_not_none('job_collection_id', job_collection_id) path = self._get_cloud_services_path( cloud_service_id, "scheduler", "jobCollections") ...
The Check Name Availability operation checks if a new job collection with the given name may be created, or if it is unavailable. The result of the operation is a Boolean true or false.
def check_job_collection_name(self, cloud_service_id, job_collection_id): ''' The Check Name Availability operation checks if a new job collection with the given name may be created, or if it is unavailable. The result of the operation is a Boolean true or false. cloud_service_i...
azure-servicemanagement-legacy/azure/servicemanagement/schedulermanagementservice.py
Azure/azure-sdk-for-python
SchedulerManagementService.get_job_collection
def get_job_collection(self, cloud_service_id, job_collection_id): _validate_not_none('cloud_service_id', cloud_service_id) _validate_not_none('job_collection_id', job_collection_id) path = self._get_job_collection_path( cloud_service_id, job_collection_id) return self._per...
The Get Job Collection operation gets the details of a job collection
def get_job_collection(self, cloud_service_id, job_collection_id): ''' The Get Job Collection operation gets the details of a job collection cloud_service_id: The cloud service id job_collection_id: Name of the hosted service. ''' _validate_not_no...
azure-servicemanagement-legacy/azure/servicemanagement/schedulermanagementservice.py
Azure/azure-sdk-for-python
ManagedDatabasesOperations.complete_restore
def complete_restore( self, location_name, operation_id, last_backup_name, custom_headers=None, raw=False, polling=True, **operation_config): raw_result = self._complete_restore_initial( location_name=location_name, operation_id=operation_id, last_backup_name=last...
Completes the restore operation on a managed database.
def complete_restore( self, location_name, operation_id, last_backup_name, custom_headers=None, raw=False, polling=True, **operation_config): """Completes the restore operation on a managed database. :param location_name: The name of the region where the resource is located. ...
azure-mgmt-sql/azure/mgmt/sql/operations/managed_databases_operations.py
Azure/azure-sdk-for-python
Sender.cancel_scheduled_messages
async def cancel_scheduled_messages(self, *sequence_numbers): if not self.running: await self.open() numbers = [types.AMQPLong(s) for s in sequence_numbers] request_body = {'sequence-numbers': types.AMQPArray(numbers)} return await self._mgmt_request_response( REQ...
Cancel one or more messages that have previsouly been scheduled and are still pending.
async def cancel_scheduled_messages(self, *sequence_numbers): """Cancel one or more messages that have previsouly been scheduled and are still pending. :param sequence_numbers: The seqeuence numbers of the scheduled messages. :type sequence_numbers: int Example: .. literali...
azure-servicebus/azure/servicebus/aio/async_send_handler.py
Azure/azure-sdk-for-python
Sender.send_pending_messages
async def send_pending_messages(self): if not self.running: await self.open() try: pending = self._handler._pending_messages[:] await self._handler.wait_async() results = [] for m in pending: if m.state == constants.MessageSta...
Wait until all pending messages have been sent.
async def send_pending_messages(self): """Wait until all pending messages have been sent. :returns: A list of the send results of all the pending messages. Each send result is a tuple with two values. The first is a boolean, indicating `True` if the message sent, or `False` if it fail...
azure-servicebus/azure/servicebus/aio/async_send_handler.py
Azure/azure-sdk-for-python
get_certificate_from_publish_settings
def get_certificate_from_publish_settings(publish_settings_path, path_to_write_certificate, subscription_id=None): import base64 try: from xml.etree import cElementTree as ET except ImportError: from xml.etree import ElementTree as ET try: import OpenSSL.crypto as crypto ex...
Writes a certificate file to the specified location. This can then be used to instantiate ServiceManagementService.
def get_certificate_from_publish_settings(publish_settings_path, path_to_write_certificate, subscription_id=None): ''' Writes a certificate file to the specified location. This can then be used to instantiate ServiceManagementService. Returns the subscription ID. publish_settings_path: Path...
azure-servicemanagement-legacy/azure/servicemanagement/publishsettings.py
streamlink/streamlink
Plugin.load_cookies
def load_cookies(self): if not self.session or not self.cache: raise RuntimeError("Cannot loaded cached cookies in unbound plugin") restored = [] for key, value in self.cache.get_all().items(): if key.startswith("__cookie"): cookie = requests.cookies.cre...
Load any stored cookies for the plugin that have not expired.
def load_cookies(self): """ Load any stored cookies for the plugin that have not expired. :return: list of the restored cookie names """ if not self.session or not self.cache: raise RuntimeError("Cannot loaded cached cookies in unbound plugin") restored = []...
src/streamlink/plugin/plugin.py
streamlink/streamlink
get_cut_prefix
def get_cut_prefix(value, max_len): should_convert = isinstance(value, bytes) if should_convert: value = value.decode("utf8", "ignore") for i in range(len(value)): if terminal_width(value[i:]) <= max_len: break return value[i:].encode("utf8", "ignore") if should_convert else ...
Drops Characters by unicode not by bytes.
def get_cut_prefix(value, max_len): """Drops Characters by unicode not by bytes.""" should_convert = isinstance(value, bytes) if should_convert: value = value.decode("utf8", "ignore") for i in range(len(value)): if terminal_width(value[i:]) <= max_len: break return value[...
src/streamlink_cli/utils/progress.py
streamlink/streamlink
print_inplace
def print_inplace(msg): term_width = get_terminal_size().columns spacing = term_width - terminal_width(msg) if is_win32: spacing -= 1 sys.stderr.write("\r{0}".format(msg)) sys.stderr.write(" " * max(0, spacing)) sys.stderr.flush()
Clears out the previous line and prints a new one.
def print_inplace(msg): """Clears out the previous line and prints a new one.""" term_width = get_terminal_size().columns spacing = term_width - terminal_width(msg) # On windows we need one less space or we overflow the line for some reason. if is_win32: spacing -= 1 sys.stderr.write("...
src/streamlink_cli/utils/progress.py
streamlink/streamlink
format_filesize
def format_filesize(size): for suffix in ("bytes", "KB", "MB", "GB", "TB"): if size < 1024.0: if suffix in ("GB", "TB"): return "{0:3.2f} {1}".format(size, suffix) else: return "{0:3.1f} {1}".format(size, suffix) size /= 1024.0
Formats the file size into a human readable format.
def format_filesize(size): """Formats the file size into a human readable format.""" for suffix in ("bytes", "KB", "MB", "GB", "TB"): if size < 1024.0: if suffix in ("GB", "TB"): return "{0:3.2f} {1}".format(size, suffix) else: return "{0:3.1f} {1}...
src/streamlink_cli/utils/progress.py
streamlink/streamlink
format_time
def format_time(elapsed): hours = int(elapsed / (60 * 60)) minutes = int((elapsed % (60 * 60)) / 60) seconds = int(elapsed % 60) rval = "" if hours: rval += "{0}h".format(hours) if elapsed > 60: rval += "{0}m".format(minutes) rval += "{0}s".format(seconds) return rval
Formats elapsed seconds into a human readable format.
def format_time(elapsed): """Formats elapsed seconds into a human readable format.""" hours = int(elapsed / (60 * 60)) minutes = int((elapsed % (60 * 60)) / 60) seconds = int(elapsed % 60) rval = "" if hours: rval += "{0}h".format(hours) if elapsed > 60: rval += "{0}m".form...
src/streamlink_cli/utils/progress.py
streamlink/streamlink
create_status_line
def create_status_line(**params): max_size = get_terminal_size().columns - 1 for fmt in PROGRESS_FORMATS: status = fmt.format(**params) if len(status) <= max_size: break return status
Creates a status line with appropriate size.
def create_status_line(**params): """Creates a status line with appropriate size.""" max_size = get_terminal_size().columns - 1 for fmt in PROGRESS_FORMATS: status = fmt.format(**params) if len(status) <= max_size: break return status
src/streamlink_cli/utils/progress.py
streamlink/streamlink
progress
def progress(iterator, prefix): if terminal_width(prefix) > 25: prefix = (".." + get_cut_prefix(prefix, 23)) speed_updated = start = time() speed_written = written = 0 speed_history = deque(maxlen=5) for data in iterator: yield data now = time() elapsed = now - star...
Progress an iterator and updates a pretty status line to the terminal. The status line
def progress(iterator, prefix): """Progress an iterator and updates a pretty status line to the terminal. The status line contains: - Amount of data read from the iterator - Time elapsed - Average speed, based on the last few seconds. """ if terminal_width(prefix) > 25: prefix = ...
src/streamlink_cli/utils/progress.py
streamlink/streamlink
SegmentedStreamWorker.wait
def wait(self, time): self._wait = Event() return not self._wait.wait(time)
Pauses the thread for a specified time.
def wait(self, time): """Pauses the thread for a specified time. Returns False if interrupted by another thread and True if the time runs out normally. """ self._wait = Event() return not self._wait.wait(time)
src/streamlink/stream/segmented.py
streamlink/streamlink
SegmentedStreamWriter.put
def put(self, segment): if self.closed: return if segment is not None: future = self.executor.submit(self.fetch, segment, retries=self.retries) else: future = None self.queue(self.futures, (segment, future))
Adds a segment to the download pool and write queue.
def put(self, segment): """Adds a segment to the download pool and write queue.""" if self.closed: return if segment is not None: future = self.executor.submit(self.fetch, segment, retries=self.retries) else: ...
src/streamlink/stream/segmented.py
streamlink/streamlink
SegmentedStreamWriter.queue
def queue(self, queue_, value): while not self.closed: try: queue_.put(value, block=True, timeout=1) return except queue.Full: continue
Puts a value into a queue but aborts if this thread is closed.
def queue(self, queue_, value): """Puts a value into a queue but aborts if this thread is closed.""" while not self.closed: try: queue_.put(value, block=True, timeout=1) return except queue.Full: continue
src/streamlink/stream/segmented.py
streamlink/streamlink
BBCiPlayer.find_vpid
def find_vpid(self, url, res=None): log.debug("Looking for vpid on {0}", url) res = res or self.session.http.get(url) m = self.mediator_re.search(res.text) vpid = m and parse_json(m.group(1), schema=self.mediator_schema) return vpid
Find the Video Packet ID in the HTML for the provided URL
def find_vpid(self, url, res=None): """ Find the Video Packet ID in the HTML for the provided URL :param url: URL to download, if res is not provided. :param res: Provide a cached version of the HTTP response to search :type url: string :type res: requests.Response ...
src/streamlink/plugins/bbciplayer.py
streamlink/streamlink
parse_json
def parse_json(data, name="JSON", exception=PluginError, schema=None): try: json_data = json.loads(data) except ValueError as err: snippet = repr(data) if len(snippet) > 35: snippet = snippet[:35] + " ..." else: snippet = data raise exception("Una...
Wrapper around json.loads. Wraps errors in custom exception with a snippet of the data in the message.
def parse_json(data, name="JSON", exception=PluginError, schema=None): """Wrapper around json.loads. Wraps errors in custom exception with a snippet of the data in the message. """ try: json_data = json.loads(data) except ValueError as err: snippet = repr(data) if len(snippe...
src/streamlink/utils/__init__.py
streamlink/streamlink
parse_xml
def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=None, invalid_char_entities=False): if is_py2 and isinstance(data, unicode): data = data.encode("utf8") elif is_py3 and isinstance(data, str): data = bytearray(data, "utf8") if ignore_ns: data = re.sub(br...
Wrapper around ElementTree.fromstring with some extras. Provides these extra
def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=None, invalid_char_entities=False): """Wrapper around ElementTree.fromstring with some extras. Provides these extra features: - Handles incorrectly encoded XML - Allows stripping namespace information - Wraps errors i...
src/streamlink/utils/__init__.py
streamlink/streamlink
parse_qsd
def parse_qsd(data, name="query string", exception=PluginError, schema=None, **params): value = dict(parse_qsl(data, **params)) if schema: value = schema.validate(value, name=name, exception=exception) return value
Parses a query string into a dict. Unlike parse_qs and parse_qsl, duplicate keys are not preserved in favor of a simpler return value.
def parse_qsd(data, name="query string", exception=PluginError, schema=None, **params): """Parses a query string into a dict. Unlike parse_qs and parse_qsl, duplicate keys are not preserved in favor of a simpler return value. """ value = dict(parse_qsl(data, **params)) if schema: value...
src/streamlink/utils/__init__.py
streamlink/streamlink
search_dict
def search_dict(data, key): if isinstance(data, dict): for dkey, value in data.items(): if dkey == key: yield value for result in search_dict(value, key): yield result elif isinstance(data, list): for value in data: for result i...
Search for a key in a nested dict, or list of nested dicts, and return the values.
def search_dict(data, key): """ Search for a key in a nested dict, or list of nested dicts, and return the values. :param data: dict/list to search :param key: key to find :return: matches for key """ if isinstance(data, dict): for dkey, value in data.items(): if dkey ==...
src/streamlink/utils/__init__.py
streamlink/streamlink
DASHStream.parse_manifest
def parse_manifest(cls, session, url_or_manifest, **args): ret = {} if url_or_manifest.startswith('<?xml'): mpd = MPD(parse_xml(url_or_manifest, ignore_ns=True)) else: res = session.http.get(url_or_manifest, **args) url = res.url urlp = list(urlp...
Attempt to parse a DASH manifest file and return its streams
def parse_manifest(cls, session, url_or_manifest, **args): """ Attempt to parse a DASH manifest file and return its streams :param session: Streamlink session instance :param url_or_manifest: URL of the manifest file or an XML manifest string :return: a dict of name -> DASHStrea...
src/streamlink/stream/dash.py
streamlink/streamlink
HTTPSession.determine_json_encoding
def determine_json_encoding(cls, sample): nulls_at = [i for i, j in enumerate(bytearray(sample[:4])) if j == 0] if nulls_at == [0, 1, 2]: return "UTF-32BE" elif nulls_at == [0, 2]: return "UTF-16BE" elif nulls_at == [1, 2, 3]: return "UTF-32LE" ...
Determine which Unicode encoding the JSON text sample is encoded with RFC4627 (
def determine_json_encoding(cls, sample): """ Determine which Unicode encoding the JSON text sample is encoded with RFC4627 (http://www.ietf.org/rfc/rfc4627.txt) suggests that the encoding of JSON text can be determined by checking the pattern of NULL bytes in first 4 octets of the text...
src/streamlink/plugin/api/http_session.py
streamlink/streamlink
HTTPSession.json
def json(cls, res, *args, **kwargs): if res.encoding is None: res.encoding = cls.determine_json_encoding(res.content[:4]) return parse_json(res.text, *args, **kwargs)
Parses JSON from a response.
def json(cls, res, *args, **kwargs): """Parses JSON from a response.""" # if an encoding is already set then use the provided encoding if res.encoding is None: res.encoding = cls.determine_json_encoding(res.content[:4]) return parse_json(res.text, *args, **kwargs)
src/streamlink/plugin/api/http_session.py
streamlink/streamlink
HTTPSession.xml
def xml(cls, res, *args, **kwargs): return parse_xml(res.text, *args, **kwargs)
Parses XML from a response.
def xml(cls, res, *args, **kwargs): """Parses XML from a response.""" return parse_xml(res.text, *args, **kwargs)
src/streamlink/plugin/api/http_session.py
streamlink/streamlink
HTTPSession.parse_cookies
def parse_cookies(self, cookies, **kwargs): for name, value in _parse_keyvalue_list(cookies): self.cookies.set(name, value, **kwargs)
Parses a semi-colon delimited list of cookies.
def parse_cookies(self, cookies, **kwargs): """Parses a semi-colon delimited list of cookies. Example: foo=bar;baz=qux """ for name, value in _parse_keyvalue_list(cookies): self.cookies.set(name, value, **kwargs)
src/streamlink/plugin/api/http_session.py
streamlink/streamlink
HTTPSession.parse_headers
def parse_headers(self, headers): for name, value in _parse_keyvalue_list(headers): self.headers[name] = value
Parses a semi-colon delimited list of headers.
def parse_headers(self, headers): """Parses a semi-colon delimited list of headers. Example: foo=bar;baz=qux """ for name, value in _parse_keyvalue_list(headers): self.headers[name] = value
src/streamlink/plugin/api/http_session.py
streamlink/streamlink
HTTPSession.parse_query_params
def parse_query_params(self, cookies, **kwargs): for name, value in _parse_keyvalue_list(cookies): self.params[name] = value
Parses a semi-colon delimited list of query parameters.
def parse_query_params(self, cookies, **kwargs): """Parses a semi-colon delimited list of query parameters. Example: foo=bar;baz=qux """ for name, value in _parse_keyvalue_list(cookies): self.params[name] = value
src/streamlink/plugin/api/http_session.py
streamlink/streamlink
_LogRecord.getMessage
def getMessage(self): msg = self.msg if self.args: msg = msg.format(*self.args) return maybe_encode(msg)
Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message.
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ msg = self.msg if self.args: msg = msg.format(*self.args) return maybe_encod...
src/streamlink/logger.py
streamlink/streamlink
StreamlinkLogger.makeRecord
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): if name.startswith("streamlink"): rv = _LogRecord(name, level, fn, lno, msg, args, exc_info, func, sinfo) else: rv = _CompatLogRecord(name, level, fn, lno, msg, ...
A factory method which can be overridden in subclasses to create specialized LogRecords.
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ if name.startswith("streamlink"): rv = _LogRecord(na...
src/streamlink/logger.py
streamlink/streamlink
LiveEdu.login
def login(self): email = self.get_option("email") password = self.get_option("password") if email and password: res = self.session.http.get(self.login_url) csrf_match = self.csrf_re.search(res.text) token = csrf_match and csrf_match.group(1) self....
Attempt a login to LiveEdu.tv
def login(self): """ Attempt a login to LiveEdu.tv """ email = self.get_option("email") password = self.get_option("password") if email and password: res = self.session.http.get(self.login_url) csrf_match = self.csrf_re.search(res.text) ...
src/streamlink/plugins/liveedu.py
streamlink/streamlink
update_qsd
def update_qsd(url, qsd=None, remove=None): qsd = qsd or {} remove = remove or [] parsed = urlparse(url) current_qsd = OrderedDict(parse_qsl(parsed.query)) if remove == "*": remove = list(current_qsd.keys()) for key in remove: if key not in qsd: del ...
Update or remove keys from a query string in a URL
def update_qsd(url, qsd=None, remove=None): """ Update or remove keys from a query string in a URL :param url: URL to update :param qsd: dict of keys to update, a None value leaves it unchanged :param remove: list of keys to remove, or "*" to remove all note: updated keys are nev...
src/streamlink/utils/url.py
streamlink/streamlink
FLVTagConcat.iter_chunks
def iter_chunks(self, fd=None, buf=None, skip_header=None): timestamps = dict(self.timestamps_add) tag_iterator = self.iter_tags(fd=fd, buf=buf, skip_header=skip_header) if not self.flv_header_written: analyzed_tags = self.analyze_tags(tag_iterator) else: analyze...
Reads FLV tags from fd or buf and returns them with adjusted timestamps.
def iter_chunks(self, fd=None, buf=None, skip_header=None): """Reads FLV tags from fd or buf and returns them with adjusted timestamps.""" timestamps = dict(self.timestamps_add) tag_iterator = self.iter_tags(fd=fd, buf=buf, skip_header=skip_header) if not self.flv_header_writ...
src/streamlink/stream/flvconcat.py
streamlink/streamlink
Arguments.requires
def requires(self, name): results = set([name]) argument = self.get(name) for reqname in argument.requires: required = self.get(reqname) if not required: raise KeyError("{0} is not a valid argument for this plugin".format(reqname)) if required...
Find all the arguments required by name
def requires(self, name): """ Find all the arguments required by name :param name: name of the argument the find the dependencies :return: list of dependant arguments """ results = set([name]) argument = self.get(name) for reqname in argument.requires: ...
src/streamlink/options.py
streamlink/streamlink
check_file_output
def check_file_output(filename, force): log.debug("Checking file output") if os.path.isfile(filename) and not force: if sys.stdin.isatty(): answer = console.ask("File {0} already exists! Overwrite it? [y/N] ", filename) if answer.lower() != "y":...
Checks if file already exists and ask the user if it should be overwritten if it does.
def check_file_output(filename, force): """Checks if file already exists and ask the user if it should be overwritten if it does.""" log.debug("Checking file output") if os.path.isfile(filename) and not force: if sys.stdin.isatty(): answer = console.ask("File {0} already exists! Ov...
src/streamlink_cli/main.py
streamlink/streamlink
create_output
def create_output(plugin): if (args.output or args.stdout) and (args.record or args.record_and_pipe): console.exit("Cannot use record options with other file output options.") if args.output: if args.output == "-": out = FileOutput(fd=stdout) else: out = check_fi...
Decides where to write the stream. Depending on arguments it can be one of
def create_output(plugin): """Decides where to write the stream. Depending on arguments it can be one of these: - The stdout pipe - A subprocess' stdin pipe - A named pipe that the subprocess reads from - A regular file """ if (args.output or args.stdout) and (args.record or args....
src/streamlink_cli/main.py
streamlink/streamlink
create_http_server
def create_http_server(host=None, port=0): try: http = HTTPServer() http.bind(host=host, port=port) except OSError as err: console.exit("Failed to create HTTP server: {0}", err) return http
Creates a HTTP server listening on a given host and port. If host is empty, listen on all available interfaces, and if port is 0, listen on a random high port.
def create_http_server(host=None, port=0): """Creates a HTTP server listening on a given host and port. If host is empty, listen on all available interfaces, and if port is 0, listen on a random high port. """ try: http = HTTPServer() http.bind(host=host, port=port) except OSEr...
src/streamlink_cli/main.py
streamlink/streamlink
iter_http_requests
def iter_http_requests(server, player): while not player or player.running: try: yield server.open(timeout=2.5) except OSError: continue
Repeatedly accept HTTP connections on a server. Forever if the serving externally, or while a player is running if it is not empty.
def iter_http_requests(server, player): """Repeatedly accept HTTP connections on a server. Forever if the serving externally, or while a player is running if it is not empty. """ while not player or player.running: try: yield server.open(timeout=2.5) except OSError: ...
src/streamlink_cli/main.py
streamlink/streamlink
output_stream_http
def output_stream_http(plugin, initial_streams, external=False, port=0): global output if not external: if not args.player: console.exit("The default player (VLC) does not seem to be " "installed. You must specify the path to a player " "exe...
Continuously output the stream over HTTP.
def output_stream_http(plugin, initial_streams, external=False, port=0): """Continuously output the stream over HTTP.""" global output if not external: if not args.player: console.exit("The default player (VLC) does not seem to be " "installed. You must specify ...
src/streamlink_cli/main.py
streamlink/streamlink
output_stream_passthrough
def output_stream_passthrough(plugin, stream): global output title = create_title(plugin) filename = '"{0}"'.format(stream_to_url(stream)) output = PlayerOutput(args.player, args=args.player_args, filename=filename, call=True, quiet=not args.verbose_p...
Prepares a filename to be passed to the player.
def output_stream_passthrough(plugin, stream): """Prepares a filename to be passed to the player.""" global output title = create_title(plugin) filename = '"{0}"'.format(stream_to_url(stream)) output = PlayerOutput(args.player, args=args.player_args, filename=filename, cal...
src/streamlink_cli/main.py
streamlink/streamlink
open_stream
def open_stream(stream): global stream_fd try: stream_fd = stream.open() except StreamError as err: raise StreamError("Could not open stream: {0}".format(err)) try: log.debug("Pre-buffering 8192 bytes") prebuffer = stream_fd.read(8192) except IOError ...
Opens a stream and reads 8192 bytes from it. This is useful to check if a stream actually has data before opening the output.
def open_stream(stream): """Opens a stream and reads 8192 bytes from it. This is useful to check if a stream actually has data before opening the output. """ global stream_fd # Attempts to open the stream try: stream_fd = stream.open() except StreamError as err: raise ...
src/streamlink_cli/main.py
streamlink/streamlink
output_stream
def output_stream(plugin, stream): global output success_open = False for i in range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream) success_open = True break except StreamError as err: log.error("Try {0}/{1}: Could not open ...
Open stream, create output and finally write the stream to output.
def output_stream(plugin, stream): """Open stream, create output and finally write the stream to output.""" global output success_open = False for i in range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream) success_open = True break e...
src/streamlink_cli/main.py
streamlink/streamlink
read_stream
def read_stream(stream, output, prebuffer, chunk_size=8192): is_player = isinstance(output, PlayerOutput) is_http = isinstance(output, HTTPServer) is_fifo = is_player and output.namedpipe show_progress = isinstance(output, FileOutput) and output.fd is not stdout and sys.stdout.isatty() show_record_p...
Reads data from stream and then writes it to the output.
def read_stream(stream, output, prebuffer, chunk_size=8192): """Reads data from stream and then writes it to the output.""" is_player = isinstance(output, PlayerOutput) is_http = isinstance(output, HTTPServer) is_fifo = is_player and output.namedpipe show_progress = isinstance(output, FileOutput) an...
src/streamlink_cli/main.py
streamlink/streamlink
handle_stream
def handle_stream(plugin, streams, stream_name): stream_name = resolve_stream_name(streams, stream_name) stream = streams[stream_name] if args.subprocess_cmdline: if isinstance(stream, StreamProcess): try: cmdline = stream.cmdline() except StreamErr...
Decides what to do with the selected stream. Depending on arguments it can be one of
def handle_stream(plugin, streams, stream_name): """Decides what to do with the selected stream. Depending on arguments it can be one of these: - Output internal command-line - Output JSON represenation - Continuously output the stream over HTTP - Output stream data to selected output ...
src/streamlink_cli/main.py
streamlink/streamlink
fetch_streams
def fetch_streams(plugin): return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes)
Fetches streams using correct parameters.
def fetch_streams(plugin): """Fetches streams using correct parameters.""" return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes)
src/streamlink_cli/main.py
streamlink/streamlink
fetch_streams_with_retry
def fetch_streams_with_retry(plugin, interval, count): try: streams = fetch_streams(plugin) except PluginError as err: log.error(u"{0}", err) streams = None if not streams: log.info("Waiting for streams, retrying every {0} " "second(s)", interval) attemp...
Attempts to fetch streams repeatedly until some are returned or limit hit.
def fetch_streams_with_retry(plugin, interval, count): """Attempts to fetch streams repeatedly until some are returned or limit hit.""" try: streams = fetch_streams(plugin) except PluginError as err: log.error(u"{0}", err) streams = None if not streams: log.info(...
src/streamlink_cli/main.py
streamlink/streamlink
format_valid_streams
def format_valid_streams(plugin, streams): delimiter = ", " validstreams = [] for name, stream in sorted(streams.items(), key=lambda stream: plugin.stream_weight(stream[0])): if name in STREAM_SYNONYMS: continue def synonymfilter(n): r...
Formats a dict of streams. Filters out synonyms and displays them next to the stream they point to. Streams are sorted according to their quality (based on plugin.stream_weight).
def format_valid_streams(plugin, streams): """Formats a dict of streams. Filters out synonyms and displays them next to the stream they point to. Streams are sorted according to their quality (based on plugin.stream_weight). """ delimiter = ", " validstreams = [] for name, strea...
src/streamlink_cli/main.py
streamlink/streamlink
print_plugins
def print_plugins(): pluginlist = list(streamlink.get_plugins().keys()) pluginlist_formatted = ", ".join(sorted(pluginlist)) if console.json: console.msg_json(pluginlist) else: console.msg("Loaded plugins: {0}", pluginlist_formatted)
Outputs a list of all plugins Streamlink has loaded.
def print_plugins(): """Outputs a list of all plugins Streamlink has loaded.""" pluginlist = list(streamlink.get_plugins().keys()) pluginlist_formatted = ", ".join(sorted(pluginlist)) if console.json: console.msg_json(pluginlist) else: console.msg("Loaded plugins: {0}", pluginlist_...
src/streamlink_cli/main.py
streamlink/streamlink
authenticate_twitch_oauth
def authenticate_twitch_oauth(): client_id = TWITCH_CLIENT_ID redirect_uri = "https://streamlink.github.io/twitch_oauth.html" url = ("https://api.twitch.tv/kraken/oauth2/authorize" "?response_type=token" "&client_id={0}" "&redirect_uri={1}" "&scope=user_read+user_...
Opens a web browser to allow the user to grant Streamlink access to their Twitch account.
def authenticate_twitch_oauth(): """Opens a web browser to allow the user to grant Streamlink access to their Twitch account.""" client_id = TWITCH_CLIENT_ID redirect_uri = "https://streamlink.github.io/twitch_oauth.html" url = ("https://api.twitch.tv/kraken/oauth2/authorize" "?respon...
src/streamlink_cli/main.py
streamlink/streamlink
load_plugins
def load_plugins(dirs): dirs = [os.path.expanduser(d) for d in dirs] for directory in dirs: if os.path.isdir(directory): streamlink.load_plugins(directory) else: log.warning("Plugin path {0} does not exist or is not " "a directory!", directory)
Attempts to load plugins from a list of directories.
def load_plugins(dirs): """Attempts to load plugins from a list of directories.""" dirs = [os.path.expanduser(d) for d in dirs] for directory in dirs: if os.path.isdir(directory): streamlink.load_plugins(directory) else: log.warning("Plugin path {0} does not exist o...
src/streamlink_cli/main.py
streamlink/streamlink
setup_args
def setup_args(parser, config_files=[], ignore_unknown=False): global args arglist = sys.argv[1:] for config_file in filter(os.path.isfile, config_files): arglist.insert(0, "@" + config_file) args, unknown = parser.parse_known_args(arglist) if unknown and not ignore_unknown: m...
Parses arguments.
def setup_args(parser, config_files=[], ignore_unknown=False): """Parses arguments.""" global args arglist = sys.argv[1:] # Load arguments from config files for config_file in filter(os.path.isfile, config_files): arglist.insert(0, "@" + config_file) args, unknown = parser.parse_known_...
src/streamlink_cli/main.py
streamlink/streamlink
setup_console
def setup_console(output): global console console = ConsoleOutput(output, streamlink) console.json = args.json signal.signal(signal.SIGTERM, signal.default_int_handler)
Console setup.
def setup_console(output): """Console setup.""" global console # All console related operations is handled via the ConsoleOutput class console = ConsoleOutput(output, streamlink) console.json = args.json # Handle SIGTERM just like SIGINT signal.signal(signal.SIGTERM, signal.default_int_han...
src/streamlink_cli/main.py
streamlink/streamlink
setup_http_session
def setup_http_session(): if args.http_proxy: streamlink.set_option("http-proxy", args.http_proxy) if args.https_proxy: streamlink.set_option("https-proxy", args.https_proxy) if args.http_cookie: streamlink.set_option("http-cookies", dict(args.http_cookie)) if args.http_header...
Sets the global HTTP settings, such as proxy and headers.
def setup_http_session(): """Sets the global HTTP settings, such as proxy and headers.""" if args.http_proxy: streamlink.set_option("http-proxy", args.http_proxy) if args.https_proxy: streamlink.set_option("https-proxy", args.https_proxy) if args.http_cookie: streamlink.set_opt...
src/streamlink_cli/main.py
streamlink/streamlink
setup_plugins
def setup_plugins(extra_plugin_dir=None): if os.path.isdir(PLUGINS_DIR): load_plugins([PLUGINS_DIR]) if extra_plugin_dir: load_plugins(extra_plugin_dir)
Loads any additional plugins.
def setup_plugins(extra_plugin_dir=None): """Loads any additional plugins.""" if os.path.isdir(PLUGINS_DIR): load_plugins([PLUGINS_DIR]) if extra_plugin_dir: load_plugins(extra_plugin_dir)
src/streamlink_cli/main.py
streamlink/streamlink
setup_options
def setup_options(): if args.hls_live_edge: streamlink.set_option("hls-live-edge", args.hls_live_edge) if args.hls_segment_attempts: streamlink.set_option("hls-segment-attempts", args.hls_segment_attempts) if args.hls_playlist_reload_attempts: streamlink.set_option("hls-playlist-re...
Sets Streamlink options.
def setup_options(): """Sets Streamlink options.""" if args.hls_live_edge: streamlink.set_option("hls-live-edge", args.hls_live_edge) if args.hls_segment_attempts: streamlink.set_option("hls-segment-attempts", args.hls_segment_attempts) if args.hls_playlist_reload_attempts: str...
src/streamlink_cli/main.py
streamlink/streamlink
log_current_versions
def log_current_versions(): if logger.root.isEnabledFor(logging.DEBUG): if sys.platform == "darwin": os_version = "macOS {0}".format(platform.mac_ver()[0]) elif sys.platform.startswith("win"): os_version = "{0} {1}".format(platform.system(), platform.release...
Show current installed versions
def log_current_versions(): """Show current installed versions""" if logger.root.isEnabledFor(logging.DEBUG): # MAC OS X if sys.platform == "darwin": os_version = "macOS {0}".format(platform.mac_ver()[0]) # Windows elif sys.platform.startswith("win"): os_v...
src/streamlink_cli/main.py
streamlink/streamlink
Viasat._get_stream_id
def _get_stream_id(self, text): m = self._image_re.search(text) if m: return m.group("stream_id")
Try to find a stream_id
def _get_stream_id(self, text): """Try to find a stream_id""" m = self._image_re.search(text) if m: return m.group("stream_id")
src/streamlink/plugins/viasat.py
streamlink/streamlink
Viasat._get_iframe
def _get_iframe(self, text): m = self._iframe_re.search(text) if m: return self.session.streams(m.group("url"))
Fallback if no stream_id was found before
def _get_iframe(self, text): """Fallback if no stream_id was found before""" m = self._iframe_re.search(text) if m: return self.session.streams(m.group("url"))
src/streamlink/plugins/viasat.py
streamlink/streamlink
Streamlink.set_option
def set_option(self, key, value): if key == "rtmpdump": key = "rtmp-rtmpdump" elif key == "rtmpdump-proxy": key = "rtmp-proxy" elif key == "errorlog": key = "subprocess-errorlog" elif key == "errorlog-path": key = "subprocess-error...
Sets general options used by plugins and streams originating from this session object.
def set_option(self, key, value): """Sets general options used by plugins and streams originating from this session object. :param key: key of the option :param value: value to set the option to **Available options**: ======================== =========================...
src/streamlink/session.py
streamlink/streamlink
Streamlink.set_plugin_option
def set_plugin_option(self, plugin, key, value): if plugin in self.plugins: plugin = self.plugins[plugin] plugin.set_option(key, value)
Sets plugin specific options used by plugins originating from this session object.
def set_plugin_option(self, plugin, key, value): """Sets plugin specific options used by plugins originating from this session object. :param plugin: name of the plugin :param key: key of the option :param value: value to set the option to """ if plugin in self...
src/streamlink/session.py
streamlink/streamlink
Streamlink.resolve_url
def resolve_url(self, url, follow_redirect=True): url = update_scheme("http://", url) available_plugins = [] for name, plugin in self.plugins.items(): if plugin.can_handle_url(url): available_plugins.append(plugin) available_plugins.sort(key=lambda x: x.prio...
Attempts to find a plugin that can use this URL. The default protocol (http) will be prefixed to the URL if not specified.
def resolve_url(self, url, follow_redirect=True): """Attempts to find a plugin that can use this URL. The default protocol (http) will be prefixed to the URL if not specified. Raises :exc:`NoPluginError` on failure. :param url: a URL to match against loaded plugins :pa...
src/streamlink/session.py
streamlink/streamlink
Streamlink.load_plugins
def load_plugins(self, path): for loader, name, ispkg in pkgutil.iter_modules([path]): file, pathname, desc = imp.find_module(name, [path]) module_name = "streamlink.plugin.{0}".format(name) try: self.load_plugin(module_name, file, pathname, desc...
Attempt to load plugins from the path specified.
def load_plugins(self, path): """Attempt to load plugins from the path specified. :param path: full path to a directory where to look for plugins """ for loader, name, ispkg in pkgutil.iter_modules([path]): file, pathname, desc = imp.find_module(name, [path]) # ...
src/streamlink/session.py
streamlink/streamlink
hours_minutes_seconds
def hours_minutes_seconds(value): try: return int(value) except ValueError: pass match = (_hours_minutes_seconds_re.match(value) or _hours_minutes_seconds_2_re.match(value)) if not match: raise ValueError s = 0 s += int(match.group("hours") or "0") * 60 * 6...
converts a timestamp to seconds -
def hours_minutes_seconds(value): """converts a timestamp to seconds - hours:minutes:seconds to seconds - minutes:seconds to seconds - 11h22m33s to seconds - 11h to seconds - 20h15m to seconds - seconds to seconds :param value: hh:mm:ss ; 00h00m00s ; seconds :return: se...
src/streamlink/utils/times.py
streamlink/streamlink
startswith
def startswith(string): def starts_with(value): validate(text, value) if not value.startswith(string): raise ValueError("'{0}' does not start with '{1}'".format(value, string)) return True return starts_with
Checks if the string value starts with another string.
def startswith(string): """Checks if the string value starts with another string.""" def starts_with(value): validate(text, value) if not value.startswith(string): raise ValueError("'{0}' does not start with '{1}'".format(value, string)) return True return starts_with
src/streamlink/plugin/api/validate.py
streamlink/streamlink
endswith
def endswith(string): def ends_with(value): validate(text, value) if not value.endswith(string): raise ValueError("'{0}' does not end with '{1}'".format(value, string)) return True return ends_with
Checks if the string value ends with another string.
def endswith(string): """Checks if the string value ends with another string.""" def ends_with(value): validate(text, value) if not value.endswith(string): raise ValueError("'{0}' does not end with '{1}'".format(value, string)) return True return ends_with
src/streamlink/plugin/api/validate.py
streamlink/streamlink
contains
def contains(string): def contains_str(value): validate(text, value) if string not in value: raise ValueError("'{0}' does not contain '{1}'".format(value, string)) return True return contains_str
Checks if the string value contains another string.
def contains(string): """Checks if the string value contains another string.""" def contains_str(value): validate(text, value) if string not in value: raise ValueError("'{0}' does not contain '{1}'".format(value, string)) return True return contains_str
src/streamlink/plugin/api/validate.py
streamlink/streamlink
getattr
def getattr(attr, default=None): def getter(value): return _getattr(value, attr, default) return transform(getter)
Get a named attribute from an object. When a default argument is given, it is returned when the attribute doesn't exist.
def getattr(attr, default=None): """Get a named attribute from an object. When a default argument is given, it is returned when the attribute doesn't exist. """ def getter(value): return _getattr(value, attr, default) return transform(getter)
src/streamlink/plugin/api/validate.py
streamlink/streamlink
filter
def filter(func): def expand_kv(kv): return func(*kv) def filter_values(value): cls = type(value) if isinstance(value, dict): return cls(_filter(expand_kv, value.items())) else: return cls(_filter(func, value)) return transform(filter_values)
Filters out unwanted items using the specified function. Supports both dicts and sequences, key/value pairs are expanded when applied to a dict.
def filter(func): """Filters out unwanted items using the specified function. Supports both dicts and sequences, key/value pairs are expanded when applied to a dict. """ def expand_kv(kv): return func(*kv) def filter_values(value): cls = type(value) if isinstance(value,...
src/streamlink/plugin/api/validate.py
streamlink/streamlink
map
def map(func): if is_py2 and text == func: func = unicode def expand_kv(kv): return func(*kv) def map_values(value): cls = type(value) if isinstance(value, dict): return cls(_map(expand_kv, value.items())) else: return cls(_map...
Apply function to each value inside the sequence or dict. Supports both dicts and sequences, key/value pairs are expanded when applied to a dict.
def map(func): """Apply function to each value inside the sequence or dict. Supports both dicts and sequences, key/value pairs are expanded when applied to a dict. """ # text is an alias for basestring on Python 2, which cannot be # instantiated and therefore can't be used to transform the valu...
src/streamlink/plugin/api/validate.py
streamlink/streamlink
url
def url(**attributes): def check_url(value): validate(text, value) parsed = urlparse(value) if not parsed.netloc: raise ValueError("'{0}' is not a valid URL".format(value)) for name, schema in attributes.items(): if not _hasattr(parsed, name): ...
Parses an URL and validates its attributes.
def url(**attributes): """Parses an URL and validates its attributes.""" def check_url(value): validate(text, value) parsed = urlparse(value) if not parsed.netloc: raise ValueError("'{0}' is not a valid URL".format(value)) for name, schema in attributes.items(): ...
src/streamlink/plugin/api/validate.py
streamlink/streamlink
xml_find
def xml_find(xpath): def xpath_find(value): validate(ET.iselement, value) value = value.find(xpath) if value is None: raise ValueError("XPath '{0}' did not return an element".format(xpath)) return validate(ET.iselement, value) return transform(xpath_find)
Find a XML element via xpath.
def xml_find(xpath): """Find a XML element via xpath.""" def xpath_find(value): validate(ET.iselement, value) value = value.find(xpath) if value is None: raise ValueError("XPath '{0}' did not return an element".format(xpath)) return validate(ET.iselement, value) ...
src/streamlink/plugin/api/validate.py
streamlink/streamlink
xml_findall
def xml_findall(xpath): def xpath_findall(value): validate(ET.iselement, value) return value.findall(xpath) return transform(xpath_findall)
Find a list of XML elements via xpath.
def xml_findall(xpath): """Find a list of XML elements via xpath.""" def xpath_findall(value): validate(ET.iselement, value) return value.findall(xpath) return transform(xpath_findall)
src/streamlink/plugin/api/validate.py
streamlink/streamlink
_find_player_url
def _find_player_url(response): url = '' matches = _player_re.search(response.text) if matches: tmp_url = matches.group(0).replace('&amp;', '&') if 'hash' not in tmp_url: matches = _hash_re.search(response.text) if matches: url = tmp_url +...
Finds embedded player url in HTTP response.
def _find_player_url(response): """ Finds embedded player url in HTTP response. :param response: Response object. :returns: Player url (str). """ url = '' matches = _player_re.search(response.text) if matches: tmp_url = matches.group(0).replace('&amp;', '&') if 'hash' no...
src/streamlink/plugins/ceskatelevize.py
streamlink/streamlink
load
def load(data, base_uri=None, parser=M3U8Parser, **kwargs): return parser(base_uri, **kwargs).parse(data)
Attempts to parse a M3U8 playlist from a string of data. If specified, *base_uri
def load(data, base_uri=None, parser=M3U8Parser, **kwargs): """Attempts to parse a M3U8 playlist from a string of data. If specified, *base_uri* is the base URI that relative URIs will be joined together with, otherwise relative URIs will be as is. If specified, *parser* can be a M3U8Parser subclass t...
src/streamlink/stream/hls_playlist.py
streamlink/streamlink
PlayerOutput.supported_player
def supported_player(cls, cmd): if not is_win32: cmd = shlex.split(cmd)[0] cmd = os.path.basename(cmd.lower()) for player, possiblecmds in SUPPORTED_PLAYERS.items(): for possiblecmd in possiblecmds: if cmd.startswith(possiblecmd)...
Check if the current player supports adding a title
def supported_player(cls, cmd): """ Check if the current player supports adding a title :param cmd: command to test :return: name of the player|None """ if not is_win32: # under a POSIX system use shlex to find the actual command # under windows t...
src/streamlink_cli/output.py
streamlink/streamlink
SteamBroadcastPlugin.dologin
def dologin(self, email, password, emailauth="", emailsteamid="", captchagid="-1", captcha_text="", twofactorcode=""): epassword, rsatimestamp = self.encrypt_password(email, password) login_data = { 'username': email, "password": epassword, "emailauth": emailauth, ...
Logs in to Steam
def dologin(self, email, password, emailauth="", emailsteamid="", captchagid="-1", captcha_text="", twofactorcode=""): """ Logs in to Steam """ epassword, rsatimestamp = self.encrypt_password(email, password) login_data = { 'username': email, "password":...
src/streamlink/plugins/steam.py
streamlink/streamlink
ABweb._login
def _login(self, username, password): self.logger.debug('login ...') res = self.session.http.get(self.login_url) input_list = self._input_re.findall(res.text) if not input_list: raise PluginError('Missing input data on login website.') data = {} for _input_d...
login and update cached cookies
def _login(self, username, password): '''login and update cached cookies''' self.logger.debug('login ...') res = self.session.http.get(self.login_url) input_list = self._input_re.findall(res.text) if not input_list: raise PluginError('Missing input data on login webs...
src/streamlink/plugins/abweb.py
streamlink/streamlink
CrunchyrollAPI._api_call
def _api_call(self, entrypoint, params=None, schema=None): url = self._api_url.format(entrypoint) params = params or {} if self.session_id: params.update({ "session_id": self.session_id }) else: params.update({ ...
Makes a call against the api.
def _api_call(self, entrypoint, params=None, schema=None): """Makes a call against the api. :param entrypoint: API method to call. :param params: parameters to include in the request data. :param schema: schema to use to validate the data """ url = self._api_url.format(e...
src/streamlink/plugins/crunchyroll.py
streamlink/streamlink
CrunchyrollAPI.start_session
def start_session(self): params = {} if self.auth: params["auth"] = self.auth self.session_id = self._api_call("start_session", params, schema=_session_schema) log.debug("Session created with ID: {0}".format(self.session_id)) return self.session_id
Starts a session against Crunchyroll's server. Is recommended that you call this method before making any other calls to make sure you have a valid session against the server.
def start_session(self): """ Starts a session against Crunchyroll's server. Is recommended that you call this method before making any other calls to make sure you have a valid session against the server. """ params = {} if self.auth: param...
src/streamlink/plugins/crunchyroll.py
streamlink/streamlink
Crunchyroll._create_api
def _create_api(self): if self.options.get("purge_credentials"): self.cache.set("session_id", None, 0) self.cache.set("auth", None, 0) self.cache.set("session_id", None, 0) locale = self.get_option("locale") or self.session.localization.language_code ...
Creates a new CrunchyrollAPI object, initiates it's session and tries to authenticate it either by using saved credentials or the user's username and password.
def _create_api(self): """Creates a new CrunchyrollAPI object, initiates it's session and tries to authenticate it either by using saved credentials or the user's username and password. """ if self.options.get("purge_credentials"): self.cache.set("session_id", None, 0...
src/streamlink/plugins/crunchyroll.py
open-mmlab/mmcv
frames2video
def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True): if end == 0: ext = filename_tmpl.split('.')[-1] end =...
Read the frame images from a directory and join them as a video
def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True): """Read the frame images from a directory and join them as a video ...
mmcv/video/io.py
open-mmlab/mmcv
VideoReader.read
def read(self): if self._cache: img = self._cache.get(self._position) if img is not None: ret = True else: if self._position != self._get_real_position(): self._set_real_position(self._position) ret,...
Read the next frame. If the next frame have been decoded before and in the cache, then return it directly, otherwise decode, cache and return it.
def read(self): """Read the next frame. If the next frame have been decoded before and in the cache, then return it directly, otherwise decode, cache and return it. Returns: ndarray or None: Return the frame if successful, otherwise None. """ # pos = self._p...
mmcv/video/io.py
open-mmlab/mmcv
VideoReader.get_frame
def get_frame(self, frame_id): if frame_id < 0 or frame_id >= self._frame_cnt: raise IndexError( '"frame_id" must be between 0 and {}'.format(self._frame_cnt - 1)) if frame_id == self._position: return s...
Get frame by index.
def get_frame(self, frame_id): """Get frame by index. Args: frame_id (int): Index of the expected frame, 0-based. Returns: ndarray or None: Return the frame if successful, otherwise None. """ if frame_id < 0 or frame_id >= self._frame_cnt: ra...
mmcv/video/io.py
open-mmlab/mmcv
VideoReader.cvt2frames
def cvt2frames(self, frame_dir, file_start=0, filename_tmpl='{:06d}.jpg', start=0, max_num=0, show_progress=True): mkdir_or_exist(frame_dir) if max_num == 0: task_num = self.fram...
Convert a video to frame images
def cvt2frames(self, frame_dir, file_start=0, filename_tmpl='{:06d}.jpg', start=0, max_num=0, show_progress=True): """Convert a video to frame images Args: frame_dir (str): Outp...
mmcv/video/io.py
open-mmlab/mmcv
track_progress
def track_progress(func, tasks, bar_width=50, **kwargs): if isinstance(tasks, tuple): assert len(tasks) == 2 assert isinstance(tasks[0], collections_abc.Iterable) assert isinstance(tasks[1], int) task_num = tasks[1] tasks = tasks[0] elif isinstance(tasks, collections_abc....
Track the progress of tasks execution with a progress bar. Tasks are done with a simple for-loop.
def track_progress(func, tasks, bar_width=50, **kwargs): """Track the progress of tasks execution with a progress bar. Tasks are done with a simple for-loop. Args: func (callable): The function to be applied to each task. tasks (list or tuple[Iterable, int]): A list of tasks or ...
mmcv/utils/progressbar.py
open-mmlab/mmcv
imflip
def imflip(img, direction='horizontal'): assert direction in ['horizontal', 'vertical'] if direction == 'horizontal': return np.flip(img, axis=1) else: return np.flip(img, axis=0)
Flip an image horizontally or vertically.
def imflip(img, direction='horizontal'): """Flip an image horizontally or vertically. Args: img (ndarray): Image to be flipped. direction (str): The flip direction, either "horizontal" or "vertical". Returns: ndarray: The flipped image. """ assert direction in ['horizontal'...
mmcv/image/transforms/geometry.py
open-mmlab/mmcv
imrotate
def imrotate(img, angle, center=None, scale=1.0, border_value=0, auto_bound=False): if center is not None and auto_bound: raise ValueError('`auto_bound` conflicts with `center`') h, w = img.shape[:2] if center is None: center =...
Rotate an image.
def imrotate(img, angle, center=None, scale=1.0, border_value=0, auto_bound=False): """Rotate an image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees, positive values mean clockwise...
mmcv/image/transforms/geometry.py
open-mmlab/mmcv
bbox_clip
def bbox_clip(bboxes, img_shape): assert bboxes.shape[-1] % 4 == 0 clipped_bboxes = np.empty_like(bboxes, dtype=bboxes.dtype) clipped_bboxes[..., 0::2] = np.maximum( np.minimum(bboxes[..., 0::2], img_shape[1] - 1), 0) clipped_bboxes[..., 1::2] = np.maximum( np.minimum(bboxes[..., 1::2], ...
Clip bboxes to fit the image shape.
def bbox_clip(bboxes, img_shape): """Clip bboxes to fit the image shape. Args: bboxes (ndarray): Shape (..., 4*k) img_shape (tuple): (height, width) of the image. Returns: ndarray: Clipped bboxes. """ assert bboxes.shape[-1] % 4 == 0 clipped_bboxes = np.empty_like(bboxe...
mmcv/image/transforms/geometry.py
open-mmlab/mmcv
bbox_scaling
def bbox_scaling(bboxes, scale, clip_shape=None): if float(scale) == 1.0: scaled_bboxes = bboxes.copy() else: w = bboxes[..., 2] - bboxes[..., 0] + 1 h = bboxes[..., 3] - bboxes[..., 1] + 1 dw = (w * (scale - 1)) * 0.5 dh = (h * (scale - 1)) * 0.5 scaled_bboxes = ...
Scaling bboxes w.r.t the box center.
def bbox_scaling(bboxes, scale, clip_shape=None): """Scaling bboxes w.r.t the box center. Args: bboxes (ndarray): Shape(..., 4). scale (float): Scaling factor. clip_shape (tuple, optional): If specified, bboxes that exceed the boundary will be clipped according to the given ...
mmcv/image/transforms/geometry.py
open-mmlab/mmcv
imcrop
def imcrop(img, bboxes, scale=1.0, pad_fill=None): chn = 1 if img.ndim == 2 else img.shape[2] if pad_fill is not None: if isinstance(pad_fill, (int, float)): pad_fill = [pad_fill for _ in range(chn)] assert len(pad_fill) == chn _bboxes = bboxes[None, ...] if bboxes.ndim == 1 els...
Crop image patches. 3
def imcrop(img, bboxes, scale=1.0, pad_fill=None): """Crop image patches. 3 steps: scale the bboxes -> clip bboxes -> crop and pad. Args: img (ndarray): Image to be cropped. bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes. scale (float, optional): Scale ratio of...
mmcv/image/transforms/geometry.py
open-mmlab/mmcv
impad
def impad(img, shape, pad_val=0): if not isinstance(pad_val, (int, float)): assert len(pad_val) == img.shape[-1] if len(shape) < len(img.shape): shape = shape + (img.shape[-1], ) assert len(shape) == len(img.shape) for i in range(len(shape) - 1): assert shape[i] >= img.shape[i] ...
Pad an image to a certain shape.
def impad(img, shape, pad_val=0): """Pad an image to a certain shape. Args: img (ndarray): Image to be padded. shape (tuple): Expected padding shape. pad_val (number or sequence): Values to be filled in padding areas. Returns: ndarray: The padded image. """ if not i...
mmcv/image/transforms/geometry.py
open-mmlab/mmcv
impad_to_multiple
def impad_to_multiple(img, divisor, pad_val=0): pad_h = int(np.ceil(img.shape[0] / divisor)) * divisor pad_w = int(np.ceil(img.shape[1] / divisor)) * divisor return impad(img, (pad_h, pad_w), pad_val)
Pad an image to ensure each edge to be multiple to some number.
def impad_to_multiple(img, divisor, pad_val=0): """Pad an image to ensure each edge to be multiple to some number. Args: img (ndarray): Image to be padded. divisor (int): Padded image edges will be multiple to divisor. pad_val (number or sequence): Same as :func:`impad`. Returns: ...
mmcv/image/transforms/geometry.py
open-mmlab/mmcv
_scale_size
def _scale_size(size, scale): w, h = size return int(w * float(scale) + 0.5), int(h * float(scale) + 0.5)
Rescale a size by a ratio.
def _scale_size(size, scale): """Rescale a size by a ratio. Args: size (tuple): w, h. scale (float): Scaling factor. Returns: tuple[int]: scaled size. """ w, h = size return int(w * float(scale) + 0.5), int(h * float(scale) + 0.5)
mmcv/image/transforms/resize.py
open-mmlab/mmcv
imresize
def imresize(img, size, return_scale=False, interpolation='bilinear'): h, w = img.shape[:2] resized_img = cv2.resize( img, size, interpolation=interp_codes[interpolation]) if not return_scale: return resized_img else: w_scale = size[0] / w h_scale = size[1] / h re...
Resize image to a given size.
def imresize(img, size, return_scale=False, interpolation='bilinear'): """Resize image to a given size. Args: img (ndarray): The input image. size (tuple): Target (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, a...
mmcv/image/transforms/resize.py