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 _effectinit_raise_line_padding_on_focus(self, name, **kwargs):
"""Init the effect for the empty space around the focused entry. Keyword arguments can contain... |
self._effects[name] = kwargs
if "enlarge_time" not in kwargs:
kwargs['enlarge_time'] = 0.5
if "padding" not in kwargs:
kwargs['padding'] = 10
kwargs['padding_pps'] = kwargs['padding'] / kwargs['enlarge_time']
# Now, every menu voices need additional 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 _effectupdate_raise_line_padding_on_focus(self, time_passed):
"""Gradually enlarge the padding of the focused line.""" |
data = self._effects['raise-line-padding-on-focus']
pps = data['padding_pps']
for i, option in enumerate(self.options):
if i == self.option:
# Raise me
if option['padding_line'] < data['padding']:
option['padding_line'] += pps * 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 _effectinit_raise_col_padding_on_focus(self, name, **kwargs):
"""Init the column padding on focus effect. Keyword arguments can contain enlarge_time and padd... |
self._effects[name] = kwargs
if "enlarge_time" not in kwargs:
kwargs['enlarge_time'] = 0.5
if "padding" not in kwargs:
kwargs['padding'] = 10
kwargs['padding_pps'] = kwargs['padding'] / kwargs['enlarge_time']
for option in self.options:
opti... |
<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_choices_tuple(choices, get_display_name):
""" Make a tuple for the choices parameter for a data model field. :param choices: sequence of valid values fo... |
assert callable(get_display_name)
return tuple((x, get_display_name(x)) for x in choices) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edit(self):
""" Edit the file """ |
self.changed = False
with self:
editor = self.get_editor()
cmd = [editor, self.name]
try:
res = subprocess.call(cmd)
except Exception as e:
print("Error launching editor %(editor)s" % locals())
print(e)
return
if res != 0:
msg = '%(editor)s returned error status %(res)d' % locals... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _search_env(keys):
""" Search the environment for the supplied keys, returning the first one found or None if none was found. """ |
matches = (os.environ[key] for key in keys if key in os.environ)
return next(matches, 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_editor(self):
""" Give preference to an XML_EDITOR or EDITOR defined in the environment. Otherwise use a default editor based on platform. """ |
env_search = ['EDITOR']
if 'xml' in self.content_type:
env_search.insert(0, 'XML_EDITOR')
default_editor = self.platform_default_editors[sys.platform]
return self._search_env(env_search) or default_editor |
<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_json(cls, json_obj):
"""Build an Event from JSON. :param json_obj: JSON data representing a Cube Event :type json_obj: `String` or `json` :throws: `Inva... |
if isinstance(json_obj, str):
json_obj = json.loads(json_obj)
type = None
time = None
data = None
if cls.TYPE_FIELD_NAME in json_obj:
type = json_obj[cls.TYPE_FIELD_NAME]
if cls.TIME_FIELD_NAME in json_obj:
time = json_obj[cls.TIME_F... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autodiscover():
"""Autodiscover for urls.py""" |
# Get permissions based on urlpatterns from urls.py
url_conf = getattr(settings, 'ROOT_URLCONF', ())
resolver = urlresolvers.get_resolver(url_conf)
urlpatterns = resolver.url_patterns
permissions = generate_permissions(urlpatterns)
# Refresh permissions
refresh_permissions(permissions) |
<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_driver_blacklist(driver):
# noqa: E501 """Retrieve the blacklist in the driver Retrieve the blacklist in the driver # noqa: E501 :param driver: The drive... |
response = errorIfUnauthorized(role='admin')
if response:
return response
else:
response = ApitaxResponse()
driver: Driver = LoadedDrivers.getDriver(driver)
response.body.add({'blacklist': driver.getDriverBlacklist()})
return Response(status=200, body=response.getResponseBody... |
<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_driver_config(driver):
# noqa: E501 """Retrieve the config of a loaded driver Retrieve the config of a loaded driver # noqa: E501 :param driver: The driv... |
response = errorIfUnauthorized(role='admin')
if response:
return response
else:
response = ApitaxResponse()
# TODO: This needs an implementation, but likely requires a change to configs in apitaxcore
return Response(status=200, body=response.getResponseBody()) |
<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_driver_list():
# noqa: E501 """Retrieve the catalog of drivers Retrieve the catalog of drivers # noqa: E501 :rtype: Response """ |
response = errorIfUnauthorized(role='admin')
if response:
return response
else:
response = ApitaxResponse()
response.body.add({'drivers': LoadedDrivers.drivers})
return Response(status=200, body=response.getResponseBody()) |
<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_driver_whitelist(driver):
# noqa: E501 """Retrieve the whitelist in the driver Retrieve the whitelist in the driver # noqa: E501 :param driver: The drive... |
response = errorIfUnauthorized(role='admin')
if response:
return response
else:
response = ApitaxResponse()
driver: Driver = LoadedDrivers.getDriver(driver)
response.body.add({'whitelist': driver.getDriverWhitelist()})
return Response(status=200, body=response.getResponseBody... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tag_post_save_handler(sender, **kwargs):
""" Makes sure that a translation is created when a tag is saved. Also ensures that the original tag name gets updat... |
instance = kwargs.get('instance')
try:
translation = instance.tagtitle_set.get(language='en')
except TagTitle.DoesNotExist:
translation = TagTitle.objects.create(
trans_name=instance.name, tag=instance, language='en')
if translation.trans_name != instance.name:
insta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_editable(f):
""" Makes sure the registry key is editable before trying to edit it. """ |
def wrapper(self, *args, **kwargs):
if not self._edit:
raise RegistryKeyNotEditable("The key is not set as editable.")
return f(self, *args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createHiddenFolder(self) -> 'File': """ Create Hidden Folder Create a hidden folder. Raise exception if auto delete isn't True. @return: Created folder. """ |
if not self._autoDelete:
raise Exception("Hidden folders can only be created within"
" an autoDelete directory")
return tempfile.mkdtemp(dir=self._path, prefix=".") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _listFilesWin(self) -> ['File']: """ List Files for Windows OS Search and list the files and folder in the current directory for the Windows file system. @ret... |
output = []
for dirname, dirnames, filenames in os.walk(self._path):
for subdirname in dirnames:
output.append(os.path.join(dirname, subdirname))
for filename in filenames:
output.append(os.path.join(dirname, filename))
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _listFilesPosix(self) -> ['File']: """ List Files for POSIX Search and list the files and folder in the current directory for the POSIX file system. @return: ... |
find = "find %s -type f" % self._path
output = check_output(args=find.split()).strip().decode().split(
'\n')
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pathName(self, pathName: str):
""" Path Name Setter Set path name with passed in variable, create new directory and move previous directory contents to new p... |
if self.pathName == pathName:
return
pathName = self.sanitise(pathName)
before = self.realPath
after = self._realPath(pathName)
assert (not os.path.exists(after))
newRealDir = os.path.dirname(after)
if not os.path.exists(newRealDir):
o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def namedTempFileReader(self) -> NamedTempFileReader: """ Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading... |
# Get the weak ref
directory = self._directory()
assert isinstance(directory, Directory), (
"Expected Directory, receieved %s" % directory)
# Return the object
return NamedTempFileReader(directory, 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 _realPath(self, newPathName: str = None) -> str: """ Private Real Path Get path name. @param newPathName: variable for new path name if passed argument. @type... |
directory = self._directory()
assert directory
return os.path.join(directory.path,
newPathName if newPathName else self._pathName) |
<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_file(package: str, fname: str) -> ModuleType: """Import file directly. This is a hack to import files from packages without importing <package>/__init_... |
mod_name = fname.rstrip('.py')
spec = spec_from_file_location(mod_name, '{}/{}'.format(package, fname))
module = module_from_spec(spec)
spec.loader.exec_module(module)
return module |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def t_FLOAT(tok): # pylint: disable=locally-disabled,invalid-name
r'\d+\.\d+'
tok.value = (tok.type, float(tok.value))
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 trigger_arbitrary_job(repo_name, builder, revision, auth, files=None, dry_run=False, extra_properties=None):
""" Request buildapi to trigger a job for us. We... |
assert len(revision) == 40, \
'We do not accept revisions shorter than 40 chars'
url = _builders_api_url(repo_name, builder, revision)
payload = _payload(repo_name, revision, files, extra_properties)
if dry_run:
LOG.info("Dry-run: We were going to request a job for '{}'".format(builder... |
<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_retrigger_request(repo_name, request_id, auth, count=DEFAULT_COUNT_NUM, priority=DEFAULT_PRIORITY, dry_run=True):
""" Retrigger a request using buildapi... |
url = '{}/{}/request'.format(SELF_SERVE, repo_name)
payload = {'request_id': request_id}
if count != DEFAULT_COUNT_NUM or priority != DEFAULT_PRIORITY:
payload.update({'count': count,
'priority': priority})
if dry_run:
LOG.info('We would make a POST request to ... |
<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_cancel_request(repo_name, request_id, auth, dry_run=True):
""" Cancel a request using buildapi self-serve. Returns a request. Buildapi documentation: DE... |
url = '{}/{}/request/{}'.format(SELF_SERVE, repo_name, request_id)
if dry_run:
LOG.info('We would make a DELETE request to %s.' % url)
return None
LOG.info("We're going to cancel the job at %s" % url)
req = requests.delete(url, auth=auth, timeout=TCP_TIMEOUT)
# TODO: add debug mes... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_jobs_schedule(repo_name, revision, auth):
""" Query Buildapi for jobs. """ |
url = "%s/%s/rev/%s?format=json" % (SELF_SERVE, repo_name, revision)
LOG.debug("About to fetch %s" % url)
req = requests.get(url, auth=auth, timeout=TCP_TIMEOUT)
# If the revision doesn't exist on buildapi, that means there are
# no buildapi jobs for this revision
if req.status_code not in [20... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_pending_jobs(auth, repo_name=None, return_raw=False):
"""Return pending jobs""" |
url = '%s/pending?format=json' % HOST_ROOT
LOG.debug('About to fetch %s' % url)
req = requests.get(url, auth=auth, timeout=TCP_TIMEOUT)
# If the revision doesn't exist on buildapi, that means there are
# no builapi jobs for this revision
if req.status_code not in [200]:
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 set_object(self, object):
""" Set object for rendering component and set object to all components :param object: :return: """ |
if self.object is False:
self.object = object
# Pass object along to child components for rendering
for component in self.components:
component.set_object(object) |
<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_fields(self):
"""Get all fields""" |
if not hasattr(self, '__fields'):
self.__fields = [
self.parse_field(field, index)
for index, field in enumerate(getattr(self, 'fields', []))
]
return self.__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 parse_field(self, field_data, index=0):
"""Parse field and add missing options""" |
field = {
'__index__': index,
}
if isinstance(field_data, str):
field.update(self.parse_string_field(field_data))
elif isinstance(field_data, dict):
field.update(field_data)
else:
raise TypeError('Expected a str or dict get {}'.fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_field(self, field, data):
"""Render field for given data""" |
from trionyx.renderer import renderer
if 'value' in field:
value = field['value']
elif isinstance(data, object) and hasattr(data, field['field']):
value = getattr(data, field['field'])
if 'renderer' not in field:
value = renderer.render_field... |
<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_attr_text(self):
"""Get html attr text to render in template""" |
return ' '.join([
'{}="{}"'.format(key, value)
for key, value in self.attr.items()
]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def mk_dropdown_tree(cls, model, root_node, for_node=None):
'''
Override of ``treebeard`` method to enforce the same root.
'''
options = []
# The difference is that we only generate the subtree for the current root.
logger.debug("Using root node pk of %s" % root_node.pk)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale_v2(vec, amount):
"""Return a new Vec2 with x and y from vec and multiplied by amount.""" |
return Vec2(vec.x * amount, vec.y * amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dot_v2(vec1, vec2):
"""Return the dot product of two vectors""" |
return vec1.x * vec2.x + vec1.y * vec2.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 cross_v2(vec1, vec2):
"""Return the crossproduct of the two vectors as a Vec2. Cross product doesn't really make sense in 2D, but return the Z component of t... |
return vec1.y * vec2.x - vec1.x * vec2.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 truncate(self, max_length):
"""Truncate this vector so it's length does not exceed max.""" |
if self.length() > max_length:
# If it's longer than the max_length, scale to the max_length.
self.scale(max_length / self.length()) |
<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_scaled_v2(self, amount):
"""Return a new Vec2 with x and y multiplied by amount.""" |
return Vec2(self.x * amount, self.y * amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dot(self, vec):
"""Return the dot product of self and another Vec2.""" |
return self.x * vec.x + self.y * vec.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 cross(self, vec):
"""Return the 2d cross product of self with another vector. Cross product doesn't make sense in 2D, but return the Z component of the 3d re... |
return self.x * vec.y - vec.x * self.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 _get_action(self, action):
""" Retrieve a descriptor for the named action. Caches descriptors for efficiency. """ |
# If we don't have an action named that, bail out
if action not in self.wsgi_actions:
return None
# Generate an ActionDescriptor if necessary
if action not in self.wsgi_descriptors:
self.wsgi_descriptors[action] = actions.ActionDescriptor(
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 _route(self, action, method):
""" Given an action method, generates a route for it. """ |
# First thing, determine the path for the method
path = method._wsgi_path
methods = None
if path is None:
map_rule = self.wsgi_method_map.get(method.__name__)
if map_rule is None:
# Can't connect this method
LOG.warning("No path 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 on_message(self, data):
""" Parsing data, and try to call responding message """ |
# Trying to parse response
data = json.loads(data)
if not data["name"] is None:
logging.debug("%s: receiving message %s" % (data["name"], data["data"]))
fct = getattr(self, "on_" + data["name"])
try:
res = fct(Struct(data["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 join(self, _id):
""" Join a room """ |
if not SockJSRoomHandler._room.has_key(self._gcls() + _id):
SockJSRoomHandler._room[self._gcls() + _id] = set()
SockJSRoomHandler._room[self._gcls() + _id].add(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 leave(self, _id):
""" Leave a room """ |
if SockJSRoomHandler._room.has_key(self._gcls() + _id):
SockJSRoomHandler._room[self._gcls() + _id].remove(self)
if len(SockJSRoomHandler._room[self._gcls() + _id]) == 0:
del SockJSRoomHandler._room[self._gcls() + _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 getRoom(self, _id):
""" Retrieve a room from it's id """ |
if SockJSRoomHandler._room.has_key(self._gcls() + _id):
return SockJSRoomHandler._room[self._gcls() + _id]
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 publishToRoom(self, roomId, name, data, userList=None):
""" Publish to given room data submitted """ |
if userList is None:
userList = self.getRoom(roomId)
# Publish data to all room users
logging.debug("%s: broadcasting (name: %s, data: %s, number of users: %s)" % (self._gcls(), name, data, len(userList)))
self.broadcast(userList, {
"name": name,
"da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publishToOther(self, roomId, name, data):
""" Publish to only other people than myself """ |
tmpList = self.getRoom(roomId)
# Select everybody except me
userList = [x for x in tmpList if x is not self]
self.publishToRoom(roomId, name, data, userList) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publishToMyself(self, roomId, name, data):
""" Publish to only myself """ |
self.publishToRoom(roomId, name, data, [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 isInRoom(self, _id):
""" Check a given user is in given room """ |
if SockJSRoomHandler._room.has_key(self._gcls() + _id):
if self in SockJSRoomHandler._room[self._gcls() + _id]:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readline(self, size=None):
""" Read a line from the stream, including the trailing new line character. If `size` is set, don't read more than `size` bytes, e... |
if self._pos >= self.length:
return ''
if size:
amount = min(size, (self.length - self._pos))
else:
amount = self.length - self._pos
out = self.stream.readline(amount)
self._pos += len(out)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_tag(__matcher: str = 'v[0-9]*', *, strict: bool = True, git_dir: str = '.') -> str: """Find closest tag for a git repository. Note: This defaults to `Sem... |
command = 'git describe --abbrev=12 --dirty'.split()
with chdir(git_dir):
try:
stdout = check_output(command + ['--match={}'.format(__matcher), ])
except CalledProcessError:
if strict:
raise
stdout = check_output(command + ['--always', ])
... |
<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_message(self, *args, accept_query=False, matcher=None, **kwargs):
""" Convenience wrapper of `Client.on_message` pre-bound with `channel=self.name`. """ |
if accept_query:
def new_matcher(msg: Message):
ret = True
if matcher:
ret = matcher(msg)
if ret is None or ret is False:
return ret
if msg.recipient is not self and not isinstance(msg.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 await_message(self, *args, **kwargs) -> 'asyncio.Future[Message]': """ Block until a message matches. See `on_message` """ |
fut = asyncio.Future()
@self.on_message(*args, **kwargs)
async def handler(message):
fut.set_result(message)
# remove handler when done or cancelled
fut.add_done_callback(lambda _: self.remove_message_handler(handler))
return fut |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def await_command(self, *args, **kwargs) -> 'asyncio.Future[IrcMessage]': """ Block until a command matches. See `on_command` """ |
fut = asyncio.Future()
@self.on_command(*args, **kwargs)
async def handler(msg):
fut.set_result(msg)
# remove handler when done or cancelled
fut.add_done_callback(lambda _: self.remove_command_handler(handler))
return fut |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def message(self, recipient: str, text: str, notice: bool=False) -> None: """ Lower level messaging function used by User and Channel """ |
await self._send(cc.PRIVMSG if not notice else cc.NOTICE, recipient, rest=text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bg(self, coro: coroutine) -> asyncio.Task: """Run coro in background, log errors""" |
async def runner():
try:
await coro
except:
self._log.exception("async: Coroutine raised exception")
return asyncio.ensure_future(runner()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _populate(self, client):
""" Populate module with the client when available """ |
self.client = client
for fn in self._buffered_calls:
self._log.debug("Executing buffered call {}".format(fn))
fn() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datatype2schemacls( _datatype, _registry=None, _factory=None, _force=True, _besteffort=True, **kwargs ):
"""Get a schema class which has been associated to i... |
result = None
gdbt = getbydatatype if _registry is None else _registry.getbydatatype
result = gdbt(_datatype, besteffort=_besteffort)
if result is None:
gscls = getschemacls if _factory is None else _factory.getschemacls
result = gscls(_datatype, besteffort=_besteffort)
if resul... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data2schema( _data=None, _force=False, _besteffort=True, _registry=None, _factory=None, _buildkwargs=None, **kwargs ):
"""Get the schema able to instanciate ... |
if _data is None:
return lambda _data: data2schema(
_data, _force=False, _besteffort=True, _registry=None,
_factory=None, _buildkwargs=None, **kwargs
)
result = None
fdata = _data() if isinstance(_data, DynamicValue) else _data
datatype = type(fdata)
cont... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data2schemacls(_data, **kwargs):
"""Convert a data to a schema cls. :param data: object or dictionary from where get a schema cls. :return: schema class. :rt... |
content = {}
for key in list(kwargs): # fill kwargs
kwargs[key] = data2schema(kwargs[key])
if isinstance(_data, dict):
datacontent = iteritems(_data)
else:
datacontent = getmembers(_data)
for name, value in datacontent:
if name[0] == '_':
continue
... |
<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(schema, data, owner=None):
"""Validate input data with input schema. :param Schema schema: schema able to validate input data. :param data: data to ... |
schema._validate(data=data, owner=owner) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(schema):
"""Get a serialized value of input schema. :param Schema schema: schema to serialize. :rtype: dict """ |
result = {}
for name, _ in iteritems(schema.getschemas()):
if hasattr(schema, name):
val = getattr(schema, name)
if isinstance(val, DynamicValue):
val = val()
if isinstance(val, Schema):
val = dump(val)
result[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 updatecontent(schemacls=None, updateparents=True, exclude=None):
"""Transform all schema class attributes to schemas. It can be used such as a decorator in o... |
if schemacls is None:
return lambda schemacls: updatecontent(
schemacls=schemacls, updateparents=updateparents, exclude=exclude
)
if updateparents and hasattr(schemacls, 'mro'):
schemaclasses = reversed(list(schemacls.mro()))
else:
schemaclasses = [schemacls]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_key(self, url):
"""For verifying your API key. Provide the URL of your site or blog you will be checking spam from. """ |
response = self._request('verify-key', {
'blog': url,
'key': self._key
})
if response.status is 200:
# Read response (trimmed of whitespace)
return response.read().strip() == "valid"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comment_check(self, params):
"""For checking comments.""" |
# Check required params for comment-check
for required in ['blog', 'user_ip', 'user_agent']:
if required not in params:
raise MissingParams(required)
response = self._request('comment-check', params)
if response.status is 200:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def submit_ham(self, params):
"""For submitting a ham comment to Akismet.""" |
# Check required params for submit-ham
for required in ['blog', 'user_ip', 'user_agent']:
if required not in params:
raise MissingParams(required)
response = self._request('submit-ham', params)
if response.status is 200:
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 _request(self, function, params, method='POST', headers={}):
"""Builds a request object.""" |
if method is 'POST':
params = urllib.parse.urlencode(params)
headers = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain" }
path = '/%s/%s' % (self._version, function)
self._conn.request(method, path, params, headers)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh_token():
# noqa: E501 """Refreshes login token using refresh token Refreshes login token using refresh token # noqa: E501 :rtype: UserAuth """ |
current_user = get_jwt_identity()
if not current_user:
return ErrorResponse(status=401, message="Not logged in")
access_token = create_access_token(identity=current_user)
return AuthResponse(status=201, message='Refreshed Access Token', access_token=access_token, auth=UserAuth()) |
<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(_resource, _cache=True, **kwargs):
"""Build a schema from input _resource. :param _resource: object from where get the right schema. :param bool _cache... |
return _SCHEMAFACTORY.build(_resource=_resource, _cache=True, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def registerbuilder(self, builder, name=None):
"""Register a schema builder with a key name. Can be used such as a decorator where the builder can be the name fo... |
if name is None:
name = uuid()
self._builders[name] = builder
return builder |
<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(self, _resource, _cache=True, updatecontent=True, **kwargs):
"""Build a schema class from input _resource. :param _resource: object from where get the ... |
result = None
if _cache and _resource in self._schemasbyresource:
result = self._schemasbyresource[_resource]
else:
for builder in self._builders.values():
try:
result = builder.build(_resource=_resource, **kwargs)
e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def stop():
'''Stops lazarus, regardless of which mode it was started in.
For example:
>>> import lazarus
>>> lazarus.default()
>>> lazarus.stop()
'''
global _active
if not _active:
msg = 'lazarus is not active'
raise RuntimeWarning(msg)
_observer.stop()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _restart():
'''Schedule the restart; returning True if cancelled, False otherwise.'''
if _restart_cb:
# https://github.com/formwork-io/lazarus/issues/2
if _restart_cb() is not None:
# restart cancelled
return True
def down_watchdog():
_observer.stop()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def default(restart_cb=None, restart_func=None, close_fds=True):
'''Sets up lazarus in default mode.
See the :py:func:`custom` function for a more powerful mode of use.
The default mode of lazarus is to watch all modules rooted at
``PYTHONPATH`` for changes and restart when they take place.
Keywo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def custom(srcpaths, event_cb=None, poll_interval=1, recurse=True,
restart_cb=None, restart_func=None, close_fds=True):
'''Sets up lazarus in custom mode.
See the :py:func:`default` function for a simpler mode of use.
The custom mode of lazarus is to watch all modules rooted at any of the
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 tty_stream(self):
""" Whether or not our stream is a tty """ |
return hasattr(self.options.stream, "isatty") \
and self.options.stream.isatty() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def color(self):
""" Whether or not color should be output """ |
return self.tty_stream if self.options.color is None \
else self.options.color |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def api_auth(func):
""" If the user is not logged in, this decorator looks for basic HTTP auth data in the request header. """ |
@wraps(func)
def _decorator(request, *args, **kwargs):
authentication = APIAuthentication(request)
if authentication.authenticate():
return func(request, *args, **kwargs)
raise Http404
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 _status_change(id, new_status):
"""Update the status of a job The status associated with the id is updated, an update command is issued to the job's pubsub, ... |
job_info = json.loads(r_client.get(id))
old_status = job_info['status']
job_info['status'] = new_status
_deposit_payload(job_info)
return old_status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deposit_payload(to_deposit):
"""Store job info, and publish an update Parameters to_deposit : dict The job info """ |
pubsub = to_deposit['pubsub']
id = to_deposit['id']
with r_client.pipeline() as pipe:
pipe.set(id, json.dumps(to_deposit), ex=REDIS_KEY_TIMEOUT)
pipe.publish(pubsub, json.dumps({"update": [id]}))
pipe.execute() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _redis_wrap(job_info, func, *args, **kwargs):
"""Wrap something to compute The function that will have available, via kwargs['moi_update_status'], a method t... |
status_changer = partial(_status_change, job_info['id'])
kwargs['moi_update_status'] = status_changer
kwargs['moi_context'] = job_info['context']
kwargs['moi_parent_id'] = job_info['parent']
job_info['status'] = 'Running'
job_info['date_start'] = str(datetime.now())
_deposit_payload(job_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 submit(ctx_name, parent_id, name, url, func, *args, **kwargs):
"""Submit through a context Parameters ctx_name : str The name of the context to submit throug... |
if isinstance(ctx_name, Context):
ctx = ctx_name
else:
ctx = ctxs.get(ctx_name, ctxs[ctx_default])
return _submit(ctx, parent_id, name, url, func, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _submit(ctx, parent_id, name, url, func, *args, **kwargs):
"""Submit a function to a cluster Parameters parent_id : str The ID of the group that the job is a... |
parent_info = r_client.get(parent_id)
if parent_info is None:
parent_info = create_info('unnamed', 'group', id=parent_id)
parent_id = parent_info['id']
r_client.set(parent_id, json.dumps(parent_info))
parent_pubsub_key = parent_id + ':pubsub'
job_info = create_info(name, 'job'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trc(postfix: Optional[str] = None, *, depth=1) -> logging.Logger: """ Automatically generate a logger from the calling function :param postfix: append another... |
x = inspect.stack()[depth]
code = x[0].f_code
func = [obj for obj in gc.get_referrers(code) if inspect.isfunction(obj)][0]
mod = inspect.getmodule(x.frame)
parts = (mod.__name__, func.__qualname__)
if postfix:
parts += (postfix,)
logger_name = '.'.join(parts)
return loggin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _recv_loop(self):
""" Waits for data forever and feeds the input queue. """ |
while True:
try:
data = self._socket.recv(4096)
self._ibuffer += data
while '\r\n' in self._ibuffer:
line, self._ibuffer = self._ibuffer.split('\r\n', 1)
self.iqueue.put(line)
except 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 _send_loop(self):
""" Waits for data in the output queue to send. """ |
while True:
try:
line = self.oqueue.get().splitlines()[0][:500]
self._obuffer += line + '\r\n'
while self._obuffer:
sent = self._socket.send(self._obuffer)
self._obuffer = self._obuffer[sent:]
except... |
<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_socket(self):
""" Creates a new SSL enabled socket and sets its timeout. """ |
log.warning('No certificate check is performed for SSL connections')
s = super(SSL, self)._create_socket()
return wrap_socket(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 load_config(filename):
"""Load the event definitions from yaml config file.""" |
logger.debug("Event Definitions configuration file: %s", filename)
with open(filename, 'r') as cf:
config = cf.read()
try:
events_config = yaml.safe_load(config)
except yaml.YAMLError as err:
if hasattr(err, 'problem_mark'):
mark = err.problem_mark
errm... |
<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_when(body):
"""Extract the generated datetime from the notification.""" |
# NOTE: I am keeping the logic the same as it was in openstack
# code, However, *ALL* notifications should have a 'timestamp'
# field, it's part of the notification envelope spec. If this was
# put here because some openstack project is generating notifications
# without a 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 list_buckets(self, offset=0, limit=100):
"""Limit breaks above 100""" |
# TODO: If limit > 100, do multiple fetches
if limit > 100:
raise Exception("Zenobase can't handle limits over 100")
return self._get("/users/{}/buckets/?order=label&offset={}&limit={}".format(self.client_id, offset, 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 _create_table(db, table_name, columns, overwrite=False):
""" Create's `table_name` in `db` if it does not already exist, and adds any missing columns. :param... |
with contextlib.closing(db.cursor()) as c:
table_exists = c.execute((
u'SELECT EXISTS(SELECT 1 FROM sqlite_master'
u' WHERE type="table" and name=?) as "exists"'
), (table_name,)).fetchone()
if table_exists['exists']:
if not overwrite:
ra... |
<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_colorbox():
"""Update Colorbox code from vendor tree""" |
base_name = os.path.dirname(__file__)
destination = os.path.join(base_name, "armstrong", "apps", "images", "static", "colorbox")
colorbox_source = os.path.join(base_name, "vendor", "colorbox")
colorbox_files = [
os.path.join(colorbox_source, "example1", "colorbox.css"),
os.path.join(col... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def environment_variables_for_task(task):
""" This will build a dict with all the environment variables that should be present when running a build or deployment... |
env = {
'CI': 'frigg',
'FRIGG': 'true',
'FRIGG_CI': 'true',
'GH_TOKEN': task['gh_token'],
'FRIGG_BUILD_BRANCH': task['branch'],
'FRIGG_BUILD_COMMIT_HASH': task['sha'],
'FRIGG_BUILD_DIR': '~/builds/{0}'.format(task['id']),
'FRIGG_BUILD_ID': task['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 hkdf(self, chaining_key, input_key_material, dhlen=64):
"""Hash-based key derivation function Takes a ``chaining_key'' byte sequence of len HASHLEN, and an `... |
if len(chaining_key) != self.HASHLEN:
raise HashError("Incorrect chaining key length")
if len(input_key_material) not in (0, 32, dhlen):
raise HashError("Incorrect input key material length")
temp_key = self.hmac_hash(chaining_key, input_key_material)
output1 = ... |
<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, val):
"""Append byte string val to buffer If the result exceeds the length of the buffer, behavior depends on whether instance was initialized a... |
new_len = self.length + len(val)
to_add = new_len - len(self.bfr)
if self.strict and to_add > 0:
raise ValueError("Cannot resize buffer")
self.bfr[self.length:new_len] = val
self.length = new_len |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addr_info(addr):
""" Interprets an address in standard tuple format to determine if it is valid, and, if so, which socket family it is. Returns the socket fa... |
# If it's a string, it's in the UNIX family
if isinstance(addr, basestring):
return socket.AF_UNIX
# Verify that addr is a tuple
if not isinstance(addr, collections.Sequence):
raise ValueError("address is not a tuple")
# Make sure it has at least 2 fields
if len(addr) < 2:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_labels(X):
"""Helper function that generates a single 1D numpy.ndarray with labels which are good targets for stock logistic regression. Parameters: X (... |
return numpy.hstack([k*numpy.ones(len(X[k]), dtype=int) for k in range(len(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 add_bias(X):
"""Helper function to add a bias column to the input array X Parameters: X (numpy.ndarray):
The input data matrix. This must be a numpy.ndarray... |
return numpy.hstack((numpy.ones((len(X),1), dtype=X.dtype), X)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.