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 interface(self, value):
""" Sets the interface used to connect to the device. :param value: may specify either the serial number or the device index :type va... |
self._interface = value
if isinstance(value, int):
self._device_number = value
else:
self._serial_number = 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_serial_number(self):
""" Retrieves the FTDI device serial number. :returns: string containing the device serial number """ |
return usb.util.get_string(self._device.usb_dev, 64, self._device.usb_dev.iSerialNumber) |
<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_color(color):
"""Parse a color value. I've decided not to expect a leading '#' because it's a comment character in some shells. True True True True Rai... |
if len(color) not in (3, 4, 6, 8):
raise ValueError('bad color %s' % repr(color))
if len(color) in (3, 4):
r = int(color[0], 16) * 0x11
g = int(color[1], 16) * 0x11
b = int(color[2], 16) * 0x11
elif len(color) in (6, 8):
r = int(color[0:2], 16)
g = int(color[... |
<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_color(option, opt, value):
"""Validate and convert an option value of type 'color'. ``option`` is an optparse.Option instance. ``opt`` is a string with... |
try:
return parse_color(value)
except ValueError:
raise optparse.OptionValueError("option %s: invalid color value: %r"
% (opt, 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 pick_orientation(img1, img2, spacing, desired_aspect=1.618):
"""Pick a tiling orientation for two images. Returns either 'lr' for left-and-right, or 'tb' for... |
w1, h1 = img1.size
w2, h2 = img2.size
size_a = (w1 + spacing + w2, max(h1, h2, 1))
size_b = (max(w1, w2, 1), h1 + spacing + h2)
aspect_a = size_a[0] / size_a[1]
aspect_b = size_b[0] / size_b[1]
goodness_a = min(desired_aspect, aspect_a) / max(desired_aspect, aspect_a)
goodness_b = mi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tile_images(img1, img2, mask1, mask2, opts):
"""Combine two images into one by tiling them. ``mask1`` and ``mask2`` provide optional masks for alpha-blending... |
w1, h1 = img1.size
w2, h2 = img2.size
if opts.orientation == 'auto':
opts.orientation = pick_orientation(img1, img2, opts.spacing)
B, S = opts.border, opts.spacing
if opts.orientation == 'lr':
w, h = (B + w1 + S + w2 + B, B + max(h1, h2) + B)
pos1 = (B, (h - h1) // 2)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spawn_viewer(viewer, img, filename, grace):
"""Launch an external program to view an image. ``img`` is an Image object. ``viewer`` is a command name. Argumen... |
tempdir = tempfile.mkdtemp(prefix='imgdiff-')
try:
imgfile = os.path.join(tempdir, filename)
img.save(imgfile)
started = time.time()
subprocess.call([viewer, imgfile])
elapsed = time.time() - started
if elapsed < grace:
# Program exited too quickly. I... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tweak_diff(diff, opacity):
"""Adjust a difference map into an opacity mask for a given lowest opacity. Performs a linear map from [0; 255] to [opacity; 255].... |
mask = diff.point(lambda i: opacity + i * (255 - opacity) // 255)
return mask |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diff(img1, img2, x1y1, x2y2):
"""Compare two images with given alignments. Returns a difference map. ``x1y1``: a tuple ``(x1, y1)`` to specify the top-left c... |
x1, y1 = x1y1
x2, y2 = x2y2
w1, h1 = img1.size
w2, h2 = img2.size
w, h = min(w1, w2), min(h1, h2)
diff = ImageChops.difference(img1.crop((x1, y1, x1+w, y1+h)),
img2.crop((x2, y2, x2+w, y2+h)))
diff = diff.convert('L')
return diff |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diff_badness(diff):
"""Estimate the "badness" value of a difference map. Returns 0 if the pictures are identical Returns a large number if the pictures are c... |
# identical pictures = black image = return 0
# completely different pictures = white image = return lots
return sum(i * n for i, n in enumerate(diff.histogram())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def best_diff(img1, img2, opts):
"""Find the best alignment of two images that minimizes the differences. Returns (diff, alignments) where ``diff`` is a differen... |
w1, h1 = img1.size
w2, h2 = img2.size
w, h = min(w1, w2), min(h1, h2)
best = None
best_value = 255 * w * h + 1
xr = abs(w1 - w2) + 1
yr = abs(h1 - h2) + 1
p = Progress(xr * yr, timeout=opts.timeout)
for x in range(xr):
if w1 > w2:
x1, x2 = x, 0
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple_highlight(img1, img2, opts):
"""Try to align the two images to minimize pixel differences. Produces two masks for img1 and img2. The algorithm works b... |
try:
diff, ((x1, y1), (x2, y2)) = best_diff(img1, img2, opts)
except KeyboardInterrupt:
return None, None
diff = diff.filter(ImageFilter.MaxFilter(9))
diff = tweak_diff(diff, opts.opacity)
# If the images have different sizes, the areas outside the alignment
# zone are consider... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slow_highlight(img1, img2, opts):
"""Try to find similar areas between two images. Produces two masks for img1 and img2. The algorithm works by comparing eve... |
w1, h1 = img1.size
w2, h2 = img2.size
W, H = max(w1, w2), max(h1, h2)
pimg1 = Image.new('RGB', (W, H), opts.bgcolor)
pimg2 = Image.new('RGB', (W, H), opts.bgcolor)
pimg1.paste(img1, (0, 0))
pimg2.paste(img2, (0, 0))
diff = Image.new('L', (W, H), 255)
# It is not a good idea to ke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SOAPAction(self, Action, responseElement, params = "", recursive = False):
"""Generate the SOAP action call. :type Action: str :type responseElement: str :ty... |
# Authenticate client
if self.authenticated is None:
self.authenticated = self.auth()
auth = self.authenticated
#If not legacy protocol, ensure auth() is called for every call
if not self.use_legacy_protocol:
self.authenticated = None
if auth is ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetchMyCgi(self):
"""Fetches statistics from my_cgi.cgi""" |
try:
response = urlopen(Request('http://{}/my_cgi.cgi'.format(self.ip), b'request=create_chklst'));
except (HTTPError, URLError):
_LOGGER.warning("Failed to open url to {}".format(self.ip))
self._error_report = True
return None
lines = response.r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def current_consumption(self):
"""Get the current power consumption in Watt.""" |
res = 'N/A'
if self.use_legacy_protocol:
# Use /my_cgi.cgi to retrieve current consumption
try:
res = self.fetchMyCgi()['Meter Watt']
except:
return 'N/A'
else:
try:
res = self.SOAPAction('GetCurrent... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def total_consumption(self):
"""Get the total power consumpuntion in the device lifetime.""" |
if self.use_legacy_protocol:
# TotalConsumption currently fails on the legacy protocol and
# creates a mess in the logs. Just return 'N/A' for now.
return 'N/A'
res = 'N/A'
try:
res = self.SOAPAction("GetPMWarningThreshold", "TotalConsumption", s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def state(self, value):
"""Set device state. :type value: str :param value: Future state (either ON or OFF) """ |
if value.upper() == ON:
return self.SOAPAction('SetSocketSettings', 'SetSocketSettingsResult', self.controlParameters("1", "true"))
elif value.upper() == OFF:
return self.SOAPAction('SetSocketSettings', 'SetSocketSettingsResult', self.controlParameters("1", "false"))
els... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auth(self):
"""Authenticate using the SOAP interface. Authentication is a two-step process. First a initial payload is sent to the device requesting addition... |
payload = self.initial_auth_payload()
# Build initial header
headers = {'Content-Type' : '"text/xml; charset=utf-8"',
'SOAPAction': '"http://purenetworks.com/HNAP1/Login"'}
# Request privatekey, cookie and challenge
try:
response = urlopen(Request(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 get_known_read_position(fp, buffered=True):
""" Return a position in a file which is known to be read & handled. It assumes a buffered file and streaming pro... |
buffer_size = io.DEFAULT_BUFFER_SIZE if buffered else 0
return max(fp.tell() - buffer_size, 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 recover(gzfile, last_good_position):
# type: (gzip.GzipFile, int) -> gzip.GzipFile """ Skip to the next possibly decompressable part of a gzip file. Return a... |
pos = get_recover_position(gzfile, last_good_position=last_good_position)
if pos == -1:
return None
fp = gzfile.fileobj
fp.seek(pos)
# gzfile.close()
return gzip.GzipFile(fileobj=fp, mode='r') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maybe_gzip_open(path, *args, **kwargs):
""" Open file with either open or gzip.open, depending on file extension. This function doesn't handle json lines for... |
path = path_to_str(path)
if path.endswith('.gz') or path.endswith('.gzip'):
_open = gzip.open
else:
_open = open
return _open(path, *args, **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 path_to_str(path):
""" Convert pathlib.Path objects to str; return other objects as-is. """ |
try:
from pathlib import Path as _Path
except ImportError: # Python < 3.4
class _Path:
pass
if isinstance(path, _Path):
return str(path)
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 calculate_signature(key, data, timestamp=None):
""" Calculates the signature for the given request data. """ |
# Create a timestamp if one was not given
if timestamp is None:
timestamp = int(time.time())
# Construct the message from the timestamp and the data in the request
message = str(timestamp) + ''.join("%s%s" % (k,v) for k,v in sorted(data.items()))
# Calculate the signature (HMAC SHA256) ac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate(self):
""" Indicate to the client that it needs to authenticate via a 401. """ |
if request.headers.get('Authorization') or request.args.get('access_token'):
realm = 'Bearer realm="%s", error="invalid_token"' % __package__
else:
realm = 'Bearer realm="%s"' % __package__
resp = Response(None, 401, {'WWW-Authenticate': realm})
abort(401, descri... |
<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_token(self, token, allowed_roles, resource, method):
""" This function is called when a token is sent throught the access_token parameter or the Author... |
resource_conf = config.DOMAIN[resource]
audiences = resource_conf.get('audiences', config.JWT_AUDIENCES)
return self._perform_verification(token, audiences, allowed_roles) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requires_token(self, audiences=None, allowed_roles=None):
""" Decorator for functions that will be protected with token authentication. Token must be provvid... |
def requires_token_wrapper(f):
@wraps(f)
def decorated(*args, **kwargs):
try:
token = request.args['access_token']
except KeyError:
token = request.headers.get('Authorization', '').partition(' ')[2]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_library(self,libname):
"""Given the name of a library, load it.""" |
paths = self.getpaths(libname)
for path in paths:
if os.path.exists(path):
return self.load(path)
raise ImportError("%s not found." % libname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getpaths(self,libname):
"""Return a list of paths where the library might be found.""" |
if os.path.isabs(libname):
yield libname
else:
# FIXME / TODO return '.' and os.path.dirname(__file__)
for path in self.getplatformpaths(libname):
yield path
path = ctypes.util.find_library(libname)
if path: yield 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 to_json(content, indent=None):
""" Serializes a python object as JSON This method uses the DJangoJSONEncoder to to ensure that python objects such as Decimal... |
if isinstance(content, QuerySet):
json_serializer = serializers.get_serializer('json')()
serialized_content = json_serializer.serialize(content, ensure_ascii=False, indent=indent)
else:
try:
serialized_content = json.dumps(content, cls=DecimalEncoder, ensure_ascii=False, ind... |
<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_html(data):
""" Serializes a python object as HTML This method uses the to_json method to turn the given data object into formatted JSON that is displayed... |
base_html_template = Template('''
<html>
<head>
{% if style %}
<style type="text/css">
{{ style }}
</style>
{% endif %}
</head>
<body>
{% if style %}
{... |
<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_text(data):
""" Serializes a python object as plain text If the data can be serialized as JSON, this method will use the to_json method to format the data... |
try:
serialized_content = to_json(data, indent=4)
except Exception, e:
serialized_content = data
return serialized_content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auth_required(secret_key_func):
""" Requires that the user be authenticated either by a signature or by being actively logged in. """ |
def actual_decorator(obj):
def test_func(request, *args, **kwargs):
secret_key = secret_key_func(request, *args, **kwargs)
return validate_signature(request, secret_key) or request.user.is_authenticated()
decorator = request_passes_test(test_func)
return wrap_objec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login_required(obj):
""" Requires that the user be logged in order to gain access to the resource at the specified the URI. """ |
decorator = request_passes_test(lambda r, *args, **kwargs: r.user.is_authenticated())
return wrap_object(obj, 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 admin_required(obj):
""" Requires that the user be logged AND be set as a superuser """ |
decorator = request_passes_test(lambda r, *args, **kwargs: r.user.is_superuser)
return wrap_object(obj, 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 signature_required(secret_key_func):
""" Requires that the request contain a valid signature to gain access to a specified resource. """ |
def actual_decorator(obj):
def test_func(request, *args, **kwargs):
secret_key = secret_key_func(request, *args, **kwargs)
return validate_signature(request, secret_key)
decorator = request_passes_test(test_func)
return wrap_object(obj, decorator)
return actua... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_signature(request, secret_key):
""" Validates the signature associated with the given request. """ |
# Extract the request parameters according to the HTTP method
data = request.GET.copy()
if request.method != 'GET':
message_body = getattr(request, request.method, {})
data.update(message_body)
# Make sure the request contains a signature
if data.get('sig', False):
sig = 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 exists(self, session_key):
""" Checks to see if a session currently exists in DynamoDB. :rtype: bool :returns: ``True`` if a session with the given key exist... |
response = self.table.get_item(
Key={'session_key': session_key},
ConsistentRead=ALWAYS_CONSISTENT)
if 'Item' in response:
return True
else:
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 save(self, must_create=False):
""" Saves the current session data to the database. :keyword bool must_create: If ``True``, a ``CreateError`` exception will b... |
# If the save method is called with must_create equal to True, I'm
# setting self._session_key equal to None and when
# self.get_or_create_session_key is called the new
# session_key will be created.
if must_create:
self._session_key = None
self._get_or_cre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, session_key=None):
""" Deletes the current session, or the one specified in ``session_key``. :keyword str session_key: Optionally, override the ... |
if session_key is None:
if self.session_key is None:
return
session_key = self.session_key
self.table.delete_item(Key={'session_key': session_key}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flush(self):
""" Removes the current session data from the database and regenerates the key. """ |
self.clear()
self.delete(self.session_key)
self.create() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_object(obj, decorator):
""" Decorates the given object with the decorator function. If obj is a method, the method is decorated with the decorator funct... |
actual_decorator = method_decorator(decorator)
if inspect.isfunction(obj):
wrapped_obj = actual_decorator(obj)
update_wrapper(wrapped_obj, obj, assigned=available_attrs(obj))
elif inspect.isclass(obj):
for method_name in obj.http_method_names:
if hasattr(obj, method_nam... |
<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_package_versions(self, name):
""" Gives all the compatible package canonical name name : str Name of the package """ |
package_data = self._packages.get(name)
versions = []
if package_data:
versions = sort_versions(list(package_data.get('versions', [])))
return versions |
<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_conf_path(filename=None):
"""Return absolute path for configuration file with specified filename.""" |
conf_dir = osp.join(get_home_dir(), '.condamanager')
if not osp.isdir(conf_dir):
os.mkdir(conf_dir)
if filename is None:
return conf_dir
else:
return osp.join(conf_dir, filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort_versions(versions=(), reverse=False, sep=u'.'):
"""Sort a list of version number strings.
This function ensures that the package sorting based on nu... |
if versions == []:
return []
digits = u'0123456789'
def toint(x):
try:
n = int(x)
except:
n = x
return n
versions = list(versions)
new_versions, alpha, sizes = [], set(), set()
for item in versions:
it = item.spl... |
<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_file(fname_parts, content):
""" write a file and create all needed directories """ |
fname_parts = [str(part) for part in fname_parts]
# try to create the directory
if len(fname_parts) > 1:
try:
os.makedirs(os.path.join(*fname_parts[:-1]))
except OSError:
pass
# write file
fhandle = open(os.path.join(*fname_parts), "w")
fhandle.write(con... |
<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_filter_function(self, name):
"""Removes the filter function associated with name, if it exists. name : hashable object """ |
if name in self._filter_functions.keys():
del self._filter_functions[name]
self.invalidateFilter() |
<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_data_files():
"""Return data_files in a platform dependent manner""" |
if sys.platform.startswith('linux'):
if PY3:
data_files = [('share/applications',
['scripts/condamanager3.desktop']),
('share/pixmaps',
['img_src/condamanager3.png'])]
else:
data_files = [('share... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(text, orig_coding):
"""
Function to encode a text.
@param text text to encode (string)
@param orig_coding type of the original coding (string)
@r... |
if orig_coding == 'utf-8-bom':
return BOM_UTF8 + text.encode("utf-8"), 'utf-8-bom'
# Try declared coding spec
coding = get_coding(text)
if coding:
try:
return text.encode(coding), coding
except (UnicodeError, LookupError):
raise RuntimeError("I... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qapplication(translate=True, test_time=3):
"""Return QApplication instance
Creates it if it doesn't already exist""" |
app = QApplication.instance()
if app is None:
app = QApplication(['Conda-Manager'])
app.setApplicationName('Conda-Manager')
if translate:
install_translator(app)
test_travis = os.environ.get('TEST_CI', None)
if test_travis is not None:
timer_shutdown = QTi... |
<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_aes_mode(mode):
"""Return pycrypto's AES mode, raise exception if not supported""" |
aes_mode_attr = "MODE_{}".format(mode.upper())
try:
aes_mode = getattr(AES, aes_mode_attr)
except AttributeError:
raise Exception(
"Pycrypto/pycryptodome does not seem to support {}. ".format(aes_mode_attr) +
"If you use pycrypto, you need a version >= 2.7a1 (or a sp... |
<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_proxy_servers(proxy_settings):
"""Split the proxy conda configuration to be used by the proxy factory.""" |
proxy_settings_dic = {}
for key in proxy_settings:
proxy = proxy_settings[key]
proxy_config = [m.groupdict() for m in PROXY_RE.finditer(proxy)]
if proxy_config:
proxy_config = proxy_config[0]
host_port = proxy_config.pop('host_port')
if ':' in host_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def proxy_servers(self):
""" Return the proxy servers available. First env variables will be searched and updated with values from condarc config file. """ |
proxy_servers = {}
if self._load_rc_func is None:
return proxy_servers
else:
HTTP_PROXY = os.environ.get('HTTP_PROXY')
HTTPS_PROXY = os.environ.get('HTTPS_PROXY')
if HTTP_PROXY:
proxy_servers['http'] = HTTP_PROXY
if H... |
<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_proxy(proxy_setting):
"""Create a Network proxy for the given proxy settings.""" |
proxy = QNetworkProxy()
proxy_scheme = proxy_setting['scheme']
proxy_host = proxy_setting['host']
proxy_port = proxy_setting['port']
proxy_username = proxy_setting['username']
proxy_password = proxy_setting['password']
proxy_scheme_host = '{0}://{1}'.format(proxy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request_finished(self, reply):
"""Callback for download once the request has finished.""" |
url = to_text_string(reply.url().toEncoded(), encoding='utf-8')
if url in self._paths:
path = self._paths[url]
if url in self._workers:
worker = self._workers[url]
if url in self._head_requests:
error = reply.error()
# print(url, error)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _save(self, url, path, data):
"""Save `data` of downloaded `url` in `path`.""" |
worker = self._workers[url]
path = self._paths[url]
if len(data):
try:
with open(path, 'wb') as f:
f.write(data)
except Exception:
logger.error((url, path))
# Clean up
worker.finished = True
wo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _progress(bytes_received, bytes_total, worker):
"""Return download progress.""" |
worker.sig_download_progress.emit(
worker.url, worker.path, bytes_received, bytes_total) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, url, path):
"""Download url and save data to path.""" |
# original_url = url
# print(url)
qurl = QUrl(url)
url = to_text_string(qurl.toEncoded(), encoding='utf-8')
logger.debug(str((url, path)))
if url in self._workers:
while not self._workers[url].finished:
return self._workers[url]
worke... |
<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):
"""Start the next threaded worker in the queue.""" |
if len(self._queue) == 1:
thread = self._queue.popleft()
thread.start()
self._timer.start() |
<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_worker(self, method, *args, **kwargs):
"""Create a new worker instance.""" |
thread = QThread()
worker = RequestsDownloadWorker(method, args, kwargs)
worker.moveToThread(thread)
worker.sig_finished.connect(self._start)
self._sig_download_finished.connect(worker.sig_download_finished)
self._sig_download_progress.connect(worker.sig_download_progres... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _download(self, url, path=None, force=False):
"""Callback for download.""" |
if path is None:
path = url.split('/')[-1]
# Make dir if non existent
folder = os.path.dirname(os.path.abspath(path))
if not os.path.isdir(folder):
os.makedirs(folder)
# Start actual download
try:
r = requests.get(url, stream=True, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_valid_url(self, url):
"""Callback for is_valid_url.""" |
try:
r = requests.head(url, proxies=self.proxy_servers)
value = r.status_code in [200]
except Exception as error:
logger.error(str(error))
value = False
return 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 _is_valid_channel(self, channel, conda_url='https://conda.anaconda.org'):
"""Callback for is_valid_channel.""" |
if channel.startswith('https://') or channel.startswith('http://'):
url = channel
else:
url = "{0}/{1}".format(conda_url, channel)
if url[-1] == '/':
url = url[:-1]
plat = self._conda_api.get_platform()
repodata_url = "{0}/{1}/{2}".format(ur... |
<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_valid_api_url(self, url):
"""Callback for is_valid_api_url.""" |
# Check response is a JSON with ok: 1
data = {}
try:
r = requests.get(url, proxies=self.proxy_servers)
content = to_text_string(r.content, encoding='utf-8')
data = json.loads(content)
except Exception as error:
logger.error(str(error))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, url, path=None, force=False):
"""Download file given by url and save it to path.""" |
logger.debug(str((url, path, force)))
method = self._download
return self._create_worker(method, url, path=path, force=force) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def terminate(self):
"""Terminate all workers and threads.""" |
for t in self._threads:
t.quit()
self._thread = []
self._workers = [] |
<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_valid_url(self, url, non_blocking=True):
"""Check if url is valid.""" |
logger.debug(str((url)))
if non_blocking:
method = self._is_valid_url
return self._create_worker(method, url)
else:
return self._is_valid_url(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 is_valid_api_url(self, url, non_blocking=True):
"""Check if anaconda api url is valid.""" |
logger.debug(str((url)))
if non_blocking:
method = self._is_valid_api_url
return self._create_worker(method, url)
else:
return self._is_valid_api_url(url=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 is_valid_channel(self, channel, conda_url='https://conda.anaconda.org', non_blocking=True):
"""Check if a conda channel is valid.""" |
logger.debug(str((channel, conda_url)))
if non_blocking:
method = self._is_valid_channel
return self._create_worker(method, channel, conda_url)
else:
return self._is_valid_channel(channel, conda_url=conda_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 human_bytes(n):
""" Return the number of bytes n in more human readable form. """ |
if n < 1024:
return '%d B' % n
k = n/1024
if k < 1024:
return '%d KB' % round(k)
m = k/1024
if m < 1024:
return '%.1f MB' % m
g = m/1024
return '%.2f GB' % g |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ready_print(worker, output, error):
# pragma : no cover """Local test helper.""" |
global COUNTER
COUNTER += 1
print(COUNTER, output, error) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clean(self):
"""Remove references of inactive workers periodically.""" |
if self._workers:
for w in self._workers:
if w.is_finished():
self._workers.remove(w)
else:
self._current_worker = None
self._timer.stop() |
<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_conda(self, extra_args, abspath=True, parse=False, callback=None):
""" Call conda with the list of extra arguments, and return the worker. The result c... |
if abspath:
if sys.platform == 'win32':
python = join(self.ROOT_PREFIX, 'python.exe')
conda = join(self.ROOT_PREFIX, 'Scripts',
'conda-script.py')
else:
python = join(self.ROOT_PREFIX, 'bin/python')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup_install_commands_from_kwargs(kwargs, keys=tuple()):
"""Setup install commands for conda.""" |
cmd_list = []
if kwargs.get('override_channels', False) and 'channel' not in kwargs:
raise TypeError('conda search: override_channels requires channel')
if 'env' in kwargs:
cmd_list.extend(['--name', kwargs.pop('env')])
if 'prefix' in kwargs:
cmd_lis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_conda_version(stdout, stderr):
"""Callback for get_conda_version.""" |
# argparse outputs version to stderr in Python < 3.4.
# http://bugs.python.org/issue18920
pat = re.compile(r'conda:?\s+(\d+\.\d\S+|unknown)')
m = pat.match(stderr.decode().strip())
if m is None:
m = pat.match(stdout.decode().strip())
if m is 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_envs(self, log=True):
"""Return environment list of absolute path to their prefixes.""" |
if log:
logger.debug('')
# return self._call_and_parse(['info', '--json'],
# callback=lambda o, e: o['envs'])
envs = os.listdir(os.sep.join([self.ROOT_PREFIX, 'envs']))
envs = [os.sep.join([self.ROOT_PREFIX, 'envs', i]) for i in envs]
... |
<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_prefix_envname(self, name, log=False):
"""Return full prefix path of environment defined by `name`.""" |
prefix = None
if name == 'root':
prefix = self.ROOT_PREFIX
# envs, error = self.get_envs().communicate()
envs = self.get_envs()
for p in envs:
if basename(p) == name:
prefix = p
return prefix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def linked(prefix):
"""Return set of canonical names of linked packages in `prefix`.""" |
logger.debug(str(prefix))
if not isdir(prefix):
return set()
meta_dir = join(prefix, 'conda-meta')
if not isdir(meta_dir):
# We might have nothing in linked (and no conda-meta directory)
return set()
return set(fn[:-5] for fn in os.listdir(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info(self, abspath=True):
""" Return a dictionary with configuration information. No guarantee is made about which keys exist. Therefore this function should... |
logger.debug(str(''))
return self._call_and_parse(['info', '--json'], abspath=abspath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def package_info(self, package, abspath=True):
"""Return a dictionary with package information.""" |
return self._call_and_parse(['info', package, '--json'],
abspath=abspath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, regex=None, spec=None, **kwargs):
"""Search for packages.""" |
cmd_list = ['search', '--json']
if regex and spec:
raise TypeError('conda search: only one of regex or spec allowed')
if regex:
cmd_list.append(regex)
if spec:
cmd_list.extend(['--spec', spec])
if 'platform' in kwargs:
cmd_list... |
<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_from_yaml(self, name, yamlfile):
""" Create new environment using conda-env via a yaml specification file. Unlike other methods, this calls conda-env,... |
logger.debug(str((name, yamlfile)))
cmd_list = ['env', 'create', '-n', name, '-f', yamlfile, '--json']
return self._call_and_parse(cmd_list) |
<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=None, prefix=None, pkgs=None, channels=None):
"""Create an environment with a specified set of packages.""" |
logger.debug(str((prefix, pkgs, channels)))
# TODO: Fix temporal hack
if (not pkgs or (not isinstance(pkgs, (list, tuple)) and
not is_text_string(pkgs))):
raise TypeError('must specify a list of one or more packages to '
'install... |
<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_token_channel(self, channel, token):
""" Adapt a channel to include token of the logged user. Ignore default channels. """ |
if (token and channel not in self.DEFAULT_CHANNELS and
channel != 'defaults'):
url_parts = channel.split('/')
start = url_parts[:-1]
middle = 't/{0}'.format(token)
end = url_parts[-1]
token_channel = '{0}/{1}/{2}'.format('/'.join(start... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(self, name=None, prefix=None, pkgs=None, dep=True, channels=None, token=None):
""" Install a set of packages into an environment by name or path. If ... |
logger.debug(str((prefix, pkgs, channels)))
# TODO: Fix temporal hack
if not pkgs or not isinstance(pkgs, (list, tuple, str)):
raise TypeError('must specify a list of one or more packages to '
'install into existing environment')
cmd_list = ['in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_environment(self, name=None, path=None, **kwargs):
""" Remove an environment entirely. See ``remove``. """ |
return self.remove(name=name, path=path, all=True, **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 clone_environment(self, clone, name=None, prefix=None, **kwargs):
"""Clone the environment `clone` into `name` or `prefix`.""" |
cmd_list = ['create', '--json']
if (name and prefix) or not (name or prefix):
raise TypeError("conda clone_environment: exactly one of `name` "
"or `path` required")
if name:
cmd_list.extend(['--name', name])
if prefix:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup_config_from_kwargs(kwargs):
"""Setup config commands for conda.""" |
cmd_list = ['--json', '--force']
if 'file' in kwargs:
cmd_list.extend(['--file', kwargs['file']])
if 'system' in kwargs:
cmd_list.append('--system')
return cmd_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config_add(self, key, value, **kwargs):
""" Add a value to a key. Returns a list of warnings Conda may have emitted. """ |
cmd_list = ['config', '--add', key, value]
cmd_list.extend(self._setup_config_from_kwargs(kwargs))
return self._call_and_parse(
cmd_list,
abspath=kwargs.get('abspath', True),
callback=lambda o, e: o.get('warnings', [])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dependencies(self, name=None, prefix=None, pkgs=None, channels=None, dep=True):
"""Get dependenciy list for packages to be installed in an env.""" |
if not pkgs or not isinstance(pkgs, (list, tuple)):
raise TypeError('must specify a list of one or more packages to '
'install into existing environment')
cmd_list = ['install', '--dry-run', '--json', '--force-pscheck']
if not dep:
cmd_list.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def environment_exists(self, name=None, prefix=None, abspath=True, log=True):
"""Check if an environment exists by 'name' or by 'prefix'. If query is by 'name' o... |
if log:
logger.debug(str((name, prefix)))
if name and prefix:
raise TypeError("Exactly one of 'name' or 'prefix' is required.")
if name:
prefix = self.get_prefix_envname(name, log=log)
if prefix is None:
prefix = self.ROOT_PREFIX
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_lock(self, abspath=True):
"""Clean any conda lock in the system.""" |
cmd_list = ['clean', '--lock', '--json']
return self._call_and_parse(cmd_list, abspath=abspath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def package_version(self, prefix=None, name=None, pkg=None, build=False):
"""Get installed package version in a given env.""" |
package_versions = {}
if name and prefix:
raise TypeError("Exactly one of 'name' or 'prefix' is required.")
if name:
prefix = self.get_prefix_envname(name)
if self.environment_exists(prefix=prefix):
for package in self.linked(prefix):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_rc(self, path=None, system=False):
""" Load the conda configuration file. If both user and system configuration exists, user will be used. """ |
if os.path.isfile(self.user_rc_path) and not system:
path = self.user_rc_path
elif os.path.isfile(self.sys_rc_path):
path = self.sys_rc_path
if not path or not os.path.isfile(path):
return {}
with open(path) as f:
return yaml.load(f) or ... |
<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_condarc_channels(self, normalize=False, conda_url='https://conda.anaconda.org', channels=None):
"""Return all the channel urls defined in .condarc. If no... |
# https://docs.continuum.io/anaconda-repository/configuration
# They can only exist on a system condarc
default_channels = self.load_rc(system=True).get('default_channels',
self.DEFAULT_CHANNELS)
normalized_channels = []
... |
<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_pip(self, name=None, prefix=None, extra_args=None, callback=None):
"""Call pip in QProcess worker.""" |
cmd_list = self._pip_cmd(name=name, prefix=prefix)
cmd_list.extend(extra_args)
process_worker = ProcessWorker(cmd_list, pip=True, callback=callback)
process_worker.sig_finished.connect(self._start)
self._queue.append(process_worker)
self._start()
return process... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pip_cmd(self, name=None, prefix=None):
"""Get pip location based on environment `name` or `prefix`.""" |
if (name and prefix) or not (name or prefix):
raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
"required.")
if name and self.environment_exists(name=name):
prefix = self.get_prefix_envname(name)
if sys.platform == 'win32':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pip_list(self, name=None, prefix=None, abspath=True):
"""Get list of pip installed packages.""" |
if (name and prefix) or not (name or prefix):
raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
"required.")
if name:
prefix = self.get_prefix_envname(name)
pip_command = os.sep.join([prefix, 'bin', 'python'])
cmd_lis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pip_list(self, stdout, stderr, prefix=None):
"""Callback for `pip_list`.""" |
result = stdout # A dict
linked = self.linked(prefix)
pip_only = []
linked_names = [self.split_canonical_name(l)[0] for l in linked]
for pkg in result:
name = self.split_canonical_name(pkg)[0]
if name not in linked_names:
pip_only.appe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pip_remove(self, name=None, prefix=None, pkgs=None):
"""Remove a pip package in given environment by `name` or `prefix`.""" |
logger.debug(str((prefix, pkgs)))
if isinstance(pkgs, (list, tuple)):
pkg = ' '.join(pkgs)
else:
pkg = pkgs
extra_args = ['uninstall', '--yes', pkg]
return self._call_pip(name=name, prefix=prefix, extra_args=extra_args) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.