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 find_cookie(self):
""" Find a list of all cookies for a given domain """ |
return_cookies = []
origin_domain = self.request_object.dest_addr
for cookie in self.cookiejar:
for cookie_morsals in cookie[0].values():
cover_domain = cookie_morsals['domain']
if cover_domain == '':
if origin_domain == cookie[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 get_response(self):
""" Get the response from the socket """ |
self.sock.setblocking(0)
our_data = []
# Beginning time
begin = time.time()
while True:
# If we have data then if we're passed the timeout break
if our_data and time.time() - begin > self.HTTP_TIMEOUT:
break
# If we're dataless... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_regex(self, key):
""" Extract the value of key from dictionary if available and process it as a python regex """ |
return re.compile(self.output_dict[key]) if \
key in self.output_dict 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 instantiate_database(sqlite_file='ftwj.sqlite'):
""" Create journal database for FTW runs """ |
table_name = 'ftw'
col1 = 'rule_id'
col1_t = 'INTEGER'
col2 = 'test_id'
col2_t = 'STRING'
col3 = 'time_start'
col3_t = 'TEXT'
col4 = 'time_end'
col4_t = 'TEXT'
col5 = 'response_blob'
col5_t = 'TEXT'
col6 = 'status_code'
col6_t = 'INTEGER'
col7 = 'stage'
col7_... |
<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_rulesets(ruledir, recurse):
""" List of ruleset objects extracted from the yaml directory """ |
if os.path.isdir(ruledir) and recurse:
yaml_files = [y for x in os.walk(ruledir) for y in glob(os.path.join(x[0], '*.yaml'))]
elif os.path.isdir(ruledir) and not recurse:
yaml_files = get_files(ruledir, 'yaml')
elif os.path.isfile(ruledir):
yaml_files = [ruledir]
extracted_files... |
<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_yaml(yaml_files):
""" Take a list of yaml_files and load them to return back to the testing program """ |
loaded_yaml = []
for yaml_file in yaml_files:
try:
with open(yaml_file, 'r') as fd:
loaded_yaml.append(yaml.safe_load(fd))
except IOError as e:
print('Error reading file', yaml_file)
raise e
except yaml.YAMLError as e:
prin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deserialize(cls, raw_bytes):
""" Deserializes the given raw bytes into an instance. Since this is a subclass of ``Part`` but a top-level one (i.e. no other s... |
instance, _ = cls.parse(raw_bytes, offset=0)
return instance |
<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(self, parts=None):
""" Returns a two-element tuple with the ``struct`` format and values. Iterates over the applicable sub-parts and calls `render()` ... |
if not parts:
parts = self.parts
fmt = []
data = []
for name, part_class in parts:
if issubclass(part_class, Primitive):
part = part_class(getattr(self, name, None))
else:
part = getattr(self, name, 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 render(self):
""" Returns the ``struct`` format and list of the size and value. The format is derived from the size primitive and the length of the resulting... |
size_format = self.size_primitive.fmt
if self.value is None:
return size_format, [-1]
value = self.render_value(self.value)
size = len(value)
fmt = "%s%ds" % (size_format, size)
return fmt, [size, 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 of(cls, part_class):
""" Creates a new class with the ``item_class`` attribute properly set. """ |
copy = type(
"VectorOf%s" % part_class.__name__,
cls.__bases__, dict(cls.__dict__)
)
copy.item_class = part_class
return copy |
<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(self):
""" Creates a composite ``struct`` format and the data to render with it. The format and data are prefixed with a 32-bit integer denoting the n... |
value = self.value
if value is None:
value = []
fmt = [Int.fmt]
data = [len(value)]
for item_value in value:
if issubclass(self.item_class, Primitive):
item = self.item_class(item_value)
else:
item = item_valu... |
<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(cls, buff, offset):
""" Parses a raw buffer at offset and returns the resulting array value. Starts off by `parse()`-ing the 32-bit element count, foll... |
count, offset = Int.parse(buff, offset)
values = []
for _ in range(count):
value, new_offset = cls.item_class.parse(buff, offset)
values.append(value)
offset = new_offset
return values, offset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def round_robin(members, items):
""" Default allocator with a round robin approach. In this algorithm, each member of the group is cycled over and given an item ... |
allocation = collections.defaultdict(set)
for member, item in zip(itertools.cycle(members), items):
allocation[member].add(item)
return allocation |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xfrange(start, stop, step=1, maxSize=-1):
""" Returns a generator that yields the frames from start to stop, inclusive. In other words it adds or subtracts a... |
if start <= stop:
stop, step = stop + 1, abs(step)
else:
stop, step = stop - 1, -abs(step)
if maxSize >= 0:
size = lenRange(start, stop, step)
if size > maxSize:
raise exceptions.MaxSizeException(
"Size %d > %s (MAX_FRAME_SIZE)" % (size, maxSize)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unique(seen, *iterables):
""" Get the unique items in iterables while preserving order. Note that this mutates the seen set provided only when the returned g... |
_add = seen.add
# return a generator of the unique items and the set of the seen items
# the seen set will mutate when the generator is iterated over
return (i for i in chain(*iterables) if i not in seen and not _add(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 copy(self):
""" Create a deep copy of this sequence Returns: :obj:`.FileSequence`: """ |
fs = self.__class__.__new__(self.__class__)
fs.__dict__ = self.__dict__.copy()
fs._frameSet = None
if self._frameSet is not None:
fs._frameSet = self._frameSet.copy()
return fs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format(self, template="{basename}{range}{padding}{extension}"):
"""Return the file sequence as a formatted string according to the given template. Utilizes t... |
# Potentially expensive if inverted range is large
# and user never asked for it in template
inverted = (self.invertedFrameRange() or "") if "{inverted}" in template else ""
return template.format(
basename=self.basename(),
extension=self.extension(), start=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 setDirname(self, dirname):
""" Set a new directory name for the sequence. Args: dirname (str):
the new directory name """ |
# Make sure the dirname always ends in
# a path separator character
sep = utils._getPathSep(dirname)
if not dirname.endswith(sep):
dirname += sep
self._dir = utils.asString(dirname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setExtension(self, ext):
""" Set a new file extension for the sequence. Note: A leading period will be added if none is provided. Args: ext (str):
the new f... |
if ext[0] != ".":
ext = "." + ext
self._ext = utils.asString(ext) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frame(self, frame):
""" Return a path go the given frame in the sequence. Integer or string digits are treated as a frame number and padding is applied, all ... |
try:
zframe = str(int(frame)).zfill(self._zfill)
except ValueError:
zframe = frame
# There may have been no placeholder for frame IDs in
# the sequence, in which case we don't want to insert
# a frame ID
if self._zfill == 0:
zframe =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yield_sequences_in_list(paths):
""" Yield the discrete sequences within paths. This does not try to determine if the files actually exist on disk, it assumes... |
seqs = {}
_check = DISK_RE.match
for match in ifilter(None, imap(_check, imap(utils.asString, paths))):
dirname, basename, frame, ext = match.groups()
if not basename and not ext:
continue
key = (dirname, basename, ext)
seqs.setde... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findSequencesOnDisk(cls, pattern, include_hidden=False, strictPadding=False):
""" Yield the sequences found in the given directory. Examples: The `pattern` c... |
# reserve some functions we're going to need quick access to
_not_hidden = lambda f: not f.startswith('.')
_match_pattern = None
_filter_padding = None
_join = os.path.join
seq = None
dirpath = pattern
# Support the pattern defining a filter for the fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findSequenceOnDisk(cls, pattern, strictPadding=False):
""" Search for a specific sequence on disk. The padding characters used in the `pattern` are used to f... |
seq = cls(pattern)
if seq.frameRange() == '' and seq.padding() == '':
if os.path.isfile(pattern):
return seq
patt = seq.format('{dirname}{basename}*{extension}')
ext = seq.extension()
basename = seq.basename()
pad = seq.padding()
g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _filterByPaddingNum(cls, iterable, num):
""" Yield only path elements from iterable which have a frame padding that matches the given target padding number A... |
_check = DISK_RE.match
for item in iterable:
# Add a filter for paths that don't match the frame
# padding of a given number
matches = _check(item)
if not matches:
if num <= 0:
# Not a sequence pattern, but we were ask... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getPaddingNum(chars):
""" Given a supported group of padding characters, return the amount of padding. Args: chars (str):
a supported group of padding chara... |
match = PRINTF_SYNTAX_PADDING_RE.match(chars)
if match:
return int(match.group(1))
try:
return sum([PAD_MAP[char] for char in chars])
except KeyError:
msg = "Detected an unsupported padding character: \"{}\"."
msg += " Supported padding c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conformPadding(cls, chars):
""" Ensure alternate input padding formats are conformed to formats defined in PAD_MAP If chars is already a format defined in PA... |
pad = chars
if pad and pad[0] not in PAD_MAP:
pad = cls.getPaddingChars(cls.getPaddingNum(pad))
return pad |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cast_to_frameset(cls, other):
""" Private method to simplify comparison operations. Args: other (:class:`FrameSet` or set or frozenset or or iterable):
ite... |
if isinstance(other, FrameSet):
return other
try:
return FrameSet(other)
except Exception:
return NotImplemented |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def issubset(self, other):
""" Check if the contents of `self` is a subset of the contents of `other.` Args: other (:class:`FrameSet`):
Returns: bool: :class:`N... |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items <= other.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 issuperset(self, other):
""" Check if the contents of `self` is a superset of the contents of `other.` Args: other (:class:`FrameSet`):
Returns: bool: :clas... |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items >= other.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 _maxSizeCheck(cls, obj):
""" Raise a MaxSizeException if ``obj`` exceeds MAX_FRAME_SIZE Args: obj (numbers.Number or collection):
Raises: :class:`fileseq.ex... |
fail = False
size = 0
if isinstance(obj, numbers.Number):
if obj > constants.MAX_FRAME_SIZE:
fail = True
size = obj
elif hasattr(obj, '__len__'):
size = len(obj)
fail = size > constants.MAX_FRAME_SIZE
if fail... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def padFrameRange(frange, zfill):
""" Return the zero-padded version of the frame range string. Args: frange (str):
a frame range to test zfill (int):
Returns:... |
def _do_pad(match):
"""
Substitutes padded for unpadded frames.
"""
result = list(match.groups())
result[1] = pad(result[1], zfill)
if result[4]:
result[4] = pad(result[4], zfill)
return ''.join((i for i in resu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def framesToFrameRanges(frames, zfill=0):
""" Converts a sequence of frames to a series of padded frame range strings. Args: frames (collections.Iterable):
sequ... |
_build = FrameSet._build_frange_part
curr_start = None
curr_stride = None
curr_frame = None
last_frame = None
curr_count = 0
for curr_frame in frames:
if curr_start is None:
curr_start = curr_frame
last_frame = curr_fra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def framesToFrameRange(frames, sort=True, zfill=0, compress=False):
""" Converts an iterator of frames into a frame range string. Args: frames (collections.Itera... |
if compress:
frames = unique(set(), frames)
frames = list(frames)
if not frames:
return ''
if len(frames) == 1:
return pad(frames[0], zfill)
if sort:
frames.sort()
return ','.join(FrameSet.framesToFrameRanges(frames, zfill)... |
<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_optional_params(self, oauth_params, req_kwargs):
'''
Parses and sets optional OAuth parameters on a request.
:param oauth_param: The OAuth parameter to parse.
:type oauth_param: str
:param req_kwargs: The keyworded arguments passed to the request
method.
... |
<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_oauth_params(self, req_kwargs):
'''Prepares OAuth params for signing.'''
oauth_params = {}
oauth_params['oauth_consumer_key'] = self.consumer_key
oauth_params['oauth_nonce'] = sha1(
str(random()).encode('ascii')).hexdigest()
oauth_params['oauth_signature_met... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sign(url, app_id, app_secret, hash_meth='sha1', **params):
'''
A signature method which generates the necessary Ofly parameters.
:param app_id: The oFlyAppId, i.e. "application ID".
:type app_id: str
:param app_secret: The oFlyAppSecret, i.e. "shared secret".
:type a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_auth_header(self):
''' Constructs and returns an authentication header. '''
realm = 'realm="{realm}"'.format(realm=self.realm)
params = ['{k}="{v}"'.format(k=k, v=quote(str(v), safe=''))
for k, v in self.oauth_params.items()]
return 'OAuth ' + ','.join([realm] ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _remove_qs(self, url):
'''
Removes a query string from a URL before signing.
:param url: The URL to strip.
:type url: str
'''
scheme, netloc, path, query, fragment = urlsplit(url)
return urlunsplit((scheme, netloc, path, '', fragment)) |
<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_request_parameters(self, oauth_params, req_kwargs):
'''
This process normalizes the request parameters as detailed in the OAuth
1.0 spec.
Additionally we apply a `Content-Type` header to the request of the
`FORM_URLENCODE` type if the `Content-Type` was previously... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sign(self, consumer_secret, access_token_secret, method, url,
oauth_params, req_kwargs):
'''Sign request using PLAINTEXT method.
:param consumer_secret: Consumer secret.
:type consumer_secret: str
:param access_token_secret: Access token secret (optional).
:type... |
<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_request_token(self,
method='GET',
decoder=parse_utf8_qsl,
key_token='oauth_token',
key_token_secret='oauth_token_secret',
**kwargs):
'''
Return a request token pair.
... |
<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_access_token(self,
request_token,
request_token_secret,
method='GET',
decoder=parse_utf8_qsl,
key_token='oauth_token',
key_token_secret='oauth_token_secret',
... |
<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_access_token(self,
method='POST',
decoder=parse_utf8_qsl,
key='access_token',
**kwargs):
'''
Returns an access token.
:param method: A string representation of the HTTP method to be used,... |
<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_logged_in(username=None):
"""Checks if user is logged in if `username` is passed check if specified user is logged in username can be a list""" |
if username:
if not isinstance(username, (list, tuple)):
username = [username]
return 'simple_logged_in' in session and get_username() in username
return 'simple_logged_in' in session |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login_required(function=None, username=None, basic=False, must=None):
"""Decorate views to require login @login_required @login_required() @login_required(us... |
if function and not callable(function):
raise ValueError(
'Decorator receives only named arguments, '
'try login_required(username="foo")'
)
def check(validators):
"""Return in the first validation error, else return None"""
if validators is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_message(message, *args, **kwargs):
"""Helper to get internal messages outside this instance""" |
msg = current_app.extensions['simplelogin'].messages.get(message)
if msg and (args or kwargs):
return msg.format(*args, **kwargs)
return msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_my_users(user):
"""Check if user exists and its credentials. Take a look at encrypt_app.py and encrypt_cli.py to see how to encrypt passwords """ |
user_data = my_users.get(user['username'])
if not user_data:
return False # <--- invalid credentials
elif user_data.get('password') == user['password']:
return True # <--- user is logged in!
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 create_user(**data):
"""Creates user with encrypted password""" |
if 'username' not in data or 'password' not in data:
raise ValueError('username and password are required.')
# Hash the user password
data['password'] = generate_password_hash(
data.pop('password'),
method='pbkdf2:sha256'
)
# Here you insert the `data` in your users databa... |
<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_app(f):
"""Calls function passing app as first argument""" |
@wraps(f)
def decorator(*args, **kwargs):
app = create_app()
configure_extensions(app)
configure_views(app)
return f(app=app, *args, **kwargs)
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 adduser(app, username, password):
"""Add new user with admin access""" |
with app.app_context():
create_user(username=username, password=password)
click.echo('user created!') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pulse_data(self, value):
"""Pulse the `enable` flag to process value.""" |
if self._i2c_expander == 'PCF8574':
self.bus.write_byte(self._address, ((value & ~PCF8574_E) | self._backlight))
c.usleep(1)
self.bus.write_byte(self._address, value | PCF8574_E | self._backlight)
c.usleep(1)
self.bus.write_byte(self._address, ((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 _write4bits(self, value):
"""Write 4 bits of data into the data bus.""" |
for i in range(4):
bit = (value >> i) & 0x01
GPIO.output(self.pins[i + 7], bit)
self._pulse_enable() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pulse_enable(self):
"""Pulse the `enable` flag to process data.""" |
GPIO.output(self.pins.e, 0)
c.usleep(1)
GPIO.output(self.pins.e, 1)
c.usleep(1)
GPIO.output(self.pins.e, 0)
c.usleep(100) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_string(self, value):
""" Write the specified unicode string to the display. To control multiline behavior, use newline (``\\n``) and carriage return (`... |
encoded = self.codec.encode(value) # type: List[int]
ignored = False
for [char, lookahead] in c.sliding_window(encoded, lookahead=1):
# If the previous character has been ignored, skip this one too.
if ignored is True:
ignored = False
c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
"""Overwrite display with blank characters and reset cursor position.""" |
self.command(c.LCD_CLEARDISPLAY)
self._cursor_pos = (0, 0)
self._content = [[0x20] * self.lcd.cols for _ in range(self.lcd.rows)]
c.msleep(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 home(self):
"""Set cursor to initial position and reset any shifting.""" |
self.command(c.LCD_RETURNHOME)
self._cursor_pos = (0, 0)
c.msleep(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 shift_display(self, amount):
"""Shift the display. Use negative amounts to shift left and positive amounts to shift right.""" |
if amount == 0:
return
direction = c.LCD_MOVERIGHT if amount > 0 else c.LCD_MOVELEFT
for i in range(abs(amount)):
self.command(c.LCD_CURSORSHIFT | c.LCD_DISPLAYMOVE | direction)
c.usleep(50) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, value):
# type: (int) -> None """Write a raw byte to the LCD.""" |
# Get current position
row, col = self._cursor_pos
# Write byte if changed
try:
if self._content[row][col] != value:
self._send_data(value)
self._content[row][col] = value # Update content cache
unchanged = 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 cursor(lcd, row, col):
""" Context manager to control cursor position. DEPRECATED. """ |
warnings.warn('The `cursor` context manager is deprecated', DeprecationWarning)
lcd.cursor_pos = (row, col)
yield |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sliding_window(seq, lookahead):
""" Create a sliding window with the specified number of lookahead characters. """ |
it = itertools.chain(iter(seq), ' ' * lookahead) # Padded iterator
window_size = lookahead + 1
result = tuple(itertools.islice(it, window_size))
if len(result) == window_size:
yield result
for elem in it:
result = result[1:] + (elem,)
yield 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_params():
""" get the cmdline params """ |
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=float,
default=10.0,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_unbuffered_mode():
""" make output unbuffered """ |
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = Unbuffered(sys.stdou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(cls, acl):
""" transform an ACL to a dict """ |
return {
"perms": acl.perms,
"id": {
"scheme": acl.id.scheme,
"id": acl.id.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 from_dict(cls, acl_dict):
""" ACL from dict """ |
perms = acl_dict.get("perms", Permissions.ALL)
id_dict = acl_dict.get("id", {})
id_scheme = id_dict.get("scheme", "world")
id_id = id_dict.get("id", "anyone")
return ACL(perms, Id(id_scheme, id_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 connected(func):
""" check connected, fails otherwise """ |
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if not self.connected:
self.show_output("Not connected.")
else:
try:
return func(*args, **kwargs)
except APIError:
self.show_output("ZooKeeper internal error.")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_add_auth(self, params):
""" \x1b[1mNAME\x1b[0m add_auth - Authenticates the session \x1b[1mSYNOPSIS\x1b[0m add_auth <scheme> <credential> \x1b[1mEXAMPLES\... |
self._zk.add_auth(params.scheme, params.credential) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_set_acls(self, params):
""" \x1b[1mNAME\x1b[0m set_acls - Sets ACLs for a given path \x1b[1mSYNOPSIS\x1b[0m set_acls <path> <acls> [recursive] \x1b[1mOPTI... |
try:
acls = ACLReader.extract(shlex.split(params.acls))
except ACLReader.BadACL as ex:
self.show_output("Failed to set ACLs: %s.", ex)
return
def set_acls(path):
try:
self._zk.set_acls(path, acls)
except (NoNodeError, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_get_acls(self, params):
""" \x1b[1mNAME\x1b[0m get_acls - Gets ACLs for a given path \x1b[1mSYNOPSIS\x1b[0m get_acls <path> [depth] [ephemerals] \x1b[1mOP... |
def replace(plist, oldv, newv):
try:
plist.remove(oldv)
plist.insert(0, newv)
except ValueError:
pass
for path, acls in self._zk.get_acls_recursive(params.path, params.depth, params.ephemerals):
replace(acls, READ_ACL_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_watch(self, params):
""" \x1b[1mNAME\x1b[0m watch - Recursively watch for all changes under a path. \x1b[1mSYNOPSIS\x1b[0m watch <start|stop|stats> <path>... |
wm = get_watch_manager(self._zk)
if params.command == "start":
debug = to_bool(params.debug)
children = to_int(params.sleep, -1)
wm.add(params.path, debug, children)
elif params.command == "stop":
wm.remove(params.path)
elif params.command... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_child_count(self, params):
""" \x1b[1mNAME\x1b[0m child_count - Prints the child count for paths \x1b[1mSYNOPSIS\x1b[0m child_count [path] [depth] \x1b[1m... |
for child, level in self._zk.tree(params.path, params.depth, full_path=True):
self.show_output("%s: %d", child, self._zk.child_count(child)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_du(self, params):
""" \x1b[1mNAME\x1b[0m du - Total number of bytes under a path \x1b[1mSYNOPSIS\x1b[0m du [path] \x1b[1mOPTIONS\x1b[0m * path: the path (... |
self.show_output(pretty_bytes(self._zk.du(params.path))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_find(self, params):
""" \x1b[1mNAME\x1b[0m find - Find znodes whose path matches a given text \x1b[1mSYNOPSIS\x1b[0m find [path] [match] \x1b[1mOPTIONS\x1... |
for path in self._zk.find(params.path, params.match, 0):
self.show_output(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_summary(self, params):
""" \x1b[1mNAME\x1b[0m summary - Prints summarized details of a path's children \x1b[1mSYNOPSIS\x1b[0m summary [path] [top] \x1b[1m... |
self.show_output("%s%s%s%s",
"Created".ljust(32),
"Last modified".ljust(32),
"Owner".ljust(23),
"Name")
results = sorted(self._zk.stat_map(params.path))
# what slice do we want?
if par... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_grep(self, params):
""" \x1b[1mNAME\x1b[0m grep - Prints znodes with a value matching the given text \x1b[1mSYNOPSIS\x1b[0m grep [path] <content> [show_ma... |
self.grep(params.path, params.content, 0, params.show_matches) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_get(self, params):
""" \x1b[1mNAME\x1b[0m get - Gets the znode's value \x1b[1mSYNOPSIS\x1b[0m get <path> [watch] \x1b[1mOPTIONS\x1b[0m * watch: set a (dat... |
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
value, _ = self._zk.get(params.path, **kwargs)
# maybe it's compressed?
if value is not None:
try:
value = zlib.decompress(value)
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 do_exists(self, params):
""" \x1b[1mNAME\x1b[0m exists - Gets the znode's stat information \x1b[1mSYNOPSIS\x1b[0m exists <path> [watch] [pretty_date] \x1b[1m... |
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
pretty = params.pretty_date
path = self.resolve_path(params.path)
stat = self._zk.exists(path, **kwargs)
if stat:
session = stat.ephemeralOwner if stat.epheme... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_create(self, params):
""" \x1b[1mNAME\x1b[0m create - Creates a znode \x1b[1mSYNOPSIS\x1b[0m create <path> <value> [ephemeral] [sequence] [recursive] [asy... |
try:
kwargs = {"acl": None, "ephemeral": params.ephemeral, "sequence": params.sequence}
if not self.in_transaction:
kwargs["makepath"] = params.recursive
if params.asynchronous and not self.in_transaction:
self.client_context.create_async(par... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_set(self, params):
""" \x1b[1mNAME\x1b[0m set - Updates the znode's value \x1b[1mSYNOPSIS\x1b[0m set <path> <value> [version] \x1b[1mOPTIONS\x1b[0m * vers... |
self.set(params.path, decoded(params.value), version=params.version) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, path, value, version):
""" sets a znode's data """ |
if self.in_transaction:
self.client_context.set_data(path, value, version=version)
else:
self.client_context.set(path, value, version=version) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_rm(self, params):
""" \x1b[1mNAME\x1b[0m rm - Remove the znode \x1b[1mSYNOPSIS\x1b[0m \x1b[1mEXAMPLES\x1b[0m > rm /foo > rm /foo /bar """ |
for path in params.paths:
try:
self.client_context.delete(path)
except NotEmptyError:
self.show_output("%s is not empty.", path)
except NoNodeError:
self.show_output("%s doesn't exist.", path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_txn(self, params):
""" \x1b[1mNAME\x1b[0m txn - Create and execute a transaction \x1b[1mSYNOPSIS\x1b[0m \x1b[1mDESCRIPTION\x1b[0m Allowed cmds are check, ... |
try:
with self.transaction():
for cmd in params.cmds:
try:
self.onecmd(cmd)
except AttributeError:
# silently swallow unrecognized commands
pass
except BadVersionE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_session_info(self, params):
""" \x1b[1mNAME\x1b[0m session_info - Shows information about the current session \x1b[1mSYNOPSIS\x1b[0m session_info [match] ... |
fmt_str = """state=%s
sessionid=%s
auth_info=%s
protocol_version=%d
xid=%d
last_zxid=0x%.16x
timeout=%d
client=%s
server=%s
data_watches=%s
child_watches=%s"""
content = fmt_str % (
self._zk.client_state,
self._zk.sessionid,
list(self._zk.auth_data),
self._zk... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_mntr(self, params):
""" \x1b[1mNAME\x1b[0m mntr - Executes the mntr four-letter command \x1b[1mSYNOPSIS\x1b[0m mntr [hosts] [match] \x1b[1mOPTIONS\x1b[0m ... |
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_cons(self, params):
""" \x1b[1mNAME\x1b[0m cons - Executes the cons four-letter command \x1b[1mSYNOPSIS\x1b[0m cons [hosts] [match] \x1b[1mOPTIONS\x1b[0m ... |
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_dump(self, params):
""" \x1b[1mNAME\x1b[0m dump - Executes the dump four-letter command \x1b[1mSYNOPSIS\x1b[0m dump [hosts] [match] \x1b[1mOPTIONS\x1b[0m ... |
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_rmr(self, params):
""" \x1b[1mNAME\x1b[0m rmr - Delete a path and all its children \x1b[1mSYNOPSIS\x1b[0m \x1b[1mEXAMPLES\x1b[0m > rmr /foo > rmr /foo /ba... |
for path in params.paths:
self._zk.delete(path, recursive=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_child_watch(self, params):
""" \x1b[1mNAME\x1b[0m child_watch - Watch a path for child changes \x1b[1mSYNOPSIS\x1b[0m child_watch <path> [verbose] \x1b[1m... |
get_child_watcher(self._zk, print_func=self.show_output).update(
params.path, params.verbose) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_diff(self, params):
""" \x1b[1mNAME\x1b[0m diff - Display the differences between two paths \x1b[1mSYNOPSIS\x1b[0m diff <src> <dst> \x1b[1mDESCRIPTION\x1b... |
count = 0
for count, (diff, path) in enumerate(self._zk.diff(params.path_a, params.path_b), 1):
if diff == -1:
self.show_output("-- %s", path)
elif diff == 0:
self.show_output("-+ %s", path)
elif diff == 1:
self.show_ou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_json_valid(self, params):
""" \x1b[1mNAME\x1b[0m json_valid - Checks znodes for valid JSON \x1b[1mSYNOPSIS\x1b[0m json_valid <path> [recursive] \x1b[1mOPT... |
def check_valid(path, print_path):
result = "no"
value, _ = self._zk.get(path)
if value is not None:
try:
x = json.loads(value)
result = "yes"
except ValueError:
pass
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_json_cat(self, params):
""" \x1b[1mNAME\x1b[0m json_cat - Pretty prints a znode's JSON \x1b[1mSYNOPSIS\x1b[0m json_cat <path> [recursive] \x1b[1mOPTIONS\x... |
def json_output(path, print_path):
value, _ = self._zk.get(path)
if value is not None:
try:
value = json.dumps(json.loads(value), indent=4)
except ValueError:
pass
if print_path:
self.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 do_json_count_values(self, params):
""" \x1b[1mNAME\x1b[0m json_count_values - Gets the frequency of the values associated with the given keys \x1b[1mSYNOPSI... |
try:
Keys.validate(params.keys)
except Keys.Bad as ex:
self.show_output(str(ex))
return
path_map = PathMap(self._zk, params.path)
values = defaultdict(int)
for path, data in path_map.get():
try:
value = Keys.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 do_json_dupes_for_keys(self, params):
""" \x1b[1mNAME\x1b[0m json_duples_for_keys - Gets the duplicate znodes for the given keys \x1b[1mSYNOPSIS\x1b[0m json_... |
try:
Keys.validate(params.keys)
except Keys.Bad as ex:
self.show_output(str(ex))
return
path_map = PathMap(self._zk, params.path)
dupes_by_path = defaultdict(lambda: defaultdict(list))
for path, data in path_map.get():
parent, ch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_edit(self, params):
""" \x1b[1mNAME\x1b[0m edit - Opens up an editor to modify and update a znode. \x1b[1mSYNOPSIS\x1b[0m edit <path> \x1b[1mDESCRIPTION\x... |
if os.getuid() == 0:
self.show_output("edit cannot be run as root.")
return
editor = os.getenv("EDITOR", os.getenv("VISUAL", "/usr/bin/vi"))
if editor is None:
self.show_output("No editor found, please set $EDITOR")
return
editor = which... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_loop(self, params):
""" \x1b[1mNAME\x1b[0m loop - Runs commands in a loop \x1b[1mSYNOPSIS\x1b[0m \x1b[1mDESCRIPTION\x1b[0m Runs <cmds> <repeat> times (0 m... |
repeat = params.repeat
if repeat < 0:
self.show_output("<repeat> must be >= 0.")
return
pause = params.pause
if pause < 0:
self.show_output("<pause> must be >= 0.")
return
cmds = params.cmds
i = 0
with self.transi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_fill(self, params):
""" \x1b[1mNAME\x1b[0m fill - Fills a znode with the given value \x1b[1mSYNOPSIS\x1b[0m fill <path> <char> <count> \x1b[1mEXAMPLES\x1b... |
self._zk.set(params.path, decoded(params.val * params.repeat)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_time(self, params):
""" \x1b[1mNAME\x1b[0m time - Measures elapsed seconds after running commands \x1b[1mSYNOPSIS\x1b[0m \x1b[1mEXAMPLES\x1b[0m > time 'lo... |
start = time.time()
for cmd in params.cmds:
try:
self.onecmd(cmd)
except Exception as ex:
self.show_output("Command failed: %s.", ex)
elapsed = "{0:.5f}".format(time.time() - start)
self.show_output("Took %s seconds" % elapsed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_echo(self, params):
""" \x1b[1mNAME\x1b[0m echo - displays formatted data \x1b[1mSYNOPSIS\x1b[0m \x1b[1mEXAMPLES\x1b[0m > echo hello hello > echo 'The val... |
values = []
with self.output_context() as context:
for cmd in params.cmds:
rv = self.onecmd(cmd)
val = "" if rv is False else context.value.rstrip("\n")
values.append(val)
context.reset()
try:
self.show_ou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connected_socket(address, timeout=3):
""" yields a connected socket """ |
sock = socket.create_connection(address, timeout)
yield sock
sock.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bytes(self, *args, **kwargs):
""" no string decoding performed """ |
return super(XClient, self).get(*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 get_acls_recursive(self, path, depth, include_ephemerals):
"""A recursive generator wrapper for get_acls :param path: path from which to start :param depth: ... |
yield path, self.get_acls(path)[0]
if depth == -1:
return
for tpath, _ in self.tree(path, depth, full_path=True):
try:
acls, stat = self.get_acls(tpath)
except NoNodeError:
continue
if not include_ephemerals and ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.