INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
make sure we can ping the head and assigned node. Possibly after an env. exit () | def resync(self):
"""make sure we can ping the head and assigned node.
Possibly after an env.exit()"""
success = 0
for head in [True, False]:
for _ in range(30):
try:
self.status(head)
success += 1
br... |
Exit the current Minecraft and wait for new one to replace it. | def exit_resync(self):
"""Exit the current Minecraft and wait for new one to replace it."""
print("********** exit & resync **********")
try:
if self.client_socket:
self.client_socket.close()
self.client_socket = None
try:
s... |
Change q_table to reflect what we have learnt. | def updateQTable( self, reward, current_state ):
"""Change q_table to reflect what we have learnt."""
# retrieve the old action value from the Q-table (indexed by the previous state and the previous action)
old_q = self.q_table[self.prev_s][self.prev_a]
# TODO: what sho... |
Change q_table to reflect what we have learnt after reaching a terminal state. | def updateQTableFromTerminatingState( self, reward ):
"""Change q_table to reflect what we have learnt, after reaching a terminal state."""
# retrieve the old action value from the Q-table (indexed by the previous state and the previous action)
old_q = self.q_table[self.prev_s][self.pre... |
take 1 action in response to the current world state | def act(self, world_state, agent_host, current_r ):
"""take 1 action in response to the current world state"""
obs_text = world_state.observations[-1].text
obs = json.loads(obs_text) # most recent observation
self.logger.debug(obs)
if not u'XPos' in obs or not u'ZPos' in... |
run the agent on the world | def run(self, agent_host):
"""run the agent on the world"""
total_reward = 0
self.prev_s = None
self.prev_a = None
is_first_action = True
# main loop:
world_state = agent_host.getWorldState()
while world_state.is_mission_running... |
Get commands from xml string as a list of ( command_type: int turnbased: boolean command: string ) | def get_commands(self, mission_xml, role):
"""Get commands from xml string as a list of (command_type:int, turnbased:boolean, command:string)"""
mission = etree.fromstring(mission_xml)
return self.get_commands_from_xml(mission, role) |
Get commands from xml file as a list of ( command_type: int turnbased: boolean command: string ) | def get_commands_from_file(self, mission_file, role):
"""Get commands from xml file as a list of (command_type:int, turnbased:boolean, command:string)"""
doc = etree.parse(mission_file)
mission = doc.getroot()
return self.get_commands_from_xml(mission, role) |
Get commands from etree | def get_commands_from_xml(self, mission, role):
"""Get commands from etree"""
handlers = mission.findall(CommandParser.ns + "AgentSection" + "/" + CommandParser.ns + "AgentHandlers")
if len(handlers) <= role:
raise CommandHandlerException("Not enough agents sections in XML")
... |
Get parameterized actions from command list based on command type and verb. | def get_actions(self, commands):
"""Get parameterized actions from command list based on command type and verb."""
actions = []
for type, turn_based, verb in commands:
if len(self.action_filter) != 0 and verb not in self.action_filter:
continue
if type == ... |
load q table from model_file | def loadModel(self, model_file):
"""load q table from model_file"""
with open(model_file) as f:
self.q_table = json.load(f) |
run the agent on the world | def run(self, agent_host):
"""run the agent on the world"""
total_reward = 0
current_r = 0
tol = 0.01
self.prev_s = None
self.prev_a = None
# wait for a valid observation
world_state = agent_host.peekWorldState()
while world_stat... |
Download Malmo from github and build ( by default ) the Minecraft Mod. Example usage: import malmoenv. bootstrap ; malmoenv. bootstrap. download () Args: branch: optional branch to clone. TODO Default is release version. build: build the Mod unless build arg is given as False. installdir: the install dir name. Defaults... | def download(branch=None, build=True, installdir="MalmoPlatform"):
"""Download Malmo from github and build (by default) the Minecraft Mod.
Example usage: import malmoenv.bootstrap; malmoenv.bootstrap.download()
Args:
branch: optional branch to clone. TODO Default is release version.
build... |
Set up Minecraft for use with the MalmoEnv gym environment | def setup(build=True, installdir="MalmoPlatform"):
"""Set up Minecraft for use with the MalmoEnv gym environment"""
gradlew = './gradlew'
if os.name == 'nt':
gradlew = 'gradlew.bat'
cwd = os.getcwd()
os.chdir(installdir)
os.chdir("Minecraft")
try:
# Create the version prope... |
Launch Minecraft listening for malmoenv connections. Args: port: the TCP port to listen on. installdir: the install dir name. Defaults to MalmoPlatform. Must be same as given ( or defaulted ) in download call if used. replaceable: whether or not to automatically restart Minecraft ( default is false ). | def launch_minecraft(port, installdir="MalmoPlatform", replaceable=False):
"""Launch Minecraft listening for malmoenv connections.
Args:
port: the TCP port to listen on.
installdir: the install dir name. Defaults to MalmoPlatform.
Must be same as given (or defaulted) in download call if... |
Track through the middle line of the depth data and find the max discontinuities | def processFrame( frame ):
'''Track through the middle line of the depth data and find the max discontinuities'''
global current_yaw_delta_from_depth
y = int(old_div(video_height, 2))
rowstart = y * video_width
v = 0
v_max = 0
v_max_pos = 0
v_min = 0
v_min_pos = 0
dv =... |
Make sure our coal if we have any is in slot 0. | def checkFuelPosition(obs, agent_host):
'''Make sure our coal, if we have any, is in slot 0.'''
# (We need to do this because the furnace crafting commands - cooking the potato and the rabbit -
# take the first available item of fuel in the inventory. If this isn't the coal, it could end up burning the wood... |
Build an XML mission string that uses the RewardForCollectingItem mission handler. | def GetMissionXML(summary):
''' Build an XML mission string that uses the RewardForCollectingItem mission handler.'''
positions = buildPositionList(items)
return '''<?xml version="1.0" encoding="UTF-8" ?>
<Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLS... |
Re - download all subscriptions and reset the page index | def refresh_content(self, order=None, name=None):
"""
Re-download all subscriptions and reset the page index
"""
# reddit.get_my_subreddits() does not support sorting by order
if order:
self.term.flash()
return
with self.term.loader():
... |
Store the selected subreddit and return to the subreddit page | def select_subreddit(self):
"""
Store the selected subreddit and return to the subreddit page
"""
name = self.get_selected_item()['name']
self.selected_page = self.open_subreddit_page(name) |
Create a RedditContentObject function mapped to a BaseReddit function. | def alias_function(function, class_name):
"""Create a RedditContentObject function mapped to a BaseReddit function.
The BaseReddit classes define the majority of the API's functions. The
first argument for many of these functions is the RedditContentObject that
they operate on. This factory returns fun... |
Deprecate decorated method. | def deprecated(msg=''):
"""Deprecate decorated method."""
@decorator.decorator
def wrap(function, *args, **kwargs):
if not kwargs.pop('disable_warning', False):
warn(msg, DeprecationWarning)
return function(*args, **kwargs)
return wrap |
Truncate the string returned from a function and return the result. | def limit_chars(function, *args, **kwargs):
"""Truncate the string returned from a function and return the result."""
output_chars_limit = args[0].reddit_session.config.output_chars_limit
output_string = function(*args, **kwargs)
if -1 < output_chars_limit < len(output_string):
output_string = o... |
Set the _use_oauth keyword argument to True when appropriate. | def oauth_generator(function, *args, **kwargs):
"""Set the _use_oauth keyword argument to True when appropriate.
This is needed because generator functions may be called at anytime, and
PRAW relies on the Reddit._use_oauth value at original call time to know
when to make OAuth requests.
Returned d... |
Raise client side exception ( s ) when present in the API response. | def raise_api_exceptions(function, *args, **kwargs):
"""Raise client side exception(s) when present in the API response.
Returned data is not modified.
"""
try:
return_value = function(*args, **kwargs)
except errors.HTTPException as exc:
if exc._raw.status_code != 400: # pylint: d... |
Return a decorator for methods that require captchas. | def require_captcha(function, *args, **kwargs):
"""Return a decorator for methods that require captchas."""
raise_captcha_exception = kwargs.pop('raise_captcha_exception', False)
captcha_id = None
# Get a handle to the reddit session
if hasattr(args[0], 'reddit_session'):
reddit_session = a... |
Restrict function access unless the user has the necessary permissions. | def restrict_access(scope, mod=None, login=None, oauth_only=False,
generator_called=False):
"""Restrict function access unless the user has the necessary permissions.
Raises one of the following exceptions when appropriate:
* LoginRequired
* LoginOrOAuthRequired
* the sc... |
Verify that the OAuth functions can be used prior to use. | def require_oauth(function, *args, **kwargs):
"""Verify that the OAuth functions can be used prior to use.
Returned data is not modified.
"""
if not args[0].has_oauth_app_info:
err_msg = ("The OAuth app config parameters client_id, client_secret "
"and redirect_url must be s... |
Return an iterator that starts and the current index and increments by the given step. | def iterate(self, index, step, n_cols=70):
"""
Return an iterator that starts and the current index and increments
by the given step.
"""
while True:
if step < 0 and index < 0:
# Hack to prevent displaying a submission's post if iterating
... |
Flatten a PRAW comment tree while preserving the nested level of each comment via the nested_level attribute. | def flatten_comments(comments, root_level=0):
"""
Flatten a PRAW comment tree while preserving the nested level of each
comment via the `nested_level` attribute.
There are a couple of different ways that the input comment list can be
organized depending on its source:
... |
Parse through a submission comment and return a dict with data ready to be displayed through the terminal. | def strip_praw_comment(cls, comment):
"""
Parse through a submission comment and return a dict with data ready to
be displayed through the terminal.
"""
data = {}
data['object'] = comment
if isinstance(comment, praw.objects.MoreComments):
data['type'... |
Parse through a submission and return a dict with data ready to be displayed through the terminal. | def strip_praw_submission(cls, sub):
"""
Parse through a submission and return a dict with data ready to be
displayed through the terminal.
Definitions:
permalink - URL to the reddit page with submission comments.
url_full - URL that the submission points to.
... |
Parse through a subscription and return a dict with data ready to be displayed through the terminal. | def strip_praw_subscription(subscription):
"""
Parse through a subscription and return a dict with data ready to be
displayed through the terminal.
"""
data = {}
data['object'] = subscription
if isinstance(subscription, praw.objects.Multireddit):
data... |
Parse through a message and return a dict with data ready to be displayed through the terminal. Messages can be of either type praw. objects. Message or praw. object. Comment. The comments returned will contain special fields unique to messages and can t be parsed as normal comment objects. | def strip_praw_message(cls, msg):
"""
Parse through a message and return a dict with data ready to be
displayed through the terminal. Messages can be of either type
praw.objects.Message or praw.object.Comment. The comments returned will
contain special fields unique to messages a... |
Convert a utc timestamp into a human readable relative - time. | def humanize_timestamp(utc_timestamp, verbose=False):
"""
Convert a utc timestamp into a human readable relative-time.
"""
timedelta = datetime.utcnow() - datetime.utcfromtimestamp(utc_timestamp)
seconds = int(timedelta.total_seconds())
if seconds < 60:
retu... |
Wrap text paragraphs to the given character width while preserving newlines. | def wrap_text(text, width):
"""
Wrap text paragraphs to the given character width while preserving
newlines.
"""
out = []
for paragraph in text.splitlines():
# Wrap returns an empty list when paragraph is a newline. In order
# to preserve newlines ... |
Extract a list of hyperlinks from an HTML document. | def extract_links(html):
"""
Extract a list of hyperlinks from an HTML document.
"""
links = []
soup = BeautifulSoup(html, 'html.parser')
for link in soup.findAll('a'):
href = link.get('href')
if not href:
continue
if hr... |
Grab the i th submission with the title field formatted to fit inside of a window of width n | def get(self, index, n_cols=70):
"""
Grab the `i`th submission, with the title field formatted to fit inside
of a window of width `n`
"""
if index < -1:
raise IndexError
elif index == -1:
data = self._submission_data
data['split_title... |
Toggle the state of the object at the given index. | def toggle(self, index, n_cols=70):
"""
Toggle the state of the object at the given index.
If it is a comment, pack it into a hidden comment.
If it is a hidden comment, unpack it.
If it is more comments, load the comments.
"""
data = self.get(index)
if d... |
Params: reddit ( praw. Reddit ): Instance of the reddit api. name ( text ): The name of the desired subreddit user multireddit etc. In most cases this translates directly from the URL that reddit itself uses. This is what users will type in the command prompt when they navigate to a new location. loader ( terminal. loa... | def from_name(cls, reddit, name, loader, order=None, query=None):
"""
Params:
reddit (praw.Reddit): Instance of the reddit api.
name (text): The name of the desired subreddit, user, multireddit,
etc. In most cases this translates directly from the URL that
... |
Grab the i th submission with the title field formatted to fit inside of a window of width n_cols | def get(self, index, n_cols=70):
"""
Grab the `i`th submission, with the title field formatted to fit inside
of a window of width `n_cols`
"""
if index < 0:
raise IndexError
nsfw_count = 0
while index >= len(self._submission_data):
try:
... |
Grab the i th object with the title field formatted to fit inside of a window of width n_cols | def get(self, index, n_cols=70):
"""
Grab the `i`th object, with the title field formatted to fit
inside of a window of width `n_cols`
"""
if index < 0:
raise IndexError
while index >= len(self._subscription_data):
try:
with self.... |
Grab the i th object with the title field formatted to fit inside of a window of width n_cols | def get(self, index, n_cols=70):
"""
Grab the `i`th object, with the title field formatted to fit
inside of a window of width `n_cols`
"""
if index < 0:
raise IndexError
while index >= len(self._content_data):
try:
with self._load... |
Pause before making the next HTTP request. | def _delay(self):
"""
Pause before making the next HTTP request.
"""
if self.next_request_timestamp is None:
return
sleep_seconds = self.next_request_timestamp - time.time()
if sleep_seconds <= 0:
return
time.sleep(sleep_seconds) |
Update the state of the rate limiter based on the response headers: | def _update(self, response_headers):
"""
Update the state of the rate limiter based on the response headers:
X-Ratelimit-Used: Approximate number of requests used this period
X-Ratelimit-Remaining: Approximate number of requests left to use
X-Ratelimit-Reset: Approxi... |
Clear the cache of timed out results. | def _clear_timeouts(self, cache_timeout):
"""
Clear the cache of timed out results.
"""
for key in list(self.timeouts):
if timer() - self.timeouts[key] > cache_timeout:
del self.timeouts[key]
del self.cache[key] |
Remove items from cache matching URLs. | def evict(self, urls):
"""Remove items from cache matching URLs.
Return the number of items removed.
"""
if isinstance(urls, six.text_type):
urls = [urls]
urls = set(normalize_url(url) for url in urls)
retval = 0
for key in list(self.cache):
... |
This is a wrapper function that handles the caching of the request. | def request(self, _cache_key, _cache_ignore, _cache_timeout, **kwargs):
"""
This is a wrapper function that handles the caching of the request.
See DefaultHandler.with_cache for reference.
"""
if _cache_key:
# Pop the request's session cookies from the cache key.
... |
This is where we apply rate limiting and make the HTTP request. | def _request(self, request, proxies, timeout, verify, **_):
"""
This is where we apply rate limiting and make the HTTP request.
"""
settings = self.http.merge_environment_settings(
request.url, proxies, False, verify, None)
self._delay()
response = self.http... |
Return the user - agent string. | def ua_string(praw_info):
"""Return the user-agent string.
The user-agent string contains PRAW version and platform version info.
"""
if os.environ.get('SERVER_SOFTWARE') is not None:
# Google App Engine information
# https://developers.google.com/appengine/docs... |
Given a page url and a dict of params open and return the page. | def _request(self, url, params=None, data=None, files=None, auth=None,
timeout=None, raw_response=False, retry_on_error=True,
method=None):
"""Given a page url and a dict of params, open and return the page.
:param url: the url to grab content from.
:param para... |
Return an appropriate RedditObject from json_data when possible. | def _json_reddit_objecter(self, json_data):
"""Return an appropriate RedditObject from json_data when possible."""
try:
object_class = self.config.by_kind[json_data['kind']]
except KeyError:
if 'json' in json_data:
if len(json_data) != 1:
... |
Evict url ( s ) from the cache. | def evict(self, urls):
"""Evict url(s) from the cache.
:param urls: An iterable containing normalized urls.
:returns: The number of items removed from the cache.
"""
if isinstance(urls, six.string_types):
urls = (urls,)
return self.handler.evict(urls) |
A generator method to return reddit content from a URL. | def get_content(self, url, params=None, limit=0, place_holder=None,
root_field='data', thing_field='children',
after_field='after', object_filter=None, **kwargs):
"""A generator method to return reddit content from a URL.
Starts at the initial url, and fetches co... |
Make a HTTP request and return the response. | def request(self, url, params=None, data=None, retry_on_error=True,
method=None):
"""Make a HTTP request and return the response.
:param url: the url to grab content from.
:param params: a dictionary containing the GET data to put in the url
:param data: a dictionary con... |
Get the JSON processed from a page. | def request_json(self, url, params=None, data=None, as_objects=True,
retry_on_error=True, method=None):
"""Get the JSON processed from a page.
:param url: the url to grab content from.
:param params: a dictionary containing the GET data to put in the url
:param data... |
Return the access information for an OAuth2 authorization grant. | def get_access_information(self, code):
"""Return the access information for an OAuth2 authorization grant.
:param code: the code received in the request from the OAuth2 server
:returns: A dictionary with the key/value pairs for ``access_token``,
``refresh_token`` and ``scope``. The... |
Return the URL to send the user to for OAuth2 authorization. | def get_authorize_url(self, state, scope='identity', refreshable=False):
"""Return the URL to send the user to for OAuth2 authorization.
:param state: a unique string of your choice that represents this
individual client
:param scope: the reddit scope to ask permissions for. Multipl... |
Return updated access information for an OAuth2 authorization grant. | def refresh_access_information(self, refresh_token):
"""Return updated access information for an OAuth2 authorization grant.
:param refresh_token: the refresh token used to obtain the updated
information
:returns: A dictionary with the key/value pairs for access_token,
r... |
Set the app information to use with OAuth2. | def set_oauth_app_info(self, client_id, client_secret, redirect_uri):
"""Set the app information to use with OAuth2.
This function need only be called if your praw.ini site configuration
does not already contain the necessary information.
Go to https://www.reddit.com/prefs/apps/ to dis... |
Register a new user. | def create_redditor(self, user_name, password, email=''):
"""Register a new user.
:returns: The json response from the server.
"""
data = {'email': email,
'passwd': password,
'passwd2': password,
'user': user_name}
return self.req... |
Return a get_content generator for the default subreddits. | def default_subreddits(self, *args, **kwargs):
"""Return a get_content generator for the default subreddits.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
"""
url = self.config['default_subreddits']
... |
Return a get_content generator for comments in the given subreddit. | def get_comments(self, subreddit, gilded_only=False, *args, **kwargs):
"""Return a get_content generator for comments in the given subreddit.
:param gilded_only: If True only return gilded comments.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url... |
Return a get_content generator for controversial submissions. | def get_controversial(self, *args, **kwargs):
"""Return a get_content generator for controversial submissions.
Corresponds to submissions provided by
``https://www.reddit.com/controversial/`` for the session.
The additional parameters are passed directly into
:meth:`.get_conten... |
Return a get_content generator for submissions by domain. | def get_domain_listing(self, domain, sort='hot', period=None, *args,
**kwargs):
"""Return a get_content generator for submissions by domain.
Corresponds to the submissions provided by
``https://www.reddit.com/domain/{domain}``.
:param domain: The domain to ge... |
Return the flair for a user on the given subreddit. | def get_flair(self, subreddit, redditor, **params):
"""Return the flair for a user on the given subreddit.
:param subreddit: Can be either a Subreddit object or the name of a
subreddit.
:param redditor: Can be either a Redditor object or the name of a
redditor.
:... |
Return a get_content generator for the front page submissions. | def get_front_page(self, *args, **kwargs):
"""Return a get_content generator for the front page submissions.
Corresponds to the submissions provided by ``https://www.reddit.com/``
for the session.
The additional parameters are passed directly into
:meth:`.get_content`. Note: th... |
Look up existing items by thing_id ( fullname ) or url. | def get_info(self, url=None, thing_id=None, *args, **kwargs):
"""Look up existing items by thing_id (fullname) or url.
:param url: A url to lookup.
:param thing_id: A single thing_id, or a list of thing_ids. A thing_id
can be any one of Comment (``t1_``), Link (``t3_``), or Subreddi... |
Return the list of moderators for the given subreddit. | def get_moderators(self, subreddit, **kwargs):
"""Return the list of moderators for the given subreddit."""
url = self.config['moderators'].format(
subreddit=six.text_type(subreddit))
return self.request_json(url, **kwargs) |
Return a get_content generator for new submissions. | def get_new(self, *args, **kwargs):
"""Return a get_content generator for new submissions.
Corresponds to the submissions provided by
``https://www.reddit.com/new/`` for the session.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parame... |
Return a get_content generator for the newest subreddits. | def get_new_subreddits(self, *args, **kwargs):
"""Return a get_content generator for the newest subreddits.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
"""
url = self.config['new_subreddits']
retu... |
Return a get_content generator for the most active subreddits. | def get_popular_subreddits(self, *args, **kwargs):
"""Return a get_content generator for the most active subreddits.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
"""
url = self.config['popular_subreddits']... |
Return a random Subreddit object. | def get_random_subreddit(self, nsfw=False):
"""Return a random Subreddit object.
:param nsfw: When true, return a random NSFW Subreddit object. Calling
in this manner will set the 'over18' cookie for the duration of the
PRAW session.
"""
path = 'random'
... |
Return a random Submission object. | def get_random_submission(self, subreddit='all'):
"""Return a random Submission object.
:param subreddit: Limit the submission to the specified
subreddit(s). Default: all
"""
url = self.config['subreddit_random'].format(
subreddit=six.text_type(subreddit))
... |
Return a Redditor instance for the user_name specified. | def get_redditor(self, user_name, *args, **kwargs):
"""Return a Redditor instance for the user_name specified.
The additional parameters are passed directly into the
:class:`.Redditor` constructor.
"""
return objects.Redditor(self, user_name, *args, **kwargs) |
Return a get_content generator for rising submissions. | def get_rising(self, *args, **kwargs):
"""Return a get_content generator for rising submissions.
Corresponds to the submissions provided by
``https://www.reddit.com/rising/`` for the session.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `ur... |
Return the json dictionary containing rules for a subreddit. | def get_rules(self, subreddit, bottom=False):
"""Return the json dictionary containing rules for a subreddit.
:param subreddit: The subreddit whose rules we will return.
"""
url = self.config['rules'].format(subreddit=six.text_type(subreddit))
return self.request_json(url) |
Return a Submission object for the sticky of the subreddit. | def get_sticky(self, subreddit, bottom=False):
"""Return a Submission object for the sticky of the subreddit.
:param bottom: Get the top or bottom sticky. If the subreddit has only
a single sticky, it is considered the top one.
"""
url = self.config['sticky'].format(subredd... |
Return a Submission object for the given url or submission_id. | def get_submission(self, url=None, submission_id=None, comment_limit=0,
comment_sort=None, params=None):
"""Return a Submission object for the given url or submission_id.
:param comment_limit: The desired number of comments to fetch. If <= 0
fetch the default number f... |
Generate Submission objects for each item provided in fullnames. | def get_submissions(self, fullnames, *args, **kwargs):
"""Generate Submission objects for each item provided in `fullnames`.
A submission fullname looks like `t3_<base36_id>`. Submissions are
yielded in the same order they appear in `fullnames`.
Up to 100 items are batched at a time --... |
Return a Subreddit object for the subreddit_name specified. | def get_subreddit(self, subreddit_name, *args, **kwargs):
"""Return a Subreddit object for the subreddit_name specified.
The additional parameters are passed directly into the
:class:`.Subreddit` constructor.
"""
sr_name_lower = subreddit_name.lower()
if sr_name_lower =... |
Return a list of recommended subreddits as Subreddit objects. | def get_subreddit_recommendations(self, subreddits, omit=None):
"""Return a list of recommended subreddits as Subreddit objects.
Subreddits with activity less than a certain threshold, will not have
any recommendations due to lack of data.
:param subreddits: A list of subreddits (eithe... |
Return a get_content generator for top submissions. | def get_top(self, *args, **kwargs):
"""Return a get_content generator for top submissions.
Corresponds to the submissions provided by
``https://www.reddit.com/top/`` for the session.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parame... |
Return a get_content generator for gilded submissions. | def get_gilded(self, *args, **kwargs):
"""Return a get_content generator for gilded submissions.
Corresponds to the submissions provided by
``https://www.reddit.com/gilded/`` for the session.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `ur... |
Return the json dictionary containing traffic stats for a subreddit. | def get_traffic(self, subreddit):
"""Return the json dictionary containing traffic stats for a subreddit.
:param subreddit: The subreddit whose /about/traffic page we will
collect.
"""
url = self.config['subreddit_traffic'].format(
subreddit=six.text_type(subred... |
Return a WikiPage object for the subreddit and page provided. | def get_wiki_page(self, subreddit, page):
"""Return a WikiPage object for the subreddit and page provided."""
return objects.WikiPage(self, six.text_type(subreddit), page.lower()) |
Return True if username is valid and available otherwise False. | def is_username_available(self, username):
"""Return True if username is valid and available, otherwise False."""
params = {'user': username}
try:
result = self.request_json(self.config['username_available'],
params=params)
except errors... |
Return a generator for submissions that match the search query. | def search(self, query, subreddit=None, sort=None, syntax=None,
period=None, *args, **kwargs):
"""Return a generator for submissions that match the search query.
:param query: The query string to search for. If query is a URL only
submissions which link to that URL will be re... |
Return subreddits whose display name contains the query. | def search_reddit_names(self, query):
"""Return subreddits whose display name contains the query."""
data = {'query': query}
results = self.request_json(self.config['search_reddit_names'],
data=data)
return [self.get_subreddit(name) for name in results... |
Accept a moderator invite to the given subreddit. | def accept_moderator_invite(self, subreddit):
"""Accept a moderator invite to the given subreddit.
Callable upon an instance of Subreddit with no arguments.
:returns: The json response from the server.
"""
data = {'r': six.text_type(subreddit)}
# Clear moderated subred... |
Clear any existing authentication on the reddit object. | def clear_authentication(self):
"""Clear any existing authentication on the reddit object.
This function is implicitly called on `login` and
`set_access_credentials`.
"""
self._authentication = None
self.access_token = None
self.refresh_token = None
self... |
Delete the currently authenticated redditor. | def delete(self, password, message=""):
"""Delete the currently authenticated redditor.
WARNING!
This action is IRREVERSIBLE. Use only if you're okay with NEVER
accessing this reddit account again.
:param password: password for currently authenticated account
:param me... |
Create or edit a wiki page with title page for subreddit. | def edit_wiki_page(self, subreddit, page, content, reason=''):
"""Create or edit a wiki page with title `page` for `subreddit`.
:returns: The json response from the server.
"""
data = {'content': content,
'page': page,
'r': six.text_type(subreddit),
... |
Return the access information for an OAuth2 authorization grant. | def get_access_information(self, code, # pylint: disable=W0221
update_session=True):
"""Return the access information for an OAuth2 authorization grant.
:param code: the code received in the request from the OAuth2 server
:param update_session: Update the current... |
Return available flair choices and current flair. | def get_flair_choices(self, subreddit, link=None):
"""Return available flair choices and current flair.
:param link: If link is given, return the flair options for this
submission. Not normally given directly, but instead set by calling
the flair_choices method for Submission ob... |
Return a UserList of Redditors with whom the user is friends. | def get_friends(self, **params):
"""Return a UserList of Redditors with whom the user is friends."""
url = self.config['friends']
return self.request_json(url, params=params)[0] |
Return a LoggedInRedditor object. | def get_me(self):
"""Return a LoggedInRedditor object.
Note: This function is only intended to be used with an 'identity'
providing OAuth2 grant.
"""
response = self.request_json(self.config['me'])
user = objects.Redditor(self, response['name'], response)
user.__... |
Return True if OAuth2 authorized for the passed in scope ( s ). | def has_scope(self, scope):
"""Return True if OAuth2 authorized for the passed in scope(s)."""
if not self.is_oauth_session():
return False
if '*' in self._authentication:
return True
if isinstance(scope, six.string_types):
scope = [scope]
retu... |
Login to a reddit site. | def login(self, username=None, password=None, **kwargs):
"""Login to a reddit site.
**DEPRECATED**. Will be removed in a future version of PRAW.
https://www.reddit.com/comments/2ujhkr/
https://www.reddit.com/comments/37e2mv/
Look for username first in parameter, then praw.ini ... |
Return updated access information for an OAuth2 authorization grant. | def refresh_access_information(self, # pylint: disable=W0221
refresh_token=None,
update_session=True):
"""Return updated access information for an OAuth2 authorization grant.
:param refresh_token: The refresh token used to obtain th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.