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 taper(path,
length,
final_width,
final_distance,
direction=None,
layer=0,
datatype=0):
'''
Linear tapers for the lazy.
path : `gdspy.Path` to append the taper
length : total length
final_width : final width of th taper
direction : taper direction
layer : GDSII layer number (int or list)
datatype : GDSII datatype number (int or list)
Parameters `layer` and `datatype` must be of the same type. If they
are lists, they must have the same length. Their length indicate the
number of pieces that compose the taper.
Return `path`.
'''
if layer.__class__ == datatype.__class__ == [].__class__:
assert len(layer) == len(datatype)
elif isinstance(layer, int) and isinstance(datatype, int):
layer = [layer]
datatype = [datatype]
else:
raise ValueError('Parameters layer and datatype must have the same '
'type (either int or list) and length.')
n = len(layer)
w = numpy.linspace(2 * path.w, final_width, n + 1)[1:]
d = numpy.linspace(path.distance, final_distance, n + 1)[1:]
l = float(length) / n
for i in range(n):
path.segment(
l, direction, w[i], d[i], layer=layer[i], datatype=datatype[i])
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def grating(period,
number_of_teeth,
fill_frac,
width,
position,
direction,
lda=1,
sin_theta=0,
focus_distance=-1,
focus_width=-1,
evaluations=99,
layer=0,
datatype=0):
'''
Straight or focusing grating.
period : grating period
number_of_teeth : number of teeth in the grating
fill_frac : filling fraction of the teeth (w.r.t. the period)
width : width of the grating
position : grating position (feed point)
direction : one of {'+x', '-x', '+y', '-y'}
lda : free-space wavelength
sin_theta : sine of incidence angle
focus_distance : focus distance (negative for straight grating)
focus_width : if non-negative, the focusing area is included in
the result (usually for negative resists) and this
is the width of the waveguide connecting to the
grating
evaluations : number of evaluations of `path.parametric`
layer : GDSII layer number
datatype : GDSII datatype number
Return `PolygonSet`
'''
if focus_distance < 0:
path = gdspy.L1Path(
(position[0] - 0.5 * width,
position[1] + 0.5 * (number_of_teeth - 1 + fill_frac) * period),
'+x',
period * fill_frac, [width], [],
number_of_teeth,
period,
layer=layer,
datatype=datatype)
else:
neff = lda / float(period) + sin_theta
qmin = int(focus_distance / float(period) + 0.5)
path = gdspy.Path(period * fill_frac, position)
max_points = 199 if focus_width < 0 else 2 * evaluations
c3 = neff**2 - sin_theta**2
w = 0.5 * width
for q in range(qmin, qmin + number_of_teeth):
c1 = q * lda * sin_theta
c2 = (q * lda)**2
path.parametric(
lambda t: (width * t - w, (c1 + neff * numpy.sqrt(c2 - c3 * (
width * t - w)**2)) / c3),
number_of_evaluations=evaluations,
max_points=max_points,
layer=layer,
datatype=datatype)
path.x = position[0]
path.y = position[1]
if focus_width >= 0:
path.polygons[0] = numpy.vstack(
(path.polygons[0][:evaluations, :],
([position] if focus_width == 0 else
[(position[0] + 0.5 * focus_width, position[1]),
(position[0] - 0.5 * focus_width, position[1])])))
path.fracture()
if direction == '-x':
return path.rotate(0.5 * numpy.pi, position)
elif direction == '+x':
return path.rotate(-0.5 * numpy.pi, position)
elif direction == '-y':
return path.rotate(numpy.pi, position)
else:
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_pdf(html, stylesheets=None, download_filename=None, automatic_download=True):
"""Render a PDF to a response with the correct ``Content-Type`` header. :param html: Either a :class:`weasyprint.HTML` object or an URL to be passed to :func:`flask_weasyprint.HTML`. The latter case requires a request context. :param stylesheets: A list of user stylesheets, passed to :meth:`~weasyprint.HTML.write_pdf` :param download_filename: If provided, the ``Content-Disposition`` header is set so that most web browser will show the "Save as…" dialog with the value as the default filename. :param automatic_download: If True, the browser will automatic download file. :returns: a :class:`flask.Response` object. """ |
if not hasattr(html, 'write_pdf'):
html = HTML(html)
pdf = html.write_pdf(stylesheets=stylesheets)
response = current_app.response_class(pdf, mimetype='application/pdf')
if download_filename:
if automatic_download:
value = 'attachment'
else:
value = 'inline'
response.headers.add('Content-Disposition', value,
filename=download_filename)
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 _inject_args(sig, types):
""" A function to inject arguments manually into a method signature before it's been parsed. If using keyword arguments use 'kw=type' instead in the types array. sig the string signature types a list of types to be inserted Returns the altered signature. """ |
if '(' in sig:
parts = sig.split('(')
sig = '%s(%s%s%s' % (
parts[0], ', '.join(types),
(', ' if parts[1].index(')') > 0 else ''), parts[1])
else:
sig = '%s(%s)' % (sig, ', '.join(types))
return sig |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jsonrpc_method(name, authenticated=False, authentication_arguments=['username', 'password'], safe=False, validate=False, site=default_site):
""" Wraps a function turns it into a json-rpc method. Adds several attributes to the function specific to the JSON-RPC machinery and adds it to the default jsonrpc_site if one isn't provided. You must import the module containing these functions in your urls.py. name The name of your method. IE: `namespace.methodName` The method name can include type information, like `ns.method(String, Array) -> Nil`. authenticated=False Adds `username` and `password` arguments to the beginning of your method if the user hasn't already been authenticated. These will be used to authenticate the user against `django.contrib.authenticate` If you use HTTP auth or other authentication middleware, `username` and `password` will not be added, and this method will only check against `request.user.is_authenticated`. You may pass a callable to replace `django.contrib.auth.authenticate` as the authentication method. It must return either a User or `None` and take the keyword arguments `username` and `password`. safe=False Designates whether or not your method may be accessed by HTTP GET. By default this is turned off. validate=False Validates the arguments passed to your method based on type information provided in the signature. Supply type information by including types in your method declaration. Like so: @jsonrpc_method('myapp.specialSauce(Array, String)', validate=True) def special_sauce(self, ingredients, instructions):
return SpecialSauce(ingredients, instructions) Calls to `myapp.specialSauce` will now check each arguments type before calling `special_sauce`, throwing an `InvalidParamsError` when it encounters a discrepancy. This can significantly reduce the amount of code required to write JSON-RPC services. site=default_site Defines which site the jsonrpc method will be added to. Can be any object that provides a `register(name, func)` method. """ |
def decorator(func):
arg_names = getargspec(func)[0][1:]
X = {'name': name, 'arg_names': arg_names}
if authenticated:
if authenticated is True or six.callable(authenticated):
# TODO: this is an assumption
X['arg_names'] = authentication_arguments + X['arg_names']
X['name'] = _inject_args(X['name'], ('String', 'String'))
from django.contrib.auth import authenticate as _authenticate
from django.contrib.auth.models import User
else:
authenticate = authenticated
@six.wraps(func)
def _func(request, *args, **kwargs):
user = getattr(request, 'user', None)
is_authenticated = getattr(user, 'is_authenticated',
lambda: False)
if ((user is not None and six.callable(is_authenticated) and
not is_authenticated()) or user is None):
user = None
try:
creds = args[:len(authentication_arguments)]
if len(creds) == 0:
raise IndexError
# Django's authenticate() method takes arguments as dict
user = _authenticate(username=creds[0],
password=creds[1], *creds[2:])
if user is not None:
args = args[len(authentication_arguments):]
except IndexError:
auth_kwargs = {}
try:
for auth_kwarg in authentication_arguments:
auth_kwargs[auth_kwarg] = kwargs[auth_kwarg]
except KeyError:
raise InvalidParamsError(
'Authenticated methods require at least '
'[%(arguments)s] or {%(arguments)s} arguments' %
{'arguments': ', '.join(authentication_arguments)})
user = _authenticate(**auth_kwargs)
if user is not None:
for auth_kwarg in authentication_arguments:
kwargs.pop(auth_kwarg)
if user is None:
raise InvalidCredentialsError
request.user = user
return func(request, *args, **kwargs)
else:
_func = func
@six.wraps(_func)
def exc_printer(*a, **kw):
try:
return _func(*a, **kw)
except Exception as e:
try:
print('JSONRPC SERVICE EXCEPTION')
import traceback
traceback.print_exc()
except:
pass
six.reraise(*sys.exc_info())
ret_func = exc_printer
method, arg_types, return_type = \
_parse_sig(X['name'], X['arg_names'], validate)
ret_func.json_args = X['arg_names']
ret_func.json_arg_types = arg_types
ret_func.json_return_type = return_type
ret_func.json_method = method
ret_func.json_safe = safe
ret_func.json_sig = X['name']
ret_func.json_validate = validate
site.register(method, ret_func)
return ret_func
return decorator |
<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_payload(self, params):
"""Performs the actual sending action and returns the result""" |
data = dumps({
'jsonrpc': self.version,
'method': self.service_name,
'params': params,
'id': str(uuid.uuid1())
}).encode('utf-8')
headers = {
'Content-Type': 'application/json-rpc',
'Accept': 'application/json-rpc',
'Content-Length': len(data)
}
try:
req = urllib_request.Request(self.service_url, data, headers)
resp = urllib_request.urlopen(req)
except IOError as e:
if isinstance(e, urllib_error.HTTPError):
if e.code not in (
401, 403
) and e.headers['Content-Type'] == 'application/json-rpc':
return e.read().decode('utf-8') # we got a jsonrpc-formatted respnose
raise ServiceProxyException(e.code, e.headers, req)
else:
raise e
return resp.read().decode('utf-8') |
<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_rpc_format(self):
""" return the Exception data in a format for JSON-RPC """ |
error = {
'name': smart_text(self.__class__.__name__),
'code': self.code,
'message': "%s: %s" %
(smart_text(self.__class__.__name__), smart_text(self.message)),
'data': self.data
}
from django.conf import settings
if settings.DEBUG:
import sys, traceback
error['stack'] = traceback.format_exc()
error['executable'] = sys.executable
return error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def directory(self, query, **kwargs):
"""Search by users or channels on all server.""" |
if isinstance(query, dict):
query = str(query).replace("'", '"')
return self.__call_api_get('directory', query=query, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spotlight(self, query, **kwargs):
"""Searches for users or rooms that are visible to the user.""" |
return self.__call_api_get('spotlight', query=query, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def users_get_presence(self, user_id=None, username=None, **kwargs):
"""Gets the online presence of the a user.""" |
if user_id:
return self.__call_api_get('users.getPresence', userId=user_id, kwargs=kwargs)
elif username:
return self.__call_api_get('users.getPresence', username=username, kwargs=kwargs)
else:
raise RocketMissingParamException('userID or username required') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def users_create(self, email, name, password, username, **kwargs):
"""Creates a user""" |
return self.__call_api_post('users.create', email=email, name=name, password=password, username=username,
kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def users_create_token(self, user_id=None, username=None, **kwargs):
"""Create a user authentication token.""" |
if user_id:
return self.__call_api_post('users.createToken', userId=user_id, kwargs=kwargs)
elif username:
return self.__call_api_post('users.createToken', username=username, kwargs=kwargs)
else:
raise RocketMissingParamException('userID or username required') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def users_forgot_password(self, email, **kwargs):
"""Send email to reset your password.""" |
return self.__call_api_post('users.forgotPassword', email=email, data=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chat_post_message(self, text, room_id=None, channel=None, **kwargs):
"""Posts a new chat message.""" |
if room_id:
return self.__call_api_post('chat.postMessage', roomId=room_id, text=text, kwargs=kwargs)
elif channel:
return self.__call_api_post('chat.postMessage', channel=channel, text=text, kwargs=kwargs)
else:
raise RocketMissingParamException('roomId or channel required') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chat_delete(self, room_id, msg_id, **kwargs):
"""Deletes a chat message.""" |
return self.__call_api_post('chat.delete', roomId=room_id, msgId=msg_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chat_search(self, room_id, search_text, **kwargs):
"""Search for messages in a channel by id and text message.""" |
return self.__call_api_get('chat.search', roomId=room_id, searchText=search_text, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chat_get_message_read_receipts(self, message_id, **kwargs):
"""Get Message Read Receipts""" |
return self.__call_api_get('chat.getMessageReadReceipts', messageId=message_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_history(self, room_id, **kwargs):
"""Retrieves the messages from a channel.""" |
return self.__call_api_get('channels.history', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_add_all(self, room_id, **kwargs):
"""Adds all of the users of the Rocket.Chat server to the channel.""" |
return self.__call_api_post('channels.addAll', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_add_moderator(self, room_id, user_id, **kwargs):
"""Gives the role of moderator for a user in the current channel.""" |
return self.__call_api_post('channels.addModerator', roomId=room_id, userId=user_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_remove_moderator(self, room_id, user_id, **kwargs):
"""Removes the role of moderator from a user in the current channel.""" |
return self.__call_api_post('channels.removeModerator', roomId=room_id, userId=user_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_add_owner(self, room_id, user_id=None, username=None, **kwargs):
"""Gives the role of owner for a user in the current channel.""" |
if user_id:
return self.__call_api_post('channels.addOwner', roomId=room_id, userId=user_id, kwargs=kwargs)
elif username:
return self.__call_api_post('channels.addOwner', roomId=room_id, username=username, kwargs=kwargs)
else:
raise RocketMissingParamException('userID or username required') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_remove_owner(self, room_id, user_id, **kwargs):
"""Removes the role of owner from a user in the current channel.""" |
return self.__call_api_post('channels.removeOwner', roomId=room_id, userId=user_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_archive(self, room_id, **kwargs):
"""Archives a channel.""" |
return self.__call_api_post('channels.archive', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_create(self, name, **kwargs):
"""Creates a new public channel, optionally including users.""" |
return self.__call_api_post('channels.create', name=name, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_get_integrations(self, room_id, **kwargs):
"""Retrieves the integrations which the channel has""" |
return self.__call_api_get('channels.getIntegrations', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_kick(self, room_id, user_id, **kwargs):
"""Removes a user from the channel.""" |
return self.__call_api_post('channels.kick', roomId=room_id, userId=user_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_leave(self, room_id, **kwargs):
"""Causes the callee to be removed from the channel.""" |
return self.__call_api_post('channels.leave', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_rename(self, room_id, name, **kwargs):
"""Changes the name of the channel.""" |
return self.__call_api_post('channels.rename', roomId=room_id, name=name, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_set_description(self, room_id, description, **kwargs):
"""Sets the description for the channel.""" |
return self.__call_api_post('channels.setDescription', roomId=room_id, description=description, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_set_join_code(self, room_id, join_code, **kwargs):
"""Sets the code required to join the channel.""" |
return self.__call_api_post('channels.setJoinCode', roomId=room_id, joinCode=join_code, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_set_topic(self, room_id, topic, **kwargs):
"""Sets the topic for the channel.""" |
return self.__call_api_post('channels.setTopic', roomId=room_id, topic=topic, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_set_type(self, room_id, a_type, **kwargs):
"""Sets the type of room this channel should be. The type of room this channel should be, either c or p.""" |
return self.__call_api_post('channels.setType', roomId=room_id, type=a_type, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_set_announcement(self, room_id, announce, **kwargs):
"""Sets the announcement for the channel.""" |
return self.__call_api_post('channels.setAnnouncement', roomId=room_id, announcement=announce, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_set_custom_fields(self, rid, custom_fields):
"""Sets the custom fields for the channel.""" |
return self.__call_api_post('channels.setCustomFields', roomId=rid, customFields=custom_fields) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_delete(self, room_id=None, channel=None, **kwargs):
"""Delete a public channel.""" |
if room_id:
return self.__call_api_post('channels.delete', roomId=room_id, kwargs=kwargs)
elif channel:
return self.__call_api_post('channels.delete', roomName=channel, kwargs=kwargs)
else:
raise RocketMissingParamException('roomId or channel required') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_get_all_user_mentions_by_channel(self, room_id, **kwargs):
"""Gets all the mentions of a channel.""" |
return self.__call_api_get('channels.getAllUserMentionsByChannel', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_history(self, room_id, **kwargs):
"""Retrieves the messages from a private group.""" |
return self.__call_api_get('groups.history', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_add_moderator(self, room_id, user_id, **kwargs):
"""Gives the role of moderator for a user in the current groups.""" |
return self.__call_api_post('groups.addModerator', roomId=room_id, userId=user_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_remove_moderator(self, room_id, user_id, **kwargs):
"""Removes the role of moderator from a user in the current groups.""" |
return self.__call_api_post('groups.removeModerator', roomId=room_id, userId=user_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_moderators(self, room_id=None, group=None, **kwargs):
"""Lists all moderators of a group.""" |
if room_id:
return self.__call_api_get('groups.moderators', roomId=room_id, kwargs=kwargs)
elif group:
return self.__call_api_get('groups.moderators', roomName=group, kwargs=kwargs)
else:
raise RocketMissingParamException('roomId or group required') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_add_owner(self, room_id, user_id, **kwargs):
"""Gives the role of owner for a user in the current Group.""" |
return self.__call_api_post('groups.addOwner', roomId=room_id, userId=user_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_remove_owner(self, room_id, user_id, **kwargs):
"""Removes the role of owner from a user in the current Group.""" |
return self.__call_api_post('groups.removeOwner', roomId=room_id, userId=user_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_unarchive(self, room_id, **kwargs):
"""Unarchives a private group.""" |
return self.__call_api_post('groups.unarchive', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_get_integrations(self, room_id, **kwargs):
"""Retrieves the integrations which the group has""" |
return self.__call_api_get('groups.getIntegrations', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_invite(self, room_id, user_id, **kwargs):
"""Adds a user to the private group.""" |
return self.__call_api_post('groups.invite', roomId=room_id, userId=user_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_kick(self, room_id, user_id, **kwargs):
"""Removes a user from the private group.""" |
return self.__call_api_post('groups.kick', roomId=room_id, userId=user_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_rename(self, room_id, name, **kwargs):
"""Changes the name of the private group.""" |
return self.__call_api_post('groups.rename', roomId=room_id, name=name, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_set_description(self, room_id, description, **kwargs):
"""Sets the description for the private group.""" |
return self.__call_api_post('groups.setDescription', roomId=room_id, description=description, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_set_read_only(self, room_id, read_only, **kwargs):
"""Sets whether the group is read only or not.""" |
return self.__call_api_post('groups.setReadOnly', roomId=room_id, readOnly=bool(read_only), kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_set_topic(self, room_id, topic, **kwargs):
"""Sets the topic for the private group.""" |
return self.__call_api_post('groups.setTopic', roomId=room_id, topic=topic, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_set_type(self, room_id, a_type, **kwargs):
"""Sets the type of room this group should be. The type of room this channel should be, either c or p.""" |
return self.__call_api_post('groups.setType', roomId=room_id, type=a_type, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_delete(self, room_id=None, group=None, **kwargs):
"""Delete a private group.""" |
if room_id:
return self.__call_api_post('groups.delete', roomId=room_id, kwargs=kwargs)
elif group:
return self.__call_api_post('groups.delete', roomName=group, kwargs=kwargs)
else:
raise RocketMissingParamException('roomId or group required') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def im_history(self, room_id, **kwargs):
"""Retrieves the history for a private im chat""" |
return self.__call_api_get('im.history', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def im_create(self, username, **kwargs):
"""Create a direct message session with another user.""" |
return self.__call_api_post('im.create', username=username, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def im_messages_others(self, room_id, **kwargs):
"""Retrieves the messages from any direct message in the server""" |
return self.__call_api_get('im.messages.others', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def im_set_topic(self, room_id, topic, **kwargs):
"""Sets the topic for the direct message""" |
return self.__call_api_post('im.setTopic', roomId=room_id, topic=topic, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def im_files(self, room_id=None, user_name=None, **kwargs):
"""Retrieves the files from a direct message.""" |
if room_id:
return self.__call_api_get('im.files', roomId=room_id, kwargs=kwargs)
elif user_name:
return self.__call_api_get('im.files', username=user_name, kwargs=kwargs)
else:
raise RocketMissingParamException('roomId or username required') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rooms_upload(self, rid, file, **kwargs):
"""Post a message with attached file to a dedicated room.""" |
files = {
'file': (os.path.basename(file), open(file, 'rb'), mimetypes.guess_type(file)[0]),
}
return self.__call_api_post('rooms.upload/' + rid, kwargs=kwargs, use_json=False, files=files) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rooms_clean_history(self, room_id, latest, oldest, **kwargs):
"""Cleans up a room, removing messages from the provided time range.""" |
return self.__call_api_post('rooms.cleanHistory', roomId=room_id, latest=latest, oldest=oldest, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rooms_favorite(self, room_id=None, room_name=None, favorite=True):
"""Favorite or unfavorite room.""" |
if room_id is not None:
return self.__call_api_post('rooms.favorite', roomId=room_id, favorite=favorite)
elif room_name is not None:
return self.__call_api_post('rooms.favorite', roomName=room_name, favorite=favorite)
else:
raise RocketMissingParamException('roomId or roomName required') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rooms_info(self, room_id=None, room_name=None):
"""Retrieves the information about the room.""" |
if room_id is not None:
return self.__call_api_get('rooms.info', roomId=room_id)
elif room_name is not None:
return self.__call_api_get('rooms.info', roomName=room_name)
else:
raise RocketMissingParamException('roomId or roomName required') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subscriptions_get_one(self, room_id, **kwargs):
"""Get the subscription by room id.""" |
return self.__call_api_get('subscriptions.getOne', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subscriptions_unread(self, room_id, **kwargs):
"""Mark messages as unread by roomId or from a message""" |
return self.__call_api_post('subscriptions.unread', roomId=room_id, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subscriptions_read(self, rid, **kwargs):
"""Mark room as read""" |
return self.__call_api_post('subscriptions.read', rid=rid, kwargs=kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assets_set_asset(self, asset_name, file, **kwargs):
"""Set an asset image by name.""" |
content_type = mimetypes.MimeTypes().guess_type(file)
files = {
asset_name: (file, open(file, 'rb'), content_type[0], {'Expires': '0'}),
}
return self.__call_api_post('assets.setAsset', kwargs=kwargs, use_json=False, files=files) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def find_callback(args, kw=None):
'Return callback whether passed as a last argument or as a keyword'
if args and callable(args[-1]):
return args[-1], args[:-1]
try:
return kw['callback'], args
except (KeyError, TypeError):
return None, args |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def once(self, event, callback):
'Define a callback to handle the first event emitted by the server'
self._once_events.add(event)
self.on(event, callback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def off(self, event):
'Remove an event handler'
try:
self._once_events.remove(event)
except KeyError:
pass
self._callback_by_event.pop(event, 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 wait(self, seconds=None, **kw):
'Wait in a loop and react to events as defined in the namespaces'
# Use ping/pong to unblock recv for polling transport
self._heartbeat_thread.hurry()
# Use timeout to unblock recv for websocket transport
self._transport.set_timeout(seconds=1)
# Listen
warning_screen = self._yield_warning_screen(seconds)
for elapsed_time in warning_screen:
if self._should_stop_waiting(**kw):
break
try:
try:
self._process_packets()
except TimeoutError:
pass
except KeyboardInterrupt:
self._close()
raise
except ConnectionError as e:
self._opened = False
try:
warning = Exception('[connection error] %s' % e)
warning_screen.throw(warning)
except StopIteration:
self._warn(warning)
try:
namespace = self.get_namespace()
namespace._find_packet_callback('disconnect')()
except PacketError:
pass
self._heartbeat_thread.relax()
self._transport.set_timeout() |
<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_to_send_ack(self, path, ack_id):
'Return function that acknowledges the server'
return lambda *args: self._ack(path, ack_id, *args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotateX(self, angle):
""" Rotates the point around the X axis by the given angle in degrees. """ |
rad = angle * math.pi / 180
cosa = math.cos(rad)
sina = math.sin(rad)
y = self.y * cosa - self.z * sina
z = self.y * sina + self.z * cosa
return Point3D(self.x, y, z) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def animate(canvas, fn, delay=1./24, *args, **kwargs):
"""Animation automation function :param canvas: :class:`Canvas` object :param fn: Callable. Frame coord generator :param delay: Float. Delay between frames. :param *args, **kwargs: optional fn parameters """ |
# python2 unicode curses fix
if not IS_PY3:
import locale
locale.setlocale(locale.LC_ALL, "")
def animation(stdscr):
for frame in fn(*args, **kwargs):
for x,y in frame:
canvas.set(x,y)
f = canvas.frame()
stdscr.addstr(0, 0, '{0}\n'.format(f))
stdscr.refresh()
if delay:
sleep(delay)
canvas.clear()
curses.wrapper(animation) |
<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_text(self, x, y, text):
"""Set text to the given coords. :param x: x coordinate of the text start position :param y: y coordinate of the text start position """ |
col, row = get_pos(x, y)
for i,c in enumerate(text):
self.chars[row][col+i] = c |
<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(self, x, y):
"""Get the state of a pixel. Returns bool. :param x: x coordinate of the pixel :param y: y coordinate of the pixel """ |
x = normalize(x)
y = normalize(y)
dot_index = pixel_map[y % 4][x % 2]
col, row = get_pos(x, y)
char = self.chars.get(row, {}).get(col)
if not char:
return False
if type(char) != int:
return True
return bool(char & dot_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 forward(self, step):
"""Move the turtle forward. :param step: Integer. Distance to move forward. """ |
x = self.pos_x + math.cos(math.radians(self.rotation)) * step
y = self.pos_y + math.sin(math.radians(self.rotation)) * step
prev_brush_state = self.brush_on
self.brush_on = True
self.move(x, y)
self.brush_on = prev_brush_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 move(self, x, y):
"""Move the turtle to a coordinate. :param x: x coordinate :param y: y coordinate """ |
if self.brush_on:
for lx, ly in line(self.pos_x, self.pos_y, x, y):
self.set(lx, ly)
self.pos_x = x
self.pos_y = y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def URL(base, path, segments=None, defaults=None):
""" URL segment handler capable of getting and setting segments by name. The URL is constructed by joining base, path and segments. For each segment a property capable of getting and setting that segment is created dynamically. """ |
# Make a copy of the Segments class
url_class = type(Segments.__name__, Segments.__bases__,
dict(Segments.__dict__))
segments = [] if segments is None else segments
defaults = [] if defaults is None else defaults
# For each segment attach a property capable of getting and setting it
for segment in segments:
setattr(url_class, segment, url_class._segment(segment))
# Instantiate the class with the actual parameters
return url_class(base, path, segments, defaults) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _segment(cls, segment):
""" Returns a property capable of setting and getting a segment. """ |
return property(
fget=lambda x: cls._get_segment(x, segment),
fset=lambda x, v: cls._set_segment(x, segment, v),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def self_if_parameters(func):
""" If any parameter is given, the method's binded object is returned after executing the function. Else the function's result is returned. """ |
@wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
if args or kwargs:
return self
else:
return result
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 items(self):
""" Request URL and parse response. Yield a ``Torrent`` for every torrent on page. """ |
request = get(str(self.url), headers={'User-Agent' : "Magic Browser","origin_req_host" : "thepiratebay.se"})
root = html.fromstring(request.text)
items = [self._build_torrent(row) for row in
self._get_torrent_rows(root)]
for item in items:
yield item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_torrent(self, row):
""" Builds and returns a Torrent object for the given parsed row. """ |
# Scrape, strip and build!!!
cols = row.findall('.//td') # split the row into it's columns
# this column contains the categories
[category, sub_category] = [c.text for c in cols[0].findall('.//a')]
# this column with all important info
links = cols[1].findall('.//a') # get 4 a tags from this columns
title = unicode(links[0].text)
url = self.url.build().path(links[0].get('href'))
magnet_link = links[1].get('href') # the magnet download link
try:
torrent_link = links[2].get('href') # the torrent download link
if not torrent_link.endswith('.torrent'):
torrent_link = None
except IndexError:
torrent_link = None
comments = 0
has_cover = 'No'
images = cols[1].findall('.//img')
for image in images:
image_title = image.get('title')
if image_title is None:
continue
if "comments" in image_title:
comments = int(image_title.split(" ")[3])
if "cover" in image_title:
has_cover = 'Yes'
user_status = "MEMBER"
if links[-2].get('href').startswith("/user/"):
user_status = links[-2].find('.//img').get('title')
meta_col = cols[1].find('.//font').text_content() # don't need user
match = self._meta.match(meta_col)
created = match.groups()[0].replace('\xa0', ' ')
size = match.groups()[1].replace('\xa0', ' ')
user = match.groups()[2] # uploaded by user
# last 2 columns for seeders and leechers
seeders = int(cols[2].text)
leechers = int(cols[3].text)
t = Torrent(title, url, category, sub_category, magnet_link,
torrent_link, comments, has_cover, user_status, created,
size, user, seeders, leechers)
return 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 items(self):
""" Request URL and parse response. Yield a ``Torrent`` for every torrent on page. If in multipage mode, Torrents from next pages are automatically chained. """ |
if self._multipage:
while True:
# Pool for more torrents
items = super(Paginated, self).items()
# Stop if no more torrents
first = next(items, None)
if first is None:
raise StopIteration()
# Yield them if not
else:
yield first
for item in items:
yield item
# Go to the next page
self.next()
else:
for item in super(Paginated, self).items():
yield item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page(self, number=None):
""" If page is given, modify the URL correspondingly, return the current page otherwise. """ |
if number is None:
return int(self.url.page)
self.url.page = str(number) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, query=None):
""" If query is given, modify the URL correspondingly, return the current query otherwise. """ |
if query is None:
return self.url.query
self.url.query = query |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def order(self, order=None):
""" If order is given, modify the URL correspondingly, return the current order otherwise. """ |
if order is None:
return int(self.url.order)
self.url.order = str(order) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def category(self, category=None):
""" If category is given, modify the URL correspondingly, return the current category otherwise. """ |
if category is None:
return int(self.url.category)
self.url.category = str(category) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, query, page=0, order=7, category=0, multipage=False):
""" Searches TPB for query and returns a list of paginated Torrents capable of changing query, categories and orders. """ |
search = Search(self.base_url, query, page, order, category)
if multipage:
search.multipage()
return search |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def created(self):
""" Attempt to parse the human readable torrent creation datetime. """ |
timestamp, current = self._created
if timestamp.endswith('ago'):
quantity, kind, ago = timestamp.split()
quantity = int(quantity)
if 'sec' in kind:
current -= quantity
elif 'min' in kind:
current -= quantity * 60
elif 'hour' in kind:
current -= quantity * 60 * 60
return datetime.datetime.fromtimestamp(current)
current = datetime.datetime.fromtimestamp(current)
timestamp = timestamp.replace(
'Y-day', str(current.date() - datetime.timedelta(days=1)))
timestamp = timestamp.replace('Today', current.date().isoformat())
try:
return dateutil.parser.parse(timestamp)
except:
return current |
<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_torrent(self):
""" Print the details of a torrent """ |
print('Title: %s' % self.title)
print('URL: %s' % self.url)
print('Category: %s' % self.category)
print('Sub-Category: %s' % self.sub_category)
print('Magnet Link: %s' % self.magnet_link)
print('Torrent Link: %s' % self.torrent_link)
print('Uploaded: %s' % self.created)
print('Comments: %d' % self.comments)
print('Has Cover Image: %s' % self.has_cover)
print('User Status: %s' % self.user_status)
print('Size: %s' % self.size)
print('User: %s' % self.user)
print('Seeders: %d' % self.seeders)
print('Leechers: %d' % self.leechers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def foreground(color, content, readline=False):
""" Color the text of the content :param color: pick a constant, any constant :type color: int :type content: unicode :return: ansi string :rtype: unicode """ |
return encode(color, readline=readline) + content + encode(DEFAULT, readline=readline) |
<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_or_create(cls, **kwargs):
'''
Creates an object or returns the object if exists
credit to Kevin @ StackOverflow
from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
'''
session = Session()
instance = session.query(cls).filter_by(**kwargs).first()
session.close()
if not instance:
self = cls(**kwargs)
self.save()
else:
self = instance
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calling_logger(height=1):
""" Obtain a logger for the calling module. Uses the inspect module to find the name of the calling function and its position in the module hierarchy. With the optional height argument, logs for caller's caller, and so forth. see: http://stackoverflow.com/a/900404/48251 """ |
stack = inspect.stack()
height = min(len(stack) - 1, height)
caller = stack[height]
scope = caller[0].f_globals
path = scope['__name__']
if path == '__main__':
path = scope['__package__'] or os.path.basename(sys.argv[0])
return logging.getLogger(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fillna(self, series, addition=0):
""" Fills with encoder specific default values. :param data: examined to determine defaults :param addition: uniquely identify this set of fillnas if necessary :return: filled data """ |
if series.dtype == numpy.object:
return series
return series.fillna(self.missing_value + addition).astype(self.dtype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hyper_parameter_search( self, param_distributions, n_iter=10, scoring=None, fit_params={}, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch='2*njobs', random_state=None, error_score='raise', return_train_score=True, test=True, score=True, save=True, custom_data=None ):
"""Random search hyper params """ |
params = locals()
params.pop('self')
self.fitting = lore.metadata.Fitting.create(
model=self.name,
custom_data=custom_data,
snapshot=lore.metadata.Snapshot(pipeline=self.pipeline.name,
head=str(self.pipeline.training_data.head(2)),
tail=str(self.pipeline.training_data.tail(2))
)
)
result = RandomizedSearchCV(
self.estimator,
param_distributions,
n_iter=n_iter,
scoring=scoring,
n_jobs=n_jobs,
iid=iid,
refit=refit,
cv=cv,
verbose=verbose,
pre_dispatch=pre_dispatch,
random_state=random_state,
error_score=error_score,
return_train_score=return_train_score
).fit(
self.pipeline.encoded_training_data.x,
y=self.pipeline.encoded_training_data.y,
validation_x=self.pipeline.encoded_validation_data.x,
validation_y=self.pipeline.encoded_validation_data.y,
**fit_params
)
self.estimator = result.best_estimator_
self.stats = {}
self.estimator_kwargs = self.estimator.__getstate__()
if test:
self.stats['test'] = self.evaluate(self.pipeline.test_data)
if score:
self.stats['score'] = self.score(self.pipeline.test_data)
self.complete_fitting()
if save:
self.save()
return 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 require(packages):
"""Ensures that a pypi package has been installed into the App's python environment. If not, the package will be installed and your env will be rebooted. Example: :: lore.env.require('pandas') # -> pandas is required. Dependencies added to requirements.txt :param packages: requirements.txt style name and versions of packages :type packages: [unicode] """ |
global INSTALLED_PACKAGES, _new_requirements
if _new_requirements:
INSTALLED_PACKAGES = None
set_installed_packages()
if not INSTALLED_PACKAGES:
return
if not isinstance(packages, list):
packages = [packages]
missing = []
for package in packages:
name = re.split(r'[!<>=]', package)[0].lower()
if name not in INSTALLED_PACKAGES:
print(ansi.info() + ' %s is required.' % package)
missing += [package]
if missing:
mode = 'a' if os.path.exists(REQUIREMENTS) else 'w'
with open(REQUIREMENTS, mode) as requirements:
requirements.write('\n' + '\n'.join(missing) + '\n')
print(ansi.info() + ' Dependencies added to requirements.txt. Rebooting.')
_new_requirements = True
import lore.__main__
lore.__main__.install(None, None)
reboot('--env-checked') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def launched():
"""Test whether the current python environment is the correct lore env. :return: :any:`True` if the environment is launched :rtype: bool """ |
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX) |
<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():
"""Display error messages and exit if no lore environment can be found. """ |
if not os.path.exists(os.path.join(ROOT, APP, '__init__.py')):
message = ansi.error() + ' Python module not found.'
if os.environ.get('LORE_APP') is None:
message += ' $LORE_APP is not set. Should it be different than "%s"?' % APP
else:
message += ' $LORE_APP is set to "%s". Should it be different?' % APP
sys.exit(message)
if exists():
return
if len(sys.argv) > 1:
command = sys.argv[1]
else:
command = 'lore'
sys.exit(
ansi.error() + ' %s is only available in lore '
'app directories (missing %s)' % (
ansi.bold(command),
ansi.underline(VERSION_PATH)
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def launch():
"""Ensure that python is running from the Lore virtualenv past this point. """ |
if launched():
check_version()
os.chdir(ROOT)
return
if not os.path.exists(BIN_LORE):
missing = ' %s virtualenv is missing.' % APP
if '--launched' in sys.argv:
sys.exit(ansi.error() + missing + ' Please check for errors during:\n $ lore install\n')
else:
print(ansi.warning() + missing)
import lore.__main__
lore.__main__.install(None, None)
reboot('--env-launched') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reboot(*args):
"""Reboot python in the Lore virtualenv """ |
args = list(sys.argv) + list(args)
if args[0] == 'python' or not args[0]:
args[0] = BIN_PYTHON
elif os.path.basename(sys.argv[0]) in ['lore', 'lore.exe']:
args[0] = BIN_LORE
try:
os.execv(args[0], args)
except Exception as e:
if args[0] == BIN_LORE and args[1] == 'console' and JUPYTER_KERNEL_PATH:
print(ansi.error() + ' Your jupyter kernel may be corrupt. Please remove it so lore can reinstall:\n $ rm ' + JUPYTER_KERNEL_PATH)
raise e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.