text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_grant(self, grant):
""" Adds a Grant that the provider should support. :param grant: An instance of a class that extends :class:`oauth2.grant.GrantHandle... |
if hasattr(grant, "expires_in"):
self.token_generator.expires_in[grant.grant_type] = grant.expires_in
if hasattr(grant, "refresh_expires_in"):
self.token_generator.refresh_expires_in = grant.refresh_expires_in
self.grant_types.append(grant) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(self, request, environ):
""" Checks which Grant supports the current request and dispatches to it. :param request: The incoming request. :type reque... |
try:
grant_type = self._determine_grant_type(request)
response = self.response_class()
grant_type.read_validate_params(request)
return grant_type.process(request, response, environ)
except OAuthInvalidNoRedirectError:
response = self.respon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_unique_tokens(self):
""" Enable the use of unique access tokens on all grant types that support this option. """ |
for grant_type in self.grant_types:
if hasattr(grant_type, "unique_token"):
grant_type.unique_token = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def header(self, name, default=None):
""" Returns the value of the HTTP header identified by `name`. """ |
wsgi_header = "HTTP_{0}".format(name.upper())
try:
return self.env_raw[wsgi_header]
except KeyError:
return default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def http_basic_auth(request):
""" Extracts the credentials of a client using HTTP Basic Auth. Expects the ``client_id`` to be the username and the ``client_secre... |
auth_header = request.header("authorization")
if auth_header is None:
raise OAuthInvalidError(error="invalid_request",
explanation="Authorization header is missing")
auth_parts = auth_header.strip().encode("latin1").split(None)
if auth_parts[0].strip().lower()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_identifier(self, request):
""" Authenticates a client by its identifier. :param request: The incoming request :type request: oauth2.web.Request :return: T... |
client_id = request.get_param("client_id")
if client_id is None:
raise OAuthInvalidNoRedirectError(error="missing_client_id")
try:
client = self.client_store.fetch_by_client_id(client_id)
except ClientNotFoundError:
raise OAuthInvalidNoRedirectError... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expires_in(self):
""" Returns the time until the token expires. :return: The remaining time until expiration in seconds or 0 if the token has expired. """ |
time_left = self.expires_at - int(time.time())
if time_left > 0:
return time_left
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, query, *params):
""" Executes a query and returns the identifier of the modified row. :param query: The query to be executed as a `str`. :param... |
cursor = self.connection.cursor()
try:
cursor.execute(query, params)
self.connection.commit()
return cursor.lastrowid
finally:
cursor.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetchone(self, query, *args):
""" Returns the first result of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of... |
cursor = self.connection.cursor()
try:
cursor.execute(query, args)
return cursor.fetchone()
finally:
cursor.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetchall(self, query, *args):
""" Returns all results of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of para... |
cursor = self.connection.cursor()
try:
cursor.execute(query, args)
return cursor.fetchall()
finally:
cursor.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_by_refresh_token(self, refresh_token):
""" Retrieves an access token by its refresh token. :param refresh_token: The refresh token of an access token a... |
row = self.fetchone(self.fetch_by_refresh_token_query, refresh_token)
if row is None:
raise AccessTokenNotFound
scopes = self._fetch_scopes(access_token_id=row[0])
data = self._fetch_data(access_token_id=row[0])
return self._row_to_token(data=data, scopes=scopes,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_existing_token_of_user(self, client_id, grant_type, user_id):
""" Retrieve an access token issued to a client and user for a specific grant. :param cli... |
token_data = self.fetchone(self.fetch_existing_token_of_user_query,
client_id, grant_type, user_id)
if token_data is None:
raise AccessTokenNotFound
scopes = self._fetch_scopes(access_token_id=token_data[0])
data = self._fetch_data(acces... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_token(self, access_token):
""" Creates a new entry for an access token in the database. :param access_token: An instance of :class:`oauth2.datatype.Acce... |
access_token_id = self.execute(self.create_access_token_query,
access_token.client_id,
access_token.grant_type,
access_token.token,
access_token.expires_at... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_by_code(self, code):
""" Retrieves an auth code by its code. :param code: The code of an auth code. :return: An instance of :class:`oauth2.datatype.Aut... |
auth_code_data = self.fetchone(self.fetch_code_query, code)
if auth_code_data is None:
raise AuthCodeNotFound
data = dict()
data_result = self.fetchall(self.fetch_data_query, auth_code_data[0])
if data_result is not None:
for dataset in data_result:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_code(self, authorization_code):
""" Creates a new entry of an auth code in the database. :param authorization_code: An instance of :class:`oauth2.dataty... |
auth_code_id = self.execute(self.create_auth_code_query,
authorization_code.client_id,
authorization_code.code,
authorization_code.expires_at,
authorization_code.redir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_by_client_id(self, client_id):
""" Retrieves a client by its identifier. :param client_id: The identifier of a client. :return: An instance of :class:`... |
grants = None
redirect_uris = None
response_types = None
client_data = self.fetchone(self.fetch_client_query, client_id)
if client_data is None:
raise ClientNotFoundError
grant_data = self.fetchall(self.fetch_grants_query, client_data[0])
if grant_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_by_code(self, code):
""" Returns data belonging to an authorization code from memcache or ``None`` if no data was found. See :class:`oauth2.store.AuthC... |
code_data = self.mc.get(self._generate_cache_key(code))
if code_data is None:
raise AuthCodeNotFound
return AuthorizationCode(**code_data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_code(self, authorization_code):
""" Stores the data belonging to an authorization code token in memcache. See :class:`oauth2.store.AuthCodeStore`. """ |
key = self._generate_cache_key(authorization_code.code)
self.mc.set(key, {"client_id": authorization_code.client_id,
"code": authorization_code.code,
"expires_at": authorization_code.expires_at,
"redirect_uri": authorization... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_token(self, access_token):
""" Stores the access token and additional data in memcache. See :class:`oauth2.store.AccessTokenStore`. """ |
key = self._generate_cache_key(access_token.token)
self.mc.set(key, access_token.__dict__)
unique_token_key = self._unique_token_key(access_token.client_id,
access_token.grant_type,
access_token... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_scopes(scopes, use_quote=False):
""" Creates a string out of a list of scopes. :param scopes: A list of scopes :param use_quote: Boolean flag indicati... |
scopes_as_string = Scope.separator.join(scopes)
if use_quote:
return quote(scopes_as_string)
return scopes_as_string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json_error_response(error, response, status_code=400):
""" Formats an error as a response containing a JSON body. """ |
msg = {"error": error.error, "error_description": error.explanation}
response.status_code = status_code
response.add_header("Content-Type", "application/json")
response.body = json.dumps(msg)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json_success_response(data, response):
""" Formats the response of a successful token request as JSON. Also adds default headers and status code. """ |
response.body = json.dumps(data)
response.status_code = 200
response.add_header("Content-Type", "application/json")
response.add_header("Cache-Control", "no-store")
response.add_header("Pragma", "no-cache") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare(self, previous_scopes):
""" Compares the scopes read from request with previously issued scopes. :param previous_scopes: A list of scopes. :return: `... |
for scope in self.scopes:
if scope not in previous_scopes:
raise OAuthInvalidError(
error="invalid_scope",
explanation="Invalid scope parameter in request")
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, request, source):
""" Parses scope value in given request. Expects the value of the "scope" parameter in request to be a string where each reques... |
if source == "body":
req_scope = request.post_param("scope")
elif source == "query":
req_scope = request.get_param("scope")
else:
raise ValueError("Unknown scope source '" + source + "'")
if req_scope is None:
if self.default is not None:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_validate_params(self, request):
""" Reads and validates data in an incoming request as required by the Authorization Request of the Authorization Code G... |
self.client = self.client_authenticator.by_identifier(request)
response_type = request.get_param("response_type")
if self.client.response_type_supported(response_type) is False:
raise OAuthInvalidError(error="unauthorized_client")
self.state = request.get_param("state")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorize(self, request, response, environ, scopes):
""" Controls all steps to authorize a request by a user. :param request: The incoming :class:`oauth2.web... |
if self.site_adapter.user_has_denied_access(request) is True:
raise OAuthInvalidError(error="access_denied",
explanation="Authorization denied by user")
try:
result = self.site_adapter.authenticate(request, environ, scopes,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, request, response, environ):
""" Generates a new authorization token. A form to authorize the access of the application can be displayed with t... |
data = self.authorize(request, response, environ,
self.scope_handler.scopes)
if isinstance(data, Response):
return data
code = self.token_generator.generate()
expires = int(time.time()) + self.token_expiration
auth_code = Authorizatio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_error(self, error, response):
""" Redirects the client in case an error in the auth process occurred. """ |
query_params = {"error": error.error}
query = urlencode(query_params)
location = "%s?%s" % (self.client.redirect_uri, query)
response.status_code = 302
response.body = ""
response.add_header("Location", location)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, request, response, environ):
""" Generates a new access token and returns it. Returns the access token and the type of the token as JSON. Calls... |
token_data = self.create_token(
client_id=self.client.identifier,
data=self.data,
grant_type=AuthorizationCodeGrant.grant_type,
scopes=self.scopes,
user_id=self.user_id)
self.auth_code_store.delete_code(self.code)
if self.scopes:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, request, response, environ):
""" Takes the incoming request, asks the concrete SiteAdapter to validate it and issues a new access token that is... |
try:
data = self.site_adapter.authenticate(request, environ,
self.scope_handler.scopes,
self.client)
data = AuthorizeMixin.sanitize_return_value(data)
except UserNotAuthenticated:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_validate_params(self, request):
""" Checks if all incoming parameters meet the expected values. """ |
self.client = self.client_authenticator.by_identifier_secret(request)
self.password = request.post_param("password")
self.username = request.post_param("username")
self.scope_handler.parse(request=request, source="body")
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_validate_params(self, request):
""" Validate the incoming request. :param request: The incoming :class:`oauth2.web.Request`. :return: Returns ``True`` i... |
self.refresh_token = request.post_param("refresh_token")
if self.refresh_token is None:
raise OAuthInvalidError(
error="invalid_request",
explanation="Missing refresh_token in request body")
self.client = self.client_authenticator.by_identifier_secr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value_for_keypath(obj, path):
"""Get value from walking key path with start object obj. """ |
val = obj
for part in path.split('.'):
match = re.match(list_index_re, part)
if match is not None:
val = _extract(val, match.group(1))
if not isinstance(val, list) and not isinstance(val, tuple):
raise TypeError('expected list/tuple')
index = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_value_for_keypath(obj, path, new_value, preserve_child = False):
"""Set attribute value new_value at key path of start object obj. """ |
parts = path.split('.')
last_part = len(parts) - 1
dst = obj
for i, part in enumerate(parts):
match = re.match(list_index_re, part)
if match is not None:
dst = _extract(dst, match.group(1))
if not isinstance(dst, list) and not isinstance(dst, tuple):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view_for_image_named(image_name):
"""Create an ImageView for the given image.""" |
image = resource.get_image(image_name)
if not image:
return None
return ImageView(pygame.Rect(0, 0, 0, 0), image) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill_gradient(surface, color, gradient, rect=None, vertical=True, forward=True):
"""Fill a surface with a linear gradient pattern. color starting color gradi... |
if rect is None:
rect = surface.get_rect()
x1, x2 = rect.left, rect.right
y1, y2 = rect.top, rect.bottom
if vertical:
h = y2 - y1
else:
h = x2 - x1
assert h > 0
if forward:
a, b = color, gradient
else:
b, a = color, gradient
rate = (floa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shrink_wrap(self):
"""Tightly bound the current text respecting current padding.""" |
self.frame.size = (self.text_size[0] + self.padding[0] * 2,
self.text_size[1] + self.padding[1] * 2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def layout(self):
"""Call to have the view layout itself. Subclasses should invoke this after laying out child views and/or updating its own frame. """ |
if self.shadowed:
shadow_size = theme.current.shadow_size
shadowed_frame_size = (self.frame.w + shadow_size,
self.frame.h + shadow_size)
self.surface = pygame.Surface(
shadowed_frame_size, pygame.SRCALPHA, 32)
sh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stylize(self):
"""Apply theme style attributes to this instance and its children. This also causes a relayout to occur so that any changes in padding or othe... |
# do children first in case parent needs to override their style
for child in self.children:
child.stylize()
style = theme.current.get_dict(self)
preserve_child = False
try:
preserve_child = getattr(theme.current, 'preserve_child')
except:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self):
"""Do not call directly.""" |
if self.hidden:
return False
if self.background_color is not None:
render.fillrect(self.surface, self.background_color,
rect=pygame.Rect((0, 0), self.frame.size))
for child in self.children:
if not child.hidden:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_border_widths(self):
"""Return border width for each side top, left, bottom, right.""" |
if type(self.border_widths) is int: # uniform size
return [self.border_widths] * 4
return self.border_widths |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def use_theme(theme):
"""Make the given theme current. There are two included themes: light_theme, dark_theme. """ |
global current
current = theme
import scene
if scene.current is not None:
scene.current.stylize() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, class_name, state, key, value):
"""Set a single style value for a view class and state. class_name The name of the class to be styled; do not inclu... |
self._styles.setdefault(class_name, {}).setdefault(state, {})
self._styles[class_name][state][key] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dict_for_class(self, class_name, state=None, base_name='View'):
"""The style dict for a given class and state. This collects the style attributes from pa... |
classes = []
klass = class_name
while True:
classes.append(klass)
if klass.__name__ == base_name:
break
klass = klass.__bases__[0]
if state is None:
state = 'normal'
style = {}
for klass in classes:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dict(self, obj, state=None, base_name='View'):
"""The style dict for a view instance. """ |
return self.get_dict_for_class(class_name=obj.__class__,
state=obj.state,
base_name=base_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_value(self, class_name, attr, default_value=None, state='normal', base_name='View'):
"""Get a single style attribute value for the given class. """ |
styles = self.get_dict_for_class(class_name, state, base_name)
try:
return styles[attr]
except KeyError:
return default_value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instantiate_object_id_field(object_id_class_or_tuple=models.TextField):
""" Instantiates and returns a model field for FieldHistory.object_id. object_id_clas... |
if isinstance(object_id_class_or_tuple, (list, tuple)):
object_id_class, object_id_kwargs = object_id_class_or_tuple
else:
object_id_class = object_id_class_or_tuple
object_id_kwargs = {}
if not issubclass(object_id_class, models.fields.Field):
raise TypeError('settings.%s ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_expired(self, lifetime, now=None):
"""Report if the session key has expired. :param lifetime: A :class:`datetime.timedelta` that specifies the maximum ag... |
now = now or datetime.utcnow()
return now > self.created + lifetime |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unserialize(cls, string):
"""Unserializes from a string. :param string: A string created by :meth:`serialize`. """ |
id_s, created_s = string.split('_')
return cls(int(id_s, 16),
datetime.utcfromtimestamp(int(created_s, 16))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def destroy(self):
"""Destroys a session completely, by deleting all keys and removing it from the internal store immediately. This allows removing a session for... |
for k in list(self.keys()):
del self[k]
if getattr(self, 'sid_s', None):
current_app.kvsession_store.delete(self.sid_s)
self.sid_s = None
self.modified = False
self.new = False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regenerate(self):
"""Generate a new session id for this session. To avoid vulnerabilities through `session fixation attacks <http://en.wikipedia.org/wiki/Ses... |
self.modified = True
if getattr(self, 'sid_s', None):
# delete old session
current_app.kvsession_store.delete(self.sid_s)
# remove sid_s, set modified
self.sid_s = None
self.modified = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_sessions(self, app=None):
"""Removes all expired session from the store. Periodically, this function can be called to remove sessions from the backen... |
if not app:
app = current_app
for key in app.kvsession_store.keys():
m = self.key_regex.match(key)
now = datetime.utcnow()
if m:
# read id
sid = SessionID.unserialize(key)
# remove if expired
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app, session_kvstore=None):
"""Initialize application and KVSession. This will replace the session management of the application with Flask-KV... |
app.config.setdefault('SESSION_KEY_BITS', 64)
app.config.setdefault('SESSION_RANDOM_SOURCE', SystemRandom())
if not session_kvstore and not self.default_kvstore:
raise ValueError('Must supply session_kvstore either on '
'construction or init_app().')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transfer_config_dict(soap_object, data_dict):
""" This is a utility function used in the certification modules to transfer the data dicts above to SOAP objec... |
for key, val in data_dict.items():
# Transfer each key to the matching attribute ont he SOAP object.
setattr(soap_object, key, val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_package(self, package_item):
""" Adds a package to the ship request. @type package_item: WSDL object, type of RequestedPackageLineItem WSDL object. @keyw... |
self.RequestedShipment.RequestedPackageLineItems.append(package_item)
package_weight = package_item.Weight.Value
self.RequestedShipment.TotalWeight.Value += package_weight
self.RequestedShipment.PackageCount += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_wsdl_objects(self):
""" Preps the WSDL data structures for the user. """ |
self.DeletionControlType = self.client.factory.create('DeletionControlType')
self.TrackingId = self.client.factory.create('TrackingId')
self.TrackingId.TrackingIdType = self.client.factory.create('TrackingIdType') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __set_web_authentication_detail(self):
""" Sets up the WebAuthenticationDetail node. This is required for all requests. """ |
# Start of the authentication stuff.
web_authentication_credential = self.client.factory.create('WebAuthenticationCredential')
web_authentication_credential.Key = self.config_obj.key
web_authentication_credential.Password = self.config_obj.password
# Encapsulates the auth cred... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __set_client_detail(self, *args, **kwargs):
""" Sets up the ClientDetail node, which is required for all shipping related requests. """ |
client_detail = self.client.factory.create('ClientDetail')
client_detail.AccountNumber = self.config_obj.account_number
client_detail.MeterNumber = self.config_obj.meter_number
client_detail.IntegratorId = self.config_obj.integrator_id
if hasattr(client_detail, 'Region'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __set_transaction_detail(self, *args, **kwargs):
""" Checks kwargs for 'customer_transaction_id' and sets it if present. """ |
customer_transaction_id = kwargs.get('customer_transaction_id', None)
if customer_transaction_id:
transaction_detail = self.client.factory.create('TransactionDetail')
transaction_detail.CustomerTransactionId = customer_transaction_id
self.logger.debug(transaction_de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __set_version_id(self):
""" Pulles the versioning info for the request from the child request. """ |
version_id = self.client.factory.create('VersionId')
version_id.ServiceId = self._version_info['service_id']
version_id.Major = self._version_info['major']
version_id.Intermediate = self._version_info['intermediate']
version_id.Minor = self._version_info['minor']
self.l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __check_response_for_fedex_error(self):
""" This checks the response for general Fedex errors that aren't related to any one WSDL. """ |
if self.response.HighestSeverity == "FAILURE":
for notification in self.response.Notifications:
if notification.Severity == "FAILURE":
raise FedexFailure(notification.Code,
notification.Message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_response_for_request_errors(self):
""" Override this in each service module to check for errors that are specific to that module. For example, invalid... |
if self.response.HighestSeverity == "ERROR":
for notification in self.response.Notifications:
if notification.Severity == "ERROR":
raise FedexError(notification.Code,
notification.Message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_request(self, send_function=None):
""" Sends the assembled request on the child object. @type send_function: function reference @keyword send_function: ... |
# Send the request and get the response back.
try:
# If the user has overridden the send function, use theirs
# instead of the default.
if send_function:
# Follow the overridden function.
self.response = send_function()
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_wsdl_objects(self):
""" This sets the package identifier information. This may be a tracking number or a few different things as per the Fedex spec.... |
self.SelectionDetails = self.client.factory.create('TrackSelectionDetail')
# Default to Fedex
self.SelectionDetails.CarrierCode = 'FDXE'
track_package_id = self.client.factory.create('TrackPackageIdentifier')
# Default to tracking number.
track_package_id.Type = 'TRA... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_label(self, package_num=None):
""" Prints all of a shipment's labels, or optionally just one. @type package_num: L{int} @param package_num: 0-based ind... |
if package_num:
packages = [
self.shipment.response.CompletedShipmentDetail.CompletedPackageDetails[package_num]
]
else:
packages = self.shipment.response.CompletedShipmentDetail.CompletedPackageDetails
for package in packages:
l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _print_base64(self, base64_data):
""" Pipe the binary directly to the label printer. Works under Linux without requiring PySerial. This is not typically some... |
label_file = open(self.device, "w")
label_file.write(base64_data)
label_file.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def guess_tags(filename):
""" Function to get potential tags for files using the file names. :param filename: This field is the name of file. """ |
tags = []
stripped_filename = strip_zip_suffix(filename)
if stripped_filename.endswith('.vcf'):
tags.append('vcf')
if stripped_filename.endswith('.json'):
tags.append('json')
if stripped_filename.endswith('.csv'):
tags.append('csv')
return tags |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def characterize_local_files(filedir, max_bytes=MAX_FILE_DEFAULT):
""" Collate local file info as preperation for Open Humans upload. Note: Files with filesize >... |
file_data = {}
logging.info('Characterizing files in {}'.format(filedir))
for filename in os.listdir(filedir):
filepath = os.path.join(filedir, filename)
file_stats = os.stat(filepath)
creation_date = arrow.get(file_stats.st_ctime).isoformat()
file_size = file_stats.st_size
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_metadata(target_dir, metadata):
""" Check that the files listed in metadata exactly match files in target dir. :param target_dir: This field is the ... |
if not os.path.isdir(target_dir):
print("Error: " + target_dir + " is not a directory")
return False
file_list = os.listdir(target_dir)
for filename in file_list:
if filename not in metadata:
print("Error: " + filename + " present at" + target_dir +
" n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_metadata_csv_single_user(csv_in, header, tags_idx):
""" Return the metadata as requested for a single user. :param csv_in: This field is the csv file to... |
metadata = {}
n_headers = len(header)
for index, row in enumerate(csv_in, 2):
if row[0] == "":
raise ValueError('Error: In row number ' + str(index) + ':' +
' "filename" must not be empty.')
if row[0] == 'None' and [x == 'NA' for x in row[1:]]:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_metadata_csv(input_filepath):
""" Return dict of metadata. Format is either dict (filenames are keys) or dict-of-dicts (project member IDs as top level ... |
with open(input_filepath) as f:
csv_in = csv.reader(f)
header = next(csv_in)
if 'tags' in header:
tags_idx = header.index('tags')
else:
raise ValueError('"tags" is a compulsory column in metadata file.')
if header[0] == 'project_member_id':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_date(date, project_member_id, filename):
""" Check if date is in ISO 8601 format. :param date: This field is the date to be checked. :param project_... |
try:
arrow.get(date)
except Exception:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_single_file_metadata_valid(file_metadata, project_member_id, filename):
""" Check if metadata fields like project member id, description, tags, md5 and cr... |
if project_member_id is not None:
if not project_member_id.isdigit() or len(project_member_id) != 8:
raise ValueError(
'Error: for project member id: ', project_member_id,
' and filename: ', filename,
' project member id must be of 8 digits from 0... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def review_metadata_csv_single_user(filedir, metadata, csv_in, n_headers):
""" Check validity of metadata for single user. :param filedir: This field is the file... |
try:
if not validate_metadata(filedir, metadata):
return False
for filename, file_metadata in metadata.items():
is_single_file_metadata_valid(file_metadata, None, filename)
except ValueError as e:
print_error(e)
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_subfolders(filedir, metadata):
""" Check that all folders in the given directory have a corresponding entry in the metadata file, and vice versa. :p... |
if not os.path.isdir(filedir):
print("Error: " + filedir + " is not a directory")
return False
subfolders = os.listdir(filedir)
for subfolder in subfolders:
if subfolder not in metadata:
print("Error: folder " + subfolder +
" present on disk but not in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def review_metadata_csv_multi_user(filedir, metadata, csv_in, n_headers):
""" Check validity of metadata for multi user. :param filedir: This field is the filepa... |
try:
if not validate_subfolders(filedir, metadata):
return False
for project_member_id, member_metadata in metadata.items():
if not validate_metadata(os.path.join
(filedir, project_member_id),
member_m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def review_metadata_csv(filedir, input_filepath):
""" Check validity of metadata fields. :param filedir: This field is the filepath of the directory whose csv ha... |
try:
metadata = load_metadata_csv(input_filepath)
except ValueError as e:
print_error(e)
return False
with open(input_filepath) as f:
csv_in = csv.reader(f)
header = next(csv_in)
n_headers = len(header)
if header[0] == 'filename':
res = r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mk_metadata_csv(filedir, outputfilepath, max_bytes=MAX_FILE_DEFAULT):
""" Make metadata file for all files in a directory. :param filedir: This field is the ... |
with open(outputfilepath, 'w') as filestream:
write_metadata_to_filestream(filedir, filestream, max_bytes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_id_list(filepath):
""" Get project member id from a file. :param filepath: This field is the path of file to read. """ |
if not filepath:
return None
id_list = []
with open(filepath) as f:
for line in f:
line = line.rstrip()
if not re.match('^[0-9]{8}$', line):
raise('Each line in whitelist or blacklist is expected '
'to contain an eight digit ID, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_log_level(debug, verbose):
""" Function for setting the logging level. :param debug: This boolean field is the logging level. :param verbose: This boolea... |
if debug:
logging.basicConfig(level=logging.DEBUG)
elif verbose:
logging.basicConfig(level=logging.INFO) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(directory, master_token=None, member=None, access_token=None, source=None, project_data=False, max_size='128m', verbose=False, debug=False, memberlis... |
set_log_level(debug, verbose)
if (memberlist or excludelist) and (member or access_token):
raise UsageError('Please do not provide a memberlist or excludelist '
'when retrieving data for a single member.')
memberlist = read_id_list(memberlist)
excludelist = read_id_lis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_metadata(master_token, output_csv, verbose=False, debug=False):
""" Output CSV with metadata for a project's downloadable files in Open Humans. :par... |
set_log_level(debug, verbose)
project = OHProject(master_access_token=master_token)
with open(output_csv, 'w') as f:
csv_writer = csv.writer(f)
header = ['project_member_id', 'data_source', 'file_basename',
'file_upload_date']
csv_writer.writerow(header)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(directory, metadata_csv, master_token=None, member=None, access_token=None, safe=False, sync=False, max_size='128m', mode='default', verbose=False, deb... |
if safe and sync:
raise UsageError('Safe (--safe) and sync (--sync) modes are mutually '
'incompatible!')
if not (master_token or access_token) or (master_token and access_token):
raise UsageError('Please specify either a master access token (-T), '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def public_data_download_cli(source, username, directory, max_size, quiet, debug):
""" Command line tools for downloading public data. """ |
return public_download(source, username, directory, max_size, quiet, debug) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(source=None, username=None, directory='.', max_size='128m', quiet=None, debug=None):
""" Download public data from Open Humans. :param source: This ... |
if debug:
logging.basicConfig(level=logging.DEBUG)
elif quiet:
logging.basicConfig(level=logging.ERROR)
else:
logging.basicConfig(level=logging.INFO)
logging.debug("Running with source: '{}'".format(source) +
" and username: '{}'".format(username) +
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_members_by_source(base_url=BASE_URL_API):
""" Function returns which members have joined each activity. :param base_url: It is URL: `https://www.openhuma... |
url = '{}members-by-source/'.format(base_url)
response = get_page(url)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_sources_by_member(base_url=BASE_URL_API, limit=LIMIT_DEFAULT):
""" Function returns which activities each member has joined. :param base_url: It is URL: ... |
url = '{}sources-by-member/'.format(base_url)
page = '{}?{}'.format(url, urlencode({'limit': limit}))
results = []
while True:
data = get_page(page)
results = results + data['results']
if data['next']:
page = data['next']
else:
break
return re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_member_file_data(member_data, id_filename=False):
""" Helper function to get file data of member of a project. :param member_data: This field is data re... |
file_data = {}
for datafile in member_data['data']:
if id_filename:
basename = '{}.{}'.format(datafile['id'], datafile['basename'])
else:
basename = datafile['basename']
if (basename not in file_data or
arrow.get(da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_data(self):
""" Returns data for all users including shared data files. """ |
url = ('https://www.openhumans.org/api/direct-sharing/project/'
'members/?access_token={}'.format(self.master_access_token))
results = get_all_results(url)
self.project_data = dict()
for result in results:
self.project_data[result['project_member_id']] = resul... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_member_project_data(cls, member_data, target_member_dir, max_size=MAX_SIZE_DEFAULT, id_filename=False):
""" Download files to sync a local dir to ma... |
logging.debug('Download member project data...')
sources_shared = member_data['sources_shared']
file_data = cls._get_member_file_data(member_data,
id_filename=id_filename)
for basename in file_data:
# This is using a trick to ide... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_member_shared(cls, member_data, target_member_dir, source=None, max_size=MAX_SIZE_DEFAULT, id_filename=False):
""" Download files to sync a local di... |
logging.debug('Download member shared data...')
sources_shared = member_data['sources_shared']
file_data = cls._get_member_file_data(member_data,
id_filename=id_filename)
logging.info('Downloading member data to {}'.format(target_member_dir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_all(self, target_dir, source=None, project_data=False, memberlist=None, excludelist=None, max_size=MAX_SIZE_DEFAULT, id_filename=False):
""" Downloa... |
members = self.project_data.keys()
for member in members:
if not (memberlist is None) and member not in memberlist:
logging.debug('Skipping {}, not in memberlist'.format(member))
continue
if excludelist and member in excludelist:
l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_member_from_dir(member_data, target_member_dir, metadata, access_token, mode='default', max_size=MAX_SIZE_DEFAULT):
""" Upload files in target directo... |
if not validate_metadata(target_member_dir, metadata):
raise ValueError('Metadata should match directory contents!')
project_data = {f['basename']: f for f in member_data['data'] if
f['source'] not in member_data['sources_shared']}
for filename in metadata:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_page(url):
""" Get a single page of results. :param url: This field is the url from which data will be requested. """ |
response = requests.get(url)
handle_error(response, 200)
data = response.json()
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_results(starting_page):
""" Given starting API query for Open Humans, iterate to get all results. :param starting page: This field is the first page,... |
logging.info('Retrieving all results for {}'.format(starting_page))
page = starting_page
results = []
while True:
logging.debug('Getting data from: {}'.format(page))
data = get_page(page)
logging.debug('JSON data: {}'.format(data))
results = results + data['results']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exchange_oauth2_member(access_token, base_url=OH_BASE_URL, all_files=False):
""" Returns data for a specific user, including shared data files. :param access... |
url = urlparse.urljoin(
base_url,
'/api/direct-sharing/project/exchange-member/?{}'.format(
urlparse.urlencode({'access_token': access_token})))
member_data = get_page(url)
returned = member_data.copy()
# Get all file data if all_files is True.
if all_files:
wh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_error(r, expected_code):
""" Helper function to match reponse of a request to the expected status code :param r: This field is the response of request... |
code = r.status_code
if code != expected_code:
info = 'API response status code {}'.format(code)
try:
if 'detail' in r.json():
info = info + ": {}".format(r.json()['detail'])
elif 'metadata' in r.json():
info = info + ": {}".format(r.json(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pack_list(from_, pack_type):
""" Return the wire packed version of `from_`. `pack_type` should be some subclass of `xcffib.Struct`, or a string that can be p... |
# We need from_ to not be empty
if len(from_) == 0:
return bytes()
if pack_type == 'c':
if isinstance(from_, bytes):
# Catch Python 3 bytes and Python 2 strings
# PY3 is "helpful" in that when you do tuple(b'foo') you get
# (102, 111, 111) instead of som... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_connected(f):
""" Check that the connection is valid both before and after the function is invoked. """ |
@functools.wraps(f)
def wrapper(*args):
self = args[0]
self.invalid()
try:
return f(*args)
finally:
self.invalid()
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_screen_pointers(self):
""" Returns the xcb_screen_t for every screen useful for other bindings """ |
root_iter = lib.xcb_setup_roots_iterator(self._setup)
screens = [root_iter.data]
for i in range(self._setup.roots_len - 1):
lib.xcb_screen_next(ffi.addressof((root_iter)))
screens.append(root_iter.data)
return screens |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.