text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_packages(dname, pkgname=None, results=None, ignore=None, parent=None):
""" Get all packages which are under dname. This is necessary for Python 2.2's dis... |
parent = parent or ""
prefix = []
if parent:
prefix = [parent]
bname = os.path.basename(dname)
ignore = ignore or []
if bname in ignore:
return []
if results is None:
results = []
if pkgname is None:
pkgname = []
subfiles = os.listdir(dname)
abssu... |
<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(dname, ignore=None, parent=None):
""" Get all the data files that should be included in this distutils Project. 'dname' should be the path to ... |
parent = parent or "."
ignore = ignore or []
result = []
for directory, subdirectories, filenames in os.walk(dname):
resultfiles = []
for exname in EXCLUDE_NAMES:
if exname in subdirectories:
subdirectories.remove(exname)
for ig in ignore:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acquire(self):
""" Acquire thread and file locks. Re-opening log for 'degraded' mode. """ |
# handle thread lock
if Handler:
# under some tests Handler ends up being null due to instantiation
# order
Handler.acquire(self)
# Issue a file lock. (This is inefficient for multiple active threads
# within a single process. But if you're worried ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release(self):
""" Release file and thread locks. If in 'degraded' mode, close the stream to reduce contention until the log files can be rotated. """ |
try:
if self._rotateFailed:
self._close()
except Exception:
self.handleError(NullLogRecord())
finally:
try:
if self.stream_lock and not self.stream_lock.closed:
unlock(self.stream_lock)
except Ex... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _degrade(self, degrade, msg, *args):
""" Set degrade mode or not. Ignore msg. """ |
self._rotateFailed = degrade
del msg, args |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crossdomain(f):
"""This decorator sets the rules for the crossdomain request per http method. The settings are taken from the actual resource itself, and ret... |
@wraps(f)
def decorator(self, *args, **kwargs):
# TODO: if a non-cors request has the origin header, this will fail
if not self.cors_enabled and 'origin' in request.headers:
return self._make_response(405, "CORS request rejected")
resp = f(self, *args, **kwargs)
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 get_backend_instance(self, backend: BackendDefinitionType) -> BaseBackend: """ Returns a backend instance, either from the argument or from the settings. :rai... |
if backend is NOT_SET:
backend = self.get_setting("backend", "arca.CurrentEnvironmentBackend")
if isinstance(backend, str):
backend = load_class(backend)
if callable(backend):
backend = backend()
if not issubclass(type(backend), BaseBackend):
... |
<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_repo_url(self, repo: str):
""" Validates repo URL - if it's a valid git URL and if Arca can handle that type of repo URL :raise ValueError: If the U... |
# that should match valid git repos
if not isinstance(repo, str) or not re.match(r"^(https?|file)://[\w._\-/~]*[.git]?/?$", repo):
raise ValueError(f"{repo} is not a valid http[s] or file:// git repository.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repo_id(self, repo: str) -> str: """ Returns an unique identifier from a repo URL for the folder the repo is gonna be pulled in. """ |
if repo.startswith("http"):
repo_id = re.sub(r"https?://(.www)?", "", repo)
repo_id = re.sub(r"\.git/?$", "", repo_id)
else:
repo_id = repo.replace("file://", "")
repo_id = re.sub(r"\.git/?$", "", repo_id)
if repo_id.startswith("~"):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pull_again(self, repo: Optional[str]=None, branch: Optional[str]=None) -> None: """ When ``single_pull`` is enables, tells Arca to pull again. If ``repo`` and... |
if repo is None and branch is None:
self._current_hashes = {}
elif repo is None:
raise ValueError("You can't define just the branch to pull again.")
elif branch is None and repo is not None:
self._current_hashes.pop(self.repo_id(repo), None)
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 cache_key(self, repo: str, branch: str, task: Task, git_repo: Repo) -> str: """ Returns the key used for storing results in cache. """ |
return "{repo}_{branch}_{hash}_{task}".format(repo=self.repo_id(repo),
branch=branch,
hash=self.current_git_hash(repo, branch, git_repo),
task=task.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 run(self, repo: str, branch: str, task: Task, *, depth: DepthDefinitionType=1, reference: ReferenceDefinitionType=None ) -> Result: """ Runs the ``task`` usin... |
self.validate_repo_url(repo)
depth = self.validate_depth(depth)
reference = self.validate_reference(reference)
logger.info("Running Arca task %r for repo '%s' in branch '%s'", task, repo, branch)
git_repo, repo_path = self.get_files(repo, branch, depth=depth, reference=referen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def static_filename(self, repo: str, branch: str, relative_path: Union[str, Path], *, depth: DepthDefinitionType=1, reference: ReferenceDefinitionType=None ) -> P... |
self.validate_repo_url(repo)
depth = self.validate_depth(depth)
reference = self.validate_reference(reference)
if not isinstance(relative_path, Path):
relative_path = Path(relative_path)
_, repo_path = self.get_files(repo, branch, depth=depth, reference=reference)
... |
<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_depth(self, depth: DepthDefinitionType) -> Optional[int]: """ Converts the depth to int and validates that the value can be used. :raise ValueError: ... |
if depth is not None:
try:
depth = int(depth)
except ValueError:
raise ValueError(f"Depth '{depth}' can't be converted to int.")
if depth < 1:
raise ValueError(f"Depth '{depth}' isn't a positive number")
return de... |
<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(self, data):
""" Runs all field validators. """ |
for v in self.validators:
v(self, data)
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_styles(style_name):
""" Just list all different styles entries """ |
style = get_style_by_name(style_name)
keys = list(style)[0][1]
Styles = namedtuple("Style", keys)
existing_styles = {}
for ttype, ndef in style:
s = Styles(**ndef)
if s in existing_styles:
existing_styles[s].append(ttype)
else:
existing_styles[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 decorate(*reversed_views):
""" provide a syntax decorating views without nested calls. instead of: json_api_call(etag(<hash_fn>)(<view_fn>))) you can write: ... |
fns = reversed_views[::-1]
view = fns[0]
for wrapper in fns[1:]:
view = wrapper(view)
return view |
<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_as_object(self, *args):
""" Sets a new value to map element specified by its index. When the index is not defined, it resets the entire map value. This m... |
if len(args) == 1:
self.set_as_map(args[0])
elif len(args) == 2:
self.put(args[0], args[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 from_string(line):
""" Parses semicolon-separated key-value pairs and returns them as a StringValueMap. :param line: semicolon-separated key-value list to in... |
result = StringValueMap()
if line == None or len(line) == 0:
return result
tokens = str(line).split(';')
for token in tokens:
if len(token) == 0:
continue
index = token.find('=')
key = token[0:index] if index >= 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 delete(self, hard=False):
""" Override the vanilla delete functionality to soft-delete instead. Soft-delete is accomplished by setting the status field to "d... |
if hard:
return models.Model.delete(self)
self.status = "deleted"
self.save()
for key in self._handleref.delete_cascade:
q = getattr(self, key).all()
if not hard:
# if we are soft deleting only trigger delete on
# obj... |
<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_trainer_from_username(self, username, detail=False):
"""Returns a Trainer object from a Trainers username""" |
params = {
'detail': '1' if detail is True else '0',
'q': username
}
r = requests.get(api_url+'trainers/', params=params, headers=self.headers)
print(request_status(r))
try:
r = r.json()[0]
except IndexError:
return None
return Trainer(r) if r 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 discord_to_users(self, memberlist):
""" expects a list of discord.py user objects returns a list of TrainerDex.py user objects """ |
_memberlist = self.get_discord_user(x.id for x in memberlist)
return list(set(x.owner() for x in _memberlist)) |
<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_trainer(self, username, team, start_date=None, has_cheated=None, last_cheated=None, currently_cheats=None, statistics=True, daily_goal=None, total_goal... |
args = locals()
url = api_url+'trainers/'
payload = {
'username': username,
'faction': team,
'statistics': statistics,
'prefered': prefered,
'last_modified': maya.now().iso8601(),
'owner': account,
'verified': verified
}
for i in args:
if args[i] is not None and i not in ['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_trainer(self, trainer, username=None, start_date=None, has_cheated=None, last_cheated=None, currently_cheats=None, statistics=None, daily_goal=None, to... |
args = locals()
if not isinstance(trainer, Trainer):
raise ValueError
url = api_url+'trainers/'+str(trainer.id)+'/'
payload = {
'last_modified': maya.now().iso8601()
}
for i in args:
if args[i] is not None and i not in ['self', 'trainer', 'start_date']:
payload[i] = args[i]
elif args[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 import_discord_user(self, uid, user):
"""Add a discord user to the database if not already present, get if is present. """ |
url = api_url+'users/social/'
payload = {
'user': int(user),
'provider': 'discord',
'uid': str(uid)
}
print(json.dumps(payload))
r = requests.put(url, data=json.dumps(payload), headers=self.headers)
print(request_status(r))
r.raise_for_status()
return DiscordUser(r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_user(self, username, first_name=None, last_name=None):
""" Creates a new user object on database Returns the User Object. Must be linked to a ne... |
url = api_url+'users/'
payload = {
'username':username
}
if first_name:
payload['first_name'] = first_name
if last_name:
payload['last_name'] = last_name
r = requests.post(url, data=json.dumps(payload), headers=self.headers)
print(request_status(r))
r.raise_for_status()
return User(r.json... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_user(self, user, username=None, first_name=None, last_name=None):
"""Update user info""" |
if not isinstance(user, User):
raise ValueError
args = locals()
url = api_url+'users/'+str(user.id)+'/'
payload = {}
for i in args:
if args[i] is not None and i not in ['self', 'user']:
payload[i] = args[i]
r = requests.patch(url, data=json.dumps(payload), headers=self.headers)
print(request... |
<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_trainer(self, id_, respect_privacy=True, detail=True):
"""Returns the Trainer object for the ID""" |
parameters = {}
if respect_privacy is False:
parameters['statistics'] = 'force'
if detail is False:
parameters['detail'] = 'low'
r = requests.get(api_url+'trainers/'+str(id_)+'/', headers=self.headers) if respect_privacy is True else requests.get(api_url+'trainers/'+str(id_)+'/', params=parameters... |
<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_detailed_update(self, uid, uuid):
"""Returns the update object for the ID""" |
r = requests.get(api_url+'users/'+str(uid)+'/update/'+str(uuid)+'/', headers=self.headers)
print(request_status(r))
r.raise_for_status()
return Update(r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user(self, uid):
"""Returns the User object for the ID""" |
r = requests.get(api_url+'users/'+str(uid)+'/', headers=self.headers)
print(request_status(r))
r.raise_for_status()
return User(r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_discord_user(self, uid=None, user=None, trainer=None):
"""Returns the DiscordUsers object for the ID Expects list of string representions discord IDs... |
uids = ','.join(uid) if uid else None
users =','.join(user) if user else None
trainers = ','.join(trainer) if trainer else None
params = {
'provider': 'discord',
'uid': uids,
'user': users,
'trainer': trainers
}
r = requests.get(api_url+'users/social/', params=params, headers=self.headers)
pr... |
<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_all_users(self):
"""Returns all the users""" |
r = requests.get(api_url+'users/', headers=self.headers)
print(request_status(r))
r.raise_for_status()
output = r.json()
result = []
for x in output:
result.append(User(x))
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 combine(self, path):
""" Gives a combined `self.BASE_URL` with the given `path`. Used to build urls without modifying the current `self.path`. Handles confli... |
url = self.base_url
if url.endswith('/') and path.startswith('/'):
url += path[1:]
elif url.endswith('/') or path.startswith('/'):
url += path
else:
url += '/' + path
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_DOM(self):
""" Makes a request and updates `self._DOM`. Worth using only if you manually change `self.base_url` or `self.path`. :return: self :rtype: ... |
response = self.fetch()
self._DOM = html.fromstring(response.text)
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 fetch(self):
""" Makes a request to combined url with `self._params` as parameters. If the server at combined url responds with Client or Server error, raise... |
response = self._session.get(self.url, params=self.params)
response.raise_for_status()
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_environment():
"""Set environment variables that are important for the pipeline. :returns: None :rtype: None :raises: None """ |
os.environ['DJANGO_SETTINGS_MODULE'] = 'jukeboxcore.djsettings'
pluginpath = os.pathsep.join((os.environ.get('JUKEBOX_PLUGIN_PATH', ''), constants.BUILTIN_PLUGIN_PATH))
os.environ['JUKEBOX_PLUGIN_PATH'] = pluginpath |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unload_modules():
""" Unload all modules of the jukebox package and all plugin modules Python provides the ``reload`` command for reloading modules. The majo... |
mods = set([])
for m in sys.modules:
if m.startswith('jukebox'):
mods.add(m)
pm = PluginManager.get()
for p in pm.get_all_plugins():
mods.add(p.__module__)
for m in mods:
del(sys.modules[m]) |
<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_LDAP_connection():
""" Return a LDAP connection """ |
server = ldap3.Server('ldap://' + get_optional_env('EPFL_LDAP_SERVER_FOR_SEARCH'))
connection = ldap3.Connection(server)
connection.open()
return connection, get_optional_env('EPFL_LDAP_BASE_DN_FOR_SEARCH') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def LDAP_search(pattern_search, attribute):
""" Do a LDAP search """ |
connection, ldap_base = _get_LDAP_connection()
connection.search(
search_base=ldap_base,
search_filter=pattern_search,
attributes=[attribute]
)
return connection.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 is_unit_exist(unit_id):
""" Return True if the unit 'unid_id' exists. Otherwise return False """ |
attribute = 'objectClass'
response = LDAP_search(
pattern_search="(uniqueidentifier={})".format(unit_id),
attribute=attribute
)
try:
unit_exist = 'EPFLorganizationalUnit' in response[0]['attributes'][attribute]
except Exception:
return False
return unit_exist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_unit_name(unit_id):
""" Return the unit name to the unit 'unit_id' """ |
attribute = 'cn'
response = LDAP_search(
pattern_search='(uniqueIdentifier={})'.format(unit_id),
attribute=attribute
)
try:
unit_name = get_attribute(response, attribute)
except Exception:
raise EpflLdapException("The unit with id '{}' was not found".format(unit_id))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_unit_id(unit_name):
""" Return the unit id to the unit 'unit_name' """ |
unit_name = unit_name.lower()
attribute = 'uniqueIdentifier'
response = LDAP_search(
pattern_search='(cn={})'.format(unit_name),
attribute=attribute
)
unit_id = ""
try:
for element in response:
if 'dn' in element and element['dn'].startswith('ou={},'.format(... |
<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_units(username):
""" Return all units of user 'username' """ |
connection, ldap_base = _get_LDAP_connection()
# Search the user dn
connection.search(
search_base=ldap_base,
search_filter='(uid={}@*)'.format(username),
)
# For each user dn give me the unit
dn_list = [connection.response[index]['dn'] for index in range(len(connection.respon... |
<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_username(sciper):
""" Return username of user """ |
attribute = 'uid'
response = LDAP_search(
pattern_search='(uniqueIdentifier={})'.format(sciper),
attribute=attribute
)
try:
username = get_attribute(response, attribute)
except Exception:
raise EpflLdapException("No username corresponds to sciper {}".format(sciper))
... |
<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_email(sciper):
""" Return email of user """ |
attribute = 'mail'
response = LDAP_search(
pattern_search='(uniqueIdentifier={})'.format(sciper),
attribute=attribute
)
try:
email = get_attribute(response, attribute)
except Exception:
raise EpflLdapException("No email address corresponds to sciper {}".format(sciper... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_code(self, code):
""" Sets a unique error code. This method returns reference to this exception to implement Builder pattern to chain additional calls. ... |
self.code = code if code != None else 'UNKNOWN'
self.name = code
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 with_details(self, key, value):
""" Sets a parameter for additional error details. This details can be used to restore error description in other languages. ... |
self.details = self.details if self.details != None else {}
self.details[key] = value
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 wrap(self, cause):
""" Wraps another exception into an application exception object. If original exception is of ApplicationException type it is returned wit... |
if isinstance(cause, ApplicationException):
return cause
self.with_cause(cause)
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 wrap_exception(exception, cause):
""" Wraps another exception into specified application exception object. If original exception is of ApplicationException t... |
if isinstance(cause, ApplicationException):
return cause
exception.with_cause(cause)
return exception |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self):
""" Return the current value of a variable """ |
# Does the variable name have tags to parse?
if len(self._element):
var = ''.join(map(str, self.trigger.agentml.parse_tags(self._element, self.trigger)))
else:
var = self._element.text or attribute(self._element, 'name')
# Is there a default value defined?
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reopen(self, file_obj):
"""Reopen the file-like object in a safe manner.""" |
file_obj.open('U')
if sys.version_info[0] <= 2:
return file_obj
else:
return codecs.getreader('utf-8')(file_obj) |
<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(self):
"""wrapper for original parse function. will read pkl with bdf info, if available.""" |
if os.path.exists(self.pklname): # check for pkl with binary info
logger.info('Found bdf pkl file %s. Loading...' % (self.pklname))
try:
with open(self.pklname,'rb') as pkl:
(self.mimemsg, self.headxml, self.sizeinfo, self.binarychunks, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def toString(self):
""" Returns almost original string. If you want prettified string, try :meth:`.prettify`. Returns: str: Complete representation of the elemen... |
output = ""
if self.childs or self.isOpeningTag():
output += self.tagToString()
for c in self.childs:
output += c.toString()
if self.endtag is not None:
output += self.endtag.tagToString()
elif not self.isEndTag():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replaceWith(self, el):
""" Replace value in this element with values from `el`. This useful when you don't want change all references to object. Args: el (ob... |
self.childs = el.childs
self.params = el.params
self.endtag = el.endtag
self.openertag = el.openertag
self._tagname = el.getTagName()
self._element = el.tagToString()
self._istag = el.isTag()
self._isendtag = el.isEndTag()
self._iscomment = el.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 handle_previous(self, command):
""" Method to generate item from a ItemForm. The form must be exposed on form attribute @param command: a command tha expose ... |
self.result = command.items
self._to_commit = self.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 get_dates(raw_table) -> "list of dates": """ Goes through the first column of input table and returns the first sequence of dates it finds. """ |
dates = []
found_first = False
for i, dstr in enumerate([raw_table[i][0] for i in range(0, len(raw_table))]):
if dstr:
if len(dstr.split("/")) == 3:
d = datetime.datetime.strptime(dstr, '%m/%d/%Y')
elif len(dstr.split("-")) == 3:
... |
<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_main(self) -> 'table[category: str][label: str][date: date]': """ Returns a table with the above typesignature """ |
raw_table = self.get_raw_table("M")
categories = raw_table[0]
labels = raw_table[1]
dates = self.get_dates(raw_table)
def next_cat_col(i):
n = 1
while True:
if i+n > len(categories)-1:
return i
if cate... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def build_headers(self):
'''
Return the list of headers as two-tuples
'''
if not 'Content-Type' in self.headers:
content_type = self.content_type
if self.encoding != DEFAULT_ENCODING:
content_type += '; charset=%s' % self.encoding
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_cookie(self, key, value, **attrs):
'''
Finer control over cookies. Allow specifying an Morsel arguments.
'''
if attrs:
c = Morsel()
c.set(key, value, **attrs)
self.cookies[key] = c
else:
self.cookies[key] = 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 status(self):
'''Allow custom status messages'''
message = self.status_message
if message is None:
message = STATUS[self.status_code]
return '%s %s' % (self.status_code, message) |
<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_git_changeset():
"""Get git identifier; taken from Django project.""" |
git_log = Popen(
'git log --pretty=format:%ct --quiet -1 HEAD',
stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timest... |
<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_version(version_tuple):
"""Convert 4-tuple into a PEP 440 compliant string.""" |
if version_tuple[3] == FINAL and version_tuple[4] != 0:
raise Exception(
'Project version number misconfigured:\n'
' version may not be final and have segment number.')
if version_tuple[3] not in (DEV, FINAL) and version_tuple[4] == 0:
raise Exception(
'Pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, name):
"""If name is not in the map, append it with an empty id range set.""" |
if not isinstance(name, str):
raise TypeError(
"argument 'name' must be a string, not {}".format(
name.__class__.__name__
)
)
if not name:
raise ValueError("argument 'name' cannot be empty"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def who_has(self, subid):
"""Return a list of names who own subid in their id range set.""" |
answer = []
for name in self.__map:
if subid in self.__map[name] and not name in answer:
answer.append(name)
return answer |
<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_path_for_url(url):
"""Return the path where the URL might be cached.""" |
m = hashlib.md5()
m.update(url)
digest = m.hexdigest()
return os.path.join(CACHE_DIRECTORY, '%s.html' % digest) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_url(url, data=None, cached=True, cache_key=None, crawler='urllib'):
"""Retrieves the HTML code for a given URL. If a cached version is not available, use... |
if cache_key is None:
cache_key = url
cache_path = cache_path_for_url(cache_key)
if cached and os.path.exists(cache_path):
with open(cache_path) as f:
html = f.read().decode('utf-8')
else:
if FAIL_IF_NOT_CACHED:
raise BaseException("URL is not in cache an... |
<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_intercom_data(self):
"""Specify the data sent to Intercom API according to event type""" |
data = {
"event_name": self.get_type_display(), # event type
"created_at": calendar.timegm(self.created.utctimetuple()), # date
"metadata": self.metadata
}
if self.user:
data["user_id"] = self.user.intercom_id
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_lab_text(lab_slug, language):
"""Gets text description in English or Italian from a single lab from makeinitaly.foundation.""" |
if language == "English" or language == "english" or language == "EN" or language == "En":
language = "en"
elif language == "Italian" or language == "italian" or language == "IT" or language == "It" or language == "it":
language = "it"
else:
language = "en"
wiki = MediaWiki(make... |
<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_single_lab(lab_slug):
"""Gets data from a single lab from makeinitaly.foundation.""" |
wiki = MediaWiki(makeinitaly__foundation_api_url)
wiki_response = wiki.call(
{'action': 'query',
'titles': lab_slug,
'prop': 'revisions',
'rvprop': 'content'})
# If we don't know the pageid...
for i in wiki_response["query"]["pages"]:
content = wiki_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 get_labs(format):
"""Gets data from all labs from makeinitaly.foundation.""" |
labs = []
# Get the first page of data
wiki = MediaWiki(makeinitaly__foundation_api_url)
wiki_response = wiki.call(
{'action': 'query',
'list': 'categorymembers',
'cmtitle': 'Category:Italian_FabLabs',
'cmlimit': '500'})
if "query-continue" in wiki_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 path_eval(self, obj, keypath):
'''Given an object and a mongo-style dotted key path, return the
object value referenced by that key path.
'''
segs = keypath.split('.')
this = obj
for seg in segs:
if isinstance(this, dict):
try:
... |
<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(self, spec, data):
'''Given a mongo-style spec and some data or python object,
check whether the object complies with the spec. Fails eagerly.
'''
path_eval = self.path_eval
for keypath, specvalue in spec.items():
if keypath.startswith('$'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def handle_literal(self, val, checkable):
'''This one's tricky...check for equality,
then for contains.
'''
# I.e., spec: {'x': 1}, data: {'x': 1}
if val == checkable:
yield True
return
# I.e., spec: {'x': 1}, data: {'x': [1, 2, 3]}
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 normalize(X, norm):
'''Applies the given norm to the input data set
Parameters:
X (numpy.ndarray): A 3D numpy ndarray in which the rows represent examples
while the columns, features of the data set you want to normalize. Every
depth corresponds to data for a particular class
norm (tuple... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto_register_search_models():
"""Auto register all search models""" |
for config in models_config.get_all_configs():
if config.disable_search_index:
continue
search.register(
config.model.objects.get_queryset(),
ModelSearchAdapter,
fields=config.search_fields,
exclude=config.search_exclude_fields,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_title(self, obj):
"""Set search entry title for object""" |
search_title = self.get_model_config_value(obj, 'search_title')
if not search_title:
return super().get_title(obj)
return search_title.format(**obj.__dict__) |
<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_description(self, obj):
"""Set search entry description for object""" |
search_description = self.get_model_config_value(obj, 'search_description')
if not search_description:
return super().get_description(obj)
return search_description.format(**obj.__dict__) |
<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_model_config_value(self, obj, name):
"""Get config value for given model""" |
config = models_config.get_config(obj)
return getattr(config, 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 disconnect(self, callback):
""" Disconnects a callback from this signal. :param callback: The callback to disconnect. :param weak: A flag that must have the ... |
try:
self._callbacks.remove(callback)
except ValueError:
self._callbacks.remove(ref(callback)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_channel_names(client, e):
"""Add a new channel to self.channels and initialize its user list. Called as event handler for RPL_NAMES events. Do not call ... |
chan = IRCstr(e.channel)
names = set([IRCstr(n) for n in e.name_list])
client.channels[chan] = SeshetChannel(chan, names) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(self, channel):
"""Add this user to the channel's user list and add the channel to this user's list of joined channels. """ |
if channel not in self.channels:
channel.users.add(self.nick)
self.channels.append(channel) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def part(self, channel):
"""Remove this user from the channel's user list and remove the channel from this user's list of joined channels. """ |
if channel in self.channels:
channel.users.remove(self.nick)
self.channels.remove(channel) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quit(self):
"""Remove this user from all channels and reinitialize the user's list of joined channels. """ |
for c in self.channels:
c.users.remove(self.nick)
self.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 change_nick(self, nick):
"""Update this user's nick in all joined channels.""" |
old_nick = self.nick
self.nick = IRCstr(nick)
for c in self.channels:
c.users.remove(old_nick)
c.users.add(self.nick) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_message(self, user, message):
"""Log a channel message. This log acts as a sort of cache so that recent activity can be searched by the bot and command m... |
if isinstance(user, SeshetUser):
user = user.nick
elif not isinstance(user, IRCstr):
user = IRCstr(user)
time = datetime.utcnow()
self.message_log.append((time, user, message))
while len(self.message_log) > self._log_size:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_dependency(self, data_src, data_sink):
""" registers a dependency of data_src -> data_sink by placing appropriate entries in provides_for and depend... |
pdebug("registering dependency %s -> %s" % (data_src, data_sink))
if (data_src not in self._gettask(data_sink).depends_on):
self._gettask(data_sink).depends_on.append(data_src)
if (data_sink not in self._gettask(data_src).provides_for):
self._gettask(data_src).provide... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_task(self, name):
""" Builds a task by name, resolving any dependencies on the way """ |
try:
self._gettask(name).value = (
self._gettask(name).task.resolve_and_build())
except TaskExecutionException as e:
perror(e.header, indent="+0")
perror(e.message, indent="+4")
self._gettask(name).value = e.payload
except Excepti... |
<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_build_needed(self, data_sink, data_src):
""" returns true if data_src needs to be rebuilt, given that data_sink has had a rebuild requested. """ |
return (self._gettask(data_src).last_build_time == 0 or
self._gettask(data_src).last_build_time <
self._gettask(data_sink).last_build_time) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deep_dependendants(self, target):
""" Recursively finds the dependents of a given build target. Assumes the dependency graph is noncyclic """ |
direct_dependents = self._gettask(target).provides_for
return (direct_dependents +
reduce(
lambda a, b: a + b,
[self.deep_dependendants(x) for x in direct_dependents],
[])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_dependency_graph(self, target):
""" resolves the build order for interdependent build targets Assumes no cyclic dependencies """ |
targets = self.deep_dependendants(target)
# print "deep dependants:", targets
return sorted(targets,
cmp=lambda a, b:
1 if b in self.deep_dependendants(a) else
-1 if a in self.deep_dependendants(b) 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 resolve(self):
"""Builds all targets of this dependency and returns the result of self.function on the resulting values """ |
values = {}
for target_name in self.target_names:
if self.context.is_build_needed(self.parent, target_name):
self.context.build_task(target_name)
if len(self.keyword_chain) == 0:
values[target_name] = self.context.tasks[target_name].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 updateAllKeys(self):
"""Update times for all keys in the layout.""" |
for kf, key in zip(self.kf_list, self.sorted_key_list()):
kf.update(key, self.dct[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 print_with_header(header, message, color, indent=0):
""" Use one of the functions below for printing, not this one. """ |
print()
padding = ' ' * indent
print(padding + color + BOLD + header + ENDC + color + message + ENDC) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Perform phantomas run """ |
self._logger.info("running for <{url}>".format(url=self._url))
args = format_args(self._options)
self._logger.debug("command: `{cmd}` / args: {args}".
format(cmd=self._cmd, args=args))
# run the process
try:
process = Popen(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract(fileobj, keywords, comment_tags, options):
"""Extracts translation messages from underscore template files. This method does also extract django temp... |
encoding = options.get('encoding', 'utf-8')
original_position = fileobj.tell()
text = fileobj.read().decode(encoding)
if django.VERSION[:2] >= (1, 9):
tokens = Lexer(text).tokenize()
else:
tokens = Lexer(text, None).tokenize()
vars = [token.token_type != TOKEN_TEXT for token... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def from_radians(cls, lat_radians, long_radians):
'''
Return a new instance of Point from a pair of coordinates in radians.
'''
return cls(math.degrees(lat_radians), math.degrees(long_radians)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def distance_to(self, point):
'''
Return the distance between this point and another point in meters.
:param point: Point to measure distance to
:type point: Point
:returns: The distance to the other point
:rtype: float
'''
angle = math.acos(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def bearing_to(self, point):
'''
Return the bearing to another point.
:param point: Point to measure bearing to
:type point: Point
:returns: The bearing to the other point
:rtype: Bearing
'''
delta_long = point.long_radians - self.long_radians
y ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def relative_point(self, bearing_to_point, distance):
'''
Return a waypoint at a location described relative to the current point
:param bearing_to_point: Relative bearing from the current waypoint
:type bearing_to_point: Bearing
:param distance: Distance from the current waypoi... |
<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_app(settings):
"""Create a new Flask application""" |
app = Flask(__name__)
# Import settings from file
for name in dir(settings):
value = getattr(settings, name)
if not (name.startswith('_') or isinstance(value, ModuleType)
or isinstance(value, FunctionType)):
app.config[name] = value
# Bootstrapping
if '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.