_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q269100 | TelegramBotClient.updates | test | def updates(self, offset=None):
"""Fetch the messages that a bot can read.
When the `offset` is given it will retrieve all the messages
that are greater or equal to that offset. Take into account
that, due to how the API works, all previous messages will
be removed from the server.
:param offset: fetch the messages starting on this offset
"""
params = {}
if offset:
params[self.OFFSET] = offset
response = self._call(self.UPDATES_METHOD, params)
return response | python | {
"resource": ""
} |
q269101 | NNTP.fetch_items | test | def fetch_items(self, category, **kwargs):
"""Fetch the articles
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
offset = kwargs['offset']
logger.info("Fetching articles of '%s' group on '%s' offset %s",
self.group, self.host, str(offset))
narts, iarts, tarts = (0, 0, 0)
_, _, first, last, _ = self.client.group(self.group)
if offset <= last:
first = max(first, offset)
_, overview = self.client.over((first, last))
else:
overview = []
tarts = len(overview)
logger.debug("Total number of articles to fetch: %s", tarts)
for article_id, _ in overview:
try:
article_raw = self.client.article(article_id)
article = self.__parse_article(article_raw)
except ParseError:
logger.warning("Error parsing %s article; skipping",
article_id)
iarts += 1
continue
except nntplib.NNTPTemporaryError as e:
logger.warning("Error '%s' fetching article %s; skipping",
e.response, article_id)
iarts += 1
continue
yield article
narts += 1 | python | {
"resource": ""
} |
q269102 | NNTP.metadata | test | def metadata(self, item, filter_classified=False):
"""NNTP metadata.
This method takes items, overriding `metadata` decorator,
to add extra information related to NNTP.
:param item: an item fetched by a backend
:param filter_classified: sets if classified fields were filtered
"""
item = super().metadata(item, filter_classified=filter_classified)
item['offset'] = item['data']['offset']
return item | python | {
"resource": ""
} |
q269103 | NNTP.parse_article | test | def parse_article(raw_article):
"""Parse a NNTP article.
This method parses a NNTP article stored in a string object
and returns an dictionary.
:param raw_article: NNTP article string
:returns: a dictionary of type `requests.structures.CaseInsensitiveDict`
:raises ParseError: when an error is found parsing the article
"""
try:
message = email.message_from_string(raw_article)
article = message_to_dict(message)
except UnicodeEncodeError as e:
raise ParseError(cause=str(e))
return article | python | {
"resource": ""
} |
q269104 | NNTTPClient._fetch | test | def _fetch(self, method, args):
"""Fetch NNTP data from the server or from the archive
:param method: the name of the command to execute
:param args: the arguments required by the command
"""
if self.from_archive:
data = self._fetch_from_archive(method, args)
else:
data = self._fetch_from_remote(method, args)
return data | python | {
"resource": ""
} |
q269105 | NNTTPClient._fetch_article | test | def _fetch_article(self, article_id):
"""Fetch article data
:param article_id: id of the article to fetch
"""
fetched_data = self.handler.article(article_id)
data = {
'number': fetched_data[1].number,
'message_id': fetched_data[1].message_id,
'lines': fetched_data[1].lines
}
return data | python | {
"resource": ""
} |
q269106 | NNTTPClient._fetch_from_remote | test | def _fetch_from_remote(self, method, args):
"""Fetch data from NNTP
:param method: the name of the command to execute
:param args: the arguments required by the command
"""
try:
if method == NNTTPClient.GROUP:
data = self.handler.group(args)
elif method == NNTTPClient.OVER:
data = self.handler.over(args)
elif method == NNTTPClient.ARTICLE:
data = self._fetch_article(args)
except nntplib.NNTPTemporaryError as e:
data = e
raise e
finally:
if self.archive:
self.archive.store(method, args, None, data)
return data | python | {
"resource": ""
} |
q269107 | NNTTPClient._fetch_from_archive | test | def _fetch_from_archive(self, method, args):
"""Fetch data from the archive
:param method: the name of the command to execute
:param args: the arguments required by the command
"""
if not self.archive:
raise ArchiveError(cause="Archive not provided")
data = self.archive.retrieve(method, args, None)
if isinstance(data, nntplib.NNTPTemporaryError):
raise data
return data | python | {
"resource": ""
} |
q269108 | HttpClient._create_http_session | test | def _create_http_session(self):
"""Create a http session and initialize the retry object."""
self.session = requests.Session()
if self.headers:
self.session.headers.update(self.headers)
retries = urllib3.util.Retry(total=self.max_retries,
connect=self.max_retries_on_connect,
read=self.max_retries_on_read,
redirect=self.max_retries_on_redirect,
status=self.max_retries_on_status,
method_whitelist=self.method_whitelist,
status_forcelist=self.status_forcelist,
backoff_factor=self.sleep_time,
raise_on_redirect=self.raise_on_redirect,
raise_on_status=self.raise_on_status,
respect_retry_after_header=self.respect_retry_after_header)
self.session.mount('http://', requests.adapters.HTTPAdapter(max_retries=retries))
self.session.mount('https://', requests.adapters.HTTPAdapter(max_retries=retries)) | python | {
"resource": ""
} |
q269109 | RateLimitHandler.setup_rate_limit_handler | test | def setup_rate_limit_handler(self, sleep_for_rate=False, min_rate_to_sleep=MIN_RATE_LIMIT,
rate_limit_header=RATE_LIMIT_HEADER,
rate_limit_reset_header=RATE_LIMIT_RESET_HEADER):
"""Setup the rate limit handler.
:param sleep_for_rate: sleep until rate limit is reset
:param min_rate_to_sleep: minimun rate needed to make the fecthing process sleep
:param rate_limit_header: header from where extract the rate limit data
:param rate_limit_reset_header: header from where extract the rate limit reset data
"""
self.rate_limit = None
self.rate_limit_reset_ts = None
self.sleep_for_rate = sleep_for_rate
self.rate_limit_header = rate_limit_header
self.rate_limit_reset_header = rate_limit_reset_header
if min_rate_to_sleep > self.MAX_RATE_LIMIT:
msg = "Minimum rate to sleep value exceeded (%d)."
msg += "High values might cause the client to sleep forever."
msg += "Reset to %d."
self.min_rate_to_sleep = self.MAX_RATE_LIMIT
logger.warning(msg, min_rate_to_sleep, self.MAX_RATE_LIMIT)
else:
self.min_rate_to_sleep = min_rate_to_sleep | python | {
"resource": ""
} |
q269110 | RateLimitHandler.sleep_for_rate_limit | test | def sleep_for_rate_limit(self):
"""The fetching process sleeps until the rate limit is restored or
raises a RateLimitError exception if sleep_for_rate flag is disabled.
"""
if self.rate_limit is not None and self.rate_limit <= self.min_rate_to_sleep:
seconds_to_reset = self.calculate_time_to_reset()
if seconds_to_reset < 0:
logger.warning("Value of sleep for rate limit is negative, reset it to 0")
seconds_to_reset = 0
cause = "Rate limit exhausted."
if self.sleep_for_rate:
logger.info("%s Waiting %i secs for rate limit reset.", cause, seconds_to_reset)
time.sleep(seconds_to_reset)
else:
raise RateLimitError(cause=cause, seconds_to_reset=seconds_to_reset) | python | {
"resource": ""
} |
q269111 | RateLimitHandler.update_rate_limit | test | def update_rate_limit(self, response):
"""Update the rate limit and the time to reset
from the response headers.
:param: response: the response object
"""
if self.rate_limit_header in response.headers:
self.rate_limit = int(response.headers[self.rate_limit_header])
logger.debug("Rate limit: %s", self.rate_limit)
else:
self.rate_limit = None
if self.rate_limit_reset_header in response.headers:
self.rate_limit_reset_ts = int(response.headers[self.rate_limit_reset_header])
logger.debug("Rate limit reset: %s", self.calculate_time_to_reset())
else:
self.rate_limit_reset_ts = None | python | {
"resource": ""
} |
q269112 | Supybot.parse_supybot_log | test | def parse_supybot_log(filepath):
"""Parse a Supybot IRC log file.
The method parses the Supybot IRC log file and returns an iterator of
dictionaries. Each one of this, contains a message from the file.
:param filepath: path to the IRC log file
:returns: a generator of parsed messages
:raises ParseError: raised when the format of the Supybot log file
is invalid
:raises OSError: raised when an error occurs reading the
given file
"""
with open(filepath, 'r', errors='surrogateescape',
newline=os.linesep) as f:
parser = SupybotParser(f)
try:
for message in parser.parse():
yield message
except ParseError as e:
cause = "file: %s; reason: %s" % (filepath, str(e))
raise ParseError(cause=cause) | python | {
"resource": ""
} |
q269113 | Supybot.__retrieve_archives | test | def __retrieve_archives(self, from_date):
"""Retrieve the Supybot archives after the given date"""
archives = []
candidates = self.__list_supybot_archives()
for candidate in candidates:
dt = self.__parse_date_from_filepath(candidate)
if dt.date() >= from_date.date():
archives.append((dt, candidate))
else:
logger.debug("Archive %s stored before %s; skipped",
candidate, str(from_date))
archives.sort(key=lambda x: x[0])
return [archive[1] for archive in archives] | python | {
"resource": ""
} |
q269114 | Supybot.__list_supybot_archives | test | def __list_supybot_archives(self):
"""List the filepath of the archives stored in dirpath"""
archives = []
for root, _, files in os.walk(self.dirpath):
for filename in files:
location = os.path.join(root, filename)
archives.append(location)
return archives | python | {
"resource": ""
} |
q269115 | SupybotParser.parse | test | def parse(self):
"""Parse a Supybot IRC stream.
Returns an iterator of dicts. Each dicts contains information
about the date, type, nick and body of a single log entry.
:returns: iterator of parsed lines
:raises ParseError: when an invalid line is found parsing the given
stream
"""
for line in self.stream:
line = line.rstrip('\n')
self.nline += 1
if self.SUPYBOT_EMPTY_REGEX.match(line):
continue
ts, msg = self._parse_supybot_timestamp(line)
if self.SUPYBOT_EMPTY_COMMENT_REGEX.match(msg):
continue
elif self.SUPYBOT_EMPTY_COMMENT_ACTION_REGEX.match(msg):
continue
elif self.SUPYBOT_EMPTY_BOT_REGEX.match(msg):
continue
itype, nick, body = self._parse_supybot_msg(msg)
item = self._build_item(ts, itype, nick, body)
yield item | python | {
"resource": ""
} |
q269116 | SupybotParser._parse_supybot_timestamp | test | def _parse_supybot_timestamp(self, line):
"""Parse timestamp section"""
m = self.SUPYBOT_TIMESTAMP_REGEX.match(line)
if not m:
msg = "date expected on line %s" % (str(self.nline))
raise ParseError(cause=msg)
ts = m.group('ts')
msg = m.group('msg')
return ts, msg | python | {
"resource": ""
} |
q269117 | SupybotParser._parse_supybot_msg | test | def _parse_supybot_msg(self, line):
"""Parse message section"""
patterns = [(self.SUPYBOT_COMMENT_REGEX, self.TCOMMENT),
(self.SUPYBOT_COMMENT_ACTION_REGEX, self.TCOMMENT),
(self.SUPYBOT_SERVER_REGEX, self.TSERVER),
(self.SUPYBOT_BOT_REGEX, self.TCOMMENT)]
for p in patterns:
m = p[0].match(line)
if not m:
continue
return p[1], m.group('nick'), m.group('body').strip()
msg = "invalid message on line %s" % (str(self.nline))
raise ParseError(cause=msg) | python | {
"resource": ""
} |
q269118 | Discourse.fetch_items | test | def fetch_items(self, category, **kwargs):
"""Fetch the topics
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
logger.info("Looking for topics at '%s', updated from '%s'",
self.url, str(from_date))
ntopics = 0
topics_ids = self.__fetch_and_parse_topics_ids(from_date)
for topic_id in topics_ids:
topic = self.__fetch_and_parse_topic(topic_id)
ntopics += 1
yield topic
logger.info("Fetch process completed: %s topics fetched",
ntopics) | python | {
"resource": ""
} |
q269119 | Discourse.__parse_topics_page | test | def __parse_topics_page(self, raw_json):
"""Parse a topics page stream.
The result of parsing process is a generator of tuples. Each
tuple contains de identifier of the topic, the last date
when it was updated and whether is pinned or not.
:param raw_json: JSON stream to parse
:returns: a generator of parsed bugs
"""
topics_page = json.loads(raw_json)
topics_ids = []
for topic in topics_page['topic_list']['topics']:
topic_id = topic['id']
if topic['last_posted_at'] is None:
logger.warning("Topic %s with last_posted_at null. Ignoring it.", topic['title'])
continue
updated_at = str_to_datetime(topic['last_posted_at'])
pinned = topic['pinned']
topics_ids.append((topic_id, updated_at, pinned))
return topics_ids | python | {
"resource": ""
} |
q269120 | DiscourseClient.topic | test | def topic(self, topic_id):
"""Retrive the topic with `topic_id` identifier.
:param topic_id: identifier of the topic to retrieve
"""
params = {
self.PKEY: self.api_key
}
# http://example.com/t/8.json
response = self._call(self.TOPIC, topic_id,
params=params)
return response | python | {
"resource": ""
} |
q269121 | DiscourseClient.post | test | def post(self, post_id):
"""Retrieve the post whit `post_id` identifier.
:param post_id: identifier of the post to retrieve
"""
params = {
self.PKEY: self.api_key
}
# http://example.com/posts/10.json
response = self._call(self.POSTS, post_id,
params=params)
return response | python | {
"resource": ""
} |
q269122 | Phabricator.fetch_items | test | def fetch_items(self, category, **kwargs):
"""Fetch the tasks
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
logger.info("Fetching tasks of '%s' from %s", self.url, str(from_date))
ntasks = 0
for task in self.__fetch_tasks(from_date):
yield task
ntasks += 1
logger.info("Fetch process completed: %s tasks fetched", ntasks) | python | {
"resource": ""
} |
q269123 | Phabricator.parse_tasks | test | def parse_tasks(raw_json):
"""Parse a Phabricator tasks JSON stream.
The method parses a JSON stream and returns a list iterator.
Each item is a dictionary that contains the task parsed data.
:param raw_json: JSON string to parse
:returns: a generator of parsed tasks
"""
results = json.loads(raw_json)
tasks = results['result']['data']
for t in tasks:
yield t | python | {
"resource": ""
} |
q269124 | Phabricator.parse_users | test | def parse_users(raw_json):
"""Parse a Phabricator users JSON stream.
The method parses a JSON stream and returns a list iterator.
Each item is a dictionary that contais the user parsed data.
:param raw_json: JSON string to parse
:returns: a generator of parsed users
"""
results = json.loads(raw_json)
users = results['result']
for u in users:
yield u | python | {
"resource": ""
} |
q269125 | ConduitClient.tasks | test | def tasks(self, from_date=DEFAULT_DATETIME):
"""Retrieve tasks.
:param from_date: retrieve tasks that where updated from that date;
dates are converted epoch time.
"""
# Convert 'from_date' to epoch timestamp.
# Zero value (1970-01-01 00:00:00) is not allowed for
# 'modifiedStart' so it will be set to 1, by default.
ts = int(datetime_to_utc(from_date).timestamp()) or 1
consts = {
self.PMODIFIED_START: ts
}
attachments = {
self. PPROJECTS: True
}
params = {
self.PCONSTRAINTS: consts,
self.PATTACHMENTS: attachments,
self.PORDER: self.VOUTDATED,
}
while True:
r = self._call(self.MANIPHEST_TASKS, params)
yield r
j = json.loads(r)
after = j['result']['cursor']['after']
if not after:
break
params[self.PAFTER] = after | python | {
"resource": ""
} |
q269126 | ConduitClient.transactions | test | def transactions(self, *phids):
"""Retrieve tasks transactions.
:param phids: list of tasks identifiers
"""
params = {
self.PIDS: phids
}
response = self._call(self.MANIPHEST_TRANSACTIONS, params)
return response | python | {
"resource": ""
} |
q269127 | ConduitClient.users | test | def users(self, *phids):
"""Retrieve users.
:params phids: list of users identifiers
"""
params = {
self.PHIDS: phids
}
response = self._call(self.PHAB_USERS, params)
return response | python | {
"resource": ""
} |
q269128 | ConduitClient.phids | test | def phids(self, *phids):
"""Retrieve data about PHIDs.
:params phids: list of PHIDs
"""
params = {
self.PHIDS: phids
}
response = self._call(self.PHAB_PHIDS, params)
return response | python | {
"resource": ""
} |
q269129 | ConduitClient._call | test | def _call(self, method, params):
"""Call a method.
:param method: method to call
:param params: dict with the HTTP parameters needed to call
the given method
:raises ConduitError: when an error is returned by the server
"""
url = self.URL % {'base': self.base_url, 'method': method}
# Conduit and POST parameters
params['__conduit__'] = {'token': self.api_token}
data = {
'params': json.dumps(params, sort_keys=True),
'output': 'json',
'__conduit__': True
}
logger.debug("Phabricator Conduit client requests: %s params: %s",
method, str(data))
r = self.fetch(url, payload=data, method=HttpClient.POST, verify=False)
# Check for possible Conduit API errors
result = r.json()
if result['error_code']:
raise ConduitError(error=result['error_info'],
code=result['error_code'])
return r.text | python | {
"resource": ""
} |
q269130 | Confluence.metadata_id | test | def metadata_id(item):
"""Extracts the identifier from a Confluence item.
This identifier will be the mix of two fields because a
historical content does not have any unique identifier.
In this case, 'id' and 'version' values are combined because
it should not be possible to have two equal version numbers
for the same content. The value to return will follow the
pattern: <content>#v<version> (i.e 28979#v10).
"""
cid = item['id']
cversion = item['version']['number']
return str(cid) + '#v' + str(cversion) | python | {
"resource": ""
} |
q269131 | Confluence.parse_contents_summary | test | def parse_contents_summary(raw_json):
"""Parse a Confluence summary JSON list.
The method parses a JSON stream and returns an iterator
of diccionaries. Each dictionary is a content summary.
:param raw_json: JSON string to parse
:returns: a generator of parsed content summaries.
"""
summary = json.loads(raw_json)
contents = summary['results']
for c in contents:
yield c | python | {
"resource": ""
} |
q269132 | ConfluenceClient.contents | test | def contents(self, from_date=DEFAULT_DATETIME,
offset=None, max_contents=MAX_CONTENTS):
"""Get the contents of a repository.
This method returns an iterator that manages the pagination
over contents. Take into account that the seconds of `from_date`
parameter will be ignored because the API only works with
hours and minutes.
:param from_date: fetch the contents updated since this date
:param offset: fetch the contents starting from this offset
:param limit: maximum number of contents to fetch per request
"""
resource = self.RCONTENTS + '/' + self.MSEARCH
# Set confluence query parameter (cql)
date = from_date.strftime("%Y-%m-%d %H:%M")
cql = self.VCQL % {'date': date}
# Set parameters
params = {
self.PCQL: cql,
self.PLIMIT: max_contents,
self.PEXPAND: self.PANCESTORS
}
if offset:
params[self.PSTART] = offset
for response in self._call(resource, params):
yield response | python | {
"resource": ""
} |
q269133 | ConfluenceClient.historical_content | test | def historical_content(self, content_id, version):
"""Get the snapshot of a content for the given version.
:param content_id: fetch the snapshot of this content
:param version: snapshot version of the content
"""
resource = self.RCONTENTS + '/' + str(content_id)
params = {
self.PVERSION: version,
self.PSTATUS: self.VHISTORICAL,
self.PEXPAND: ','.join(self.VEXPAND)
}
# Only one item is returned
response = [response for response in self._call(resource, params)]
return response[0] | python | {
"resource": ""
} |
q269134 | MeasurementObservation._parse_result | test | def _parse_result(self):
''' Parse the result property, extracting the value
and unit of measure '''
if self.result is not None:
uom = testXMLAttribute(self.result, "uom")
value_str = testXMLValue(self.result)
try:
value = float(value_str)
except:
raise ValueError("Error parsing measurement value")
self.result = Measurement(value, uom) | python | {
"resource": ""
} |
q269135 | WFSCapabilitiesReader.capabilities_url | test | def capabilities_url(self, service_url):
"""Return a capabilities url
"""
qs = []
if service_url.find('?') != -1:
qs = cgi.parse_qsl(service_url.split('?')[1])
params = [x[0] for x in qs]
if 'service' not in params:
qs.append(('service', 'WFS'))
if 'request' not in params:
qs.append(('request', 'GetCapabilities'))
if 'version' not in params:
qs.append(('version', self.version))
urlqs = urlencode(tuple(qs))
return service_url.split('?')[0] + '?' + urlqs | python | {
"resource": ""
} |
q269136 | WFSCapabilitiesReader.read | test | def read(self, url, timeout=30):
"""Get and parse a WFS capabilities document, returning an
instance of WFSCapabilitiesInfoset
Parameters
----------
url : string
The URL to the WFS capabilities document.
timeout : number
A timeout value (in seconds) for the request.
"""
request = self.capabilities_url(url)
u = openURL(request, timeout=timeout,
username=self.username, password=self.password)
return etree.fromstring(u.read()) | python | {
"resource": ""
} |
q269137 | WFSCapabilitiesReader.readString | test | def readString(self, st):
"""Parse a WFS capabilities document, returning an
instance of WFSCapabilitiesInfoset
string should be an XML capabilities document
"""
if not isinstance(st, str) and not isinstance(st, bytes):
raise ValueError("String must be of type string or bytes, not %s" % type(st))
return etree.fromstring(st) | python | {
"resource": ""
} |
q269138 | MeasurementTimeseriesObservation._parse_result | test | def _parse_result(self):
''' Parse the result element of the observation type '''
if self.result is not None:
result = self.result.find(nspv(
"wml2:MeasurementTimeseries"))
self.result = MeasurementTimeseries(result) | python | {
"resource": ""
} |
q269139 | WebFeatureService_3_0_0._build_url | test | def _build_url(self, path=None):
"""
helper function to build a WFS 3.0 URL
@type path: string
@param path: path of WFS URL
@returns: fully constructed URL path
"""
url = self.url
if self.url_query_string is not None:
LOGGER.debug('base URL has a query string')
url = urljoin(url, path)
url = '?'.join([url, self.url_query_string])
else:
url = urljoin(url, path)
LOGGER.debug('URL: {}'.format(url))
return url | python | {
"resource": ""
} |
q269140 | _get_elements | test | def _get_elements(complex_type, root):
"""Get attribute elements
"""
found_elements = []
element = findall(root, '{%s}complexType' % XS_NAMESPACE,
attribute_name='name', attribute_value=complex_type)[0]
found_elements = findall(element, '{%s}element' % XS_NAMESPACE)
return found_elements | python | {
"resource": ""
} |
q269141 | _construct_schema | test | def _construct_schema(elements, nsmap):
"""Consruct fiona schema based on given elements
:param list Element: list of elements
:param dict nsmap: namespace map
:return dict: schema
"""
schema = {
'properties': {},
'geometry': None
}
schema_key = None
gml_key = None
# if nsmap is defined, use it
if nsmap:
for key in nsmap:
if nsmap[key] == XS_NAMESPACE:
schema_key = key
if nsmap[key] in GML_NAMESPACES:
gml_key = key
# if no nsmap is defined, we have to guess
else:
gml_key = 'gml'
schema_key = 'xsd'
mappings = {
'PointPropertyType': 'Point',
'PolygonPropertyType': 'Polygon',
'LineStringPropertyType': 'LineString',
'MultiPointPropertyType': 'MultiPoint',
'MultiLineStringPropertyType': 'MultiLineString',
'MultiPolygonPropertyType': 'MultiPolygon',
'MultiGeometryPropertyType': 'MultiGeometry',
'GeometryPropertyType': 'GeometryCollection',
'SurfacePropertyType': '3D Polygon',
'MultiSurfacePropertyType': '3D MultiPolygon'
}
for element in elements:
data_type = element.attrib['type'].replace(gml_key + ':', '')
name = element.attrib['name']
if data_type in mappings:
schema['geometry'] = mappings[data_type]
schema['geometry_column'] = name
else:
schema['properties'][name] = data_type.replace(schema_key+':', '')
if schema['properties'] or schema['geometry']:
return schema
else:
return None | python | {
"resource": ""
} |
q269142 | _get_describefeaturetype_url | test | def _get_describefeaturetype_url(url, version, typename):
"""Get url for describefeaturetype request
:return str: url
"""
query_string = []
if url.find('?') != -1:
query_string = cgi.parse_qsl(url.split('?')[1])
params = [x[0] for x in query_string]
if 'service' not in params:
query_string.append(('service', 'WFS'))
if 'request' not in params:
query_string.append(('request', 'DescribeFeatureType'))
if 'version' not in params:
query_string.append(('version', version))
query_string.append(('typeName', typename))
urlqs = urlencode(tuple(query_string))
return url.split('?')[0] + '?' + urlqs | python | {
"resource": ""
} |
q269143 | complex_input_with_reference | test | def complex_input_with_reference():
"""
use ComplexDataInput with a reference to a document
"""
print("\ncomplex_input_with_reference ...")
wps = WebProcessingService('http://localhost:8094/wps', verbose=verbose)
processid = 'wordcount'
textdoc = ComplexDataInput("http://www.gutenberg.org/files/28885/28885-h/28885-h.htm") # alice in wonderland
inputs = [("text", textdoc)]
# list of tuple (output identifier, asReference attribute, mimeType attribute)
# when asReference or mimeType is None - the wps service will use its default option
outputs = [("output",True,'some/mime-type')]
execution = wps.execute(processid, inputs, output=outputs)
monitorExecution(execution)
# show status
print('percent complete', execution.percentCompleted)
print('status message', execution.statusMessage)
for output in execution.processOutputs:
print('identifier=%s, dataType=%s, data=%s, reference=%s' % (output.identifier, output.dataType, output.data, output.reference)) | python | {
"resource": ""
} |
q269144 | Genres.movie_list | test | def movie_list(self, **kwargs):
"""
Get the list of Movie genres.
Args:
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('movie_list')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269145 | Genres.tv_list | test | def tv_list(self, **kwargs):
"""
Get the list of TV genres.
Args:
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('tv_list')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269146 | Genres.movies | test | def movies(self, **kwargs):
"""
Get the list of movies for a particular genre by id. By default, only
movies with 10 or more votes are included.
Args:
page: (optional) Minimum 1, maximum 1000.
language: (optional) ISO 639-1 code.
include_all_movies: (optional) Toggle the inclusion of all movies
and not just those with 10 or more ratings.
Expected value is: True or False.
include_adult: (optional) Toggle the inclusion of adult titles.
Expected value is: True or False.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('movies')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269147 | Movies.info | test | def info(self, **kwargs):
"""
Get the basic movie information for a specific movie id.
Args:
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269148 | Movies.alternative_titles | test | def alternative_titles(self, **kwargs):
"""
Get the alternative titles for a specific movie id.
Args:
country: (optional) ISO 3166-1 code.
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('alternative_titles')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269149 | Movies.credits | test | def credits(self, **kwargs):
"""
Get the cast and crew information for a specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('credits')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269150 | Movies.external_ids | test | def external_ids(self, **kwargs):
"""
Get the external ids for a specific movie id.
Args:
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('external_ids')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269151 | Movies.keywords | test | def keywords(self):
"""
Get the plot keywords for a specific movie id.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('keywords')
response = self._GET(path)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269152 | Movies.recommendations | test | def recommendations(self, **kwargs):
"""
Get a list of recommended movies for a movie.
Args:
language: (optional) ISO 639-1 code.
page: (optional) Minimum value of 1. Expected value is an integer.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('recommendations')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269153 | Movies.release_dates | test | def release_dates(self, **kwargs):
"""
Get the release dates and certification for a specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('release_dates')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269154 | Movies.releases | test | def releases(self, **kwargs):
"""
Get the release date and certification information by country for a
specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('releases')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269155 | Movies.translations | test | def translations(self, **kwargs):
"""
Get the translations for a specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('translations')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269156 | Movies.similar_movies | test | def similar_movies(self, **kwargs):
"""
Get the similar movies for a specific movie id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('similar_movies')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269157 | Movies.reviews | test | def reviews(self, **kwargs):
"""
Get the reviews for a particular movie id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('reviews')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269158 | Movies.changes | test | def changes(self, **kwargs):
"""
Get the changes for a specific movie id.
Changes are grouped by key, and ordered by date in descending order.
By default, only the last 24 hours of changes are returned. The
maximum number of days that can be returned in a single request is 14.
The language is present on fields that are translatable.
Args:
start_date: (optional) Expected format is 'YYYY-MM-DD'.
end_date: (optional) Expected format is 'YYYY-MM-DD'.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('changes')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269159 | Movies.upcoming | test | def upcoming(self, **kwargs):
"""
Get the list of upcoming movies. This list refreshes every day.
The maximum number of items this list will include is 100.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_path('upcoming')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269160 | Movies.now_playing | test | def now_playing(self, **kwargs):
"""
Get the list of movies playing in theatres. This list refreshes
every day. The maximum number of items this list will include is 100.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_path('now_playing')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269161 | Movies.popular | test | def popular(self, **kwargs):
"""
Get the list of popular movies on The Movie Database. This list
refreshes every day.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_path('popular')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269162 | Movies.top_rated | test | def top_rated(self, **kwargs):
"""
Get the list of top rated movies. By default, this list will only
include movies that have 10 or more votes. This list refreshes every
day.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_path('top_rated')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269163 | Movies.account_states | test | def account_states(self, **kwargs):
"""
This method lets users get the status of whether or not the movie has
been rated or added to their favourite or watch lists. A valid session
id is required.
Args:
session_id: see Authentication.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('account_states')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269164 | Movies.rating | test | def rating(self, **kwargs):
"""
This method lets users rate a movie. A valid session id or guest
session id is required.
Args:
session_id: see Authentication.
guest_session_id: see Authentication.
value: Rating value.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('rating')
payload = {
'value': kwargs.pop('value', None),
}
response = self._POST(path, kwargs, payload)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269165 | People.movie_credits | test | def movie_credits(self, **kwargs):
"""
Get the movie credits for a specific person id.
Args:
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any person method.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('movie_credits')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269166 | People.tv_credits | test | def tv_credits(self, **kwargs):
"""
Get the TV credits for a specific person id.
Args:
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any person method.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('tv_credits')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269167 | Credits.info | test | def info(self, **kwargs):
"""
Get the detailed information about a particular credit record. This is
currently only supported with the new credit model found in TV. These
ids can be found from any TV credit response as well as the tv_credits
and combined_credits methods for people.
The episodes object returns a list of episodes and are generally going
to be guest stars. The season array will return a list of season
numbers. Season credits are credits that were marked with the
"add to every season" option in the editing interface and are
assumed to be "season regulars".
Args:
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_credit_id_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269168 | Discover.tv | test | def tv(self, **kwargs):
"""
Discover TV shows by different types of data like average rating,
number of votes, genres, the network they aired on and air dates.
Args:
page: (optional) Minimum 1, maximum 1000.
language: (optional) ISO 639-1 code.
sort_by: (optional) Available options are 'vote_average.desc',
'vote_average.asc', 'first_air_date.desc',
'first_air_date.asc', 'popularity.desc', 'popularity.asc'
first_air_year: (optional) Filter the results release dates to
matches that include this value. Expected value
is a year.
vote_count.gte or vote_count_gte: (optional) Only include TV shows
that are equal to,
or have vote count higher than this value. Expected
value is an integer.
vote_average.gte or vote_average_gte: (optional) Only include TV
shows that are equal
to, or have a higher average rating than this
value. Expected value is a float.
with_genres: (optional) Only include TV shows with the specified
genres. Expected value is an integer (the id of a
genre). Multiple valued can be specified. Comma
separated indicates an 'AND' query, while a
pipe (|) separated value indicates an 'OR'.
with_networks: (optional) Filter TV shows to include a specific
network. Expected value is an integer (the id of a
network). They can be comma separated to indicate an
'AND' query.
first_air_date.gte or first_air_date_gte: (optional) The minimum
release to include.
Expected format is 'YYYY-MM-DD'.
first_air_date.lte or first_air_date_lte: (optional) The maximum
release to include.
Expected format is 'YYYY-MM-DD'.
Returns:
A dict respresentation of the JSON returned from the API.
"""
# Periods are not allowed in keyword arguments but several API
# arguments contain periods. See both usages in tests/test_discover.py.
for param in kwargs:
if '_lte' in param:
kwargs[param.replace('_lte', '.lte')] = kwargs.pop(param)
if '_gte' in param:
kwargs[param.replace('_gte', '.gte')] = kwargs.pop(param)
path = self._get_path('tv')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269169 | Configuration.info | test | def info(self, **kwargs):
"""
Get the system wide configuration info.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269170 | Certifications.list | test | def list(self, **kwargs):
"""
Get the list of supported certifications for movies.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('movie_list')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269171 | Account.info | test | def info(self, **kwargs):
"""
Get the basic information for an account.
Call this method first, before calling other Account methods.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('info')
kwargs.update({'session_id': self.session_id})
response = self._GET(path, kwargs)
self.id = response['id']
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269172 | Account.watchlist_movies | test | def watchlist_movies(self, **kwargs):
"""
Get the list of movies on an account watchlist.
Args:
page: (optional) Minimum 1, maximum 1000.
sort_by: (optional) 'created_at.asc' | 'created_at.desc'
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('watchlist_movies')
kwargs.update({'session_id': self.session_id})
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269173 | Authentication.token_new | test | def token_new(self, **kwargs):
"""
Generate a valid request token for user based authentication.
A request token is required to ask the user for permission to
access their account.
After obtaining the request_token, either:
(1) Direct your user to:
https://www.themoviedb.org/authenticate/REQUEST_TOKEN
or:
(2) Call token_validate_with_login() below.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('token_new')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269174 | Authentication.token_validate_with_login | test | def token_validate_with_login(self, **kwargs):
"""
Authenticate a user with a TMDb username and password. The user
must have a verified email address and be registered on TMDb.
Args:
request_token: The token you generated for the user to approve.
username: The user's username on TMDb.
password: The user's password on TMDb.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('token_validate_with_login')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269175 | Authentication.session_new | test | def session_new(self, **kwargs):
"""
Generate a session id for user based authentication.
A session id is required in order to use any of the write methods.
Args:
request_token: The token you generated for the user to approve.
The token needs to be approved before being
used here.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('session_new')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269176 | Authentication.guest_session_new | test | def guest_session_new(self, **kwargs):
"""
Generate a guest session id.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('guest_session_new')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269177 | GuestSessions.rated_movies | test | def rated_movies(self, **kwargs):
"""
Get a list of rated moview for a specific guest session id.
Args:
page: (optional) Minimum 1, maximum 1000.
sort_by: (optional) 'created_at.asc' | 'created_at.desc'
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_guest_session_id_path('rated_movies')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269178 | Lists.item_status | test | def item_status(self, **kwargs):
"""
Check to see if a movie id is already added to a list.
Args:
movie_id: The id of the movie.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('item_status')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269179 | Lists.create_list | test | def create_list(self, **kwargs):
"""
Create a new list.
A valid session id is required.
Args:
name: Name of the list.
description: Description of the list.
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('create_list')
kwargs.update({'session_id': self.session_id})
payload = {
'name': kwargs.pop('name', None),
'description': kwargs.pop('description', None),
}
if 'language' in kwargs:
payload['language'] = kwargs['language']
response = self._POST(path, kwargs, payload)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269180 | Lists.remove_item | test | def remove_item(self, **kwargs):
"""
Delete movies from a list that the user created.
A valid session id is required.
Args:
media_id: A movie id.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('remove_item')
kwargs.update({'session_id': self.session_id})
payload = {
'media_id': kwargs.pop('media_id', None),
}
response = self._POST(path, kwargs, payload)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269181 | Lists.clear_list | test | def clear_list(self, **kwargs):
"""
Clears all of the items within a list. This is an irreversible action
and should be treated with caution.
A valid session id is required.
Args:
confirm: True (do it) | False (don't do it)
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('clear')
kwargs.update({'session_id': self.session_id})
payload = {}
response = self._POST(path, kwargs, payload)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269182 | TV.content_ratings | test | def content_ratings(self, **kwargs):
"""
Get the content ratings for a TV Series.
Args:
language: (optional) ISO 639 code.
append_to_response: (optional) Comma separated, any collection
method.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('content_ratings')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269183 | TV.similar | test | def similar(self, **kwargs):
"""
Get the similar TV series for a specific TV series id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any TV method.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('similar')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269184 | TV.on_the_air | test | def on_the_air(self, **kwargs):
"""
Get the list of TV shows that are currently on the air. This query
looks for any TV show that has an episode with an air date in the
next 7 days.
Args:
page: (optional) Minimum 1, maximum 1000.
language: (optional) ISO 639 code.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('on_the_air')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269185 | TV_Seasons.info | test | def info(self, **kwargs):
"""
Get the primary information about a TV season by its season number.
Args:
language: (optional) ISO 639 code.
append_to_response: (optional) Comma separated, any TV series
method.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_series_id_season_number_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269186 | TV_Seasons.credits | test | def credits(self, **kwargs):
"""
Get the cast & crew credits for a TV season by season number.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_series_id_season_number_path('credits')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269187 | TV_Seasons.external_ids | test | def external_ids(self, **kwargs):
"""
Get the external ids that we have stored for a TV season by season
number.
Args:
language: (optional) ISO 639 code.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_series_id_season_number_path('external_ids')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269188 | TV_Episodes.info | test | def info(self, **kwargs):
"""
Get the primary information about a TV episode by combination of a
season and episode number.
Args:
language: (optional) ISO 639 code.
append_to_response: (optional) Comma separated, any TV series
method.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_series_id_season_number_episode_number_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269189 | TV_Episodes.credits | test | def credits(self, **kwargs):
"""
Get the TV episode credits by combination of season and episode number.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_series_id_season_number_episode_number_path('credits')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269190 | TV_Episodes.external_ids | test | def external_ids(self, **kwargs):
"""
Get the external ids for a TV episode by combination of a season and
episode number.
Args:
language: (optional) ISO 639 code.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_series_id_season_number_episode_number_path(
'external_ids')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269191 | TMDB._set_attrs_to_values | test | def _set_attrs_to_values(self, response={}):
"""
Set attributes to dictionary values.
- e.g.
>>> import tmdbsimple as tmdb
>>> movie = tmdb.Movies(103332)
>>> response = movie.info()
>>> movie.title # instead of response['title']
"""
if isinstance(response, dict):
for key in response.keys():
if not hasattr(self, key) or not callable(getattr(self, key)):
setattr(self, key, response[key]) | python | {
"resource": ""
} |
q269192 | Search.movie | test | def movie(self, **kwargs):
"""
Search for movies by title.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
include_adult: (optional) Toggle the inclusion of adult titles.
Expected value is True or False.
year: (optional) Filter the results release dates to matches that
include this value.
primary_release_year: (optional) Filter the results so that only
the primary release dates have this value.
search_type: (optional) By default, the search type is 'phrase'.
This is almost guaranteed the option you will want.
It's a great all purpose search type and by far the
most tuned for every day querying. For those wanting
more of an "autocomplete" type search, set this
option to 'ngram'.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('movie')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269193 | Search.collection | test | def collection(self, **kwargs):
"""
Search for collections by name.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('collection')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269194 | Search.tv | test | def tv(self, **kwargs):
"""
Search for TV shows by title.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
first_air_date_year: (optional) Filter the results to only match
shows that have a air date with with value.
search_type: (optional) By default, the search type is 'phrase'.
This is almost guaranteed the option you will want.
It's a great all purpose search type and by far the
most tuned for every day querying. For those wanting
more of an "autocomplete" type search, set this
option to 'ngram'.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('tv')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269195 | Search.person | test | def person(self, **kwargs):
"""
Search for people by name.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
include_adult: (optional) Toggle the inclusion of adult titles.
Expected value is True or False.
search_type: (optional) By default, the search type is 'phrase'.
This is almost guaranteed the option you will want.
It's a great all purpose search type and by far the
most tuned for every day querying. For those wanting
more of an "autocomplete" type search, set this
option to 'ngram'.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('person')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269196 | Search.company | test | def company(self, **kwargs):
"""
Search for companies by name.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('company')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269197 | Search.keyword | test | def keyword(self, **kwargs):
"""
Search for keywords by name.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('keyword')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269198 | Search.multi | test | def multi(self, **kwargs):
"""
Search the movie, tv show and person collections with a single query.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
include_adult: (optional) Toggle the inclusion of adult titles.
Expected value is True or False.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('multi')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | python | {
"resource": ""
} |
q269199 | normalize | test | def normalize(s):
'''Normalize and tokenize text. This is lifted from NIST mteval-v11a.pl.'''
# Added to bypass NIST-style pre-processing of hyp and ref files -- wade
if (nonorm):
return s.split()
try:
s.split()
except:
s = " ".join(s)
# language-independent part:
for (pattern, replace) in normalize1:
s = re.sub(pattern, replace, s)
s = xml.sax.saxutils.unescape(s, {'"':'"'})
# language-dependent part (assuming Western languages):
s = " %s " % s
if not preserve_case:
s = s.lower() # this might not be identical to the original
return [tok for tok in normalize3.split(s) if tok and tok != ' '] | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.