_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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 to True.
'''
path = self._get_sites_details_path(webspace_name, website_name)
query = ''
if delete_empty_server_farm:
query += '&deleteEmptyServerFarm=true'
if delete_metrics:
query += '&deleteMetrics=true'
if query:
path = path + '?' + query.lstrip('&')
return self._perform_delete(path) | 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)
'''
xml = _XmlSerializer.update_website_to_xml(state)
return self._perform_put(
self._get_sites_details_path(webspace_name, website_name),
xml, as_async=True) | 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.
'''
return self._perform_post(
self._get_restart_path(webspace_name, website_name),
None, as_async=True) | 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
'''
metrics = ('names='+','.join(metrics)) if metrics else ''
start_time = ('StartTime='+start_time) if start_time else ''
end_time = ('EndTime='+end_time) if end_time else ''
time_grain = ('TimeGrain='+time_grain) if time_grain else ''
parameters = ('&'.join(v for v in (metrics, start_time, end_time, time_grain) if v))
parameters = '?'+parameters if parameters else ''
return self._perform_get(self._get_historical_usage_metrics_path(webspace_name, website_name) + parameters,
MetricResponses) | 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:
The name of the website.
'''
return self._perform_get(self._get_metric_definitions_path(webspace_name, website_name),
MetricDefinitions) | 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.
'''
return self._perform_get(self._get_publishxml_path(webspace_name, website_name),
None).body.decode("utf-8") | 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.
'''
return self._perform_get(self._get_publishxml_path(webspace_name, website_name),
PublishData) | 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,
registry_name=registry_name,
quarantine_policy=quarantine_policy,
trust_policy=trust_policy,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
deserialized = self._deserialize('RegistryPolicies', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | 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:
The geographical region of the webspace that will be created.
'''
_validate_not_none('cloud_service_id', cloud_service_id)
_validate_not_none('label', label)
_validate_not_none('description', description)
_validate_not_none('geo_region', geo_region)
path = self._get_cloud_services_path(cloud_service_id)
body = _SchedulerManagementXmlSerializer.create_cloud_service_to_xml(
label, description, geo_region)
return self._perform_put(path, body, as_async=True) | 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:
The cloud service id
job_collection_id:
The name of the 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")
path += "?op=checknameavailability&resourceName=" + job_collection_id
return self._perform_post(path, None, AvailabilityResponse) | 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)
_validate_not_none('job_collection_id', job_collection_id)
path = self._get_job_collection_path(
cloud_service_id, job_collection_id)
return self._perform_get(path, Resource) | 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,
raw=True,
**operation_config
)
def get_long_running_output(response):
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method) | 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
:caption: Schedule messages.
"""
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(
REQUEST_RESPONSE_CANCEL_SCHEDULED_MESSAGE_OPERATION,
request_body,
mgmt_handlers.default) | 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:
pending = self._handler._pending_messages[:] # pylint: disable=protected-access
await self._handler.wait_async()
results = []
for m in pending:
if m.state == constants.MessageState.SendFailed:
results.append((False, MessageSendFailed(m._response))) # pylint: disable=protected-access
else:
results.append((True, None))
return results
except Exception as e: # pylint: disable=broad-except
raise MessageSendFailed(e) | 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
await super(Sender, self).reconnect()
try:
self._handler.queue_message(*unsent_events)
await self._handler.wait_async()
except Exception as e: # pylint: disable=broad-except
await self._handle_exception(e) | 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)
# parse the publishsettings file and find the ManagementCertificate Entry
tree = ET.parse(publish_settings_path)
subscriptions = tree.getroot().findall("./PublishProfile/Subscription")
# Default to the first subscription in the file if they don't specify
# or get the matching subscription or return none.
if subscription_id:
subscription = next((s for s in subscriptions if s.get('Id').lower() == subscription_id.lower()), None)
else:
subscription = subscriptions[0]
# validate that subscription was found
if subscription is None:
raise ValueError("The provided subscription_id '{}' was not found in the publish settings file provided at '{}'".format(subscription_id, publish_settings_path))
cert_string = _decode_base64_to_bytes(subscription.get('ManagementCertificate'))
# Load the string in pkcs12 format. Don't provide a password as it isn't encrypted.
cert = crypto.load_pkcs12(cert_string, b'')
# Write the data out as a PEM format to a random location in temp for use under this run.
with open(path_to_write_certificate, 'wb') as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert.get_certificate()))
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, cert.get_privatekey()))
return subscription.get('Id') | 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)
self.session.http.cookies.set_cookie(cookie)
restored.append(cookie.name)
if restored:
self.logger.debug("Restored cookies: {0}".format(", ".join(restored)))
return restored | python | {
"resource": ""
} |
q267617 | terminal_width | test | def terminal_width(value):
"""Returns the width of the string it would be when displayed."""
if isinstance(value, bytes):
value = value.decode("utf8", "ignore")
return sum(map(get_width, map(ord, value))) | 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 in range(len(value)):
if terminal_width(value[i:]) <= max_len:
break
return value[i:].encode("utf8", "ignore") if should_convert else value[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)
# On windows we need one less space or we overflow the line for some reason.
if is_win32:
spacing -= 1
sys.stderr.write("\r{0}".format(msg))
sys.stderr.write(" " * max(0, spacing))
sys.stderr.flush() | 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"):
return "{0:3.2f} {1}".format(size, suffix)
else:
return "{0:3.1f} {1}".format(size, suffix)
size /= 1024.0 | 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:
rval += "{0}h".format(hours)
if elapsed > 60:
rval += "{0}m".format(minutes)
rval += "{0}s".format(seconds)
return rval | 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:
status = fmt.format(**params)
if len(status) <= max_size:
break
return status | 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 = sum(h[0] for h in speed_history)
speed_history_elapsed = now - speed_history[-1][1]
speed = speed_history_written / speed_history_elapsed
status = create_status_line(
prefix=prefix,
written=format_filesize(written),
elapsed=format_time(elapsed),
speed=format_filesize(speed)
)
print_inplace(status)
sys.stderr.write("\n")
sys.stderr.flush() | 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 = count(self.startNumber)
else:
now = datetime.datetime.now(utc)
if self.presentationTimeOffset:
since_start = (now - self.presentationTimeOffset) - self.root.availabilityStartTime
available_start_date = self.root.availabilityStartTime + self.presentationTimeOffset + since_start
available_start = available_start_date
else:
since_start = now - self.root.availabilityStartTime
available_start = now
# if there is no delay, use a delay of 3 seconds
suggested_delay = datetime.timedelta(seconds=(self.root.suggestedPresentationDelay.total_seconds()
if self.root.suggestedPresentationDelay
else 3))
# the number of the segment that is available at NOW - SUGGESTED_DELAY - BUFFER_TIME
number_iter = count(self.startNumber +
int((since_start - suggested_delay - self.root.minBufferTime).total_seconds() /
self.duration_seconds))
# the time the segment number is available at NOW
available_iter = count_dt(available_start,
step=datetime.timedelta(seconds=self.duration_seconds))
for number, available_at in izip(number_iter, available_iter):
yield number, available_at | 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")
segmentTemplate = self.segmentTemplate or self.walk_back_get_attr("segmentTemplate")
if segmentTemplate:
for segment in segmentTemplate.segments(RepresentationID=self.id,
Bandwidth=int(self.bandwidth * 1000),
**kwargs):
if segment.init:
yield segment
else:
yield segment
elif segmentLists:
for segmentList in segmentLists:
for segment in segmentList.segments:
yield segment
else:
yield Segment(self.base_url, 0, True, True) | 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 normally.
"""
self._wait = Event()
return not self._wait.wait(time) | 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,
retries=self.retries)
else:
future = None
self.queue(self.futures, (segment, future)) | 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 self.closed:
try:
queue_.put(value, block=True, timeout=1)
return
except queue.Full:
continue | 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", "")
# Only save in cache if a valid date is given
if len(modified) < 40:
cache.set(key, dict(hash=hash, modified=modified))
msg = "st=0~exp=9999999999~acl=*~data={0}!{1}".format(data, hash)
auth = hmac.new(AKAMAIHD_PV_KEY, msg.encode("ascii"), sha256)
pvtoken = "{0}~hmac={1}".format(msg, auth.hexdigest())
# The "hdntl" parameter can be accepted as a cookie or passed in the
# query string, but the "pvtoken" parameter can only be in the query
# string
params = [("pvtoken", pvtoken)]
params.extend(parse_qsl(hdntl, keep_blank_values=True))
return params | 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))
# Extract the nonce from the query string in the redirect URL
final_url = urlparse(last_redirect_query['goto'])
goto_url = dict(parse_qsl(final_url.query))
goto_url_query = parse_json(goto_url['state'])
# Return the nonce we can use for future queries
return goto_url_query['nonce'] | 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
:type res: requests.Response
:return: Video Packet ID for a Programme in iPlayer
:rtype: string
"""
log.debug("Looking for vpid on {0}", url)
# Use pre-fetched page if available
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 | 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
raise exception("Unable to parse {0}: {1} ({2})".format(name, err, snippet))
if schema:
json_data = schema.validate(json_data, name=name, exception=exception)
return json_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'&', data)
try:
tree = ET.fromstring(data)
except Exception as err:
snippet = repr(data)
if len(snippet) > 35:
snippet = snippet[:35] + " ..."
raise exception("Unable to parse {0}: {1} ({2})".format(name, err, snippet))
if schema:
tree = schema.validate(tree, name=name, exception=exception)
return tree | 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.
"""
value = dict(parse_qsl(data, **params))
if schema:
value = schema.validate(value, name=name, exception=exception)
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):
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 in search_dict(value, key):
yield result | 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))
try:
process = subprocess.Popen(cmd, stderr=stderr, stdout=subprocess.PIPE)
except (OSError, IOError) as err:
raise StreamError("Failed to start process: {0} ({1})".format(self._check_cmd(), str(err)))
if timeout:
elapsed = 0
while elapsed < timeout and not process.poll():
time.sleep(0.25)
elapsed += 0.25
# kill after the timeout has expired and the process still hasn't ended
if not process.poll():
try:
log.debug("Process timeout expired ({0}s), killing process".format(timeout))
process.kill()
except Exception:
pass
process.wait()
return process | 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 match in tag_re.finditer(html):
if match.group("tag") == tag:
attrs = dict((a.group("key").lower(), a.group("value")) for a in attr_re.finditer(match.group("attr")))
yield Tag(match.group("tag"), attrs, match.group("inner")) | 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
except LookupError:
continue
if not lang:
# filter by the first language that appears
lang = audio[0] and audio[0].lang
log.debug("Available languages for DASH audio streams: {0} (using: {1})".format(", ".join(available_languages) or "NONE", lang or "n/a"))
# if the language is given by the stream, filter out other languages that do not match
if len(available_languages) > 1:
audio = list(filter(lambda a: a.lang is None or a.lang == lang, audio))
for vid, aud in itertools.product(video, audio):
stream = DASHStream(session, mpd, vid, aud, **args)
stream_name = []
if vid:
stream_name.append("{:0.0f}{}".format(vid.height or vid.bandwidth_rounded, "p" if vid.height else "k"))
if audio and len(audio) > 1:
stream_name.append("a{:0.0f}k".format(aud.bandwidth))
ret['+'.join(stream_name)] = stream
return ret | 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]:
return "UTF-32BE"
elif nulls_at == [0, 2]:
return "UTF-16BE"
elif nulls_at == [1, 2, 3]:
return "UTF-32LE"
elif nulls_at == [1, 3]:
return "UTF-16LE"
else:
return "UTF-8" | 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:
res.encoding = cls.determine_json_encoding(res.content[:4])
return parse_json(res.text, *args, **kwargs) | python | {
"resource": ""
} |
q267641 | HTTPSession.xml | test | def xml(cls, res, *args, **kwargs):
"""Parses XML from a response."""
return parse_xml(res.text, *args, **kwargs) | python | {
"resource": ""
} |
q267642 | HTTPSession.parse_cookies | test | 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) | 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
"""
for name, value in _parse_keyvalue_list(headers):
self.headers[name] = value | python | {
"resource": ""
} |
q267644 | HTTPSession.parse_query_params | test | 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 | python | {
"resource": ""
} |
q267645 | _LogRecord.getMessage | test | 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_encode(msg) | 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, lno, msg, args, exc_info, func, sinfo)
else:
rv = _CompatLogRecord(name, level, fn, lno, msg, args, exc_info, func, sinfo)
if extra is not None:
for key in extra:
if (key in ["message", "asctime"]) or (key in rv.__dict__):
raise KeyError("Attempt to overwrite %r in LogRecord" % key)
rv.__dict__[key] = extra[key]
return rv | 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),
allow_redirects=False,
raise_for_status=False,
headers={"Referer": self.login_url})
if res.status_code != 302:
self.logger.error("Failed to login to LiveEdu account: {0}", email) | 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. If we are frozen by bbfreeze the stack trace will
# contain relative paths. We therefore use the __file__ variable
# in this module to correct it.
if not os.path.isabs(path):
prefix = os.path.normpath(__file__ + "../../../../../")
path = os.path.join(prefix, path)
return load_module(name, path) | 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 before updating, but leave updated keys untouched
for key in remove:
if key not in qsd:
del current_qsd[key]
# and update the query string
for key, value in qsd.items():
if value:
current_qsd[key] = value
return parsed._replace(query=urlencode(current_qsd)).geturl() | 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)
if self.duration:
norm_timestamp = tag.timestamp / 1000
if norm_timestamp > self.duration:
break
yield tag.serialize()
timestamps[tag.type] = tag.timestamp
if not self.flatten_timestamps:
self.timestamps_add = timestamps
self.tags = [] | 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:
raise RuntimeError("cycle detected in plugin argument config")
results.add(required.name)
yield required
for r in self.requires(required.name):
if r.name in results:
raise RuntimeError("cycle detected in plugin argument config")
results.add(r.name)
yield r | 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":
sys.exit()
else:
log.error("File {0} already exists, use --force to overwrite it.".format(filename))
sys.exit()
return FileOutput(filename) | 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())
log.info("Creating pipe {0}", pipename)
try:
namedpipe = NamedPipe(pipename)
except IOError as err:
console.exit("Failed to create pipe: {0}", err)
elif args.player_http:
http = create_http_server()
title = create_title(plugin)
if args.record:
record = check_file_output(args.record, args.force)
log.info("Starting player: {0}", args.player)
out = PlayerOutput(args.player, args=args.player_args,
quiet=not args.verbose_player,
kill=not args.player_no_close,
namedpipe=namedpipe, http=http,
record=record, title=title)
return out | 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 = HTTPServer()
http.bind(host=host, port=port)
except OSError as err:
console.exit("Failed to create HTTP server: {0}", err)
return 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.
"""
while not player or player.running:
try:
yield server.open(timeout=2.5)
except OSError:
continue | 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
log.info("Starting server, access with one of:")
for url in server.urls:
log.info(" " + url)
for req in iter_http_requests(server, player):
user_agent = req.headers.get("User-Agent") or "unknown player"
log.info("Got HTTP request from {0}".format(user_agent))
stream_fd = prebuffer = None
while not stream_fd and (not player or player.running):
try:
streams = initial_streams or fetch_streams(plugin)
initial_streams = None
for stream_name in (resolve_stream_name(streams, s) for s in args.stream):
if stream_name in streams:
stream = streams[stream_name]
break
else:
log.info("Stream not available, will re-fetch "
"streams in 10 sec")
sleep(10)
continue
except PluginError as err:
log.error(u"Unable to fetch new streams: {0}", err)
continue
try:
log.info("Opening stream: {0} ({1})", stream_name,
type(stream).shortname())
stream_fd, prebuffer = open_stream(stream)
except StreamError as err:
log.error("{0}", err)
if stream_fd and prebuffer:
log.debug("Writing stream to player")
read_stream(stream_fd, server, prebuffer)
server.close(True)
player.close()
server.close() | 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,
title=title)
try:
log.info("Starting player: {0}", args.player)
output.open()
except OSError as err:
console.exit("Failed to start player: {0} ({1})", args.player, err)
return False
return True | 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:
log.debug("Pre-buffering 8192 bytes")
prebuffer = stream_fd.read(8192)
except IOError as err:
stream_fd.close()
raise StreamError("Failed to read data from stream: {0}".format(err))
if not prebuffer:
stream_fd.close()
raise StreamError("No data returned from stream")
return stream_fd, prebuffer | 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):
console.exit("Failed to start player: {0} ({1})",
args.player, err)
else:
console.exit("Failed to open output: {0} ({1})",
args.output, err)
with closing(output):
log.debug("Writing stream to output")
read_stream(stream_fd, output, prebuffer)
return True | 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 is_fifo:
output.player.poll()
if output.player.returncode is not None:
log.info("Player closed")
break
try:
output.write(data)
except IOError as err:
if is_player and err.errno in ACCEPTABLE_ERRNO:
log.info("Player closed")
elif is_http and err.errno in ACCEPTABLE_ERRNO:
log.info("HTTP connection closed")
else:
console.exit("Error when writing to output: {0}, exiting", err)
break
except IOError as err:
console.exit("Error when reading from stream: {0}, exiting", err)
finally:
stream.close()
log.info("Stream ended") | 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,
sorted(streams.keys())))
file_output = args.output or args.stdout
for stream_name in [stream_name] + alt_streams:
stream = streams[stream_name]
stream_type = type(stream).shortname()
if stream_type in args.player_passthrough and not file_output:
log.info("Opening stream: {0} ({1})", stream_name,
stream_type)
success = output_stream_passthrough(plugin, stream)
elif args.player_external_http:
return output_stream_http(plugin, streams, external=True,
port=args.player_external_http_port)
elif args.player_continuous_http and not file_output:
return output_stream_http(plugin, streams)
else:
log.info("Opening stream: {0} ({1})", stream_name,
stream_type)
success = output_stream(plugin, stream)
if success:
break | python | {
"resource": ""
} |
q267662 | fetch_streams | test | def fetch_streams(plugin):
"""Fetches streams using correct parameters."""
return plugin.streams(stream_types=args.stream_types,
sorting_excludes=args.stream_sorting_excludes) | 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 = fetch_streams(plugin)
except FatalPluginError as err:
raise
except PluginError as err:
log.error(u"{0}", err)
if count > 0:
attempts += 1
if attempts >= count:
break
return 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 in streams:
for name, stream in streams.items():
if stream is streams[stream_name] and name not in STREAM_SYNONYMS:
return name
return 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):
return stream is streams[n] and n is not name
synonyms = list(filter(synonymfilter, streams.keys()))
if len(synonyms) > 0:
joined = delimiter.join(synonyms)
name = "{0} ({1})".format(name, joined)
validstreams.append(name)
return delimiter.join(validstreams) | 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:
retry_streams = args.retry_streams
if args.retry_max:
retry_max = args.retry_max
streams = fetch_streams_with_retry(plugin, retry_streams,
retry_max)
else:
streams = fetch_streams(plugin)
except NoPluginError:
console.exit("No plugin can handle URL: {0}", args.url)
except PluginError as err:
console.exit(u"{0}", err)
if not streams:
console.exit("No playable streams found on this URL: {0}", args.url)
if args.default_stream and not args.stream and not args.json:
args.stream = args.default_stream
if args.stream:
validstreams = format_valid_streams(plugin, streams)
for stream_name in args.stream:
if stream_name in streams:
log.info("Available streams: {0}", validstreams)
handle_stream(plugin, streams, stream_name)
return
err = ("The specified stream(s) '{0}' could not be "
"found".format(", ".join(args.stream)))
if console.json:
console.msg_json(dict(streams=streams, plugin=plugin.module,
error=err))
else:
console.exit("{0}.\n Available streams: {1}",
err, validstreams)
else:
if console.json:
console.msg_json(dict(streams=streams, plugin=plugin.module))
else:
validstreams = format_valid_streams(plugin, streams)
console.msg("Available streams: {0}", validstreams) | 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:
console.msg_json(pluginlist)
else:
console.msg("Loaded plugins: {0}", pluginlist_formatted) | 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}"
"&redirect_uri={1}"
"&scope=user_read+user_subscriptions"
"&force_verify=true").format(client_id, redirect_uri)
console.msg("Attempting to open a browser to let you authenticate "
"Streamlink with Twitch")
try:
if not webbrowser.open_new_tab(url):
raise webbrowser.Error
except webbrowser.Error:
console.exit("Unable to open a web browser, try accessing this URL "
"manually instead:\n{0}".format(url)) | 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:
log.warning("Plugin path {0} does not exist or is not "
"a directory!", directory) | 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')
parser.error(msg % ' '.join(unknown))
# Force lowercase to allow case-insensitive lookup
if args.stream:
args.stream = [stream.lower() for stream in args.stream]
if not args.url and args.url_param:
args.url = args.url_param | 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
# Handle SIGTERM just like SIGINT
signal.signal(signal.SIGTERM, signal.default_int_handler) | 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)
if args.http_ssl_cert_crt_key:
streamlink.set_option("http-ssl-cert", tuple(args.http_ssl_cert_crt_key))
if args.http_timeout:
streamlink.set_option("http-timeout", args.http_timeout)
if args.http_cookies:
streamlink.set_option("http-cookies", args.http_cookies)
if args.http_headers:
streamlink.set_option("http-headers", args.http_headers)
if args.http_query_params:
streamlink.set_option("http-query-params", args.http_query_params) | python | {
"resource": ""
} |
q267673 | setup_plugins | test | 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) | 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:
streamlink.set_option("rtmp-timeout", args.rtmp_timeout)
if args.stream_segment_attempts:
streamlink.set_option("stream-segment-attempts", args.stream_segment_attempts)
if args.stream_segment_threads:
streamlink.set_option("stream-segment-threads", args.stream_segment_threads)
if args.stream_segment_timeout:
streamlink.set_option("stream-segment-timeout", args.stream_segment_timeout)
if args.stream_timeout:
streamlink.set_option("stream-timeout", args.stream_timeout)
if args.ffmpeg_ffmpeg:
streamlink.set_option("ffmpeg-ffmpeg", args.ffmpeg_ffmpeg)
if args.ffmpeg_verbose:
streamlink.set_option("ffmpeg-verbose", args.ffmpeg_verbose)
if args.ffmpeg_verbose_path:
streamlink.set_option("ffmpeg-verbose-path", args.ffmpeg_verbose_path)
if args.ffmpeg_video_transcode:
streamlink.set_option("ffmpeg-video-transcode", args.ffmpeg_video_transcode)
if args.ffmpeg_audio_transcode:
streamlink.set_option("ffmpeg-audio-transcode", args.ffmpeg_audio_transcode)
streamlink.set_option("subprocess-errorlog", args.subprocess_errorlog)
streamlink.set_option("subprocess-errorlog-path", args.subprocess_errorlog_path)
streamlink.set_option("locale", args.locale) | 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())
# linux / other
else:
os_version = platform.platform()
log.debug("OS: {0}".format(os_version))
log.debug("Python: {0}".format(platform.python_version()))
log.debug("Streamlink: {0}".format(streamlink_version))
log.debug("Requests({0}), Socks({1}), Websocket({2})".format(
requests.__version__, socks_version, websocket_version)) | python | {
"resource": ""
} |
q267676 | Viasat._get_stream_id | test | 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") | 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)
if m:
return self.session.streams(m.group("url")) | 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) Segment connect and read
timeout, default: ``10.0``.
General option used by streams not
covered by other options.
stream-timeout (float) Timeout for reading data from
stream, default: ``60.0``.
General option used by streams not
covered by other options.
locale (str) Locale setting, in the RFC 1766 format
eg. en_US or es_ES
default: ``system locale``.
user-input-requester (UserInputRequester) instance of UserInputRequester
to collect input from the user at runtime. Must be
set before the plugins are loaded.
default: ``UserInputRequester``.
======================== =========================================
"""
# Backwards compatibility
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-errorlog-path"
if key == "http-proxy":
self.http.proxies["http"] = update_scheme("http://", value)
elif key == "https-proxy":
self.http.proxies["https"] = update_scheme("https://", value)
elif key == "http-cookies":
if isinstance(value, dict):
self.http.cookies.update(value)
else:
self.http.parse_cookies(value)
elif key == "http-headers":
if isinstance(value, dict):
self.http.headers.update(value)
else:
self.http.parse_headers(value)
elif key == "http-query-params":
if isinstance(value, dict):
self.http.params.update(value)
else:
self.http.parse_query_params(value)
elif key == "http-trust-env":
self.http.trust_env = value
elif key == "http-ssl-verify":
self.http.verify = value
elif key == "http-disable-dh":
if value:
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += ':!DH'
try:
requests.packages.urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST = \
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS.encode("ascii")
except AttributeError:
# no ssl to disable the cipher on
pass
elif key == "http-ssl-cert":
self.http.cert = value
elif key == "http-timeout":
self.http.timeout = value
else:
self.options.set(key, value) | 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":
return self.http.headers
elif key == "http-query-params":
return self.http.params
elif key == "http-trust-env":
return self.http.trust_env
elif key == "http-ssl-verify":
return self.http.verify
elif key == "http-ssl-cert":
return self.http.cert
elif key == "http-timeout":
return self.http.timeout
else:
return self.options.get(key) | 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
"""
if plugin in self.plugins:
plugin = self.plugins[plugin]
plugin.set_option(key, value) | 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
"""
if plugin in self.plugins:
plugin = self.plugins[plugin]
return plugin.get_option(key) | 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:
# Attempt to handle a redirect URL
try:
res = self.http.head(url, allow_redirects=True, acceptable_status=[501])
# Fall back to GET request if server doesn't handle HEAD.
if res.status_code == 501:
res = self.http.get(url, stream=True)
if res.url != url:
return self.resolve_url(res.url, follow_redirect=follow_redirect)
except PluginError:
pass
raise NoPluginError | 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])
# set the full plugin module name
module_name = "streamlink.plugin.{0}".format(name)
try:
self.load_plugin(module_name, file, pathname, desc)
except Exception:
sys.stderr.write("Failed to load plugin {0}:\n".format(name))
print_small_exception("load_plugin")
continue | 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
:return: seconds
"""
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 * 60
s += int(match.group("minutes") or "0") * 60
s += int(match.group("seconds") or "0")
return s | 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):
raise ValueError("'{0}' does not start with '{1}'".format(value, string))
return True
return starts_with | 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):
raise ValueError("'{0}' does not end with '{1}'".format(value, string))
return True
return ends_with | 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:
raise ValueError("'{0}' does not contain '{1}'".format(value, string))
return True
return contains_str | 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.
"""
def getter(value):
return _getattr(value, attr, default)
return transform(getter) | 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)
if isinstance(value, dict):
return cls(_filter(expand_kv, value.items()))
else:
return cls(_filter(func, value))
return transform(filter_values) | 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:
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(func, value))
return transform(map_values) | 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(
"Unable to validate URL attribute '{0}': {1}".format(
name, err
)
)
return True
# Convert "http" to be either any("http", "https") for convenience
if attributes.get("scheme") == "http":
attributes["scheme"] = any("http", "https")
return check_url | 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)
if value is None:
raise ValueError("XPath '{0}' did not return an element".format(xpath))
return validate(ET.iselement, value)
return transform(xpath_find) | 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)
return value.findall(xpath)
return transform(xpath_findall) | 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('&', '&')
if 'hash' not in tmp_url:
# there's no hash in the URL, try to find it
matches = _hash_re.search(response.text)
if matches:
url = tmp_url + '&hash=' + matches.group(1)
else:
url = tmp_url
return 'http://ceskatelevize.cz/' + 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 as is.
If specified, *parser* can be a M3U8Parser subclass to be used
to parse the data.
"""
return parser(base_uri, **kwargs).parse(data) | 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
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):
return player | 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:
emailauth = None
if not emailauth:
return False
else:
raise SteamLoginFailed("Email auth key error")
# If the user must enter a two factor auth code
if resp.get(u"requires_twofactor"):
try:
twofactorcode = self.input_ask("Two factor auth code required")
except FatalPluginError:
twofactorcode = None
if not twofactorcode:
return False
if resp.get(u"message"):
raise SteamLoginFailed(resp[u"message"])
return self.dologin(email, password,
emailauth=emailauth,
emailsteamid=resp.get(u"emailsteamid", u""),
captcha_text=captcha_text,
captchagid=captchagid,
twofactorcode=twofactorcode)
elif resp.get("login_complete"):
return True
else:
log.error("Something when wrong when logging in to Steam")
return False | 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:
self.logger.error("Failed to extract stream_id.")
return stream_id.group("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)
if not stream_info:
self.logger.error("Failed to extract stream_info.")
# Rename the "" quality to "source" by transforming the tuples to a
# list and reassigning.
stream_info_list = []
for info in stream_info:
if not info[1]:
stream_info_list.append([info[0], "source"])
else:
stream_info_list.append(list(info))
return stream_info_list | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.