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 NgramScorer(frequency_map):
"""Compute the score of a text by using the frequencies of ngrams. Example: -4.3622319742618245 Args: frequency_map (dict):
ngram to frequency mapping """ |
# Calculate the log probability
length = len(next(iter(frequency_map)))
# TODO: 0.01 is a magic number. Needs to be better than that.
floor = math.log10(0.01 / sum(frequency_map.values()))
ngrams = frequency.frequency_to_probability(frequency_map, decorator=math.log10)
def inner(text):
# I dont like this, it is only for the .upper() to work,
# But I feel as though this can be removed in later refactoring
text = ''.join(text)
text = remove(text.upper(), string.whitespace + string.punctuation)
return sum(ngrams.get(ngram, floor) for ngram in iterate_ngrams(text, length))
return inner |
<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_capability(self, capability=None, uri=None, name=None):
"""Specific add function for capabilities. Takes either: - a capability object (derived from ListBase) as the first argument from which the capability name is extracted, and the URI if given - or a plain name string and - the URI of the capability """ |
if (capability is not None):
name = capability.capability_name
if (capability.uri is not None):
uri = capability.uri
self.add(Resource(uri=uri, capability=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 capability_info(self, name=None):
"""Return information about the requested capability from this list. Will return None if there is no information about the requested capability. """ |
for r in self.resources:
if (r.capability == name):
return(r)
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 ui_main(fmt_table, node_dict):
"""Create the base UI in command mode.""" |
cmd_funct = {"quit": False,
"run": node_cmd,
"stop": node_cmd,
"connect": node_cmd,
"details": node_cmd,
"update": True}
ui_print("\033[?25l") # cursor off
print("{}\n".format(fmt_table))
sys.stdout.flush()
# refresh_main values:
# None = loop main-cmd, True = refresh-list, False = exit-program
refresh_main = None
while refresh_main is None:
cmd_name = get_user_cmd(node_dict)
if callable(cmd_funct[cmd_name]):
refresh_main = cmd_funct[cmd_name](cmd_name, node_dict)
else:
refresh_main = cmd_funct[cmd_name]
if cmd_name != "connect" and refresh_main:
ui_clear(len(node_dict) + 2)
return refresh_main |
<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_cmd(node_dict):
"""Get main command selection.""" |
key_lu = {"q": ["quit", True], "r": ["run", True],
"s": ["stop", True], "u": ["update", True],
"c": ["connect", True], "d": ["details", True]}
ui_cmd_bar()
cmd_valid = False
input_flush()
with term.cbreak():
while not cmd_valid:
val = input_by_key()
cmd_name, cmd_valid = key_lu.get(val.lower(), ["invalid", False])
if not cmd_valid:
ui_print(" - {0}Invalid Entry{1}".format(C_ERR, C_NORM))
sleep(0.5)
ui_cmd_bar()
return cmd_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 node_cmd(cmd_name, node_dict):
"""Process commands that target specific nodes.""" |
sc = {"run": cmd_startstop, "stop": cmd_startstop,
"connect": cmd_connect, "details": cmd_details}
node_num = node_selection(cmd_name, len(node_dict))
refresh_main = None
if node_num != 0:
(node_valid, node_info) = node_validate(node_dict, node_num, cmd_name)
if node_valid:
sub_cmd = sc[cmd_name] # get sub-command
refresh_main = sub_cmd(node_dict[node_num], cmd_name, node_info)
else: # invalid target
ui_print_suffix(node_info, C_ERR)
sleep(1.5)
else: # '0' entered - exit command but not program
ui_print(" - Exit Command")
sleep(0.5)
return refresh_main |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node_selection(cmd_name, node_qty):
"""Determine Node via alternate input method.""" |
cmd_disp = cmd_name.upper()
cmd_title = ("\r{1}{0} NODE{2} - Enter {3}#{2}"
" ({4}0 = Exit Command{2}): ".
format(cmd_disp, C_TI, C_NORM, C_WARN, C_HEAD2))
ui_cmd_title(cmd_title)
selection_valid = False
input_flush()
with term.cbreak():
while not selection_valid:
node_num = input_by_key()
try:
node_num = int(node_num)
except ValueError:
node_num = 99999
if node_num <= node_qty:
selection_valid = True
else:
ui_print_suffix("Invalid Entry", C_ERR)
sleep(0.5)
ui_cmd_title(cmd_title)
return node_num |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node_validate(node_dict, node_num, cmd_name):
"""Validate that command can be performed on target node.""" |
# cmd: [required-state, action-to-displayed, error-statement]
req_lu = {"run": ["stopped", "Already Running"],
"stop": ["running", "Already Stopped"],
"connect": ["running", "Can't Connect, Node Not Running"],
"details": [node_dict[node_num].state, ""]}
tm = {True: ("Node {1}{2}{0} ({5}{3}{0} on {1}{4}{0})".
format(C_NORM, C_WARN, node_num,
node_dict[node_num].name,
node_dict[node_num].cloud_disp, C_TI)),
False: req_lu[cmd_name][1]}
node_valid = bool(req_lu[cmd_name][0] == node_dict[node_num].state)
node_info = tm[node_valid]
return node_valid, node_info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_startstop(node, cmd_name, node_info):
"""Confirm command and execute it.""" |
cmd_lu = {"run": ["ex_start_node", "wait_until_running", "RUNNING"],
"stop": ["ex_stop_node", "", "STOPPING"]}
# specific delay & message {provider: {command: [delay, message]}}
cld_lu = {"azure": {"stop": [6, "Initiated"]},
"aws": {"stop": [6, "Initiated"]}}
conf_mess = ("\r{0}{1}{2} {3} - Confirm [y/N]: ".
format(C_STAT[cmd_name.upper()], cmd_name.upper(), C_NORM,
node_info))
cmd_result = None
if input_yn(conf_mess):
exec_mess = ("\r{0}{1}{2} {3}: ".
format(C_STAT[cmd_name.upper()], cmd_lu[cmd_name][2],
C_NORM, node_info))
ui_erase_ln()
ui_print(exec_mess)
busy_obj = busy_disp_on() # busy indicator ON
node_drv = getattr(node, "driver")
main_cmd = getattr(node_drv, cmd_lu[cmd_name][0])
response = main_cmd(node) # noqa
cmd_wait = cmd_lu[cmd_name][1]
if cmd_wait:
seccmd = getattr(node_drv, cmd_wait)
response = seccmd([node]) # noqa
delay, cmd_end = cld_lu.get(node.cloud,
{}).get(cmd_name, [0, "Successful"])
sleep(delay)
busy_disp_off(busy_obj) # busy indicator OFF
ui_print("\033[D") # remove extra space
cmd_result = True
ui_print_suffix("{0} {1}".format(cmd_name.title(), cmd_end), C_GOOD)
sleep(1.5)
else:
ui_print_suffix("Command Aborted")
sleep(0.75)
return cmd_result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_connect(node, cmd_name, node_info):
"""Connect to node.""" |
# FUTURE: call function to check for custom connection-info
conn_info = "Defaults"
conf_mess = ("\r{0}{1} TO{2} {3} using {5}{4}{2} - Confirm [y/N]: ".
format(C_STAT[cmd_name.upper()], cmd_name.upper(), C_NORM,
node_info, conn_info, C_HEAD2))
cmd_result = None
if input_yn(conf_mess):
exec_mess = ("\r{0}CONNECTING TO{1} {2} using {4}{3}{1}: ".
format(C_STAT[cmd_name.upper()], C_NORM, node_info,
conn_info, C_HEAD2))
ui_erase_ln()
ui_print(exec_mess)
(ssh_user, ssh_key) = ssh_get_info(node)
if ssh_user:
ssh_cmd = "ssh {0}{1}@{2}".format(ssh_key, ssh_user,
node.public_ips)
else:
ssh_cmd = "ssh {0}{1}".format(ssh_key, node.public_ips)
print("\n")
ui_print("\033[?25h") # cursor on
subprocess.call(ssh_cmd, shell=True)
ui_print("\033[?25l") # cursor off
print()
cmd_result = True
else:
ui_print_suffix("Command Aborted")
sleep(0.75)
return cmd_result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssh_get_info(node):
"""Determine ssh-user and ssh-key for node.""" |
ssh_key = ""
if node.cloud == "aws":
raw_key = node.extra['key_name']
ssh_key = "-i {0}{1}.pem ".format(CONFIG_DIR, raw_key)
ssh_user = ssh_calc_aws(node)
elif node.cloud == "azure":
ssh_user = node.extra['properties']['osProfile']['adminUsername']
elif node.cloud == "gcp":
items = node.extra['metadata'].get('items', [{}])
keyname = items['key' == 'ssh-keys'].get('value', "")
pos = keyname.find(":")
ssh_user = keyname[0:pos]
elif node.cloud == "alicloud":
ssh_user = ""
return ssh_user, ssh_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 ssh_calc_aws(node):
"""Calculate default ssh-user based on image-if of AWS instance.""" |
userlu = {"ubunt": "ubuntu", "debia": "admin", "fedor": "root",
"cento": "centos", "openb": "root"}
image_name = node.driver.get_image(node.extra['image_id']).name
if not image_name:
image_name = node.name
usertemp = ['name'] + [value for key, value in list(userlu.items())
if key in image_name.lower()]
usertemp = dict(zip(usertemp[::2], usertemp[1::2]))
username = usertemp.get('name', 'ec2-user')
return username |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ui_cmd_bar():
"""Display Command Bar.""" |
cmd_bar = ("\rSELECT COMMAND - {2}(R){1}un {0}(C){1}onnect "
"{3}(S){1}top {0}(U){1}pdate"
" {0}(Q){1}uit: ".
format(C_TI, C_NORM, C_GOOD, C_ERR))
# FUTURE - TO BE USED WHEN DETAILS IMPLEMENTED
# cmd_bar = ("\rSELECT COMMAND - {2}(R){1}un {0}(C){1}onnect "
# "{3}(S){1}top {0}(D){1}etails {0}(U){1}pdate Info"
# " {4}(Q){1}uit: ".
# format(C_TI, C_NORM, C_GOOD, C_ERR, C_HEAD2))
ui_erase_ln()
ui_print(cmd_bar) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def input_flush():
"""Flush the input buffer on posix and windows.""" |
try:
import sys, termios # noqa
termios.tcflush(sys.stdin, termios.TCIFLUSH)
except ImportError:
import msvcrt
while msvcrt.kbhit():
msvcrt.getch() |
<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(email, password, *args, **kwargs):
"""Get user for grant type password. Needed for grant type 'password'. Note, grant type password is by default disabled. :param email: User email. :param password: Password. :returns: The user instance or ``None``. """ |
user = datastore.find_user(email=email)
if user and user.active and verify_password(password, user.password):
return 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 get_token(access_token=None, refresh_token=None):
"""Load an access token. Add support for personal access tokens compared to flask-oauthlib. If the access token is ``None``, it looks for the refresh token. :param access_token: The access token. (Default: ``None``) :param refresh_token: The refresh token. (Default: ``None``) :returns: The token instance or ``None``. """ |
if access_token:
t = Token.query.filter_by(access_token=access_token).first()
if t and t.is_personal and t.user.active:
t.expires = datetime.utcnow() + timedelta(
seconds=int(current_app.config.get(
'OAUTH2_PROVIDER_TOKEN_EXPIRES_IN'
))
)
elif refresh_token:
t = Token.query.join(Token.client).filter(
Token.refresh_token == refresh_token,
Token.is_personal == False, # noqa
Client.is_confidential == True,
).first()
else:
return None
return t if t and t.user.active else 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_client(client_id):
"""Load the client. Needed for grant_type client_credentials. Add support for OAuth client_credentials access type, with user inactivation support. :param client_id: The client ID. :returns: The client instance or ``None``. """ |
client = Client.query.get(client_id)
if client and client.user.active:
return client |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_token(token, request, *args, **kwargs):
"""Token persistence. :param token: A dictionary with the token data. :param request: The request instance. :returns: A :class:`invenio_oauth2server.models.Token` instance. """ |
# Exclude the personal access tokens which doesn't expire.
user = request.user if request.user else current_user
# Add user information in token endpoint response.
# Currently, this is the only way to have the access to the user of the
# token as well as the token response.
token.update(user={'id': user.get_id()})
# Add email if scope granted.
if email_scope.id in token.scopes:
token['user'].update(
email=user.email,
email_verified=user.confirmed_at is not None,
)
tokens = Token.query.filter_by(
client_id=request.client.client_id,
user_id=user.id,
is_personal=False,
)
# make sure that every client has only one token connected to a user
if tokens:
for tk in tokens:
db.session.delete(tk)
db.session.commit()
expires_in = token.get('expires_in')
expires = datetime.utcnow() + timedelta(seconds=int(expires_in))
tok = Token(
access_token=token['access_token'],
refresh_token=token.get('refresh_token'),
token_type=token['token_type'],
_scopes=token['scope'],
expires=expires,
client_id=request.client.client_id,
user_id=user.id,
is_personal=False,
)
db.session.add(tok)
db.session.commit()
return tok |
<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_oauth2_user(valid, oauth):
"""Log in a user after having been verified.""" |
if valid:
oauth.user.login_via_oauth2 = True
_request_ctx_stack.top.user = oauth.user
identity_changed.send(current_app._get_current_object(),
identity=Identity(oauth.user.id))
return valid, oauth |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jwt_verify_token(headers):
"""Verify the JWT token. :param dict headers: The request headers. :returns: The token data. :rtype: dict """ |
# Get the token from headers
token = headers.get(
current_app.config['OAUTH2SERVER_JWT_AUTH_HEADER']
)
if token is None:
raise JWTInvalidHeaderError
# Get authentication type
authentication_type = \
current_app.config['OAUTH2SERVER_JWT_AUTH_HEADER_TYPE']
# Check if the type should be checked
if authentication_type is not None:
# Get the prefix and the token
prefix, token = token.split()
# Check if the type matches
if prefix != authentication_type:
raise JWTInvalidHeaderError
try:
# Get the token data
decode = jwt_decode_token(token)
# Check the integrity of the user
if current_user.get_id() != decode.get('sub'):
raise JWTInvalidIssuer
return decode
except _JWTDecodeError as exc:
raise_from(JWTDecodeError(), exc)
except _JWTExpiredToken as exc:
raise_from(JWTExpiredToken(), exc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error_handler(f):
"""Handle uncaught OAuth errors.""" |
@wraps(f)
def decorated(*args, **kwargs):
try:
return f(*args, **kwargs)
except OAuth2Error as e:
# Only FatalClientError are handled by Flask-OAuthlib (as these
# errors should not be redirect back to the client - see
# http://tools.ietf.org/html/rfc6749#section-4.2.2.1)
if hasattr(e, 'redirect_uri'):
return redirect(e.in_uri(e.redirect_uri))
else:
return redirect(e.in_uri(oauth2.error_uri))
return decorated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorize(*args, **kwargs):
"""View for rendering authorization request.""" |
if request.method == 'GET':
client = Client.query.filter_by(
client_id=kwargs.get('client_id')
).first()
if not client:
abort(404)
scopes = current_oauth2server.scopes
ctx = dict(
client=client,
oauth_request=kwargs.get('request'),
scopes=[scopes[x] for x in kwargs.get('scopes', [])],
)
return render_template('invenio_oauth2server/authorize.html', **ctx)
confirm = request.form.get('confirm', 'no')
return confirm == 'yes' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def errors():
"""Error view in case of invalid oauth requests.""" |
from oauthlib.oauth2.rfc6749.errors import raise_from_error
try:
error = None
raise_from_error(request.values.get('error'), params=dict())
except OAuth2Error as raised:
error = raised
return render_template('invenio_oauth2server/errors.html', error=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 info():
"""Test to verify that you have been authenticated.""" |
if current_app.testing or current_app.debug:
return jsonify(dict(
user=request.oauth.user.id,
client=request.oauth.client.client_id,
scopes=list(request.oauth.scopes)
))
else:
abort(404) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def key_periods(ciphertext, max_key_period):
"""Rank all key periods for ``ciphertext`` up to and including ``max_key_period`` Example: Args: ciphertext (str):
The text to analyze max_key_period (int):
The maximum period the key could be Returns: Sorted list of keys Raises: ValueError: If max_key_period is less than or equal to 0 """ |
if max_key_period <= 0:
raise ValueError("max_key_period must be a positive integer")
key_scores = []
for period in range(1, min(max_key_period, len(ciphertext)) + 1):
score = abs(ENGLISH_IC - index_of_coincidence(*split_columns(ciphertext, period)))
key_scores.append((period, score))
return [p[0] for p in sorted(key_scores, key=lambda x: x[1])] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt(key, ciphertext):
"""Decrypt Vigenere encrypted ``ciphertext`` using ``key``. Example: HELLO Args: key (iterable):
The key to use ciphertext (str):
The text to decrypt Returns: Decrypted ciphertext """ |
index = 0
decrypted = ""
for char in ciphertext:
if char in string.punctuation + string.whitespace + string.digits:
decrypted += char
continue # Not part of the decryption
# Rotate character by the alphabet position of the letter in the key
alphabet = string.ascii_uppercase if key[index].isupper() else string.ascii_lowercase
decrypted += ''.join(shift.decrypt(int(alphabet.index(key[index])), char))
index = (index + 1) % len(key)
return decrypted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def explore(self):
"""INTERACTIVE exploration source capabilities. Will use sitemap URI taken either from explicit self.sitemap_name or derived from the mappings supplied. """ |
# Where do we start? Build options in starts which has entries
# that are a pair comprised of the uri and a list of acceptable
# capabilities
starts = []
if (self.sitemap_name is not None):
print("Starting from explicit --sitemap %s" % (self.sitemap_name))
starts.append(XResource(self.sitemap_name))
elif (len(self.mapper) > 0):
uri = self.mapper.default_src_uri()
(scheme, netloc, path, params, query, fragment) = urlparse(uri)
if (not scheme and not netloc):
if (os.path.isdir(path)):
# have a dir, look for 'likely' file names
print(
"Looking for capability documents in local directory %s" %
(path))
for name in ['resourcesync', 'capabilities.xml',
'resourcelist.xml', 'changelist.xml']:
file = os.path.join(path, name)
if (os.path.isfile(file)):
starts.append(XResource(file))
if (len(starts) == 0):
raise ClientFatalError("No likely capability files found in local directory %s" %
(path))
else:
# local file, might be anything (or not exist)
print("Starting from local file %s" % (path))
starts.append(XResource(path))
else:
# remote, can't tell whether we have a sitemap or a server name or something
# else, build list of options depending on whether there is a path and whether
# there is an extension/name
well_known = urlunparse(
[scheme, netloc, '/.well-known/resourcesync', '', '', ''])
if (not path):
# root, just look for .well-known
starts.append(
XResource(
well_known, [
'capabilitylist', 'capabilitylistindex']))
else:
starts.append(XResource(uri))
starts.append(
XResource(
well_known, [
'capabilitylist', 'capabilitylistindex']))
print("Looking for discovery information based on mappings")
else:
raise ClientFatalError(
"No source information (server base uri or capability uri) specified, use -h for help")
#
# Have list of one or more possible starting point, try them in turn
try:
for start in starts:
# For each starting point we create a fresh history
history = [start]
input = None
while (len(history) > 0):
print()
xr = history.pop()
new_xr = self.explore_uri(xr, len(history) > 0)
if (new_xr):
# Add current and new to history
history.append(xr)
history.append(new_xr)
except ExplorerQuit:
pass # expected way to exit
print("\nresync-explorer done, bye...\n") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def explore_show_head(self, uri, check_headers=None):
"""Do HEAD on uri and show infomation. Will also check headers against any values specified in check_headers. """ |
print("HEAD %s" % (uri))
if (re.match(r'^\w+:', uri)):
# Looks like a URI
response = requests.head(uri)
else:
# Mock up response if we have a local file
response = self.head_on_file(uri)
print(" status: %s" % (response.status_code))
if (response.status_code == '200'):
# print some of the headers
for header in ['content-length', 'last-modified',
'lastmod', 'content-type', 'etag']:
if header in response.headers:
check_str = ''
if (check_headers is not None and
header in check_headers):
if (response.headers[header] == check_headers[header]):
check_str = ' MATCHES EXPECTED VALUE'
else:
check_str = ' EXPECTED %s' % (
check_headers[header])
print(
" %s: %s%s" %
(header, response.headers[header], check_str)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allowed_entries(self, capability):
"""Return list of allowed entries for given capability document. Includes handling of capability = *index where the only acceptable entries are *. """ |
index = re.match(r'(.+)index$', capability)
archive = re.match(r'(.+)\-archive$', capability)
if (capability == 'capabilitylistindex'):
return([]) # not allowed so no valid references
elif (index):
return([index.group(1)]) # name without index ending
elif (archive):
return([archive.group(1)]) # name without -archive ending
elif (capability == 'description'):
return(['capabilitylist'])
elif (capability == 'capabilitylist'):
return(['resourcelist', 'resourcedump',
'changelist', 'changedump',
'resourcelist-archive', 'resourcedump-archive',
'changelist-archive', 'changedump-archive'])
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 expand_relative_uri(self, context, uri):
"""If uri is relative then expand in context. Prints warning if expansion happens. """ |
full_uri = urljoin(context, uri)
if (full_uri != uri):
print(" WARNING - expanded relative URI to %s" % (full_uri))
uri = full_uri
return(uri) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hill_climb(nsteps, start_node, get_next_node):
"""Modular hill climbing algorithm. Example: Args: nsteps (int):
The number of neighbours to visit start_node: The starting node get_next_node (function):
Function to return the next node the score of the current node and any optional output from the current node Returns: The highest node found, the score of this node and the outputs from the best nodes along the way """ |
outputs = []
best_score = -float('inf')
for step in range(nsteps):
next_node, score, output = get_next_node(copy.deepcopy(start_node))
# Keep track of best score and the start node becomes finish node
if score > best_score:
start_node = copy.deepcopy(next_node)
best_score = score
outputs.append(output)
return start_node, best_score, outputs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scopes_multi_checkbox(field, **kwargs):
"""Render multi checkbox widget.""" |
kwargs.setdefault('type', 'checkbox')
field_id = kwargs.pop('id', field.id)
html = [u'<div class="row">']
for value, label, checked in field.iter_choices():
choice_id = u'%s-%s' % (field_id, value)
options = dict(
kwargs,
name=field.name,
value=value,
id=choice_id,
class_=' ',
)
if checked:
options['checked'] = 'checked'
html.append(u'<div class="col-md-3">')
html.append(u'<label for="{0}" class="checkbox-inline">'.format(
choice_id
))
html.append(u'<input {0} /> '.format(widgets.html_params(**options)))
html.append(u'{0} <br/><small class="text-muted">{1}</small>'.format(
value, label.help_text
))
html.append(u'</label></div>')
html.append(u'</div>')
return HTMLString(u''.join(html)) |
<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_formdata(self, valuelist):
"""Process form data.""" |
if valuelist:
self.data = '\n'.join([
x.strip() for x in
filter(lambda x: x, '\n'.join(valuelist).splitlines())
]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def redirect_uris(self, value):
"""Validate and store redirect URIs for client.""" |
if isinstance(value, six.text_type):
value = value.split("\n")
value = [v.strip() for v in value]
for v in value:
validate_redirect_uri(v)
self._redirect_uris = "\n".join(value) 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 default_scopes(self, scopes):
"""Set default scopes for client.""" |
validate_scopes(scopes)
self._default_scopes = " ".join(set(scopes)) if scopes 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 get_users(self):
"""Get number of users.""" |
no_users = Token.query.filter_by(
client_id=self.client_id,
is_personal=False,
is_internal=False
).count()
return no_users |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scopes(self, scopes):
"""Set scopes. :param scopes: The list of scopes. """ |
validate_scopes(scopes)
self._scopes = " ".join(set(scopes)) if scopes 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 get_visible_scopes(self):
"""Get list of non-internal scopes for token. :returns: A list of scopes. """ |
return [k for k, s in current_oauth2server.scope_choices()
if k in self.scopes] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_personal(cls, name, user_id, scopes=None, is_internal=False):
"""Create a personal access token. A token that is bound to a specific user and which doesn't expire, i.e. similar to the concept of an API key. :param name: Client name. :param user_id: User ID. :param scopes: The list of permitted scopes. (Default: ``None``) :param is_internal: If ``True`` it's a internal access token. (Default: ``False``) :returns: A new access token. """ |
with db.session.begin_nested():
scopes = " ".join(scopes) if scopes else ""
c = Client(
name=name,
user_id=user_id,
is_internal=True,
is_confidential=False,
_default_scopes=scopes
)
c.gen_salt()
t = Token(
client_id=c.client_id,
user_id=user_id,
access_token=gen_salt(
current_app.config.get(
'OAUTH2SERVER_TOKEN_PERSONAL_SALT_LEN')
),
expires=None,
_scopes=scopes,
is_personal=True,
is_internal=is_internal,
)
db.session.add(c)
db.session.add(t)
return t |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_redirect_uri(value):
"""Validate a redirect URI. Redirect URIs must be a valid URL and use https unless the host is localhost for which http is accepted. :param value: The redirect URI. """ |
sch, netloc, path, par, query, fra = urlparse(value)
if not (sch and netloc):
raise InvalidRedirectURIError()
if sch != 'https':
if ':' in netloc:
netloc, port = netloc.split(':', 1)
if not (netloc in ('localhost', '127.0.0.1') and sch == 'http'):
raise InsecureTransportError() |
<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_scopes(value_list):
"""Validate if each element in a list is a registered scope. :param value_list: The list of scopes. :raises invenio_oauth2server.errors.ScopeDoesNotExists: The exception is raised if a scope is not registered. :returns: ``True`` if it's successfully validated. """ |
for value in value_list:
if value not in current_oauth2server.scopes:
raise ScopeDoesNotExists(value)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_output_cwd(args, cwd, timeout=None):
'''Open a subprocess in another working directory
Raises ValueError if system binary does not exist
Raises CalledProcessError if the return code is non-zero
:returns: list of standard output and standard error from subprocess
:param args: a list of command line arguments for subprocess
:param cwd: the working directory for the subprocess
:param timeout: number of seconds before giving up
'''
assertions.list_is_type(args, str)
assertions.is_binary(args[0])
stdout_stderr = []
with Popen(args, cwd=cwd, stdout=PIPE, stderr=STDOUT) as active_subprocess:
for line in iter(active_subprocess.stdout.readline, b''):
line_str = line.decode().strip()
stdout_stderr.append(line_str)
print(line_str)
active_subprocess.wait(timeout=timeout)
returncode = active_subprocess.returncode
if returncode != 0:
raise CalledProcessError(returncode, args, output=None)
else:
return stdout_stderr |
<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_otp_modehex_interpretation(self, otp):
""" Return modhex interpretation of the provided OTP. If there are multiple interpretations available, first one is used, because if the OTP uses all 16 characters in its alphabet there is only one possible interpretation of that OTP. :return: Modhex interpretation of the OTP. :rtype: ``str`` """ |
try:
interpretations = translate(u(otp))
except Exception:
return otp
if len(interpretations) == 0:
return otp
elif len(interpretations) > 1:
# If there are multiple interpretations first try to use the same
# translation as the input OTP. If the one is not found, use the
# random interpretation.
if u(otp) in interpretations:
return otp
return interpretations.pop() |
<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_shift_function(alphabet):
"""Construct a shift function from an alphabet. Examples: Shift cases independently <function make_shift_function.<locals>.shift_case_sensitive> Additionally shift punctuation characters <function make_shift_function.<locals>.shift_case_sensitive> Shift entire ASCII range, overflowing cases <function make_shift_function.<locals>.shift_case_sensitive> Args: alphabet (iterable):
Ordered iterable of strings representing separate cases of an alphabet Returns: Function (shift, symbol) """ |
def shift_case_sensitive(shift, symbol):
case = [case for case in alphabet if symbol in case]
if not case:
return symbol
case = case[0]
index = case.index(symbol)
return case[(index - shift) % len(case)]
return shift_case_sensitive |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crack(ciphertext, *fitness_functions, min_key=0, max_key=26, shift_function=shift_case_english):
"""Break ``ciphertext`` by enumerating keys between ``min_key`` and ``max_key``. Example: HELLO Args: ciphertext (iterable):
The symbols to decrypt *fitness_functions (variable length argument list):
Functions to score decryption with Keyword Args: min_key (int):
Key to start with max_key (int):
Key to stop at (exclusive) shift_function (function(shift, symbol)):
Shift function to use Returns: Sorted list of decryptions Raises: ValueError: If min_key exceeds max_key ValueError: If no fitness_functions are given """ |
if min_key >= max_key:
raise ValueError("min_key cannot exceed max_key")
decryptions = []
for key in range(min_key, max_key):
plaintext = decrypt(key, ciphertext, shift_function=shift_function)
decryptions.append(Decryption(plaintext, key, score(plaintext, *fitness_functions)))
return sorted(decryptions, reverse=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 decrypt(key, ciphertext, shift_function=shift_case_english):
"""Decrypt Shift enciphered ``ciphertext`` using ``key``. Examples: HELLO >> decrypt(15, [0xcf, 0x9e, 0xaf, 0xe0], shift_bytes) [0xde, 0xad, 0xbe, 0xef] Args: key (int):
The shift to use ciphertext (iterable):
The symbols to decrypt shift_function (function (shift, symbol)):
Shift function to apply to symbols in the ciphertext Returns: Decrypted ciphertext, list of plaintext symbols """ |
return [shift_function(key, symbol) for symbol in ciphertext] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randombytes(n):
"""Return n random bytes.""" |
# Use /dev/urandom if it is available. Fall back to random module
# if not. It might be worthwhile to extend this function to use
# other platform-specific mechanisms for getting random bytes.
if os.path.exists("/dev/urandom"):
f = open("/dev/urandom")
s = f.read(n)
f.close()
return s
else:
L = [chr(random.randrange(0, 256)) for i in range(n)]
return "".join(L) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unicode_from_html(content):
"""Attempts to decode an HTML string into unicode. If unsuccessful, the original content is returned. """ |
encodings = get_encodings_from_content(content)
for encoding in encodings:
try:
return unicode(content, encoding)
except (UnicodeError, TypeError):
pass
return 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 stream_decode_response_unicode(iterator, r):
"""Stream decodes a iterator.""" |
encoding = get_encoding_from_headers(r.headers)
if encoding is None:
for item in iterator:
yield item
return
decoder = codecs.getincrementaldecoder(encoding)(errors='replace')
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
rv = decoder.decode('', final=True)
if rv:
yield rv |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stream_decode_gzip(iterator):
"""Stream decodes a gzip-encoded iterator""" |
try:
dec = zlib.decompressobj(16 + zlib.MAX_WBITS)
for chunk in iterator:
rv = dec.decompress(chunk)
if rv:
yield rv
buf = dec.decompress('')
rv = buf + dec.flush()
if rv:
yield rv
except zlib.error:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_application_key_file(self, filename=b'spotify_appkey.key'):
"""Load your libspotify application key file. If called without arguments, it tries to read ``spotify_appkey.key`` from the current working directory. This is an alternative to setting :attr:`application_key` yourself. The file must be a binary key file, not the C code key file that can be compiled into an application. """ |
with open(filename, 'rb') as fh:
self.app_key = fh.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_layout(self, data):
""" Lays the text out into separate lines and calculates their total height. """ |
c = data['output']
word_space = c.text_width(
' ',
font_name=self.font_name,
font_size=self.font_size)
# Arrange the text as words on lines
self._layout = [[]]
x = self.font_size if self.paragraph_indent else 0
for word in self.text.split():
ww = c.text_width(
word,
font_name=self.font_name,
font_size=self.font_size)
if x + ww > self.width:
# Newline
x = 0
self._layout.append([])
self._layout[-1].append(word)
x += ww + word_space
# Work out the height we need
num_lines = len(self._layout)
self.height = (
num_lines * self.font_size +
(num_lines-1)*(self.font_size * (self.leading - 1.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 iter_content(self, chunk_size=10 * 1024, decode_unicode=None):
"""Iterates over the response data. This avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. """ |
if self._content_consumed:
raise RuntimeError(
'The content for this response was already consumed'
)
def generate():
while 1:
chunk = self.raw.read(chunk_size)
if not chunk:
break
yield chunk
self._content_consumed = True
gen = generate()
if 'gzip' in self.headers.get('content-encoding', ''):
gen = stream_decode_gzip(gen)
if decode_unicode is None:
decode_unicode = self.config.get('decode_unicode')
if decode_unicode:
gen = stream_decode_response_unicode(gen, self)
return gen |
<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_fd(fileobj):
""" Get a descriptor out of a file object. :param fileobj: An integer (existing descriptor) or any object having the `fileno()` method. :raises ValueError: if the descriptor cannot be obtained or if the descriptor is invalid :returns: file descriptor number """ |
if isinstance(fileobj, int):
fd = fileobj
else:
try:
fd = fileobj.fileno()
except AttributeError:
fd = None
if fd is None or fd < 0:
raise ValueError("invalid fileobj: {!r}".format(fileobj))
return fd |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unregister(self, fileobj):
""" Remove interest in IO events from the specified fileobj :param fileobj: Any existing file-like object that has a fileno() method and was previously registered with :meth:`register()` :raises ValueError: if `fileobj` is invalid or not supported :raises KeyError: if the descriptor associated with `fileobj` is not registered. :returns: A :class:`SelectorKey` associated with the passed arguments """ |
fd = _get_fd(fileobj)
key = self._fd_map[fd]
try:
self._epoll.unregister(fd)
except OSError:
pass
del self._fd_map[fd]
return 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 modify(self, fileobj, events, data=None):
""" Modify interest in specified IO events on the specified file object :param fileobj: Any existing file-like object that has a fileno() method :param events: A bitmask composed of EVENT_READ and EVENT_WRITE :param data: (optional) Arbitrary data :raises ValueError: if `fileobj` is invalid or not supported :raises KeyError: if the descriptor associated with `fileobj` is not registered. :returns: The new :class:`SelectorKey` associated with the passed arguments """ |
fd = _get_fd(fileobj)
epoll_events = _EpollSelectorEvents(events).get_epoll_events()
if fd not in self._fd_map:
raise KeyError("{!r} is not registered".format(fileobj))
key = SelectorKey(fileobj, fd, events, data)
self._fd_map[fd] = key
self._epoll.modify(fd, epoll_events)
return 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 select(self, timeout=None):
""" Wait until one or more of the registered file objects becomes ready or until the timeout expires. :param timeout: maximum wait time, in seconds (see below for special meaning) :returns: A list of pairs (key, events) for each ready file object. Note that the list may be empty if non-blocking behavior is selected or if the blocking wait is interrupted by a signal. The timeout argument has two additional special cases: 1) If timeout is None then the call will block indefinitely 2) If timeout <= 0 the call will never block """ |
if timeout is None:
epoll_timeout = -1
elif timeout <= 0:
epoll_timeout = 0
else:
epoll_timeout = timeout
max_events = len(self._fd_map) or -1
result = []
for fd, epoll_events in self._epoll.poll(epoll_timeout, max_events):
key = self._fd_map.get(fd)
events = _EpollSelectorEvents.from_epoll_events(epoll_events)
events &= key.events
if key:
result.append((key, _EpollSelectorEvents(events)))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self, username, password=None, blob=None, zeroconf=None):
"""Authenticate to Spotify's servers. You can login with one of three combinations: - ``username`` and ``password`` - ``username`` and ``blob`` - ``username`` and ``zeroconf`` To get the ``blob`` string, you must once log in with ``username`` and ``password``. You'll then get the ``blob`` string passed to the :attr:`~ConnectionCallbacks.new_credentials` callback. """ |
username = utils.to_char(username)
if password is not None:
password = utils.to_char(password)
spotifyconnect.Error.maybe_raise(
lib.SpConnectionLoginPassword(
username, password))
elif blob is not None:
blob = utils.to_char(blob)
spotifyconnect.Error.maybe_raise(
lib.SpConnectionLoginBlob(username, blob))
elif zeroconf is not None:
spotifyconnect.Error.maybe_raise(
lib.SpConnectionLoginZeroConf(
username, *zeroconf))
else:
raise AttributeError(
"Must specify a login method (password, blob or zeroconf)") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on(self):
"""Turn on the alsa_sink sink. This is done automatically when the sink is instantiated, so you'll only need to call this method if you ever call :meth:`off` and want to turn the sink back on. """ |
assert spotifyconnect._session_instance.player.num_listeners(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0
spotifyconnect._session_instance.player.on(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def off(self):
"""Turn off the alsa_sink sink. This disconnects the sink from the relevant session events. """ |
spotifyconnect._session_instance.player.off(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)
assert spotifyconnect._session_instance.player.num_listeners(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0
self._close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patched(f):
"""Patches a given API function to not send.""" |
def wrapped(*args, **kwargs):
kwargs['return_response'] = False
kwargs['prefetch'] = True
return f(*args, **kwargs)
return wrapped |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(r, pools=None):
"""Sends a given Request object.""" |
if pools:
r._pools = pools
r.send()
return r.response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _print_debug(self, *args):
"""Method output debug message into stderr :param args: Message(s) to output :rtype args: string """ |
if self.debuglevel > 1:
print(datetime.datetime.now().time(), *args, file=sys.stderr)
else:
print(*args, file=sys.stderr) |
<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_host(cls, host='localhost', port=0):
""" Parse provided hostname and extract port number :param host: Server hostname :type host: string :param port: Server port :return: Tuple of (host, port) :rtype: tuple """ |
if not port and (host.find(':') == host.rfind(':')):
i = host.rfind(':')
if i >= 0:
host, port = host[:i], host[i + 1:]
try:
port = int(port)
except ValueError:
raise OSError('nonnumeric port')
return host, port |
<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_proxy(self, proxy_host='localhost', proxy_port=0, proxy_type=socks.HTTP, host='localhost', port=0):
"""Connect to a host on a given port via proxy server If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use. Note: This method is automatically invoked by __init__, if a host and proxy server are specified during instantiation. :param proxy_host: Hostname of proxy server :type proxy_host: string :param proxy_port: Port of proxy server, by default port for specified proxy type is used :type proxy_port: int :param proxy_type: Proxy type to use (see socks.PROXY_TYPES for details) :type proxy_type: int :param host: Hostname of SMTP server :type host: string :param port: Port of SMTP server, by default smtplib.SMTP_PORT is used :type port: int :return: Tuple of (code, msg) :rtype: tuple """ |
if proxy_type not in socks.DEFAULT_PORTS.keys():
raise NotSupportedProxyType
(proxy_host, proxy_port) = self._parse_host(host=proxy_host, port=proxy_port)
if not proxy_port:
proxy_port = socks.DEFAULT_PORTS[proxy_type]
(host, port) = self._parse_host(host=host, port=port)
if self.debuglevel > 0:
self._print_debug('connect: via proxy', proxy_host, proxy_port)
s = socks.socksocket()
s.set_proxy(proxy_type=proxy_type, addr=proxy_host, port=proxy_port)
s.settimeout(self.timeout)
if self.source_address is not None:
s.bind(self.source_address)
s.connect((host, port))
# todo
# Send CRLF in order to get first response from destination server.
# Probably it's needed only for HTTP proxies. Further investigation required.
s.sendall(bCRLF)
self.sock = s
(code, msg) = self.getreply()
if self.debuglevel > 0:
self._print_debug('connect:', repr(msg))
return code, 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 enabled(self):
""" read or write the child sub-reaper flag of the current process This property behaves in the following manner: * If a read is attempted and a prior read or write has determined that this feature is unavailable (status is equal to ``SR_UNSUPPORTED``) then no further attempts are made and the outcome is ``False``. * If a read is attempted and the current status is ``SR_UNKNOWN`` then depends on the returned value. If prctl fails then status is set to ``SR_UNSUPPORTED`` and the return value is ``False``. If the prctl call succeeds then status is set to either ``SR_ENABLED`` or ``SR_DISABLED`` and ``True`` or ``False`` is returned, respectively. * If a write is attempted and a prior read or write has determined that this feature is unavailable (status is equal to ``SR_UNSUPPORTED``) *and* the write would have enabled the flag, a ValueError is raised with an appropriate message. Otherwise a write is attempted. If the attempt to enable the flag fails a ValueError is raised, just as in the previous case. * If a write intending to disable the flag fails then this failure is silently ignored but status is set to ``SR_UNSUPPORTED``. * If a write succeeds then the status is set accordingly to ``SR_ENABLED`` or ``SR_DISABLED``, depending on the value written ``True`` or ``False`` respectively. In other words, this property behaves as if it was really calling prctl() but it is not going to repeat operations that will always fail. Nor will it ignore failures silently where that matters. """ |
if self._status == self.SR_UNSUPPORTED:
return False
status = c_int()
try:
prctl(PR_GET_CHILD_SUBREAPER, addressof(status), 0, 0, 0)
except OSError:
self._status = self.SR_UNSUPPORTED
else:
self._status = self.SR_ENABLED if status else self.SR_DISABLED
return self._status == self.SR_ENABLED |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _sign(self,params):
'''
Generate API sign code
'''
for k, v in params.iteritems():
if type(v) == int: v = str(v)
elif type(v) == float: v = '%.2f'%v
elif type(v) in (list, set):
v = ','.join([str(i) for i in v])
elif type(v) == bool: v = 'true' if v else 'false'
elif type(v) == datetime.datetime: v = v.strftime('%Y-%m-%d %X')
if type(v) == unicode:
params[k] = v.encode('utf-8')
else:
params[k] = v
src = self.APP_SECRET + ''.join(["%s%s" % (k, v) for k, v in sorted(params.iteritems())])
return md5(src).hexdigest().upper() |
<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, data, fields=[], models={}):
'''
Create model attributes
'''
if not fields: fields = self.fields
if not models and hasattr(self, 'models'): models = self.models
for field in fields:
setattr(self,field,None)
if not data: return None
for k, v in data.iteritems():
if type(v) in (str, unicode):
v = v.strip()
if models and k in models:
if type(v) == dict:
lists = []
for k2, v2 in v.iteritems():
if type(v2) == list:
for d in v2:
model = models[k]()
lists.append(model.create(d))
if not lists:
model = models[k]()
v = model.create(v)
else:
v = lists
else:
model = models[k]()
v = model.create(v)
setattr(self,k,v)
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 get_minimum_size(self, data):
"""Returns the rotated minimum size.""" |
size = self.element.get_minimum_size(data)
if self.angle in (RotateLM.NORMAL, RotateLM.UPSIDE_DOWN):
return size
else:
return datatypes.Point(size.y, size.x) |
<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_ms_from_base(self, size):
"""Calculates the rotated minimum size from the given base minimum size.""" |
hw = size.x * 0.5
hh = size.y * 0.5
a = datatypes.Point(hw, hh).get_rotated(self.angle)
b = datatypes.Point(-hw, hh).get_rotated(self.angle)
c = datatypes.Point(hw, -hh).get_rotated(self.angle)
d = datatypes.Point(-hw, -hh).get_rotated(self.angle)
minp = a.get_minimum(b).get_minimum(c).get_minimum(d)
maxp = a.get_maximum(b).get_maximum(c).get_maximum(d)
return maxp - minp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json_data(self, name, default=None):
"""Get a JSON compatible value of the field """ |
value = self.get(name)
if value is Missing.Value:
return default
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 get(self, name):
"""Get the value by name """ |
# check read permission
sm = getSecurityManager()
permission = permissions.View
if not sm.checkPermission(permission, self.context):
raise Unauthorized("Not allowed to view the Plone portal")
# read the attribute
attr = getattr(self.context, name, None)
if callable(attr):
return attr()
# XXX no really nice, but we want the portal to behave like an ordinary
# content type. Therefore we need to inject the neccessary data.
if name == "uid":
return "0"
if name == "path":
return "/%s" % self.context.getId()
return attr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, name, value, **kw):
"""Set the attribute to the given value. The keyword arguments represent the other attribute values to integrate constraints to other values. """ |
# check write permission
sm = getSecurityManager()
permission = permissions.ManagePortal
if not sm.checkPermission(permission, self.context):
raise Unauthorized("Not allowed to modify the Plone portal")
# set the attribute
if not hasattr(self.context, name):
return False
self.context[name] = value
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, name, value, **kw):
"""Set the field to the given value. The keyword arguments represent the other field values to integrate constraints to other values. """ |
# fetch the field by name
field = api.get_field(self.context, name)
# bail out if we have no field
if not field:
return False
# call the field adapter and set the value
fieldmanager = IFieldManager(field)
return fieldmanager.set(self.context, value, **kw) |
<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_write(self):
"""Check if the field is writeable """ |
sm = getSecurityManager()
permission = permissions.ModifyPortalContent
if not sm.checkPermission(permission, self.context):
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_read(self):
"""Check if the field is readable """ |
sm = getSecurityManager()
if not sm.checkPermission(permissions.View, self.context):
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_s3_xsd(self, url_xsd):
# pragma: no cover """This method will not be re-run always, only locally and when xsd are regenerated, read the test_008_force_s3_creation on test folder """ |
if self.check_s3(self.domain, urlparse(url_xsd).path[1:]):
return url_xsd
response = urllib2.urlopen(url_xsd)
content = response.read()
cached = NamedTemporaryFile(delete=False)
named = cached.name
# Find all urls in the main xslt file.
urls = re.findall(r'href=[\'"]?([^\'" >]+)', content)
# mapping in the main file the url's
for original_url in urls:
content = content.replace(
original_url, self.s3_url(original_url))
with cached as cache:
cache.write(content)
created_url = self.cache_s3(url_xsd, named)
print('Created Url Ok!: %s' % created_url)
# Mapping all internal url in the file to s3 cached env.
for original_url in urls:
# Expecting 1 level of deepest links in xsd if more, refactor this.
response = urllib2.urlopen(original_url)
content = response.read()
# Find all urls in the main xslt file.
in_urls = re.findall(r'href=[\'"]?([^\'" >]+)', content)
# mapping in the main file the url's
for orig_url in in_urls:
content = content.replace(
orig_url, self.s3_url(orig_url))
cached = NamedTemporaryFile(delete=False)
with cached as cache:
cache.write(content)
named = cached.name
new_url = self.cache_s3(original_url, named)
print('Created Url Ok!: %s' % new_url)
return created_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 check_s3(self, bucket, element):
# pragma: no cover """This method is a helper con `cache_s3`. Read method `cache_s3` for more information. :param bucket: :param element: :return: """ |
session = boto3.Session(profile_name=self.profile_name)
s3 = session.resource('s3')
try:
s3.meta.client.head_bucket(Bucket=bucket)
except ClientError:
# If the bucket does not exists then simply use the original
# I silently fail returning everything as it is in the url
return False
try:
# If the key does not exists do not return False, but try to
# create a readonly user in order to not have problems into the
# travis environment.
s3.Object(bucket, element).load()
except ClientError:
return False
else:
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cache_it(self, url):
"""Take an url which deliver a plain document and convert it to a temporary file, this document is an xslt file expecting contains all xslt definitions, then the cache process is recursive. :param url: document origin url :type url: str :return file_path: local new absolute path :rtype file_path: str """ |
# TODO: Use directly the file object instead of the name of the file
# with seek(0)
cached = self._cache_it(url)
if not isfile(cached.name):
# If /tmp files are deleted
self._cache_it.cache_clear()
cached = self._cache_it(url)
return cached.name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_original(document, xslt):
"""Get the original chain given document path and xslt local path :param str document: local absolute path to document :param str xslt: local absolute path to xst file :return: new chain generated. :rtype: str """ |
dom = etree.parse(document) # TODO: cuando este probando -
# fuente:
# http://stackoverflow.com/questions/16698935/how-to-transform-an-xml-file-using-xslt-in-python
xslt = etree.parse(xslt)
transform = etree.XSLT(xslt)
newdom = transform(dom)
return newdom |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
""" Close the internal signalfd file descriptor if it isn't closed :raises OSError: If the underlying ``close(2)`` fails. The error message matches those found in the manual page. """ |
with self._close_lock:
sfd = self._sfd
if sfd >= 0:
self._sfd = -1
self._signals = frozenset()
close(sfd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromfd(cls, fd, signals):
""" Create a new signalfd object from a given file descriptor :param fd: A pre-made file descriptor obtained from ``signalfd_create(2)` :param signals: A pre-made frozenset that describes the monitored signals :raises ValueError: If fd is not a valid file descriptor :returns: A new signalfd object .. note:: If the passed descriptor is incorrect then various methods will fail and raise OSError with an appropriate message. """ |
if fd < 0:
_err_closed()
self = cls.__new__()
object.__init__(self)
self._sfd = fd
self._signals = signals
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 update(self, signals):
""" Update the mask of signals this signalfd reacts to :param signals: A replacement set of signal numbers to monitor :raises ValueError: If :meth:`closed()` is True """ |
if self._sfd < 0:
_err_closed()
mask = sigset_t()
sigemptyset(mask)
if signals is not None:
for signal in signals:
sigaddset(mask, signal)
# flags are ignored when sfd is not -1
_signalfd(self._sfd, mask, 0)
self._signals = frozenset(signals) |
<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, maxsignals=None):
""" Read information about currently pending signals. :param maxsignals: Maximum number of signals to read. By default this is the same as the number of signals registered with this signalfd. :returns: A list of signalfd_siginfo object with information about most recently read signals. This list may be empty (in non-blocking mode). :raises ValueError: If :meth:`closed()` is True Read up to maxsignals recent pending singals ouf of the set of signals being monitored by this signalfd. If there are no signals yet and SFD_NONBLOCK was not passed to flags in :meth:`__init__()` then this call blocks until such signal is ready. """ |
if maxsignals is None:
maxsignals = len(self._signals)
if maxsignals <= 0:
raise ValueError("maxsignals must be greater than 0")
info_list = (signalfd_siginfo * maxsignals)()
num_read = read(self._sfd, byref(info_list), sizeof(info_list))
return info_list[:num_read // sizeof(signalfd_siginfo)] |
<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_curie(self, name, href):
"""Adds a CURIE definition. A CURIE link with the given ``name`` and ``href`` is added to the document. This method returns self, allowing it to be chained with additional method calls. """ |
self.draft.set_curie(self, name, href)
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 _add_rel(self, key, rel, thing, wrap):
"""Adds ``thing`` to links or embedded resources. Calling code should not use this method directly and should use ``embed`` or ``add_link`` instead. """ |
self.o.setdefault(key, {})
if wrap:
self.o[key].setdefault(rel, [])
if rel not in self.o[key]:
self.o[key][rel] = thing
return
existing = self.o[key].get(rel)
if isinstance(existing, list):
existing.append(thing)
return
self.o[key][rel] = [existing, thing] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def about_box():
"""A simple about dialog box using the distribution data files.""" |
about_info = wx.adv.AboutDialogInfo()
for k, v in metadata.items():
setattr(about_info, snake2ucamel(k), v)
wx.adv.AboutBox(about_info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign(self, xml_doc):
"""Sign the document with a third party signatory. :param str xml_doc: Document self signed in plain xml :returns answer: Answer is given from the signatory itself if connected. """ |
try:
self.client = Client(self.url)
except ValueError as e:
self.message = e.message
except URLError:
self.message = 'The url you provided: ' + \
'%s could not be reached' % self.url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(key, default=None):
""" return the key from the request """ |
data = get_form() or get_query_string()
return data.get(key, default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_true(key, default=False):
""" Check if the value is in TRUE_VALUES """ |
value = get(key, default)
if isinstance(value, list):
value = value[0]
if isinstance(value, bool):
return value
if value is default:
return default
return value.lower() in TRUE_VALUES |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_sort_limit():
""" returns the 'sort_limit' from the request """ |
limit = _.convert(get("sort_limit"), _.to_int)
if (limit < 1):
limit = None # catalog raises IndexError if limit < 1
return limit |
<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_on(allowed_indexes=None):
""" returns the 'sort_on' from the request """ |
sort_on = get("sort_on")
if allowed_indexes and sort_on not in allowed_indexes:
logger.warn("Index '{}' is not in allowed_indexes".format(sort_on))
return None
return sort_on |
<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_json_item(key, value):
""" manipulate json data on the fly """ |
data = get_json()
data[key] = value
request = get_request()
request["BODY"] = json.dumps(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 rounded_rectangle_region(width, height, radius):
""" Returns a rounded rectangle wx.Region """ |
bmp = wx.Bitmap.FromRGBA(width, height) # Mask color is #000000
dc = wx.MemoryDC(bmp)
dc.Brush = wx.Brush((255,) * 3) # Any non-black would do
dc.DrawRoundedRectangle(0, 0, width, height, radius)
dc.SelectObject(wx.NullBitmap)
bmp.SetMaskColour((0,) * 3)
return wx.Region(bmp) |
<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_after(lag):
""" Parametrized decorator for calling a function after a time ``lag`` given in milliseconds. This cancels simultaneous calls. """ |
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
wrapper.timer.cancel() # Debounce
wrapper.timer = threading.Timer(lag, func, args=args, kwargs=kwargs)
wrapper.timer.start()
wrapper.timer = threading.Timer(0, lambda: None) # timer.cancel now exists
return wrapper
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""Starts watching the path and running the test jobs.""" |
assert not self.watching
def selector(evt):
if evt.is_directory:
return False
path = evt.path
if path in self._last_fnames: # Detected a "killing cycle"
return False
for pattern in self.skip_pattern.split(";"):
if fnmatch(path, pattern.strip()):
return False
return True
def watchdog_handler(evt):
wx.CallAfter(self._watchdog_handler, evt)
# Force a first event
self._watching = True
self._last_fnames = []
self._evts = [None]
self._run_subprocess()
# Starts the watchdog observer
from .watcher import watcher
self._watcher = watcher(path=self.directory,
selector=selector, handler=watchdog_handler)
self._watcher.__enter__() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_close(self, evt):
""" Pop-up menu and wx.EVT_CLOSE closing event """ |
self.stop() # DoseWatcher
if evt.EventObject is not self: # Avoid deadlocks
self.Close() # wx.Frame
evt.Skip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mutator(*cache_names):
"""Decorator for ``Document`` methods that change the document. This decorator ensures that the object's caches are kept in sync when changes are made. """ |
def deco(fn):
@wraps(fn)
def _fn(self, *args, **kwargs):
try:
return fn(self, *args, **kwargs)
finally:
for cache_name in cache_names:
setattr(self, cache_name, None)
return _fn
return deco |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def canonical_key(self, key):
"""Returns the canonical key for the given ``key``.""" |
if key.startswith('/'):
return urlparse.urljoin(self.base_uri, key)
else:
return self.curies.expand(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 url(self):
"""Returns the URL for the resource based on the ``self`` link. This method returns the ``href`` of the document's ``self`` link if it has one, or ``None`` if the document lacks a ``self`` link, or the ``href`` of the document's first ``self`` link if it has more than one. """ |
if not 'self' in self.links:
return None
self_link = self.links['self']
if isinstance(self_link, list):
for link in self_link:
return link.url()
return self_link.url() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.