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 get(self):
"""Return the results now. :return: the membership request results :rtype: :class:`~groupy.api.memberships.MembershipResult.Results` :raises groupy.exceptions.ResultsNotReady: if the results are not ready :raises groupy.exceptions.ResultsExpired: if the results have expired """ |
if self._expired_exception:
raise self._expired_exception
if self._not_ready_exception:
raise self._not_ready_exception
return self.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 list(self, page=1, per_page=10, omit=None):
"""List groups by page. The API allows certain fields to be excluded from the results so that very large groups can be fetched without exceeding the maximum response size. At the time of this writing, only 'memberships' is supported. :param int page: page number :param int per_page: number of groups per page :param int omit: a comma-separated list of fields to exclude :return: a list of groups :rtype: :class:`~groupy.pagers.GroupList` """ |
return pagers.GroupList(self, self._raw_list, page=page,
per_page=per_page, omit=omit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_former(self):
"""List all former groups. :return: a list of groups :rtype: :class:`list` """ |
url = utils.urljoin(self.url, 'former')
response = self.session.get(url)
return [Group(self, **group) for group in response.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(self, id):
"""Get a single group by ID. :param str id: a group ID :return: a group :rtype: :class:`~groupy.api.groups.Group` """ |
url = utils.urljoin(self.url, id)
response = self.session.get(url)
return Group(self, **response.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 update(self, id, name=None, description=None, image_url=None, office_mode=None, share=None, **kwargs):
"""Update the details of a group. .. note:: There are significant bugs in this endpoint! 1. not providing ``name`` produces 400: "Topic can't be blank" 2. not providing ``office_mode`` produces 500: "sql: Scan error on column index 14: sql/driver: couldn't convert <nil> (<nil>) into type bool" Note that these issues are "handled" automatically when calling update on a :class:`~groupy.api.groups.Group` object. :param str id: group ID :param str name: group name (140 characters maximum) :param str description: short description (255 characters maximum) :param str image_url: GroupMe image service URL :param bool office_mode: (undocumented) :param bool share: whether to generate a share URL :return: an updated group :rtype: :class:`~groupy.api.groups.Group` """ |
path = '{}/update'.format(id)
url = utils.urljoin(self.url, path)
payload = {
'name': name,
'description': description,
'image_url': image_url,
'office_mode': office_mode,
'share': share,
}
payload.update(kwargs)
response = self.session.post(url, json=payload)
return Group(self, **response.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 destroy(self, id):
"""Destroy a group. :param str id: a group ID :return: ``True`` if successful :rtype: bool """ |
path = '{}/destroy'.format(id)
url = utils.urljoin(self.url, path)
response = self.session.post(url)
return response.ok |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(self, group_id, share_token):
"""Join a group using a share token. :param str group_id: the group_id of a group :param str share_token: the share token :return: the group :rtype: :class:`~groupy.api.groups.Group` """ |
path = '{}/join/{}'.format(group_id, share_token)
url = utils.urljoin(self.url, path)
response = self.session.post(url)
group = response.data['group']
return Group(self, **group) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rejoin(self, group_id):
"""Rejoin a former group. :param str group_id: the group_id of a group :return: the group :rtype: :class:`~groupy.api.groups.Group` """ |
url = utils.urljoin(self.url, 'join')
payload = {'group_id': group_id}
response = self.session.post(url, json=payload)
return Group(self, **response.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 change_owners(self, group_id, owner_id):
"""Change the owner of a group. .. note:: you must be the owner to change owners :param str group_id: the group_id of a group :param str owner_id: the ID of the new owner :return: the result :rtype: :class:`~groupy.api.groups.ChangeOwnersResult` """ |
url = utils.urljoin(self.url, 'change_owners')
payload = {
'requests': [{
'group_id': group_id,
'owner_id': owner_id,
}],
}
response = self.session.post(url, json=payload)
result, = response.data['results'] # should be exactly one
return ChangeOwnersResult(**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 update(self, name=None, description=None, image_url=None, office_mode=None, share=None, **kwargs):
"""Update the details of the group. :param str name: group name (140 characters maximum) :param str description: short description (255 characters maximum) :param str image_url: GroupMe image service URL :param bool office_mode: (undocumented) :param bool share: whether to generate a share URL :return: an updated group :rtype: :class:`~groupy.api.groups.Group` """ |
# note we default to the current values for name and office_mode as a
# work-around for issues with the group update endpoint
if name is None:
name = self.name
if office_mode is None:
office_mode = self.office_mode
return self.manager.update(id=self.id, name=name, description=description,
image_url=image_url, office_mode=office_mode,
share=share, **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 refresh_from_server(self):
"""Refresh the group from the server in place.""" |
group = self.manager.get(id=self.id)
self.__init__(self.manager, **group.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_membership(self):
"""Get your membership. Note that your membership may not exist. For example, you do not have a membership in a former group. Also, the group returned by the API when rejoining a former group does not contain your membership. You must call :func:`refresh_from_server` to update the list of members. :return: your membership in the group :rtype: :class:`~groupy.api.memberships.Member` :raises groupy.exceptions.MissingMembershipError: if your membership is not in the group data """ |
user_id = self._user.me['user_id']
for member in self.members:
if member.user_id == user_id:
return member
raise exceptions.MissingMembershipError(self.group_id, user_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 urljoin(base, path=None):
"""Join a base url with a relative path.""" |
# /foo/bar + baz makes /foo/bar/baz instead of /foo/baz
if path is None:
url = base
else:
if not base.endswith('/'):
base += '/'
url = urllib.parse.urljoin(base, str(path))
return url |
<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_rfc3339(when):
"""Return an RFC 3339 timestamp. :param datetime.datetime when: a datetime in UTC :return: RFC 3339 timestamp :rtype: str """ |
microseconds = format(when.microsecond, '04d')[:4]
rfc3339 = '%Y-%m-%dT%H:%M:%S.{}Z'
return when.strftime(rfc3339.format(microseconds)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_filter(**tests):
"""Create a filter from keyword arguments.""" |
tests = [AttrTest(k, v) for k, v in tests.items()]
return Filter(tests) |
<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(self, objects):
"""Find exactly one match in the list of objects. :param objects: objects to filter :type objects: :class:`list` :return: the one matching object :raises groupy.exceptions.NoMatchesError: if no objects match :raises groupy.exceptions.MultipleMatchesError: if multiple objects match """ |
matches = list(self.__call__(objects))
if not matches:
raise exceptions.NoMatchesError(objects, self.tests)
elif len(matches) > 1:
raise exceptions.MultipleMatchesError(objects, self.tests,
matches=matches)
return matches[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 list(self):
"""Return a list of bots. :return: all of your bots :rtype: :class:`list` """ |
response = self.session.get(self.url)
return [Bot(self, **bot) for bot in response.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 post(self, bot_id, text, attachments=None):
"""Post a new message as a bot to its room. :param str bot_id: the ID of the bot :param str text: the text of the message :param attachments: a list of attachments :type attachments: :class:`list` :return: ``True`` if successful :rtype: bool """ |
url = utils.urljoin(self.url, 'post')
payload = dict(bot_id=bot_id, text=text)
if attachments:
payload['attachments'] = [a.to_json() for a in attachments]
response = self.session.post(url, json=payload)
return response.ok |
<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, bot_id):
"""Destroy a bot. :param str bot_id: the ID of the bot to destroy :return: ``True`` if successful :rtype: bool """ |
url = utils.urljoin(self.url, 'destroy')
payload = {'bot_id': bot_id}
response = self.session.post(url, json=payload)
return response.ok |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, text, attachments=None):
"""Post a message as the bot. :param str text: the text of the message :param attachments: a list of attachments :type attachments: :class:`list` :return: ``True`` if successful :rtype: bool """ |
return self.manager.post(self.bot_id, text, attachments) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten_until(is_leaf, xs):
""" Flatten a nested sequence. A sequence could be a nested list of lists or tuples or a combination of both :param is_leaf: Predicate. Predicate to determine whether an item in the iterable `xs` is a leaf node or not. :param xs: Iterable. Nested lists or tuples :return: list. """ |
def _flatten_until(items):
if isinstance(Iterable, items) and not is_leaf(items):
for item in items:
for i in _flatten_until(item):
yield i
else:
yield items
return list(_flatten_until(xs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flip(f):
""" Calls the function f by flipping the first two positional arguments """ |
def wrapped(*args, **kwargs):
return f(*flip_first_two(args), **kwargs)
f_spec = make_func_curry_spec(f)
return curry_by_spec(f_spec, wrapped) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cachier(stale_after=None, next_time=False, pickle_reload=True, mongetter=None):
"""A persistent, stale-free memoization decorator. The positional and keyword arguments to the wrapped function must be hashable (i.e. Python's immutable built-in objects, not mutable containers). Also, notice that since objects which are instances of user-defined classes are hashable but all compare unequal (their hash value is their id), equal objects across different sessions will not yield identical keys. Arguments --------- stale_after (optional) : datetime.timedelta The time delta afterwhich a cached result is considered stale. Calls made after the result goes stale will trigger a recalculation of the result, but whether a stale or fresh result will be returned is determined by the optional next_time argument. next_time (optional) : bool If set to True, a stale result will be returned when finding one, not waiting for the calculation of the fresh result to return. Defaults to False. pickle_reload (optional) : bool If set to True, in-memory cache will be reloaded on each cache read, enabling different threads to share cache. Should be set to False for faster reads in single-thread programs. Defaults to True. mongetter (optional) : callable A callable that takes no arguments and returns a pymongo.Collection object with writing permissions. If unset a local pickle cache is used instead. """ |
# print('Inside the wrapper maker')
# print('mongetter={}'.format(mongetter))
# print('stale_after={}'.format(stale_after))
# print('next_time={}'.format(next_time))
if mongetter:
core = _MongoCore(mongetter, stale_after, next_time)
else:
core = _PickleCore( # pylint: disable=R0204
stale_after, next_time, pickle_reload)
def _cachier_decorator(func):
core.set_func(func)
@wraps(func)
def func_wrapper(*args, **kwds): # pylint: disable=C0111,R0911
# print('Inside general wrapper for {}.'.format(func.__name__))
ignore_cache = kwds.pop('ignore_cache', False)
overwrite_cache = kwds.pop('overwrite_cache', False)
verbose_cache = kwds.pop('verbose_cache', False)
_print = lambda x: None
if verbose_cache:
_print = print
if ignore_cache:
return func(*args, **kwds)
key, entry = core.get_entry(args, kwds)
if overwrite_cache:
return _calc_entry(core, key, func, args, kwds)
if entry is not None: # pylint: disable=R0101
_print('Entry found.')
if entry.get('value', None) is not None:
_print('Cached result found.')
if stale_after:
now = datetime.datetime.now()
if now - entry['time'] > stale_after:
_print('But it is stale... :(')
if entry['being_calculated']:
if next_time:
_print('Returning stale.')
return entry['value'] # return stale val
_print('Already calc. Waiting on change.')
try:
return core.wait_on_entry_calc(key)
except RecalculationNeeded:
return _calc_entry(core, key, func, args, kwds)
if next_time:
_print('Async calc and return stale')
try:
core.mark_entry_being_calculated(key)
_get_executor().submit(
_function_thread, core, key, func,
args, kwds)
finally:
core.mark_entry_not_calculated(key)
return entry['value']
_print('Calling decorated function and waiting')
return _calc_entry(core, key, func, args, kwds)
_print('And it is fresh!')
return entry['value']
if entry['being_calculated']:
_print('No value but being calculated. Waiting.')
try:
return core.wait_on_entry_calc(key)
except RecalculationNeeded:
return _calc_entry(core, key, func, args, kwds)
_print('No entry found. No current calc. Calling like a boss.')
return _calc_entry(core, key, func, args, kwds)
def clear_cache():
"""Clear the cache."""
core.clear_cache()
def clear_being_calculated():
"""Marks all entries in this cache as not being calculated."""
core.clear_being_calculated()
func_wrapper.clear_cache = clear_cache
func_wrapper.clear_being_calculated = clear_being_calculated
return func_wrapper
return _cachier_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 defineID(defid):
"""Search for UD's definition ID and return list of UrbanDefinition objects. Keyword arguments: defid -- definition ID to search for (int or str) """ |
json = _get_urban_json(UD_DEFID_URL + urlquote(str(defid)))
return _parse_urban_json(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 has_external_dependency(name):
'Check that a non-Python dependency is installed.'
for directory in os.environ['PATH'].split(':'):
if os.path.exists(os.path.join(directory, name)):
return True
return 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 with_vtk(plot=True):
""" Tests VTK interface and mesh repair of Stanford Bunny Mesh """ |
mesh = vtki.PolyData(bunny_scan)
meshfix = pymeshfix.MeshFix(mesh)
if plot:
print('Plotting input mesh')
meshfix.plot()
meshfix.repair()
if plot:
print('Plotting repaired mesh')
meshfix.plot()
return meshfix.mesh |
<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_arrays(self, v, f):
"""Loads triangular mesh from vertex and face numpy arrays. Both vertex and face arrays should be 2D arrays with each vertex containing XYZ data and each face containing three points. Parameters v : np.ndarray n x 3 vertex array. f : np.ndarray n x 3 face array. """ |
# Check inputs
if not isinstance(v, np.ndarray):
try:
v = np.asarray(v, np.float)
if v.ndim != 2 and v.shape[1] != 3:
raise Exception('Invalid vertex format. Shape ' +
'should be (npoints, 3)')
except BaseException:
raise Exception(
'Unable to convert vertex input to valid numpy array')
if not isinstance(f, np.ndarray):
try:
f = np.asarray(f, ctypes.c_int)
if f.ndim != 2 and f.shape[1] != 3:
raise Exception('Invalid face format. ' +
'Shape should be (nfaces, 3)')
except BaseException:
raise Exception('Unable to convert face input to valid' +
' numpy array')
self.v = v
self.f = f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mesh(self):
"""Return the surface mesh""" |
triangles = np.empty((self.f.shape[0], 4))
triangles[:, -3:] = self.f
triangles[:, 0] = 3
return vtki.PolyData(self.v, triangles, deep=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 plot(self, show_holes=True):
""" Plot the mesh. Parameters show_holes : bool, optional Shows boundaries. Default True """ |
if show_holes:
edges = self.mesh.extract_edges(boundary_edges=True,
feature_edges=False,
manifold_edges=False)
plotter = vtki.Plotter()
plotter.add_mesh(self.mesh, label='mesh')
plotter.add_mesh(edges, 'r', label='edges')
plotter.plot()
else:
self.mesh.plot(show_edges=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 repair(self, verbose=False, joincomp=False, remove_smallest_components=True):
"""Performs mesh repair using MeshFix's default repair process. Parameters verbose : bool, optional Enables or disables debug printing. Disabled by default. joincomp : bool, optional Attempts to join nearby open components. remove_smallest_components : bool, optional Remove all but the largest isolated component from the mesh before beginning the repair process. Default True Notes ----- Vertex and face arrays are updated inplace. Access them with: meshfix.v meshfix.f """ |
assert self.f.shape[1] == 3, 'Face array must contain three columns'
assert self.f.ndim == 2, 'Face array must be 2D'
self.v, self.f = _meshfix.clean_from_arrays(self.v, self.f,
verbose, joincomp,
remove_smallest_components) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def scrape(url, params=None, user_agent=None):
'''
Scrape a URL optionally with parameters.
This is effectively a wrapper around urllib2.urlopen.
'''
headers = {}
if user_agent:
headers['User-Agent'] = user_agent
data = params and six.moves.urllib.parse.urlencode(params) or None
req = six.moves.urllib.request.Request(url, data=data, headers=headers)
f = six.moves.urllib.request.urlopen(req)
text = f.read()
f.close()
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pdftoxml(pdfdata, options=""):
"""converts pdf file to xml file""" |
pdffout = tempfile.NamedTemporaryFile(suffix='.pdf')
pdffout.write(pdfdata)
pdffout.flush()
xmlin = tempfile.NamedTemporaryFile(mode='r', suffix='.xml')
tmpxml = xmlin.name # "temph.xml"
cmd = 'pdftohtml -xml -nodrm -zoom 1.5 -enc UTF-8 -noframes %s "%s" "%s"' % (
options, pdffout.name, os.path.splitext(tmpxml)[0])
# can't turn off output, so throw away even stderr yeuch
cmd = cmd + " >/dev/null 2>&1"
os.system(cmd)
pdffout.close()
#xmlfin = open(tmpxml)
xmldata = xmlin.read()
xmlin.close()
return xmldata.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 execute(query, data=None):
""" Execute an arbitrary SQL query given by query, returning any results as a list of OrderedDicts. A list of values can be supplied as an, additional argument, which will be substituted into question marks in the query. """ |
connection = _State.connection()
_State.new_transaction()
if data is None:
data = []
result = connection.execute(query, data)
_State.table = None
_State.metadata = None
try:
del _State.table_pending
except AttributeError:
pass
if not result.returns_rows:
return {u'data': [], u'keys': []}
return {u'data': result.fetchall(), u'keys': list(result.keys())} |
<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_table(table_name):
""" Specify the table to work on. """ |
_State.connection()
_State.reflect_metadata()
_State.table = sqlalchemy.Table(table_name, _State.metadata,
extend_existing=True)
if list(_State.table.columns.keys()) == []:
_State.table_pending = True
else:
_State.table_pending = 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 show_tables():
""" Return the names of the tables currently in the database. """ |
_State.connection()
_State.reflect_metadata()
metadata = _State.metadata
response = select('name, sql from sqlite_master where type="table"')
return {row['name']: row['sql'] for row in 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 save_var(name, value):
""" Save a variable to the table specified by _State.vars_table_name. Key is the name of the variable, and value is the value. """ |
connection = _State.connection()
_State.reflect_metadata()
vars_table = sqlalchemy.Table(
_State.vars_table_name, _State.metadata,
sqlalchemy.Column('name', sqlalchemy.types.Text, primary_key=True),
sqlalchemy.Column('value_blob', sqlalchemy.types.LargeBinary),
sqlalchemy.Column('type', sqlalchemy.types.Text),
keep_existing=True
)
vars_table.create(bind=connection, checkfirst=True)
column_type = get_column_type(value)
if column_type == sqlalchemy.types.LargeBinary:
value_blob = value
else:
value_blob = unicode(value).encode('utf-8')
values = dict(name=name,
value_blob=value_blob,
# value_blob=Blob(value),
type=column_type.__visit_name__.lower())
vars_table.insert(prefixes=['OR REPLACE']).values(**values).execute() |
<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_var(name, default=None):
""" Returns the variable with the provided key from the table specified by _State.vars_table_name. """ |
alchemytypes = {"text": lambda x: x.decode('utf-8'),
"big_integer": lambda x: int(x),
"date": lambda x: x.decode('utf-8'),
"datetime": lambda x: x.decode('utf-8'),
"float": lambda x: float(x),
"large_binary": lambda x: x,
"boolean": lambda x: x==b'True'}
connection = _State.connection()
_State.new_transaction()
if _State.vars_table_name not in list(_State.metadata.tables.keys()):
return None
table = sqlalchemy.Table(_State.vars_table_name, _State.metadata)
s = sqlalchemy.select([table.c.value_blob, table.c.type])
s = s.where(table.c.name == name)
result = connection.execute(s).fetchone()
if not result:
return None
return alchemytypes[result[1]](result[0])
# This is to do the variable type conversion through the SQL engine
execute = connection.execute
execute("CREATE TEMPORARY TABLE _sw_tmp ('value' {})".format(result.type))
execute("INSERT INTO _sw_tmp VALUES (:value)", value=result.value_blob)
var = execute('SELECT value FROM _sw_tmp').fetchone().value
execute("DROP TABLE _sw_tmp")
return var.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 create_index(column_names, unique=False):
""" Create a new index of the columns in column_names, where column_names is a list of strings. If unique is True, it will be a unique index. """ |
connection = _State.connection()
_State.reflect_metadata()
table_name = _State.table.name
table = _State.table
index_name = re.sub(r'[^a-zA-Z0-9]', '', table_name) + '_'
index_name += '_'.join(re.sub(r'[^a-zA-Z0-9]', '', x)
for x in column_names)
if unique:
index_name += '_unique'
columns = []
for column_name in column_names:
columns.append(table.columns[column_name])
current_indices = [x.name for x in table.indexes]
index = sqlalchemy.schema.Index(index_name, *columns, unique=unique)
if index.name not in current_indices:
index.create(bind=_State.engine) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_row(connection, row, unique_keys):
""" Takes a row and checks to make sure it fits in the columns of the current table. If it does not fit, adds the required columns. """ |
new_columns = []
for column_name, column_value in list(row.items()):
new_column = sqlalchemy.Column(column_name,
get_column_type(column_value))
if not column_name in list(_State.table.columns.keys()):
new_columns.append(new_column)
_State.table.append_column(new_column)
if _State.table_pending:
create_table(unique_keys)
return
for new_column in new_columns:
add_column(connection, new_column) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_table(unique_keys):
""" Save the table currently waiting to be created. """ |
_State.new_transaction()
_State.table.create(bind=_State.engine, checkfirst=True)
if unique_keys != []:
create_index(unique_keys, unique=True)
_State.table_pending = False
_State.reflect_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 add_column(connection, column):
""" Add a column to the current table. """ |
stmt = alembic.ddl.base.AddColumn(_State.table.name, column)
connection.execute(stmt)
_State.reflect_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 drop():
""" Drop the current table if it exists """ |
# Ensure the connection is up
_State.connection()
_State.table.drop(checkfirst=True)
_State.metadata.remove(_State.table)
_State.table = None
_State.new_transaction() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attach_attrs_table(key, value, fmt, meta):
"""Extracts attributes and attaches them to element.""" |
# We can't use attach_attrs_factory() because Table is a block-level element
if key in ['Table']:
assert len(value) == 5
caption = value[0] # caption, align, x, head, body
# Set n to the index where the attributes start
n = 0
while n < len(caption) and not \
(caption[n]['t'] == 'Str' and caption[n]['c'].startswith('{')):
n += 1
try:
attrs = extract_attrs(caption, n)
value.insert(0, attrs)
except (ValueError, IndexError):
pass |
<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_tables(key, value, fmt, meta):
"""Processes the attributed tables.""" |
global has_unnumbered_tables # pylint: disable=global-statement
# Process block-level Table elements
if key == 'Table':
# Inspect the table
if len(value) == 5: # Unattributed, bail out
has_unnumbered_tables = True
if fmt in ['latex']:
return [RawBlock('tex', r'\begin{no-prefix-table-caption}'),
Table(*value),
RawBlock('tex', r'\end{no-prefix-table-caption}')]
return None
# Process the table
table = _process_table(value, fmt)
# Context-dependent output
attrs = table['attrs']
if table['is_unnumbered']:
if fmt in ['latex']:
return [RawBlock('tex', r'\begin{no-prefix-table-caption}'),
AttrTable(*value),
RawBlock('tex', r'\end{no-prefix-table-caption}')]
elif fmt in ['latex']:
if table['is_tagged']: # Code in the tags
tex = '\n'.join([r'\let\oldthetable=\thetable',
r'\renewcommand\thetable{%s}'%\
references[attrs[0]]])
pre = RawBlock('tex', tex)
tex = '\n'.join([r'\let\thetable=\oldthetable',
r'\addtocounter{table}{-1}'])
post = RawBlock('tex', tex)
return [pre, AttrTable(*value), post]
elif table['is_unreferenceable']:
attrs[0] = '' # The label isn't needed any further
elif fmt in ('html', 'html5') and LABEL_PATTERN.match(attrs[0]):
# Insert anchor
anchor = RawBlock('html', '<a name="%s"></a>'%attrs[0])
return [anchor, AttrTable(*value)]
elif fmt == 'docx':
# As per http://officeopenxml.com/WPhyperlink.php
bookmarkstart = \
RawBlock('openxml',
'<w:bookmarkStart w:id="0" w:name="%s"/>'
%attrs[0])
bookmarkend = \
RawBlock('openxml', '<w:bookmarkEnd w:id="0"/>')
return [bookmarkstart, AttrTable(*value), bookmarkend]
return 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 send(self, messages):
"""Send a SMS message, or an array of SMS messages""" |
tmpSms = SMS(to='', message='')
if str(type(messages)) == str(type(tmpSms)):
messages = [messages]
xml_root = self.__init_xml('Message')
wrapper_id = 0
for m in messages:
m.wrapper_id = wrapper_id
msg = self.__build_sms_data(m)
sms = etree.SubElement(xml_root, 'SMS')
for sms_element in msg:
element = etree.SubElement(sms, sms_element)
element.text = msg[sms_element]
# print etree.tostring(xml_root)
response = clockwork_http.request(SMS_URL, etree.tostring(xml_root, encoding='utf-8'))
response_data = response['data']
# print response_data
data_etree = etree.fromstring(response_data)
# Check for general error
err_desc = data_etree.find('ErrDesc')
if err_desc is not None:
raise clockwork_exceptions.ApiException(err_desc.text, data_etree.find('ErrNo').text)
# Return a consistent object
results = []
for sms in data_etree:
matching_sms = next((s for s in messages if str(s.wrapper_id) == sms.find('WrapperID').text), None)
new_result = SMSResponse(
sms = matching_sms,
id = '' if sms.find('MessageID') is None else sms.find('MessageID').text,
error_code = 0 if sms.find('ErrNo') is None else sms.find('ErrNo').text,
error_message = '' if sms.find('ErrDesc') is None else sms.find('ErrDesc').text,
success = True if sms.find('ErrNo') is None else (sms.find('ErrNo').text == 0)
)
results.append(new_result)
if len(results) > 1:
return results
return results[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 __init_xml(self, rootElementTag):
"""Init a etree element and pop a key in there""" |
xml_root = etree.Element(rootElementTag)
key = etree.SubElement(xml_root, "Key")
key.text = self.apikey
return xml_root |
<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_sms_data(self, message):
"""Build a dictionary of SMS message elements""" |
attributes = {}
attributes_to_translate = {
'to' : 'To',
'message' : 'Content',
'client_id' : 'ClientID',
'concat' : 'Concat',
'from_name': 'From',
'invalid_char_option' : 'InvalidCharOption',
'truncate' : 'Truncate',
'wrapper_id' : 'WrapperId'
}
for attr in attributes_to_translate:
val_to_use = None
if hasattr(message, attr):
val_to_use = getattr(message, attr)
if val_to_use is None and hasattr(self, attr):
val_to_use = getattr(self, attr)
if val_to_use is not None:
attributes[attributes_to_translate[attr]] = str(val_to_use)
return attributes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pstats2entries(data):
"""Helper to convert serialized pstats back to a list of raw entries. Converse operation of cProfile.Profile.snapshot_stats() """ |
# Each entry's key is a tuple of (filename, line number, function name)
entries = {}
allcallers = {}
# first pass over stats to build the list of entry instances
for code_info, call_info in data.stats.items():
# build a fake code object
code = Code(*code_info)
# build a fake entry object. entry.calls will be filled during the
# second pass over stats
cc, nc, tt, ct, callers = call_info
entry = Entry(code, callcount=cc, reccallcount=nc - cc, inlinetime=tt,
totaltime=ct, calls=[])
# collect the new entry
entries[code_info] = entry
allcallers[code_info] = list(callers.items())
# second pass of stats to plug callees into callers
for entry in entries.values():
entry_label = cProfile.label(entry.code)
entry_callers = allcallers.get(entry_label, [])
for entry_caller, call_info in entry_callers:
cc, nc, tt, ct = call_info
subentry = Subentry(entry.code, callcount=cc, reccallcount=nc - cc,
inlinetime=tt, totaltime=ct)
# entry_caller has the same form as code_info
entries[entry_caller].calls.append(subentry)
return list(entries.values()) |
<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_installed(prog):
"""Return whether or not a given executable is installed on the machine.""" |
with open(os.devnull, 'w') as devnull:
try:
if os.name == 'nt':
retcode = subprocess.call(['where', prog], stdout=devnull)
else:
retcode = subprocess.call(['which', prog], stdout=devnull)
except OSError as e:
# If where or which doesn't exist, a "ENOENT" error will occur (The
# FileNotFoundError subclass on Python 3).
if e.errno != errno.ENOENT:
raise
retcode = 1
return retcode == 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 main():
"""Execute the converter using parameters provided on the command line""" |
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--outfile', metavar='output_file_path',
help="Save calltree stats to <outfile>")
parser.add_argument('-i', '--infile', metavar='input_file_path',
help="Read Python stats from <infile>")
parser.add_argument('-k', '--kcachegrind',
help="Run the kcachegrind tool on the converted data",
action="store_true")
parser.add_argument('-r', '--run-script',
nargs=argparse.REMAINDER,
metavar=('scriptfile', 'args'),
dest='script',
help="Name of the Python script to run to collect"
" profiling data")
args = parser.parse_args()
outfile = args.outfile
if args.script is not None:
# collect profiling data by running the given script
if not args.outfile:
outfile = '%s.log' % os.path.basename(args.script[0])
fd, tmp_path = tempfile.mkstemp(suffix='.prof', prefix='pyprof2calltree')
os.close(fd)
try:
cmd = [
sys.executable,
'-m', 'cProfile',
'-o', tmp_path,
]
cmd.extend(args.script)
subprocess.check_call(cmd)
kg = CalltreeConverter(tmp_path)
finally:
os.remove(tmp_path)
elif args.infile is not None:
# use the profiling data from some input file
if not args.outfile:
outfile = '%s.log' % os.path.basename(args.infile)
if args.infile == outfile:
# prevent name collisions by appending another extension
outfile += ".log"
kg = CalltreeConverter(pstats.Stats(args.infile))
else:
# at least an input file or a script to run is required
parser.print_usage()
sys.exit(2)
if args.outfile is not None or not args.kcachegrind:
# user either explicitly required output file or requested by not
# explicitly asking to launch kcachegrind
sys.stderr.write("writing converted data to: %s\n" % outfile)
with open(outfile, 'w') as f:
kg.output(f)
if args.kcachegrind:
sys.stderr.write("launching kcachegrind\n")
kg.visualize() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(profiling_data, outputfile):
"""convert `profiling_data` to calltree format and dump it to `outputfile` `profiling_data` can either be: - a pstats.Stats instance - the filename of a pstats.Stats dump - the result of a call to cProfile.Profile.getstats() `outputfile` can either be: - a file() instance open in write mode - a filename """ |
converter = CalltreeConverter(profiling_data)
if is_basestring(outputfile):
with open(outputfile, "w") as f:
converter.output(f)
else:
converter.output(outputfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output(self, out_file):
"""Write the converted entries to out_file""" |
self.out_file = out_file
out_file.write('event: ns : Nanoseconds\n')
out_file.write('events: ns\n')
self._output_summary()
for entry in sorted(self.entries, key=_entry_sort_key):
self._output_entry(entry) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visualize(self):
"""Launch kcachegrind on the converted entries. One of the executables listed in KCACHEGRIND_EXECUTABLES must be present in the system path. """ |
available_cmd = None
for cmd in KCACHEGRIND_EXECUTABLES:
if is_installed(cmd):
available_cmd = cmd
break
if available_cmd is None:
sys.stderr.write("Could not find kcachegrind. Tried: %s\n" %
", ".join(KCACHEGRIND_EXECUTABLES))
return
if self.out_file is None:
fd, outfile = tempfile.mkstemp(".log", "pyprof2calltree")
use_temp_file = True
else:
outfile = self.out_file.name
use_temp_file = False
try:
if use_temp_file:
with io.open(fd, "w") as f:
self.output(f)
subprocess.call([available_cmd, outfile])
finally:
# clean the temporary file
if use_temp_file:
os.remove(outfile)
self.out_file = 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 init_app(self, app, **kwargs):
""" Initializes the Flask-Bouncer extension for the specified application. :param app: The application. """ |
self.app = app
self._init_extension()
self.app.before_request(self.check_implicit_rules)
if kwargs.get('ensure_authorization', False):
self.app.after_request(self.check_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 check_authorization(self, response):
"""checks that an authorization call has been made during the request""" |
if not hasattr(request, '_authorized'):
raise Unauthorized
elif not request._authorized:
raise Unauthorized
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 check_implicit_rules(self):
automatically check the permissions for you """ |
if not self.request_is_managed_by_flask_classy():
return
if self.method_is_explictly_overwritten():
return
class_name, action = request.endpoint.split(':')
clazz = [classy_class for classy_class in self.flask_classy_classes if classy_class.__name__ == class_name][0]
Condition(action, clazz.__target_model__).test() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotate_texture(texture, rotation, x_offset=0.5, y_offset=0.5):
"""Rotates the given texture by a given angle. Args: texture (texture):
the texture to rotate rotation (float):
the angle of rotation in degrees x_offset (float):
the x component of the center of rotation (optional) y_offset (float):
the y component of the center of rotation (optional) Returns: texture: A texture. """ |
x, y = texture
x = x.copy() - x_offset
y = y.copy() - y_offset
angle = np.radians(rotation)
x_rot = x * np.cos(angle) + y * np.sin(angle)
y_rot = x * -np.sin(angle) + y * np.cos(angle)
return x_rot + x_offset, y_rot + y_offset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN, initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
"""Makes a texture from a turtle program. Args: turtle_program (str):
a string representing the turtle program; see the docstring of `branching_turtle_generator` for more details turn_amount (float):
amount to turn in degrees initial_angle (float):
initial orientation of the turtle resolution (int):
if provided, interpolation amount for visible lines Returns: texture: A texture. """ |
generator = branching_turtle_generator(
turtle_program, turn_amount, initial_angle, resolution)
return texture_from_generator(generator) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_multiple(sequence, transformations, iterations):
"""Chains a transformation a given number of times. Args: sequence (str):
a string or generator onto which transformations are applied transformations (dict):
a dictionary mapping each char to the string that is substituted for it when the rule is applied iterations (int):
how many times to repeat the transformation Yields: str: the next character in the output sequence. """ |
for _ in range(iterations):
sequence = transform_sequence(sequence, transformations)
return sequence |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def l_system(axiom, transformations, iterations=1, angle=45, resolution=1):
"""Generates a texture by running transformations on a turtle program. First, the given transformations are applied to the axiom. This is repeated `iterations` times. Then, the output is run as a turtle program to get a texture, which is returned. For more background see: https://en.wikipedia.org/wiki/L-system Args: axiom (str):
the axiom of the Lindenmeyer system (a string) transformations (dict):
a dictionary mapping each char to the string that is substituted for it when the rule is applied iterations (int):
the number of times to apply the transformations angle (float):
the angle to use for turns when interpreting the string as a turtle graphics program resolution (int):
the number of midpoints to create in each turtle step Returns: A texture """ |
turtle_program = transform_multiple(axiom, transformations, iterations)
return turtle_to_texture(turtle_program, angle, resolution=resolution) |
<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_path(self, i):
"""Returns the path corresponding to the node i.""" |
index = (i - 1) // 2
reverse = (i - 1) % 2
path = self.paths[index]
if reverse:
return path.reversed()
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 cost(self, i, j):
"""Returns the distance between the end of path i and the start of path j.""" |
return dist(self.endpoints[i][1], self.endpoints[j][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 get_coordinates(self, i, end=False):
"""Returns the starting coordinates of node i as a pair, or the end coordinates iff end is True.""" |
if end:
endpoint = self.endpoints[i][1]
else:
endpoint = self.endpoints[i][0]
return (endpoint.real, endpoint.imag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT):
"""Preview a plot in a jupyter notebook. Args: plot (list):
the plot to display (list of layers) width (int):
the width of the preview height (int):
the height of the preview Returns: An object that renders in Jupyter as the provided plot """ |
return SVG(data=plot_to_svg(plot, width, height)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN):
"""Calculates the size of the SVG viewBox to use. Args: layers (list):
the layers in the image aspect_ratio (float):
the height of the output divided by the width margin (float):
minimum amount of buffer to add around the image, relative to the total dimensions Returns: tuple: a 4-tuple of floats representing the viewBox according to SVG specifications ``(x, y, width, height)``. """ |
min_x = min(np.nanmin(x) for x, y in layers)
max_x = max(np.nanmax(x) for x, y in layers)
min_y = min(np.nanmin(y) for x, y in layers)
max_y = max(np.nanmax(y) for x, y in layers)
height = max_y - min_y
width = max_x - min_x
if height > width * aspect_ratio:
adj_height = height * (1. + margin)
adj_width = adj_height / aspect_ratio
else:
adj_width = width * (1. + margin)
adj_height = adj_width * aspect_ratio
width_buffer = (adj_width - width) / 2.
height_buffer = (adj_height - height) / 2.
return (
min_x - width_buffer,
min_y - height_buffer,
adj_width,
adj_height
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _layer_to_path_gen(layer):
"""Generates an SVG path from a given layer. Args: layer (layer):
the layer to convert Yields: str: the next component of the path """ |
draw = False
for x, y in zip(*layer):
if np.isnan(x) or np.isnan(y):
draw = False
elif not draw:
yield 'M {} {}'.format(x, y)
draw = True
else:
yield 'L {} {}'.format(x, 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 write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT):
"""Writes a plot SVG to a file. Args: plot (list):
a list of layers to plot filename (str):
the name of the file to write width (float):
the width of the output SVG height (float):
the height of the output SVG unit (str):
the unit of the height and width """ |
svg = plot_to_svg(plot, width, height, unit)
with open(filename, 'w') as outfile:
outfile.write(svg) |
<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_layer(ax, layer):
"""Draws a layer on the given matplotlib axis. Args: ax (axis):
the matplotlib axis to draw on layer (layer):
the layers to plot """ |
ax.set_aspect('equal', 'datalim')
ax.plot(*layer)
ax.axis('off') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_texture_to_surface(texture, surface):
"""Returns values on a surface for points on a texture. Args: texture (texture):
the texture to trace over the surface surface (surface):
the surface to trace along Returns: an array of surface heights for each point in the texture. Line separators (i.e. values that are ``nan`` in the texture) will be ``nan`` in the output, so the output will have the same dimensions as the x/y axes in the input texture. """ |
texture_x, texture_y = texture
surface_h, surface_w = surface.shape
surface_x = np.clip(
np.int32(surface_w * texture_x - 1e-9), 0, surface_w - 1)
surface_y = np.clip(
np.int32(surface_h * texture_y - 1e-9), 0, surface_h - 1)
surface_z = surface[surface_y, surface_x]
return surface_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 project_texture(texture_xy, texture_z, angle=DEFAULT_ANGLE):
"""Creates a texture by adding z-values to an existing texture and projecting. When working with surfaces there are two ways to accomplish the same thing: 1. project the surface and map a texture to the projected surface 2. map a texture to the surface, and then project the result The first method, which does not use this function, is preferred because it is easier to do occlusion removal that way. This function is provided for cases where you do not wish to generate a surface (and don't care about occlusion removal.) Args: texture_xy (texture):
the texture to project texture_z (np.array):
the Z-values to use in the projection angle (float):
the angle to project at, in degrees (0 = overhead, 90 = side view) Returns: layer: A layer. """ |
z_coef = np.sin(np.radians(angle))
y_coef = np.cos(np.radians(angle))
surface_x, surface_y = texture
return (surface_x, -surface_y * y_coef + surface_z * z_coef) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_surface(surface, angle=DEFAULT_ANGLE):
"""Returns the height of the surface when projected at the given angle. Args: surface (surface):
the surface to project angle (float):
the angle at which to project the surface Returns: surface: A projected surface. """ |
z_coef = np.sin(np.radians(angle))
y_coef = np.cos(np.radians(angle))
surface_height, surface_width = surface.shape
slope = np.tile(np.linspace(0., 1., surface_height), [surface_width, 1]).T
return slope * y_coef + surface * z_coef |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE):
"""Maps a texture onto a surface, then projects to 2D and returns a layer. Args: texture (texture):
the texture to project surface (surface):
the surface to project onto angle (float):
the projection angle in degrees (0 = top-down, 90 = side view) Returns: layer: A layer. """ |
projected_surface = project_surface(surface, angle)
texture_x, _ = texture
texture_y = map_texture_to_surface(texture, projected_surface)
return texture_x, texture_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 _remove_hidden_parts(projected_surface):
"""Removes parts of a projected surface that are not visible. Args: projected_surface (surface):
the surface to use Returns: surface: A projected surface. """ |
surface = np.copy(projected_surface)
surface[~_make_occlusion_mask(projected_surface)] = np.nan
return surface |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_and_occlude_texture(texture, surface, angle=DEFAULT_ANGLE):
"""Projects a texture onto a surface with occluded areas removed. Args: texture (texture):
the texture to map to the projected surface surface (surface):
the surface to project angle (float):
the angle to project at, in degrees (0 = overhead, 90 = side view) Returns: layer: A layer. """ |
projected_surface = project_surface(surface, angle)
projected_surface = _remove_hidden_parts(projected_surface)
texture_y = map_texture_to_surface(texture, projected_surface)
texture_x, _ = texture
return texture_x, texture_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 make_lines_texture(num_lines=10, resolution=50):
"""Makes a texture consisting of a given number of horizontal lines. Args: num_lines (int):
the number of lines to draw resolution (int):
the number of midpoints on each line Returns: A texture. """ |
x, y = np.meshgrid(
np.hstack([np.linspace(0, 1, resolution), np.nan]),
np.linspace(0, 1, num_lines),
)
y[np.isnan(x)] = np.nan
return x.flatten(), y.flatten() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_grid_texture(num_h_lines=10, num_v_lines=10, resolution=50):
"""Makes a texture consisting of a grid of vertical and horizontal lines. Args: num_h_lines (int):
the number of horizontal lines to draw num_v_lines (int):
the number of vertical lines to draw resolution (int):
the number of midpoints to draw on each line Returns: A texture. """ |
x_h, y_h = make_lines_texture(num_h_lines, resolution)
y_v, x_v = make_lines_texture(num_v_lines, resolution)
return np.concatenate([x_h, x_v]), np.concatenate([y_h, y_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 make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000):
"""Makes a texture consisting of a spiral from the origin. Args: spirals (float):
the number of rotations to make ccw (bool):
make spirals counter-clockwise (default is clockwise) offset (float):
if non-zero, spirals start offset by this amount resolution (int):
number of midpoints along the spiral Returns: A texture. """ |
dist = np.sqrt(np.linspace(0., 1., resolution))
if ccw:
direction = 1.
else:
direction = -1.
angle = dist * spirals * np.pi * 2. * direction
spiral_texture = (
(np.cos(angle) * dist / 2.) + 0.5,
(np.sin(angle) * dist / 2.) + 0.5
)
return spiral_texture |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_hex_texture(grid_size = 2, resolution=1):
"""Makes a texture consisting on a grid of hexagons. Args: grid_size (int):
the number of hexagons along each dimension of the grid resolution (int):
the number of midpoints along the line of each hexagon Returns: A texture. """ |
grid_x, grid_y = np.meshgrid(
np.arange(grid_size),
np.arange(grid_size)
)
ROOT_3_OVER_2 = np.sqrt(3) / 2
ONE_HALF = 0.5
grid_x = (grid_x * np.sqrt(3) + (grid_y % 2) * ROOT_3_OVER_2).flatten()
grid_y = grid_y.flatten() * 1.5
grid_points = grid_x.shape[0]
x_offsets = np.interp(np.arange(4 * resolution),
np.arange(4) * resolution, [
ROOT_3_OVER_2,
0.,
-ROOT_3_OVER_2,
-ROOT_3_OVER_2,
])
y_offsets = np.interp(np.arange(4 * resolution),
np.arange(4) * resolution, [
-ONE_HALF,
-1.,
-ONE_HALF,
ONE_HALF
])
tmx = 4 * resolution
x_t = np.tile(grid_x, (tmx, 1)) + x_offsets.reshape((tmx, 1))
y_t = np.tile(grid_y, (tmx, 1)) + y_offsets.reshape((tmx, 1))
x_t = np.vstack([x_t, np.tile(np.nan, (1, grid_x.size))])
y_t = np.vstack([y_t, np.tile(np.nan, (1, grid_y.size))])
return fit_texture((x_t.flatten('F'), y_t.flatten('F'))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None):
"""Makes a surface by generating random noise and blurring it. Args: dims (pair):
the dimensions of the surface to create blur (float):
the amount of Gaussian blur to apply seed (int):
a random seed to use (optional) Returns: surface: A surface. """ |
if seed is not None:
np.random.seed(seed)
return gaussian_filter(np.random.normal(size=dims), blur) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_gradients(dims=DEFAULT_DIMS):
"""Makes a pair of gradients to generate textures from numpy primitives. Args: dims (pair):
the dimensions of the surface to create Returns: pair: A pair of surfaces. """ |
return np.meshgrid(
np.linspace(0.0, 1.0, dims[0]),
np.linspace(0.0, 1.0, dims[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 make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0):
"""Makes a surface from the 3D sine function. Args: dims (pair):
the dimensions of the surface to create offset (float):
an offset applied to the function scale (float):
a scale applied to the sine frequency Returns: surface: A surface. """ |
gradients = (np.array(make_gradients(dims)) - offset) * scale * np.pi
return np.sin(np.linalg.norm(gradients, axis=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 make_bubble_surface(dims=DEFAULT_DIMS, repeat=3):
"""Makes a surface from the product of sine functions on each axis. Args: dims (pair):
the dimensions of the surface to create repeat (int):
the frequency of the waves is set to ensure this many repetitions of the function Returns: surface: A surface. """ |
gradients = make_gradients(dims)
return (
np.sin((gradients[0] - 0.5) * repeat * np.pi) *
np.sin((gradients[1] - 0.5) * repeat * np.pi)) |
<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_controller(url):
"""Initialize a controller. Provides a single global controller for applications that can't do this themselves """ |
# pylint: disable=global-statement
global _VERA_CONTROLLER
created = False
if _VERA_CONTROLLER is None:
_VERA_CONTROLLER = VeraController(url)
created = True
_VERA_CONTROLLER.start()
return [_VERA_CONTROLLER, created] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_request(self, payload, timeout=TIMEOUT):
"""Perform a data_request and return the result.""" |
request_url = self.base_url + "/data_request"
return requests.get(request_url, timeout=timeout, params=payload) |
<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_simple_devices_info(self):
"""Get basic device info from Vera.""" |
j = self.data_request({'id': 'sdata'}).json()
self.scenes = []
items = j.get('scenes')
for item in items:
self.scenes.append(VeraScene(item, self))
if j.get('temperature'):
self.temperature_units = j.get('temperature')
self.categories = {}
cats = j.get('categories')
for cat in cats:
self.categories[cat.get('id')] = cat.get('name')
self.device_id_map = {}
devs = j.get('devices')
for dev in devs:
dev['categoryName'] = self.categories.get(dev.get('category'))
self.device_id_map[dev.get('id')] = dev |
<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_device_by_name(self, device_name):
"""Search the list of connected devices by name. device_name param is the string name of the device """ |
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if device.name == device_name:
found_device = device
# found the first (and should be only) one so we will finish
break
if found_device is None:
logger.debug('Did not find device with {}'.format(device_name))
return found_device |
<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_device_by_id(self, device_id):
"""Search the list of connected devices by ID. device_id param is the integer ID of the device """ |
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if device.device_id == device_id:
found_device = device
# found the first (and should be only) one so we will finish
break
if found_device is None:
logger.debug('Did not find device with {}'.format(device_id))
return found_device |
<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_devices(self, category_filter=''):
"""Get list of connected devices. category_filter param is an array of strings """ |
# pylint: disable=too-many-branches
# the Vera rest API is a bit rough so we need to make 2 calls to get
# all the info e need
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
self.devices = []
items = j.get('devices')
for item in items:
item['deviceInfo'] = self.device_id_map.get(item.get('id'))
if item.get('deviceInfo'):
device_category = item.get('deviceInfo').get('category')
if device_category == CATEGORY_DIMMER:
device = VeraDimmer(item, self)
elif ( device_category == CATEGORY_SWITCH or
device_category == CATEGORY_VERA_SIREN):
device = VeraSwitch(item, self)
elif device_category == CATEGORY_THERMOSTAT:
device = VeraThermostat(item, self)
elif device_category == CATEGORY_LOCK:
device = VeraLock(item, self)
elif device_category == CATEGORY_CURTAIN:
device = VeraCurtain(item, self)
elif device_category == CATEGORY_ARMABLE:
device = VeraBinarySensor(item, self)
elif (device_category == CATEGORY_SENSOR or
device_category == CATEGORY_HUMIDITY_SENSOR or
device_category == CATEGORY_TEMPERATURE_SENSOR or
device_category == CATEGORY_LIGHT_SENSOR or
device_category == CATEGORY_POWER_METER or
device_category == CATEGORY_UV_SENSOR):
device = VeraSensor(item, self)
elif (device_category == CATEGORY_SCENE_CONTROLLER or
device_category == CATEGORY_REMOTE):
device = VeraSceneController(item, self)
elif device_category == CATEGORY_GARAGE_DOOR:
device = VeraGarageDoor(item, self)
else:
device = VeraDevice(item, self)
self.devices.append(device)
if (device.is_armable and not (
device_category == CATEGORY_SWITCH or
device_category == CATEGORY_VERA_SIREN or
device_category == CATEGORY_CURTAIN or
device_category == CATEGORY_GARAGE_DOOR)):
self.devices.append(VeraArmableDevice(item, self))
else:
self.devices.append(VeraDevice(item, self))
if not category_filter:
return self.devices
devices = []
for device in self.devices:
if (device.category_name is not None and
device.category_name != '' and
device.category_name in category_filter):
devices.append(device)
return devices |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh_data(self):
"""Refresh data from Vera device.""" |
j = self.data_request({'id': 'sdata'}).json()
self.temperature_units = j.get('temperature', 'C')
self.model = j.get('model')
self.version = j.get('version')
self.serial_number = j.get('serial_number')
categories = {}
cats = j.get('categories')
for cat in cats:
categories[cat.get('id')] = cat.get('name')
device_id_map = {}
devs = j.get('devices')
for dev in devs:
dev['categoryName'] = categories.get(dev.get('category'))
device_id_map[dev.get('id')] = dev
return device_id_map |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_services(self):
"""Get full Vera device service info.""" |
# the Vera rest API is a bit rough so we need to make 2 calls
# to get all the info e need
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
service_map = {}
items = j.get('devices')
for item in items:
service_map[item.get('id')] = item.get('states')
self.device_services_map = service_map |
<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_changed_devices(self, timestamp):
"""Get data since last timestamp. This is done via a blocking call, pass NONE for initial state. """ |
if timestamp is None:
payload = {}
else:
payload = {
'timeout': SUBSCRIPTION_WAIT,
'minimumdelay': SUBSCRIPTION_MIN_WAIT
}
payload.update(timestamp)
# double the timeout here so requests doesn't timeout before vera
payload.update({
'id': 'lu_sdata',
})
logger.debug("get_changed_devices() requesting payload %s", str(payload))
r = self.data_request(payload, TIMEOUT*2)
r.raise_for_status()
# If the Vera disconnects before writing a full response (as lu_sdata
# will do when interrupted by a Luup reload), the requests module will
# happily return 200 with an empty string. So, test for empty response,
# so we don't rely on the JSON parser to throw an exception.
if r.text == "":
raise PyveraError("Empty response from Vera")
# Catch a wide swath of what the JSON parser might throw, within
# reason. Unfortunately, some parsers don't specifically return
# json.decode.JSONDecodeError, but so far most seem to derive what
# they do throw from ValueError, so that's helpful.
try:
result = r.json()
except ValueError as ex:
raise PyveraError("JSON decode error: " + str(ex))
if not ( type(result) is dict
and 'loadtime' in result and 'dataversion' in result ):
raise PyveraError("Unexpected/garbled response from Vera")
# At this point, all good. Update timestamp and return change data.
device_data = result.get('devices')
timestamp = {
'loadtime': result.get('loadtime'),
'dataversion': result.get('dataversion')
}
return [device_data, timestamp] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vera_request(self, **kwargs):
"""Perfom a vera_request for this device.""" |
request_payload = {
'output_format': 'json',
'DeviceNum': self.device_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) |
<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_service_value(self, service_id, set_name, parameter_name, value):
"""Set a variable on the vera device. This will call the Vera api to change device state. """ |
payload = {
'id': 'lu_action',
'action': 'Set' + set_name,
'serviceId': service_id,
parameter_name: value
}
result = self.vera_request(**payload)
logger.debug("set_service_value: "
"result of vera_request with payload %s: %s",
payload, result.text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_service(self, service_id, action):
"""Call a Vera service. This will call the Vera api to change device state. """ |
result = self.vera_request(id='action', serviceId=service_id,
action=action)
logger.debug("call_service: "
"result of vera_request with id %s: %s", service_id,
result.text)
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 set_cache_value(self, name, value):
"""Set a variable in the local state dictionary. This does not change the physical device. Useful if you want the device state to refect a new value which has not yet updated drom Vera. """ |
dev_info = self.json_state.get('deviceInfo')
if dev_info.get(name.lower()) is None:
logger.error("Could not set %s for %s (key does not exist).",
name, self.name)
logger.error("- dictionary %s", dev_info)
return
dev_info[name.lower()] = str(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 set_cache_complex_value(self, name, value):
"""Set a variable in the local complex state dictionary. This does not change the physical device. Useful if you want the device state to refect a new value which has not yet updated from Vera. """ |
for item in self.json_state.get('states'):
if item.get('variable') == name:
item['value'] = str(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_complex_value(self, name):
"""Get a value from the service dictionaries. It's best to use get_value if it has the data you require since the vera subscription only updates data in dev_info. """ |
for item in self.json_state.get('states'):
if item.get('variable') == name:
return item.get('value')
return 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 get_strict_value(self, name):
"""Get a case-sensitive keys value from the dev_info area. """ |
dev_info = self.json_state.get('deviceInfo')
return dev_info.get(name, 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 refresh_complex_value(self, name):
"""Refresh a value from the service dictionaries. It's best to use get_value / refresh if it has the data you need. """ |
for item in self.json_state.get('states'):
if item.get('variable') == name:
service_id = item.get('service')
result = self.vera_request(**{
'id': 'variableget',
'output_format': 'json',
'DeviceNum': self.device_id,
'serviceId': service_id,
'Variable': name
})
item['value'] = result.text
return item.get('value')
return 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 refresh(self):
"""Refresh the dev_info data used by get_value. Only needed if you're not using subscriptions. """ |
j = self.vera_request(id='sdata', output_format='json').json()
devices = j.get('devices')
for device_data in devices:
if device_data.get('id') == self.device_id:
self.update(device_data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.