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 parse_first_row(row, url_instance):
""" Static method that parses a given table row element by executing `Parser.FIRST_ROW_XPATH` and scrapping torrent's id, title, tracked by status, category url and torrent url. Used specifically with a torrent's first table row. :param lxml.HtmlElement row: row to parse :param urls.Url url_instance: Url used to combine base url's with scrapped links from tr :return: scrapped id, title, tracked by status, category url and torrent url :rtype: list """ |
tags = row.xpath(Parser.FIRST_ROW_XPATH)
category_url = url_instance.combine(tags[0].get('href'))
title = unicode(tags[1].text)
# work with the incomplete URL to get str_id
torrent_url = tags[1].get('href')
str_id = torrent_url.split('details/')[1]
str_id = str_id[:-1] if str_id.endswith('/') else str_id
# complete the torrent URL with BASE_URL
torrent_url = url_instance.combine(torrent_url)
# means that torrent has external property
if len(tags) == 3:
# monkey patch the missing external query param
category_url += '&external=1'
tracked_by = '(external)'
else:
tracked_by = 'Demonoid'
return [str_id, title, tracked_by, category_url, torrent_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 parse_second_row(row, url):
""" Static method that parses a given table row element by using helper methods `Parser.parse_category_subcategory_and_or_quality`, `Parser.parse_torrent_link` and scrapping torrent's category, subcategory, quality, language, user, user url, torrent link, size, comments, times completed, seeders and leechers. Used specifically with a torrent's second table row. :param lxml.HtmlElement row: row to parse :param urls.Url url_instance: Url used to combine base url's with scrapped links from tr :return: scrapped category, subcategory, quality, language, user, user url, torrent link, size, comments, times completed, seeders and leechers :rtype: list """ |
tags = row.findall('./td')
category, subcategory, quality, language = Parser.parse_torrent_properties(tags[0])
user_info = tags[1].find('./a')
user = user_info.text_content()
user_url = url.combine(user_info.get('href'))
# Two urls - one is spam, second is torrent url.
# Don't combine it with BASE_URL, since it's an absolute url.
torrent_link = Parser.parse_torrent_link(tags[2])
size = tags[3].text # as 10.5 GB
comments = tags[4].text
times_completed = tags[5].text
seeders = tags[6].text
leechers = tags[7].text
return [category, subcategory, quality, language, user, user_url, torrent_link,
size, comments, times_completed, seeders, 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 parse_torrent_properties(table_datas):
""" Static method that parses a given list of table data elements and using helper methods `Parser.is_subcategory`, `Parser.is_quality`, `Parser.is_language`, collects torrent properties. :param list lxml.HtmlElement table_datas: table_datas to parse :return: identified category, subcategory, quality and languages. :rtype: dict """ |
output = {'category': table_datas[0].text, 'subcategory': None, 'quality': None, 'language': None}
for i in range(1, len(table_datas)):
td = table_datas[i]
url = td.get('href')
params = Parser.get_params(url)
if Parser.is_subcategory(params) and not output['subcategory']:
output['subcategory'] = td.text
elif Parser.is_quality(params) and not output['quality']:
output['quality'] = td.text
elif Parser.is_language(params) and not output['language']:
output['language'] = td.text
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_torrent_link(table_data):
""" Static method that parses list of table data, finds all anchor elements and gets the torrent url. However the torrent url is usually hidden behind a fake spam ad url, this is handled. :param list lxml.HtmlElement table_data: table_data tag to parse :return: torrent url from anchor (link) element :rtype: str """ |
anchors = table_data.findall('./a')
link_tag = anchors[0] if len(anchors) < 2 else anchors[1]
return link_tag.get('href') |
<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(url, max_backoff=32, verbose=False, **kwargs):
"""Adding retries to requests.get with exponential backoff. Args: url (str):
The URL to fetch max_backoff (int):
The number of seconds to sleep at maximums verbose (bool):
Whether to print exceptions. Returns: Response: For successful requests return requests' response. `None` otherwise. """ |
sleep_seconds = 1
while sleep_seconds <= max_backoff:
try:
# you may overwrite `timeout` via `kwargs`
response = requests.get(url, **{**{'timeout': 30}, **kwargs})
# for 4xx, return instantly, no hope of success
if 400 <= response.status_code < 500:
return None
# successfully return 2XX and 3xx
if 200 <= response.status_code < 400:
return response
# for 1xx and 5xx, retry
except RequestException as e:
if verbose:
print(str(e))
time.sleep(sleep_seconds)
sleep_seconds *= 2
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 set_image(self):
"""This code must be in its own method since the fetch functions need credits to be set. m2m fields are not yet set at the end of either the save method or post_save signal.""" |
if not self.image:
scrape_image(self)
# If still no image then use first contributor image
if not self.image:
contributors = self.get_primary_contributors()
if contributors:
self.image = contributors[0].image
self.save(set_image=False)
# If still not image then default
if not self.image:
filename = settings.STATIC_ROOT + 'music/images/default.png'
if os.path.exists(filename):
image = File(
open(filename, 'rb')
)
image.name = 'default.png'
self.image = image
self.save(set_image=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 configure_api(app):
"""Configure API Endpoints. """ |
from heman.api.empowering import resources as empowering_resources
from heman.api.cch import resources as cch_resources
from heman.api.form import resources as form_resources
from heman.api import ApiCatchall
# Add Empowering resources
for resource in empowering_resources:
api.add_resource(*resource)
# Add CCHFact resources
for resource in cch_resources:
api.add_resource(*resource)
# Add Form resources
for resource in form_resources:
api.add_resource(*resource)
api.add_resource(ApiCatchall, '/<path:path>')
api.init_app(app) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_login(app):
"""Configure login authentification Uses `Flask-Login <https://flask-login.readthedocs.org>`_ """ |
from heman.auth import login_manager, login
login_manager.init_app(app)
@app.teardown_request
def force_logout(*args, **kwargs):
login.logout_user() |
<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_DragonDosBinary(self, data, strip_padding=True):
""" Dragon DOS Binary Format http://dragon32.info/info/binformt.html Offset: Type: Value: 0 byte $55 Constant 1 byte Filetype 2:3 word Load Address 4:5 word Length 6:7 word Exec Address 8 byte $AA Constant 9-xxx byte[] Data """ |
data = bytearray(data)
log.debug("Load Dragon DOS Binary Format.")
meta_data = struct.unpack(">BBHHHB", data[:9])
machine_type = meta_data[0]
if machine_type != 0x55:
log.error("ERROR: Machine type wrong: is $%02X but should be $55!", machine_type)
self.file_type = meta_data[1]
self.load_address = meta_data[2]
self.length = meta_data[3]
self.exec_address = meta_data[4]
terminator = meta_data[5]
if terminator != 0xAA:
log.error("ERROR: Terminator byte is $%02X but should be $AA!", terminator)
# print("before strip:")
# print("\n".join(bin2hexline(data, width=16)))
if strip_padding:
self.data = data[9:self.length + 9]
else:
self.data = data[9:]
# print("after strip:")
# print("\n".join(bin2hexline(self.data, width=16)))
log.debug(
"File type: $%02X Load Address: $%04X Exec Address: $%04X Length: %iBytes",
self.file_type, self.load_address, self.exec_address, self.length
)
if self.length != len(self.data):
log.error("ERROR: Wrong data size: should be: %i Bytes but is %i Bytes!", self.length, len(self.data))
# log_bytes(self.data, "data in hex: %s", level=logging.DEBUG)
self.debug2log(level=logging.DEBUG) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotatePoint(x, y, rotationDegrees, pivotx=0, pivoty=0):
""" Rotates the point at `x` and `y` by `rotationDegrees`. The point is rotated around the origin by default, but can be rotated around another pivot point by specifying `pivotx` and `pivoty`. The points are rotated counterclockwise. Returns an x and y tuple. Since the final result will be integers, there is a large amount of rounding error that can take place. (0, 10) (-10, 0) (7, 7) """ |
# Reuse the code in rotatePoints()
return list(rotatePoints([(x, y)], rotationDegrees, pivotx, pivoty))[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 rotatePoints(points, rotationDegrees, pivotx=0, pivoty=0):
""" Rotates each x and y tuple in `points`` by `rotationDegrees`. The points are rotated around the origin by default, but can be rotated around another pivot point by specifying `pivotx` and `pivoty`. The points are rotated counterclockwise. Returns a generator that produces an x and y tuple for each point in `points`. [(7, 7), (0, 9)] """ |
rotationRadians = math.radians(rotationDegrees % 360)
for x, y in points:
_checkForIntOrFloat(x)
_checkForIntOrFloat(y)
x -= pivotx
y -= pivoty
x, y = x * math.cos(rotationRadians) - y * math.sin(rotationRadians), x * math.sin(rotationRadians) + y * math.cos(rotationRadians)
x += pivotx
y += pivoty
yield int(x), int(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 line(x1, y1, x2, y2, thickness=1, endcap=None, _skipFirst=False):
""" Returns a generator that produces all of the points in a line between `x1`, `y1` and `x2`, `y2`. (Note: The `thickness` and `endcap` parameters are not yet implemented.) [(0, 0), (1, 0), (2, 1), (3, 1), (4, 1), (5, 1), (6, 2), (7, 2), (8, 2), (9, 3), (10, 3)] OOOO,,,,,,,,,,,,,,,,, ,,,,OOOOOOO,,,,,,,,,, ,,,,,,,,,,,OOOOOO,,,, ,,,,,,,,,,,,,,,,,OOOO """ |
if (thickness != 1) or (endcap is not None):
raise NotImplementedError('The pybresenham module is under development and the filled and thickness parameters are not implemented. You can contribute at https://github.com/asweigart/pybresenham')
_checkForIntOrFloat(x1)
_checkForIntOrFloat(y1)
_checkForIntOrFloat(x2)
_checkForIntOrFloat(y2)
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) # TODO - Do we want this line?
if not isinstance(_skipFirst, bool):
raise PyBresenhamException('_skipFirst argument must be a bool')
isSteep = abs(y2-y1) > abs(x2-x1)
if isSteep:
x1, y1 = y1, x1
x2, y2 = y2, x2
isReversed = x1 > x2
if isReversed:
x1, x2 = x2, x1
y1, y2 = y2, y1
deltax = x2 - x1
deltay = abs(y2-y1)
error = int(deltax / 2)
y = y2
ystep = None
if y1 < y2:
ystep = 1
else:
ystep = -1
for x in range(x2, x1 - 1, -1):
if isSteep:
if not (_skipFirst and (x, y) == (x2, y2)):
yield (y, x)
else:
if not (_skipFirst and (x, y) == (x2, y2)):
yield (x, y)
error -= deltay
if error <= 0:
y -= ystep
error += deltax
else:
deltax = x2 - x1
deltay = abs(y2-y1)
error = int(deltax / 2)
y = y1
ystep = None
if y1 < y2:
ystep = 1
else:
ystep = -1
for x in range(x1, x2 + 1):
if isSteep:
if not (_skipFirst and (x, y) == (x1, y1)):
yield (y, x)
else:
if not (_skipFirst and (x, y) == (x1, y1)):
yield (x, y)
error -= deltay
if error < 0:
y += ystep
error += deltax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit(self, record):
"""Store the message, not only the record.""" |
self.records.append(Record(levelno=record.levelno, levelname=record.levelname,
message=self.format(record)))
return super(SetupLogChecker, self).emit(record) |
<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_generic_pos(self, *tokens):
"""Check if the different tokens were logged in one record, any level.""" |
for record in self.records:
if all(token in record.message for token in tokens):
return
# didn't exit, all tokens are not present in the same record
msgs = ["Tokens {} not found, all was logged is...".format(tokens)]
for record in self.records:
msgs.append(" {:9s} {!r}".format(record.levelname, record.message))
self.test_instance.fail("\n".join(msgs)) |
<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_pos(self, level, *tokens):
"""Check if the different tokens were logged in one record, assert by level.""" |
for record in self.records:
if all(record.levelno == level and token in record.message for token in tokens):
return
# didn't exit, all tokens are not present in the same record
level_name = logging.getLevelName(level)
msgs = ["Tokens {} not found in {}, all was logged is...".format(tokens, level_name)]
for record in self.records:
msgs.append(" {:9s} {!r}".format(record.levelname, record.message))
self.test_instance.fail("\n".join(msgs)) |
<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_neg(self, level, *tokens):
"""Check that the different tokens were NOT logged in one record, assert by level.""" |
for record in self.records:
if level is not None and record.levelno != level:
continue
if all(token in record.message for token in tokens):
break
else:
return
# didn't exit, all tokens found in the same record
msg = "Tokens {} found in the following record: {} {!r}".format(
tokens, record.levelname, record.message)
self.test_instance.fail(msg) |
<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_consumers(self, _Consumer, channel):
""" | ConsumerMixin requirement. | Get the consumers list. :returns: All the consumers. :rtype: list. """ |
return [_Consumer(queues=[self.queue(channel)], callbacks=[self.main_callback], prefetch_count=self.prefetch_count)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self, *args, **kwargs):
#pylint:disable=unused-argument """ | Launch the consumer. | It can listen forever for messages or just wait for one. :param forever: If set, the consumer listens forever. Default to `True`. :type forever: bool :param timeout: If set, the consumer waits the specified seconds before quitting. :type timeout: None, int :rtype: None :raises socket.timeout: when no message has been received since `timeout`. """ |
forever = kwargs.get('forever', True)
timeout = kwargs.get('timeout', None)
if forever:
return self.run(timeout=timeout)
elif timeout:
next((self.consume(timeout=timeout)), None)
else:
next((self.consume(limit=1, timeout=timeout)), 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 modelserializer_factory(model, serializer=None, fields=None, exclude=None):
""" Returns a ModelSerializer containing fields for the given model. :param model: model class. :param fields: is an optional list of field names. If provided, only the named fields will be included in the returned fields. If omitted or '__all__', all fields will be used. :param exclude: is an optional list of field names. If provided, the named fields will be excluded from the returned fields, even if they are listed in the ``fields`` argument. :return: ModelSerializer class """ |
# default values
serializer = serializer or serializers.ModelSerializer
attrs = {'model': model}
if fields == '__all__':
opts = model._meta.concrete_model._meta
attrs['fields'] = [field.name for field in opts.fields if field.serialize]
elif fields is not None:
attrs['fields'] = fields
if exclude is not None:
attrs['exclude'] = exclude
# create meta class
parent = (object,)
Meta = type('Meta', parent, attrs)
# Give this new serializer class a reasonable name.
class_name = model.__name__ + 'Serializer'
# Class attributes for the new serializer class.
serializer_class_attrs = {
'Meta': Meta,
}
return type(serializer)(class_name, (serializer,), serializer_class_attrs) |
<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_kube_path():
"""Get the current config path. If the KUBECONFIG environment parameter is set, use it. If multiple paths are listed in KUBECONFIG, use the first path. """ |
try:
path = pathlib.Path(os.environ["KUBECONFIG"].split(':')[0])
except KeyError:
path = pathlib.Path.home().joinpath('.kube', 'config')
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 open(self, create_if_not_found=True):
"""Open a kube config file. If the file does not exist, it creates a new file. """ |
try:
self.data = self._read()
# If the file does
except FileNotFoundError as e:
if create_if_not_found is True:
self.data = {}
else:
raise e
# Enforce the following keys exists in data.
if 'clusters' not in self.data:
self.data['clusters'] = []
if 'contexts' not in self.data:
self.data['clusters'] = []
if 'users' not in self.data:
self.data['users'] = []
if 'apiVersion' not in self.data:
self.data['apiVersion'] = 'v1'
if 'kind' not in self.data:
self.data['kind'] = 'Config'
if 'preferences' not in self.data:
self.data['preferences'] = {}
if 'current-context' not in self.data:
self.data['current-context'] = ''
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 _read(self):
"""Read the kube config file. """ |
stream = self.path.read_text()
data = yaml.load(stream)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _write(self, data):
"""Write data to config file.""" |
stream = yaml.dump(data, default_flow_style=False)
self.path.write_text(stream) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cluster_exists(self, name):
"""Check if a given cluster exists.""" |
clusters = self.data['clusters']
for cluster in clusters:
if cluster['name'] == 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 get_cluster(self, name):
"""Get cluster from kubeconfig.""" |
clusters = self.data['clusters']
for cluster in clusters:
if cluster['name'] == name:
return cluster
raise KubeConfError("Cluster name not found.") |
<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_clusters(self, names=False):
"""Print contexts.""" |
clusters = self.get_clusters()
if names:
clusters = [cluster['name'] for cluster in clusters]
pprint.pprint(clusters) |
<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_cluster( self, name, server=None, certificate_authority_data=None, **attrs):
"""Add a cluster to config.""" |
if self.cluster_exists(name):
raise KubeConfError("Cluster with the given name already exists.")
clusters = self.get_clusters()
# Add parameters.
new_cluster = {'name': name, 'cluster':{}}
attrs_ = new_cluster['cluster']
if server is not None:
attrs_['server'] = server
if certificate_authority_data is not None:
attrs_['certificate-authority-data'] = certificate_authority_data
attrs_.update(attrs)
clusters.append(new_cluster) |
<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_to_cluster(self, name, **attrs):
"""Add attributes to a cluster. """ |
cluster = self.get_cluster(name=name)
attrs_ = cluster['cluster']
attrs_.update(**attrs) |
<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_from_cluster(self, name, *args):
"""Remove attributes from a cluster. """ |
cluster = self.get_cluster(name=name)
attrs_ = cluster['cluster']
for a in args:
del attrs_[a] |
<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_cluster(self, name):
"""Remove a cluster from kubeconfig. """ |
cluster = self.get_cluster(name)
clusters = self.get_clusters()
clusters.remove(cluster) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_exists(self, name):
"""Check if a given user exists.""" |
users = self.data['users']
for user in users:
if user['name'] == 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 get_user(self, name):
"""Get user from kubeconfig.""" |
users = self.data['users']
for user in users:
if user['name'] == name:
return user
raise KubeConfError("user name not found.") |
<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_user( self, name, **attrs ):
"""Add a user to config.""" |
if self.user_exists(name):
raise KubeConfError("user with the given name already exists.")
users = self.get_users()
# Add parameters.
new_user = {'name': name, 'user':{}}
attrs_ = new_user['user']
attrs_.update(attrs)
users.append(new_user) |
<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_to_user(self, name, **attrs):
"""Add attributes to a user. """ |
user = self.get_user(name=name)
attrs_ = user['user']
attrs_.update(**attrs) |
<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_from_user(self, name, *args):
"""Remove attributes from a user. """ |
user = self.get_user(name=name)
attrs_ = user['user']
for a in args:
del attrs_[a] |
<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_user(self, name):
"""Remove a user from kubeconfig. """ |
user = self.get_user(name)
users = self.get_users()
users.remove(user) |
<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_exec_to_user( self, name, env, command, args, **attrs ):
"""Add an exec option to your user.""" |
# Add exec option.
exec_options = {
'command': command,
'env': env,
'args': args,
}
exec_options.update(attrs)
# Add exec to user.
self.add_to_user(name=name, exec=exec_options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def context_exists(self, name):
"""Check if a given context exists.""" |
contexts = self.data['contexts']
for context in contexts:
if context['name'] == 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 get_context(self, name):
"""Get context from kubeconfig.""" |
contexts = self.data['contexts']
for context in contexts:
if context['name'] == name:
return context
raise KubeConfError("context name not found.") |
<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_context( self, name, cluster_name=None, user_name=None, namespace_name=None, **attrs ):
"""Add a context to config.""" |
if self.context_exists(name):
raise KubeConfError("context with the given name already exists.")
contexts = self.get_contexts()
# Add parameters.
new_context = {'name': name, 'context':{}}
# Add attributes
attrs_ = new_context['context']
if cluster_name is not None:
attrs_['cluster'] = cluster_name
if user_name is not None:
attrs_['user'] = user_name
if namespace_name is not None:
attrs_['namespace'] = namespace_name
attrs_.update(attrs)
contexts.append(new_context) |
<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_to_context(self, name, **attrs):
"""Add attributes to a context. """ |
context = self.get_context(name=name)
attrs_ = context['context']
attrs_.update(**attrs) |
<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_from_context(self, name, *args):
"""Remove attributes from a context. """ |
context = self.get_context(name=name)
attrs_ = context['context']
for a in args:
del attrs_[a] |
<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_context(self, name):
"""Remove a context from kubeconfig. """ |
context = self.get_context(name)
contexts = self.get_contexts()
contexts.remove(context) |
<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_current_context(self, name):
"""Set the current context in kubeconfig.""" |
if self.context_exists(name):
self.data['current-context'] = name
else:
raise KubeConfError("Context does not exist.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_logging(self, verbosity_lvl=None, format='%(message)s'):
"""Switches on logging at a given level. :param verbosity_lvl: :param format: """ |
if not verbosity_lvl:
verbosity_lvl = logging.INFO
logging.basicConfig(format=format)
self.logger.setLevel(verbosity_lvl) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _run_shell_command(self, command, pipe_it=True):
"""Runs the given shell command. :param command: :return: bool Status """ |
stdout = None
if pipe_it:
stdout = PIPE
self.logger.debug('Executing shell command: %s' % command)
return not bool(Popen(command, shell=True, stdout=stdout).wait()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_manage_command(self, command, venv_path, verbose=True):
"""Runs a given Django manage command in a given virtual environment. :param str command: :param str venv_path: :param bool verbose: """ |
self.logger.debug('Running manage command `%s` for `%s` ...' % (command, venv_path))
self._run_shell_command(
'. %s/bin/activate && python %s %s' % (venv_path, self._get_manage_py_path(), command),
pipe_it=(not verbose)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def venv_install(self, package_name, venv_path):
"""Installs a given python package into a given virtual environment. :param str package_name: :param str venv_path: """ |
self.logger.debug('Installing `%s` into `%s` ...' % (package_name, venv_path))
self._run_shell_command('. %s/bin/activate && pip install -U %s' % (venv_path, package_name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_venv(self, dj_version):
"""Creates a virtual environment for a given Django version. :param str dj_version: :rtype: str :return: path to created virtual env """ |
venv_path = self._get_venv_path(dj_version)
self.logger.info('Creating virtual environment for Django %s ...' % dj_version)
try:
create_venv(venv_path, **VENV_CREATE_KWARGS)
except ValueError:
self.logger.warning('Virtual environment directory already exists. Skipped.')
self.venv_install('django==%s' % dj_version, venv_path)
return venv_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 make_apps_dir(self):
"""Creates an empty directory for symlinks to Django applications. :rtype: str :return: created directory path """ |
self.logger.info('Creating a directory for symlinks to your Django applications `%s` ...' % self.apps_path)
try:
os.mkdir(self.apps_path)
except OSError:
pass # Already exists.
return self.apps_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 dispatch_op(self, op_name, args_dict):
"""Dispatches an operation requested. :param str op_name: :param dict args_dict: """ |
self.logger.debug('Requested `%s` command with `%s` args.' % (op_name, args_dict))
method = getattr(self, 'op_%s' % op_name, None)
if method is None:
error_str = '`%s` command is not supported.' % op_name
self.logger.error(error_str)
raise DjangoDevException(error_str)
method(**args_dict)
self.logger.info('Done.') |
<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_venvs(self):
"""Returns a list of names of available virtual environments. :raises: DjangoDevException on errors :rtype: list :return: list of names """ |
def raise_():
error_str = 'Virtual environments are not created. Please run `bootstrap` command.'
self.logger.error(error_str)
raise DjangoDevException(error_str)
if not os.path.exists(self.venvs_path):
raise_()
venvs = os.listdir(self.venvs_path)
if not venvs:
raise_()
venvs.sort()
return venvs |
<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_apps(self, only=None):
"""Returns a list of names of available Django applications, Optionally filters it using `only`. :param list|None only: a list on apps names to to filter all available apps against :raises: DjangoDevException on errors :rtype: list :return: list of apps names """ |
if not os.path.exists(self.apps_path):
error_str = 'It seems that this directory does not contain django-dev project. ' \
'Use `bootstrap` command to create project in the current directory.'
self.logger.error(error_str)
raise DjangoDevException(error_str)
apps = os.listdir(self.apps_path)
if not apps:
error_str = 'Applications directory is empty. ' \
'Please symlink your apps (and other apps that you apps depend upon) into %s' % self.apps_path
self.logger.error(error_str)
raise DjangoDevException(error_str)
apps.sort()
if only is None:
self.create_manage_py(apps)
return apps
diff = set(only).difference(apps)
if diff:
error_str = 'The following apps are not found: `%s`.' % ('`, `'.join(diff))
self.logger.error(error_str)
raise DjangoDevException(error_str)
self.create_manage_py(apps)
return [name for name in apps if name in only] |
<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_manage_py(self, apps):
"""Creates manage.py file, with a given list of installed apps. :param list apps: """ |
self.logger.debug('Creating manage.py ...')
with open(self._get_manage_py_path(), mode='w') as f:
south_migration_modules = []
for app in apps:
south_migration_modules.append("'%(app)s': '%(app)s.south_migrations'" % {'app': app})
f.write(MANAGE_PY % {
'apps_available': "', '".join(apps),
'apps_path': self.apps_path,
'south_migration_modules': ", ".join(south_migration_modules)
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def op_list_venvs(self):
"""Prints out and returns a list of known virtual environments. :rtype: list :return: list of virtual environments """ |
self.logger.info('Listing known virtual environments ...')
venvs = self.get_venvs()
for venv in venvs:
self.logger.info('Found `%s`' % venv)
else:
self.logger.info('No virtual environments found in `%s` directory.' % VENVS_DIRNAME)
return venvs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def op_list_apps(self):
"""Prints out and returns a list of known applications. :rtype: list :return: list of applications """ |
self.logger.info('Listing known applications ...')
apps = self.get_apps()
for app in apps:
self.logger.info('Found `%s`' % app)
else:
self.logger.info('\nDONE. No applications found in `%s` directory.\n' % APPS_DIRNAME)
return apps |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def op_bootstrap(self):
"""Bootstraps django-dev by creating required directory structure.""" |
self.logger.info('Bootstrapping django-dev directory structure in current directory ...')
self.make_venv(DJANGO_DEFAULT_VERSION)
venv_path = self.make_venv('1.6.5')
self.venv_install('south==1.0.1', venv_path)
apps_dir = self.make_apps_dir()
self.logger.info('Now you may symlink (ln -s) your apps '
'(and other apps that you apps depend upon) into %s' % apps_dir) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def op_install_package(self, names):
"""Install packages into virtual envs as to satisfy app requirements. Exact version numbers could be given as in PIP: somedep==1.5 :param list names: """ |
venvs = self.get_venvs()
for venv in venvs:
for name in names:
self.venv_install(name, self._get_venv_path(venv)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_sint(self):
"""Converts the word to a BinInt, treating it as a signed number.""" |
if self._width == 0:
return BinInt(0)
sbit = 1 << (self._width - 1)
return BinInt((self._val - sbit) ^ -sbit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sar(self, count):
"""Performs an arithmetic right-shift of a BinWord by the given number of bits. Bits shifted out of the word are lost. The word is filled on the left with copies of the top bit. The shift count can be an arbitrary non-negative number, including counts larger than the word (a word filled with copies of the sign bit is returned in this case). """ |
count = operator.index(count)
if count < 0:
raise ValueError('negative shift')
if count > self._width:
count = self._width
return BinWord(self._width, self.to_sint() >> count, trunc=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 slt(self, other):
"""Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is smaller. """ |
self._check_match(other)
return self.to_sint() < other.to_sint() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sle(self, other):
"""Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is smaller or equal. """ |
self._check_match(other)
return self.to_sint() <= other.to_sint() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sgt(self, other):
"""Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is bigger. """ |
self._check_match(other)
return self.to_sint() > other.to_sint() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sge(self, other):
"""Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is bigger or equal. """ |
self._check_match(other)
return self.to_sint() >= other.to_sint() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def concat(cls, *args):
"""Returns a BinWord made from concatenating several BinWords, in LSB-first order. """ |
width = 0
val = 0
for arg in args:
if not isinstance(arg, BinWord):
raise TypeError('need BinWord in concat')
val |= arg._val << width
width += arg._width
return cls(width, val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_sort_function(order):
""" Returns a callable similar to the built-in `cmp`, to be used on objects. Takes a list of dictionaries. In each, 'key' must be a string that is used to get an attribute of the objects to compare, and 'reverse' must be a boolean indicating whether the result should be reversed. """ |
stable = tuple((d['key'], -1 if d['reverse'] else 1) for d in order)
def sort_function(a, b):
for name, direction in stable:
v = cmp(getattr(a, name) if a else a, getattr(b, name) if b else b)
if v != 0:
return v * direction
return 0
return sort_function |
<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_order(self):
""" Return a list of dicionaries. See `set_order`. """ |
return [dict(reverse=r[0], key=r[1]) for r in self.get_model()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allow_headers(self, domain, headers, secure=True):
""" Allows ``domain`` to push data via the HTTP headers named in ``headers``. As with ``allow_domain``, ``domain`` may be either a full domain name or a wildcard. Again, use of wildcards is discouraged for security reasons. The value for ``headers`` should be a list of header names. To disable Flash's requirement of security matching (e.g., retrieving a policy via HTTPS will require that SWFs also be retrieved via HTTPS), pass ``secure=False``. Due to security concerns, it is strongly recommended that you not disable this. """ |
if self.site_control == SITE_CONTROL_NONE:
raise TypeError(
METAPOLICY_ERROR.format("allow headers from a domain")
)
self.header_domains[domain] = {'headers': headers,
'secure': secure} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allow_identity(self, fingerprint):
""" Allows access from documents digitally signed by the key with ``fingerprint``. In theory, multiple algorithms can be added in the future for calculating ``fingerprint`` from the signing key, but at this time only one algorithm -- SHA-1 -- is supported by the cross-domain policy specification. """ |
if self.site_control == SITE_CONTROL_NONE:
raise TypeError(
METAPOLICY_ERROR.format("allow access from signed documents")
)
if fingerprint not in self.identities:
self.identities.append(fingerprint) |
<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_domains_xml(self, document):
""" Generates the XML elements for allowed domains. """ |
for domain, attrs in self.domains.items():
domain_element = document.createElement('allow-access-from')
domain_element.setAttribute('domain', domain)
if attrs['to_ports'] is not None:
domain_element.setAttribute(
'to-ports',
','.join(attrs['to_ports'])
)
if not attrs['secure']:
domain_element.setAttribute('secure', 'false')
document.documentElement.appendChild(domain_element) |
<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_header_domains_xml(self, document):
""" Generates the XML elements for allowed header domains. """ |
for domain, attrs in self.header_domains.items():
header_element = document.createElement(
'allow-http-request-headers-from'
)
header_element.setAttribute('domain', domain)
header_element.setAttribute('headers', ','.join(attrs['headers']))
if not attrs['secure']:
header_element.setAttribute('secure', 'false')
document.documentElement.appendChild(header_element) |
<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_identities_xml(self, document):
""" Generates the XML elements for allowed digital signatures. """ |
for fingerprint in self.identities:
identity_element = document.createElement(
'allow-access-from-identity'
)
signatory_element = document.createElement(
'signatory'
)
certificate_element = document.createElement(
'certificate'
)
certificate_element.setAttribute(
'fingerprint',
fingerprint)
certificate_element.setAttribute(
'fingerprint-algorithm',
'sha-1')
signatory_element.appendChild(certificate_element)
identity_element.appendChild(signatory_element)
document.documentElement.appendChild(identity_element) |
<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_xml_dom(self):
""" Collects all options set so far, and produce and return an ``xml.dom.minidom.Document`` representing the corresponding XML. """ |
if self.site_control == SITE_CONTROL_NONE and \
any((self.domains, self.header_domains, self.identities)):
raise TypeError(BAD_POLICY)
policy_type = minidom.createDocumentType(
qualifiedName='cross-domain-policy',
publicId=None,
systemId='http://www.adobe.com/xml/dtds/cross-domain-policy.dtd'
)
policy = minidom.createDocument(
None,
'cross-domain-policy',
policy_type
)
if self.site_control is not None:
control_element = policy.createElement('site-control')
control_element.setAttribute(
'permitted-cross-domain-policies',
self.site_control
)
policy.documentElement.appendChild(control_element)
for elem_type in ('domains', 'header_domains', 'identities'):
getattr(self, '_add_{}_xml'.format(elem_type))(policy)
return policy |
<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_callbacks(self):
'''Eventually, this should be configured, rather than hardcoded'''
# checkpoint
filepath = os.path.join(CHECKPOINT_DIR, 'weights.best.hdf5')
checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto')
self.callbacks = [checkpoint] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reverse_with_query(named_url,**kwargs):
"Reverse named URL with GET query"
q = QueryDict('',mutable=True)
q.update(kwargs)
return '{}?{}'.format(reverse(named_url),q.urlencode()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_undo(self):
""" Are there actions to undo? """ |
return bool(self._undo) or bool(self._open and self._open[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 end_grouping(self):
""" Raises IndexError when no group is open. """ |
close = self._open.pop()
if not close:
return
if self._open:
self._open[-1].extend(close)
elif self._undoing:
self._redo.append(close)
else:
self._undo.append(close)
self.notify() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def redo(self):
""" Performs the top group on the redo stack, if present. Creates an undo group with the same name. Raises RuntimeError if called while undoing. """ |
if self._undoing or self._redoing:
raise RuntimeError
if not self._redo:
return
group = self._redo.pop()
self._redoing = True
self.begin_grouping()
group.perform()
self.set_action_name(group.name)
self.end_grouping()
self._redoing = False
self.notify() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, func, *args, **kwargs):
""" Record an undo operation. Also clears the redo stack. Raises IndexError when no group is open. """ |
self._open[-1].append(UndoOperation(func, *args, **kwargs))
if not (self._undoing or self._redoing):
self._redo = []
self.notify() |
<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_action_name(self, name):
""" Set the name of the top group, if present. """ |
if self._open and name is not None:
self._open[-1].name = name
self.notify() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def undo(self):
""" Raises IndexError if more than one group is open, otherwise closes it and invokes undo_nested_group. """ |
if self.grouping_level() == 1:
self.end_grouping()
if self._open:
raise IndexError
self.undo_nested_group()
self.notify() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def undo_action_name(self):
""" The name of the top group on the undo stack, or an empty string. """ |
if self._open:
return self._open[-1].name
elif self._undo:
return self._undo[-1].name
return "" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def undo_nested_group(self):
""" Performs the last group opened, or the top group on the undo stack. Creates a redo group with the same name. """ |
if self._undoing or self._redoing:
raise RuntimeError
if self._open:
group = self._open.pop()
elif self._undo:
group = self._undo.pop()
else:
return
self._undoing = True
self.begin_grouping()
group.perform()
self.set_action_name(group.name)
self.end_grouping()
self._undoing = False
self.notify() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dispatch(*funcs):
'''Iterates through the functions
and calls them with given the parameters
and returns the first non-empty result
>>> f = dispatch(lambda: None, lambda: 1)
>>> f()
1
:param \*funcs: funcs list of dispatched functions
:returns: dispatch functoin
'''
def _dispatch(*args, **kwargs):
for f in funcs:
result = f(*args, **kwargs)
if result is not None:
return result
return None
return _dispatch |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preproc_directive(self) -> bool: """Consume a preproc directive.""" |
self._stream.save_context()
if self.read_until("\n", '\\'):
return self._stream.validate_context()
return self._stream.restore_context() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(workbench):
"""Connection inititalization routine. """ |
d = _getContextFactory(getDataPath(), workbench)
d.addCallback(_connectWithContextFactory, workbench)
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connectWithContextFactory(ctxFactory, workbench):
"""Connect using the given context factory. Notifications go to the given workbench. """ |
endpoint = SSL4ClientEndpoint(reactor, "localhost", 4430, ctxFactory)
splash = _Splash(u"Connecting", u"Connecting...")
workbench.display(splash)
d = endpoint.connect(Factory(workbench))
@d.addBoth
def closeSplash(returnValue):
workbench.undisplay()
return returnValue
@d.addErrback
def notifyFailure(f):
f.trap(ConnectError)
d = alert(workbench, u"Couldn't connect", u"Connection failed! "
"Check internet connection, or try again later.\n"
"Error: {!r}".format(f.value))
return d.addCallback(lambda _result: reactor.stop())
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getContextFactory(path, workbench):
"""Get a context factory. If the client already has a credentials at path, use them. Otherwise, generate them at path. Notifications are reported to the given workbench. """ |
try:
return succeed(getContextFactory(path))
except IOError:
d = prompt(workbench, u"E-mail entry", u"Enter e-mail:")
d.addCallback(_makeCredentials, path, workbench)
d.addCallback(lambda _result: getContextFactory(path))
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _makeCredentials(email, path, workbench):
"""Makes client certs and writes them to disk at path. This essentially defers to clarent's ``makeCredentials`` function, except it also shows a nice splash screen. """ |
splash = _Splash(u"SSL credential generation",
u"Generating SSL credentials. (This can take a while.)")
workbench.display(splash)
makeCredentials(path, email)
workbench.undisplay() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def npm_install(package, flags=None):
"""Install a package from NPM.""" |
command = u'install %s %s' % (package, flags or u'')
npm_command(command.strip()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fasta_iter(handle, header=None):
"""Iterate over FASTA file and return FASTA entries Args: handle (file):
FASTA file handle, can be any iterator so long as it it returns subsequent "lines" of a FASTA entry header (str):
Header line of next FASTA entry, if 'handle' has been partially read and you want to start iterating at the next entry, read the next FASTA header and pass it to this variable when calling fasta_iter. See 'Examples.' Yields: FastaEntry: class containing all FASTA data Raises: IOError: If FASTA entry doesn't start with '>' Examples: The following two examples demonstrate how to use fasta_iter. Note: These doctests will not pass, examples are only in doctest format as per convention. bio_utils uses pytests for testing. """ |
# Speed tricks: reduces function calls
append = list.append
join = str.join
strip = str.strip
next_line = next
if header is None:
header = next(handle) # Read first FASTQ entry header
# Check if input is text or bytestream
if (isinstance(header, bytes)):
def next_line(i):
return next(i).decode('utf-8')
header = strip(header.decode('utf-8'))
else:
header = strip(header)
try: # Manually construct a for loop to improve speed by using 'next'
while True: # Loop until StopIteration Exception raised
line = strip(next_line(handle))
data = FastaEntry()
try:
if not header[0] == '>':
raise IOError('Bad FASTA format: no ">" at beginning of line')
except IndexError:
raise IOError('Bad FASTA format: file contains blank lines')
try:
data.id, data.description = header[1:].split(' ', 1)
except ValueError: # No description
data.id = header[1:]
data.description = ''
# Obtain sequence
sequence_list = []
while line and not line[0] == '>':
append(sequence_list, line)
line = strip(next_line(handle)) # Raises StopIteration at EOF
header = line # Store current line so it's not lost next iteration
data.sequence = join('', sequence_list)
yield data
except StopIteration: # Yield last FASTA entry
data.sequence = ''.join(sequence_list)
yield 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 embedded_images(X, images, exclusion_radius=None, ax=None, cmap=None,
zoom=1, seed=None, frameon=False):
'''Plots a subset of images on an axis. Useful for visualizing image
embeddings, especially when plotted over a scatterplot. Selects random points
to annotate with their corresponding image, respecting an exclusion_radius
around each selected point.'''
assert X.shape[0] == images.shape[0], 'Unequal number of points and images'
assert X.shape[1] == 2, 'X must be 2d'
if ax is None:
ax = plt.gca()
if exclusion_radius is None:
# TODO: make a smarter default based on image size and axis limits
exclusion_radius = 1.
if seed is not None:
np.random.seed(seed)
while X.shape[0] > 0:
i = np.random.choice(X.shape[0])
im = OffsetImage(images[i], zoom=zoom, cmap=cmap)
ab = AnnotationBbox(im, X[i], xycoords='data', frameon=frameon)
ax.add_artist(ab)
dist = np.sqrt(np.square(X[i] - X).sum(axis=1))
mask = (dist > exclusion_radius).ravel()
X = X[mask]
images = images[mask]
return plt.show |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def jitterplot(data, positions=None, ax=None, vert=True, scale=0.1,
**scatter_kwargs):
'''Plots jittered points as a distribution visualizer.
Scatter plot arguments default to: marker='.', c='k', alpha=0.75
Also known as a stripplot.
See also: boxplot, violinplot, beeswarm
'''
if ax is None:
ax = plt.gca()
if positions is None:
positions = range(len(data))
kwargs = dict(marker='.', c='k', alpha=0.75)
kwargs.update(scatter_kwargs)
for pos, y in zip(positions, data):
if scale > 0:
x = np.random.normal(loc=pos, scale=scale, size=len(y))
else:
x = np.zeros_like(y) + pos
if not vert:
x, y = y, x
ax.scatter(x, y, **kwargs)
return plt.show |
<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_type(name, library):
""" Gets object type by its name and library where it is defined. :param name: an object type name. :param library: a library where the type is defined :return: the object type or null is the type wasn't found. """ |
if name == None:
raise Exception("Class name cannot be null")
if library == None:
raise Exception("Module name cannot be null")
try:
module = importlib.import_module(library)
return getattr(module, name)
except:
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_type_by_descriptor(descriptor):
""" Gets object type by type descriptor. :param descriptor: a type descriptor that points to an object type :return: the object type or null is the type wasn't found. """ |
if descriptor == None:
raise Exception("Type descriptor cannot be null")
return TypeReflector.get_type(descriptor.get_name(), descriptor.get_library()) |
<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_instance(name, library, *args):
""" Creates an instance of an object type specified by its name and library where it is defined. :param name: an object type (factory function) to create. :param library: a library (module) where object type is defined. :param args: arguments for the object constructor. :return: the created object instance. """ |
obj_type = TypeReflector.get_type(name, library)
if obj_type == None:
raise NotFoundException(
None, "TYPE_NOT_FOUND", "Type " + name + "," + library + " was not found"
).with_details("type", name).with_details("library", library)
return obj_type(*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 is_primitive(value):
""" Checks if value has primitive type. Primitive types are: numbers, strings, booleans, date and time. Complex (non-primitive types are):
objects, maps and arrays :param value: a value to check :return: true if the value has primitive type and false if value type is complex. """ |
typeCode = TypeConverter.to_type_code(value)
return typeCode == TypeCode.String or typeCode == TypeCode.Enum or typeCode == TypeCode.Boolean \
or typeCode == TypeCode.Integer or typeCode == TypeCode.Long \
or typeCode == TypeCode.Float or typeCode == TypeCode.Double \
or typeCode == TypeCode.DateTime or typeCode == TypeCode.Duration |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restart(self, timeout=None):
"""Restarts this Splunk instance. The service is unavailable until it has successfully restarted. If a *timeout* value is specified, ``restart`` blocks until the service resumes or the timeout period has been exceeded. Otherwise, ``restart`` returns immediately. :param timeout: A timeout period, in seconds. :type timeout: ``integer`` """ |
msg = { "value": "Restart requested by " + self.username + "via the Splunk SDK for Python"}
# This message will be deleted once the server actually restarts.
self.messages.create(name="restart_required", **msg)
result = self.post("server/control/restart")
if timeout is None:
return result
start = datetime.now()
diff = timedelta(seconds=timeout)
while datetime.now() - start < diff:
try:
self.login()
if not self.restart_required:
return result
except Exception as e:
sleep(1)
raise Exception( "Operation time out.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, response):
""" Reads the current state of the entity from the server. """ |
results = self._load_state(response)
# In lower layers of the SDK, we end up trying to URL encode
# text to be dispatched via HTTP. However, these links are already
# URL encoded when they arrive, and we need to mark them as such.
unquoted_links = dict([(k, UrlEncoded(v, skip_encode=True))
for k,v in results['links'].items()])
results['links'] = unquoted_links
return 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 create(self, name, **params):
"""Creates a new entity in this collection. This function makes either one or two roundtrips to the server, depending on the type of entities in this collection, plus at most two more if the ``autologin`` field of :func:`connect` is set to ``True``. :param name: The name of the entity to create. :type name: ``string`` :param namespace: A namespace, as created by the :func:`splunklib.binding.namespace` function (optional). You can also set ``owner``, ``app``, and ``sharing`` in ``params``. :type namespace: A :class:`splunklib.data.Record` object with keys ``owner``, ``app``, and ``sharing``. :param params: Additional entity-specific arguments (optional). :type params: ``dict`` :return: The new entity. :rtype: A subclass of :class:`Entity`, chosen by :meth:`Collection.self.item`. **Example**:: import splunklib.client as client applications = s.apps new_app = applications.create("my_fake_app") """ |
if not isinstance(name, basestring):
raise InvalidNameException("%s is not a valid name for an entity." % name)
if 'namespace' in params:
namespace = params.pop('namespace')
params['owner'] = namespace.owner
params['app'] = namespace.app
params['sharing'] = namespace.sharing
response = self.post(name=name, **params)
atom = _load_atom(response, XNAME_ENTRY)
if atom is None:
# This endpoint doesn't return the content of the new
# item. We have to go fetch it ourselves.
return self[name]
else:
entry = atom.entry
state = _parse_atom_entry(entry)
entity = self.item(
self.service,
self._entity_path(state),
state=state)
return entity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.