_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q267600
WebsiteManagementService.delete_site
test
def delete_site(self, webspace_name, website_name, delete_empty_server_farm=False, delete_metrics=False): ''' Delete a website. webspace_name: The name of the webspace. website_name: The name of the website. delete_empty_server_farm: If the site being deleted is the last web site in a server farm, you can delete the server farm by setting this to True. delete_metrics: To also delete the metrics for the site that you are deleting, you can set this
python
{ "resource": "" }
q267601
WebsiteManagementService.update_site
test
def update_site(self, webspace_name, website_name, state=None): ''' Update a web site. webspace_name: The name of the webspace. website_name: The name of the website. state: The wanted state ('Running' or 'Stopped' accepted)
python
{ "resource": "" }
q267602
WebsiteManagementService.restart_site
test
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. '''
python
{ "resource": "" }
q267603
WebsiteManagementService.get_historical_usage_metrics
test
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 name of the website. metrics: Optional. List of metrics name. Otherwise, all metrics returned. start_time: Optional. An ISO8601 date. Otherwise, current hour is used. end_time: Optional. An ISO8601 date. Otherwise, current time is used. time_grain: Optional. A rollup name, as P1D. OTherwise, default rollup for the metrics is used. More information and metrics name at: http://msdn.microsoft.com/en-us/library/azure/dn166964.aspx '''
python
{ "resource": "" }
q267604
WebsiteManagementService.get_metric_definitions
test
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:
python
{ "resource": "" }
q267605
WebsiteManagementService.get_publish_profile_xml
test
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.
python
{ "resource": "" }
q267606
WebsiteManagementService.get_publish_profile
test
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.
python
{ "resource": "" }
q267607
RegistriesOperations.update_policies
test
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 group to which the container registry belongs. :type resource_group_name: str :param registry_name: The name of the container registry. :type registry_name: str :param quarantine_policy: An object that represents quarantine policy for a container registry. :type quarantine_policy: ~azure.mgmt.containerregistry.v2018_02_01_preview.models.QuarantinePolicy :param trust_policy: An object that represents content trust policy for a container registry. :type trust_policy: ~azure.mgmt.containerregistry.v2018_02_01_preview.models.TrustPolicy :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns RegistryPolicies or ClientRawResponse<RegistryPolicies> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.containerregistry.v2018_02_01_preview.models.RegistryPolicies] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.containerregistry.v2018_02_01_preview.models.RegistryPolicies]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._update_policies_initial( resource_group_name=resource_group_name,
python
{ "resource": "" }
q267608
SchedulerManagementService.create_cloud_service
test
def create_cloud_service(self, cloud_service_id, label, description, geo_region): ''' The Create Cloud Service request creates a new cloud service. When job collections are created, they are hosted within a cloud service. A cloud service groups job collections together in a given region. Once a cloud service has been created, job collections can then be created and contained within it. cloud_service_id: The cloud service id label: The name of the cloud service. description: The description of the cloud service. geo_region:
python
{ "resource": "" }
q267609
SchedulerManagementService.check_job_collection_name
test
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_id:
python
{ "resource": "" }
q267610
SchedulerManagementService.get_job_collection
test
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_none('cloud_service_id', cloud_service_id)
python
{ "resource": "" }
q267611
ManagedDatabasesOperations.complete_restore
test
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. :type location_name: str :param operation_id: Management operation id that this request tries to complete. :type operation_id: str :param last_backup_name: The last backup name to apply :type last_backup_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns None or ClientRawResponse<None> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._complete_restore_initial( location_name=location_name, operation_id=operation_id, last_backup_name=last_backup_name, custom_headers=custom_headers,
python
{ "resource": "" }
q267612
Sender.cancel_scheduled_messages
test
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: .. literalinclude:: ../examples/async_examples/test_examples_async.py :start-after: [START cancel_schedule_messages] :end-before: [END cancel_schedule_messages] :language: python :dedent: 4
python
{ "resource": "" }
q267613
Sender.send_pending_messages
test
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 failed. The second is an error if the message failed, otherwise it will be `None`. :rtype: list[tuple[bool, ~azure.servicebus.common.errors.MessageSendFailed]] Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py :start-after: [START queue_sender_messages] :end-before: [END queue_sender_messages] :language: python :dedent: 4 :caption: Schedule messages. """ if not self.running: await self.open() try:
python
{ "resource": "" }
q267614
Sender.reconnect
test
async def reconnect(self): """Reconnect the handler. If the handler was disconnected from the service with a retryable error - attempt to reconnect. This method will be called automatically for most retryable errors. Also attempts to re-queue any messages that were pending before the reconnect. """ unsent_events = self._handler.pending_messages
python
{ "resource": "" }
q267615
get_certificate_from_publish_settings
test
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 to subscription file downloaded from http://go.microsoft.com/fwlink/?LinkID=301775 path_to_write_certificate: Path to write the certificate file. subscription_id: (optional) Provide a subscription id here if you wish to use a specific subscription under the publish settings file. ''' 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 except: raise Exception("pyopenssl is required to use get_certificate_from_publish_settings") _validate_not_none('publish_settings_path', publish_settings_path) _validate_not_none('path_to_write_certificate', path_to_write_certificate)
python
{ "resource": "" }
q267616
Plugin.load_cookies
test
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 = [] for key, value in self.cache.get_all().items(): if key.startswith("__cookie"): cookie = requests.cookies.create_cookie(**value)
python
{ "resource": "" }
q267617
terminal_width
test
def terminal_width(value): """Returns the width of the string it would be when displayed."""
python
{ "resource": "" }
q267618
get_cut_prefix
test
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
python
{ "resource": "" }
q267619
print_inplace
test
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)
python
{ "resource": "" }
q267620
format_filesize
test
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"):
python
{ "resource": "" }
q267621
format_time
test
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:
python
{ "resource": "" }
q267622
create_status_line
test
def create_status_line(**params): """Creates a status line with appropriate size.""" max_size = get_terminal_size().columns - 1 for fmt in PROGRESS_FORMATS:
python
{ "resource": "" }
q267623
progress
test
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 = (".." + 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 - start written += len(data) speed_elapsed = now - speed_updated if speed_elapsed >= 0.5: speed_history.appendleft(( written - speed_written, speed_updated, )) speed_updated = now speed_written = written speed_history_written =
python
{ "resource": "" }
q267624
SegmentTemplate.segment_numbers
test
def segment_numbers(self): """ yield the segment number and when it will be available There are two cases for segment number generation, static and dynamic. In the case of static stream, the segment number starts at the startNumber and counts up to the number of segments that are represented by the periods duration. In the case of dynamic streams, the segments should appear at the specified time in the simplest case the segment number is based on the time since the availabilityStartTime :return: """ log.debug("Generating segment numbers for {0} playlist (id={1})".format(self.root.type, self.parent.id)) if self.root.type == u"static": available_iter = repeat(epoch_start) duration = self.period.duration.seconds or self.root.mediaPresentationDuration.seconds if duration: number_iter = range(self.startNumber, int(duration / self.duration_seconds) + 1) else: number_iter
python
{ "resource": "" }
q267625
Representation.segments
test
def segments(self, **kwargs): """ Segments are yielded when they are available Segments appear on a time line, for dynamic content they are only available at a certain time and sometimes for a limited time. For static content they are all available at the same time. :param kwargs: extra args to pass to the segment template :return: yields Segments """ segmentBase = self.segmentBase or self.walk_back_get_attr("segmentBase") segmentLists = self.segmentList or self.walk_back_get_attr("segmentList")
python
{ "resource": "" }
q267626
SegmentedStreamWorker.wait
test
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
python
{ "resource": "" }
q267627
SegmentedStreamWriter.put
test
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,
python
{ "resource": "" }
q267628
SegmentedStreamWriter.queue
test
def queue(self, queue_, value): """Puts a value into a queue but aborts if this thread is closed.""" while not
python
{ "resource": "" }
q267629
HDSStream._pv_params
test
def _pv_params(cls, session, pvswf, pv, **request_params): """Returns any parameters needed for Akamai HD player verification. Algorithm originally documented by KSV, source: http://stream-recorder.com/forum/showpost.php?p=43761&postcount=13 """ try: data, hdntl = pv.split(";") except ValueError: data = pv hdntl = "" cache = Cache(filename="stream.json") key = "akamaihd-player:" + pvswf cached = cache.get(key) request_params = deepcopy(request_params) headers = request_params.pop("headers", {}) if cached: headers["If-Modified-Since"] = cached["modified"] swf = session.http.get(pvswf, headers=headers, **request_params) if cached and swf.status_code == 304: # Server says not modified hash = cached["hash"] else: # Calculate SHA-256 hash of the uncompressed SWF file, base-64 # encoded hash = sha256() hash.update(swfdecompress(swf.content)) hash = base64.b64encode(hash.digest()).decode("ascii") modified = swf.headers.get("Last-Modified", "")
python
{ "resource": "" }
q267630
BBCiPlayer._extract_nonce
test
def _extract_nonce(cls, http_result): """ Given an HTTP response from the sessino endpoint, extract the nonce, so we can "sign" requests with it. We don't really sign the requests in the traditional sense of a nonce, we just incude them in the auth requests. :param http_result: HTTP response from the bbc session endpoint. :type http_result: requests.Response :return: nonce to "sign" url requests with :rtype: string """ # Extract the redirect URL from the last call last_redirect_url = urlparse(http_result.history[-1].request.url) last_redirect_query = dict(parse_qsl(last_redirect_url.query))
python
{ "resource": "" }
q267631
BBCiPlayer.find_vpid
test
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
python
{ "resource": "" }
q267632
parse_json
test
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(snippet) > 35: snippet = snippet[:35] + " ..." else: snippet = data
python
{ "resource": "" }
q267633
parse_xml
test
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 in custom exception with a snippet of the data in the message """ 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"[\t ]xmlns=\"(.+?)\"", b"", data) if invalid_char_entities: data = re.sub(br'&(?!(?:#(?:[0-9]+|[Xx][0-9A-Fa-f]+)|[A-Za-z0-9]+);)', b'&amp;', data) try:
python
{ "resource": "" }
q267634
parse_qsd
test
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.
python
{ "resource": "" }
q267635
search_dict
test
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):
python
{ "resource": "" }
q267636
StreamProcess.spawn
test
def spawn(self, parameters=None, arguments=None, stderr=None, timeout=None, short_option_prefix="-", long_option_prefix="--"): """ Spawn the process defined in `cmd` parameters is converted to options the short and long option prefixes if a list is given as the value, the parameter is repeated with each value If timeout is set the spawn will block until the process returns or the timeout expires. :param parameters: optional parameters :param arguments: positional arguments :param stderr: where to redirect stderr to :param timeout: timeout for short lived process :param long_option_prefix: option prefix, default - :param short_option_prefix: long option prefix, default -- :return: spawned process """ stderr = stderr or self.stderr cmd = self.bake(self._check_cmd(), parameters, arguments, short_option_prefix, long_option_prefix) log.debug("Spawning command: {0}", subprocess.list2cmdline(cmd))
python
{ "resource": "" }
q267637
itertags
test
def itertags(html, tag): """ Brute force regex based HTML tag parser. This is a rough-and-ready searcher to find HTML tags when standards compliance is not required. Will find tags that are commented out, or inside script tag etc. :param html: HTML page :param tag: tag name to find :return: generator with Tags """ for
python
{ "resource": "" }
q267638
DASHStream.parse_manifest
test
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 -> DASHStream instances """ 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(urlparse(url)) urlp[2], _ = urlp[2].rsplit("/", 1) mpd = MPD(session.http.xml(res, ignore_ns=True), base_url=urlunparse(urlp), url=url) video, audio = [], [] # Search for suitable video and audio representations for aset in mpd.periods[0].adaptationSets: if aset.contentProtection: raise PluginError("{} is protected by DRM".format(url)) for rep in aset.representations: if rep.mimeType.startswith("video"): video.append(rep) elif rep.mimeType.startswith("audio"): audio.append(rep) if not video: video = [None] if not audio: audio = [None] locale = session.localization locale_lang = locale.language lang = None available_languages = set() # if the locale is explicitly set, prefer that language over others for aud in audio: if aud and aud.lang: available_languages.add(aud.lang) try: if locale.explicit and aud.lang and Language.get(aud.lang) == locale_lang: lang = aud.lang
python
{ "resource": "" }
q267639
HTTPSession.determine_json_encoding
test
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. :param sample: a sample of at least 4 bytes of the JSON text :return: the most likely encoding of the JSON text """ nulls_at = [i for i, j in enumerate(bytearray(sample[:4])) if j == 0] if nulls_at == [0, 1, 2]:
python
{ "resource": "" }
q267640
HTTPSession.json
test
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:
python
{ "resource": "" }
q267641
HTTPSession.xml
test
def xml(cls, res, *args, **kwargs): """Parses XML from a response."""
python
{ "resource": "" }
q267642
HTTPSession.parse_cookies
test
def parse_cookies(self, cookies, **kwargs): """Parses a semi-colon delimited list of cookies.
python
{ "resource": "" }
q267643
HTTPSession.parse_headers
test
def parse_headers(self, headers): """Parses a semi-colon delimited list of headers. Example: foo=bar;baz=qux """
python
{ "resource": "" }
q267644
HTTPSession.parse_query_params
test
def parse_query_params(self, cookies, **kwargs): """Parses a semi-colon delimited list of query parameters.
python
{ "resource": "" }
q267645
_LogRecord.getMessage
test
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any
python
{ "resource": "" }
q267646
StreamlinkLogger.makeRecord
test
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(name, level, fn,
python
{ "resource": "" }
q267647
LiveEdu.login
test
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) token = csrf_match and csrf_match.group(1) self.logger.debug("Attempting login as {0} (token={1})", email, token) res = self.session.http.post(self.login_url, data=dict(login=email, password=password, csrfmiddlewaretoken=token),
python
{ "resource": "" }
q267648
load_support_plugin
test
def load_support_plugin(name): """Loads a plugin from the same directory as the calling plugin. The path used is extracted from the last call in module scope, therefore this must be called only from module level in the originating plugin or the correct plugin path will not be found. """ # Get the path of the caller module stack = list(filter(lambda f: f[3] == "<module>", inspect.stack())) prev_frame = stack[0] path = os.path.dirname(prev_frame[1]) # Major hack.
python
{ "resource": "" }
q267649
update_qsd
test
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 never removed, even if unchanged :return: updated URL """ qsd = qsd or {} remove = remove or [] # parse current query string parsed = urlparse(url) current_qsd = OrderedDict(parse_qsl(parsed.query)) # * removes all possible keys if remove == "*": remove = list(current_qsd.keys()) # remove keys
python
{ "resource": "" }
q267650
FLVTagConcat.iter_chunks
test
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_written: analyzed_tags = self.analyze_tags(tag_iterator) else: analyzed_tags = [] for tag in chain(analyzed_tags, tag_iterator): if not self.flv_header_written: flv_header = Header(has_video=self.has_video, has_audio=self.has_audio) yield flv_header.serialize() self.flv_header_written = True if self.verify_tag(tag): self.adjust_tag_gap(tag) self.adjust_tag_timestamp(tag)
python
{ "resource": "" }
q267651
Arguments.requires
test
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: required = self.get(reqname) if not required: raise KeyError("{0} is not a valid argument for this plugin".format(reqname)) if required.name in results:
python
{ "resource": "" }
q267652
check_file_output
test
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! Overwrite it? [y/N] ", filename) if answer.lower() != "y":
python
{ "resource": "" }
q267653
create_output
test
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.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_file_output(args.output, args.force) elif args.stdout: out = FileOutput(fd=stdout) elif args.record_and_pipe: record = check_file_output(args.record_and_pipe, args.force) out = FileOutput(fd=stdout, record=record) else: http = namedpipe = record = None if not args.player: console.exit("The default player (VLC) does not seem to be " "installed. You must specify the path to a player " "executable with --player.") if args.player_fifo: pipename = "streamlinkpipe-{0}".format(os.getpid())
python
{ "resource": "" }
q267654
create_http_server
test
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 =
python
{ "resource": "" }
q267655
iter_http_requests
test
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.
python
{ "resource": "" }
q267656
output_stream_http
test
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 the path to a player " "executable with --player.") title = create_title(plugin) server = create_http_server() player = output = PlayerOutput(args.player, args=args.player_args, filename=server.url, quiet=not args.verbose_player, title=title) try: log.info("Starting player: {0}", args.player) if player: player.open() except OSError as err: console.exit("Failed to start player: {0} ({1})", args.player, err) else: server = create_http_server(host=None, port=port) player = None
python
{ "resource": "" }
q267657
output_stream_passthrough
test
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, call=True, quiet=not args.verbose_player,
python
{ "resource": "" }
q267658
open_stream
test
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 StreamError("Could not open stream: {0}".format(err)) # Read 8192 bytes before proceeding to check for errors. # This is to avoid opening the output unnecessarily. try:
python
{ "resource": "" }
q267659
output_stream
test
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 except StreamError as err: log.error("Try {0}/{1}: Could not open stream {2} ({3})", i + 1, args.retry_open, stream, err) if not success_open: console.exit("Could not open stream {0}, tried {1} times, exiting", stream, args.retry_open) output = create_output(plugin) try: output.open() except (IOError, OSError) as err: if isinstance(output, PlayerOutput):
python
{ "resource": "" }
q267660
read_stream
test
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) and output.fd is not stdout and sys.stdout.isatty() show_record_progress = hasattr(output, "record") and isinstance(output.record, FileOutput) and output.record.fd is not stdout and sys.stdout.isatty() stream_iterator = chain( [prebuffer], iter(partial(stream.read, chunk_size), b"") ) if show_progress: stream_iterator = progress(stream_iterator, prefix=os.path.basename(args.output)) elif show_record_progress: stream_iterator = progress(stream_iterator, prefix=os.path.basename(args.record)) try: for data in stream_iterator: # We need to check if the player process still exists when # using named pipes on Windows since the named pipe is not # automatically closed by the player. if is_win32 and
python
{ "resource": "" }
q267661
handle_stream
test
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 """ stream_name = resolve_stream_name(streams, stream_name) stream = streams[stream_name] # Print internal command-line if this stream # uses a subprocess. if args.subprocess_cmdline: if isinstance(stream, StreamProcess): try: cmdline = stream.cmdline() except StreamError as err: console.exit("{0}", err) console.msg("{0}", cmdline) else: console.exit("The stream specified cannot be translated to a command") # Print JSON representation of the stream elif console.json: console.msg_json(stream) elif args.stream_url: try: console.msg("{0}", stream.to_url()) except TypeError: console.exit("The stream specified cannot be translated to a URL") # Output the stream else: # Find any streams with a '_alt' suffix and attempt # to use these in case the main stream is not usable. alt_streams = list(filter(lambda k: stream_name + "_alt" in k,
python
{ "resource": "" }
q267662
fetch_streams
test
def fetch_streams(plugin): """Fetches streams using correct parameters.""" return plugin.streams(stream_types=args.stream_types,
python
{ "resource": "" }
q267663
fetch_streams_with_retry
test
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("Waiting for streams, retrying every {0} " "second(s)", interval) attempts = 0 while not streams: sleep(interval) try: streams =
python
{ "resource": "" }
q267664
resolve_stream_name
test
def resolve_stream_name(streams, stream_name): """Returns the real stream name of a synonym.""" if stream_name in STREAM_SYNONYMS and stream_name
python
{ "resource": "" }
q267665
format_valid_streams
test
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, stream in sorted(streams.items(), key=lambda stream: plugin.stream_weight(stream[0])): if name in STREAM_SYNONYMS: continue def synonymfilter(n):
python
{ "resource": "" }
q267666
handle_url
test
def handle_url(): """The URL handler. Attempts to resolve the URL to a plugin and then attempts to fetch a list of available streams. Proceeds to handle stream if user specified a valid one, otherwise output list of valid streams. """ try: plugin = streamlink.resolve_url(args.url) setup_plugin_options(streamlink, plugin) log.info("Found matching plugin {0} for URL {1}", plugin.module, args.url) plugin_args = [] for parg in plugin.arguments: value = plugin.get_option(parg.dest) if value: plugin_args.append((parg, value)) if plugin_args: log.debug("Plugin specific arguments:") for parg, value in plugin_args: log.debug(" {0}={1} ({2})".format(parg.argument_name(plugin.module), value if not parg.sensitive else ("*" * 8), parg.dest)) if args.retry_max or args.retry_streams: retry_streams = 1 retry_max = 0 if args.retry_streams:
python
{ "resource": "" }
q267667
print_plugins
test
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:
python
{ "resource": "" }
q267668
authenticate_twitch_oauth
test
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" "?response_type=token" "&client_id={0}"
python
{ "resource": "" }
q267669
load_plugins
test
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:
python
{ "resource": "" }
q267670
setup_args
test
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_args(arglist) if unknown and not ignore_unknown: msg = gettext('unrecognized arguments: %s')
python
{ "resource": "" }
q267671
setup_console
test
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
python
{ "resource": "" }
q267672
setup_http_session
test
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_option("http-cookies", dict(args.http_cookie)) if args.http_header: streamlink.set_option("http-headers", dict(args.http_header)) if args.http_query_param: streamlink.set_option("http-query-params", dict(args.http_query_param)) if args.http_ignore_env: streamlink.set_option("http-trust-env", False) if args.http_no_ssl_verify: streamlink.set_option("http-ssl-verify", False) if args.http_disable_dh: streamlink.set_option("http-disable-dh", True) if args.http_ssl_cert: streamlink.set_option("http-ssl-cert", args.http_ssl_cert)
python
{ "resource": "" }
q267673
setup_plugins
test
def setup_plugins(extra_plugin_dir=None): """Loads any additional plugins.""" if os.path.isdir(PLUGINS_DIR):
python
{ "resource": "" }
q267674
setup_options
test
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: streamlink.set_option("hls-playlist-reload-attempts", args.hls_playlist_reload_attempts) if args.hls_segment_threads: streamlink.set_option("hls-segment-threads", args.hls_segment_threads) if args.hls_segment_timeout: streamlink.set_option("hls-segment-timeout", args.hls_segment_timeout) if args.hls_segment_ignore_names: streamlink.set_option("hls-segment-ignore-names", args.hls_segment_ignore_names) if args.hls_segment_key_uri: streamlink.set_option("hls-segment-key-uri", args.hls_segment_key_uri) if args.hls_timeout: streamlink.set_option("hls-timeout", args.hls_timeout) if args.hls_audio_select: streamlink.set_option("hls-audio-select", args.hls_audio_select) if args.hls_start_offset: streamlink.set_option("hls-start-offset", args.hls_start_offset) if args.hls_duration: streamlink.set_option("hls-duration", args.hls_duration) if args.hls_live_restart: streamlink.set_option("hls-live-restart", args.hls_live_restart) if args.hds_live_edge: streamlink.set_option("hds-live-edge", args.hds_live_edge) if args.hds_segment_attempts: streamlink.set_option("hds-segment-attempts", args.hds_segment_attempts) if args.hds_segment_threads: streamlink.set_option("hds-segment-threads", args.hds_segment_threads) if args.hds_segment_timeout: streamlink.set_option("hds-segment-timeout", args.hds_segment_timeout) if args.hds_timeout: streamlink.set_option("hds-timeout", args.hds_timeout) if args.http_stream_timeout: streamlink.set_option("http-stream-timeout", args.http_stream_timeout) if args.ringbuffer_size: streamlink.set_option("ringbuffer-size", args.ringbuffer_size) if args.rtmp_proxy: streamlink.set_option("rtmp-proxy", args.rtmp_proxy) if args.rtmp_rtmpdump: streamlink.set_option("rtmp-rtmpdump", args.rtmp_rtmpdump) if args.rtmp_timeout:
python
{ "resource": "" }
q267675
log_current_versions
test
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_version = "{0} {1}".format(platform.system(), platform.release())
python
{ "resource": "" }
q267676
Viasat._get_stream_id
test
def _get_stream_id(self, text): """Try to find a stream_id"""
python
{ "resource": "" }
q267677
Viasat._get_iframe
test
def _get_iframe(self, text): """Fallback if no stream_id was found before""" m = self._iframe_re.search(text)
python
{ "resource": "" }
q267678
Streamlink.set_option
test
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**: ======================== ========================================= hds-live-edge ( float) Specify the time live HDS streams will start from the edge of stream, default: ``10.0`` hds-segment-attempts (int) How many attempts should be done to download each HDS segment, default: ``3`` hds-segment-threads (int) The size of the thread pool used to download segments, default: ``1`` hds-segment-timeout (float) HDS segment connect and read timeout, default: ``10.0`` hds-timeout (float) Timeout for reading data from HDS streams, default: ``60.0`` hls-live-edge (int) How many segments from the end to start live streams on, default: ``3`` hls-segment-attempts (int) How many attempts should be done to download each HLS segment, default: ``3`` hls-segment-threads (int) The size of the thread pool used to download segments, default: ``1`` hls-segment-timeout (float) HLS segment connect and read timeout, default: ``10.0`` hls-timeout (float) Timeout for reading data from HLS streams, default: ``60.0`` http-proxy (str) Specify a HTTP proxy to use for all HTTP requests https-proxy (str) Specify a HTTPS proxy to use for all HTTPS requests http-cookies (dict or str) A dict or a semi-colon (;) delimited str of cookies to add to each HTTP request, e.g. ``foo=bar;baz=qux`` http-headers (dict or str) A dict or semi-colon (;) delimited str of headers to add to each HTTP request, e.g. ``foo=bar;baz=qux`` http-query-params (dict or str) A dict or a ampersand (&) delimited string of query parameters to add to each HTTP request, e.g. ``foo=bar&baz=qux`` http-trust-env (bool) Trust HTTP settings set in the environment, such as environment variables (HTTP_PROXY, etc) and ~/.netrc authentication http-ssl-verify (bool) Verify SSL certificates, default: ``True`` http-ssl-cert (str or tuple) SSL certificate to use, can be either a .pem file (str) or a .crt/.key pair (tuple) http-timeout (float) General timeout used by all HTTP requests except the ones covered by other options, default: ``20.0`` http-stream-timeout (float) Timeout for reading data from HTTP streams, default: ``60.0`` subprocess-errorlog (bool) Log errors from subprocesses to a file located in the temp directory subprocess-errorlog-path (str) Log errors from subprocesses to a specific file ringbuffer-size (int) The size of the internal ring buffer used by most stream types, default: ``16777216`` (16MB) rtmp-proxy (str) Specify a proxy (SOCKS) that RTMP streams will use rtmp-rtmpdump (str) Specify the location of the rtmpdump executable used by RTMP streams, e.g. ``/usr/local/bin/rtmpdump`` rtmp-timeout (float) Timeout for reading data from RTMP streams, default: ``60.0`` ffmpeg-ffmpeg (str) Specify the location of the ffmpeg executable use by Muxing streams e.g. ``/usr/local/bin/ffmpeg`` ffmpeg-verbose (bool) Log stderr from ffmpeg to the console ffmpeg-verbose-path (str) Specify the location of the ffmpeg stderr log file ffmpeg-video-transcode (str) The codec to use if transcoding video when muxing with ffmpeg e.g. ``h264`` ffmpeg-audio-transcode (str) The codec to use if transcoding audio when muxing with ffmpeg e.g. ``aac`` stream-segment-attempts (int) How many attempts should be done to download each segment, default: ``3``. General option used by streams not covered by other options. stream-segment-threads (int) The size of the thread pool used to download segments, default: ``1``. General option used by streams not covered by other options. stream-segment-timeout (float)
python
{ "resource": "" }
q267679
Streamlink.get_option
test
def get_option(self, key): """Returns current value of specified option. :param key: key of the option """ # Backwards compatibility if key == "rtmpdump": key = "rtmp-rtmpdump" elif key == "rtmpdump-proxy": key = "rtmp-proxy" elif key == "errorlog": key = "subprocess-errorlog" if key == "http-proxy": return self.http.proxies.get("http") elif key == "https-proxy": return self.http.proxies.get("https") elif key == "http-cookies": return self.http.cookies elif key == "http-headers":
python
{ "resource": "" }
q267680
Streamlink.set_plugin_option
test
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
python
{ "resource": "" }
q267681
Streamlink.get_plugin_option
test
def get_plugin_option(self, plugin, key): """Returns current value of plugin specific option. :param plugin: name of the plugin :param key: key of the option """
python
{ "resource": "" }
q267682
Streamlink.resolve_url
test
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 :param follow_redirect: follow redirects """ 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.priority(url), reverse=True) if available_plugins: return available_plugins[0](url) if follow_redirect:
python
{ "resource": "" }
q267683
Streamlink.load_plugins
test
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])
python
{ "resource": "" }
q267684
hours_minutes_seconds
test
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
python
{ "resource": "" }
q267685
startswith
test
def startswith(string): """Checks if the string value starts with another string.""" def starts_with(value): validate(text, value) if not value.startswith(string):
python
{ "resource": "" }
q267686
endswith
test
def endswith(string): """Checks if the string value ends with another string.""" def ends_with(value): validate(text, value) if not value.endswith(string):
python
{ "resource": "" }
q267687
contains
test
def contains(string): """Checks if the string value contains another string.""" def contains_str(value): validate(text, value) if string not in value:
python
{ "resource": "" }
q267688
getattr
test
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. """
python
{ "resource": "" }
q267689
filter
test
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)
python
{ "resource": "" }
q267690
map
test
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 value, # so we force to unicode instead. if is_py2 and text == func:
python
{ "resource": "" }
q267691
url
test
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(): if not _hasattr(parsed, name): raise ValueError("Invalid URL attribute '{0}'".format(name)) try: validate(schema, _getattr(parsed, name)) except ValueError as err: raise ValueError(
python
{ "resource": "" }
q267692
xml_find
test
def xml_find(xpath): """Find a XML element via xpath.""" def xpath_find(value): validate(ET.iselement, value) value = value.find(xpath)
python
{ "resource": "" }
q267693
xml_findall
test
def xml_findall(xpath): """Find a list of XML elements via xpath.""" def xpath_findall(value): validate(ET.iselement, value)
python
{ "resource": "" }
q267694
_find_player_url
test
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' not in tmp_url: #
python
{ "resource": "" }
q267695
load
test
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
python
{ "resource": "" }
q267696
PlayerOutput.supported_player
test
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 this is not an issue because executables end in .exe
python
{ "resource": "" }
q267697
SteamBroadcastPlugin.dologin
test
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": epassword, "emailauth": emailauth, "loginfriendlyname": "Streamlink", "captchagid": captchagid, "captcha_text": captcha_text, "emailsteamid": emailsteamid, "rsatimestamp": rsatimestamp, "remember_login": True, "donotcache": self.donotcache, "twofactorcode": twofactorcode } res = self.session.http.post(self._dologin_url, data=login_data) resp = self.session.http.json(res, schema=self._dologin_schema) if not resp[u"success"]: if resp.get(u"captcha_needed"): # special case for captcha captchagid = resp[u"captcha_gid"] log.error("Captcha result required, open this URL to see the captcha: {}".format( self._captcha_url.format(captchagid))) try: captcha_text = self.input_ask("Captcha text") except FatalPluginError: captcha_text = None if not captcha_text: return False else: # If the user must enter the code that was emailed to them if resp.get(u"emailauth_needed"): if not emailauth: try: emailauth = self.input_ask("Email auth code required") except FatalPluginError:
python
{ "resource": "" }
q267698
Huomao.get_stream_id
test
def get_stream_id(self, html): """Returns the stream_id contained in the HTML.""" stream_id = stream_id_pattern.search(html) if not stream_id:
python
{ "resource": "" }
q267699
Huomao.get_stream_info
test
def get_stream_info(self, html): """ Returns a nested list of different stream options. Each entry in the list will contain a stream_url and stream_quality_name for each stream occurrence that was found in the JS. """ stream_info = stream_info_pattern.findall(html)
python
{ "resource": "" }