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 alloc_data(self, value): """ Allocate a piece of data that will be included in the shellcode body. Arguments: string type. Returns: ~pwnypack.types.Offset: T...
if isinstance(value, six.binary_type): return self._alloc_data(value) elif isinstance(value, six.text_type): return self._alloc_data(value.encode('utf-8') + b'\0') else: raise TypeError('No idea how to encode %s' % repr(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 compile(self, ops): """ Translate a list of operations into its assembler source. Arguments: ops(list): A list of shellcode operations. Returns: str: The as...
def _compile(): code = [] for op in ops: if isinstance(op, SyscallInvoke): code.extend(self.syscall(op)) elif isinstance(op, LoadRegister): code.extend(self.reg_load(op.register, op.value)) elif is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assemble(self, ops): """ Assemble a list of operations into executable code. Arguments: ops(list): A list of shellcode operations. Returns: bytes: The execu...
return pwnypack.asm.asm(self.compile(ops), target=self.target)
<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_nearest_index(arr, value): """For a given value, the function finds the nearest value in the array and returns its index."""
arr = np.array(arr) index = (abs(arr-value)).argmin() return index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill(self): """ Shut down the socket immediately. """
self._socket.shutdown(socket.SHUT_RDWR) self._socket.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 read_eof(self, echo=None): """ Read until the channel is closed. Args: echo(bool): Whether to write the read data to stdout. Returns: bytes: The read data. ...
d = b'' while True: try: d += self.read(1, echo) except EOFError: return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_until(self, s, echo=None): """ Read until a certain string is encountered.. Args: s(bytes): The string to wait for. echo(bool): Whether to write the r...
s_len = len(s) buf = self.read(s_len, echo) while buf[-s_len:] != s: buf += self.read(1, echo) return buf
<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, data, echo=None): """ Write data to channel. Args: data(bytes): The data to write to the channel. echo(bool): Whether to echo the written data ...
if echo or (echo is None and self.echo): sys.stdout.write(data.decode('latin1')) sys.stdout.flush() self.channel.write(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 writeline(self, line=b'', sep=b'\n', echo=None): """ Write a byte sequences to the channel and terminate it with carriage return and line feed. Args: line(by...
self.writelines([line], sep, echo)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interact(self): """ Interact with the socket. This will send all keyboard input to the socket and input from the socket to the console until an EOF occurs. "...
sockets = [sys.stdin, self.channel] while True: ready = select.select(sockets, [], [])[0] if sys.stdin in ready: line = sys.stdin.readline().encode('latin1') if not line: break self.write(line) 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 get_possible_importers(file_uris, current_doc=None): """ Return all the importer objects that can handle the specified files. Possible imports may vary depen...
importers = [] for importer in IMPORTERS: if importer.can_import(file_uris, current_doc): importers.append(importer) return importers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_import(self, file_uris, current_doc=None): """ Check that the specified file looks like a PDF """
if len(file_uris) <= 0: return False for uri in file_uris: uri = self.fs.safe(uri) if not self.check_file_type(uri): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_doc(self, file_uris, docsearch, current_doc=None): """ Import the specified PDF file """
doc = None docs = [] pages = [] file_uris = [self.fs.safe(uri) for uri in file_uris] imported = [] for file_uri in file_uris: if docsearch.is_hash_in_index(PdfDoc.hash_file(self.fs, file_uri)): logger.info("Document %s already found in the in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_import(self, file_uris, current_doc=None): """ Check that the specified file looks like a directory containing many pdf files """
if len(file_uris) <= 0: return False try: for file_uri in file_uris: file_uri = self.fs.safe(file_uri) for child in self.fs.recurse(file_uri): if self.check_file_type(child): return True except 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 can_import(self, file_uris, current_doc=None): """ Check that the specified file looks like an image supported by PIL """
if len(file_uris) <= 0: return False for file_uri in file_uris: file_uri = self.fs.safe(file_uri) if not self.check_file_type(file_uri): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xor(key, data): """ Perform cyclical exclusive or operations on ``data``. The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If the key i...
if type(key) is int: key = six.int2byte(key) key_len = len(key) return b''.join( six.int2byte(c ^ six.indexbytes(key, i % key_len)) for i, c in enumerate(six.iterbytes(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 caesar(shift, data, shift_ranges=('az', 'AZ')): """ Apply a caesar cipher to a string. The caesar cipher is a substition cipher where each letter in the give...
alphabet = dict( (chr(c), chr((c - s + shift) % (e - s + 1) + s)) for s, e in map(lambda r: (ord(r[0]), ord(r[-1])), shift_ranges) for c in range(s, e + 1) ) return ''.join(alphabet.get(c, c) for c in 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 enhex(d, separator=''): """ Convert bytes to their hexadecimal representation, optionally joined by a given separator. Args: d(bytes): The data to convert t...
v = binascii.hexlify(d).decode('ascii') if separator: return separator.join( v[i:i+2] for i in range(0, len(v), 2) ) else: return v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xor_app(parser, cmd, args): # pragma: no cover """ Xor a value with a key. """
parser.add_argument( '-d', '--dec', help='interpret the key as a decimal integer', dest='type', action='store_const', const=int ) parser.add_argument( '-x', '--hex', help='interpret the key as an hexadecimal integer', dest='type', act...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def caesar_app(parser, cmd, args): # pragma: no cover """ Caesar crypt a value with a key. """
parser.add_argument('shift', type=int, help='the shift to apply') parser.add_argument('value', help='the value to caesar crypt, read from stdin if omitted', nargs='?') parser.add_argument( '-s', '--shift-range', dest='shift_ranges', action='append', help='specify a characte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rot13_app(parser, cmd, args): # pragma: no cover """ rot13 encrypt a value. """
parser.add_argument('value', help='the value to rot13, read from stdin if omitted', nargs='?') args = parser.parse_args(args) return rot13(pwnypack.main.string_value_or_stdin(args.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 enb64_app(parser, cmd, args): # pragma: no cover """ base64 encode a value. """
parser.add_argument('value', help='the value to base64 encode, read from stdin if omitted', nargs='?') args = parser.parse_args(args) return enb64(pwnypack.main.binary_value_or_stdin(args.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 deb64_app(parser, cmd, args): # pragma: no cover """ base64 decode a value. """
parser.add_argument('value', help='the value to base64 decode, read from stdin if omitted', nargs='?') args = parser.parse_args(args) return deb64(pwnypack.main.string_value_or_stdin(args.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 enhex_app(parser, cmd, args): # pragma: no cover """ hex encode a value. """
parser.add_argument('value', help='the value to hex encode, read from stdin if omitted', nargs='?') parser.add_argument( '--separator', '-s', default='', help='the separator to place between hex tuples' ) args = parser.parse_args(args) return enhex(pwnypack.main.binary_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 dehex_app(parser, cmd, args): # pragma: no cover """ hex decode a value. """
parser.add_argument('value', help='the value to base64 decode, read from stdin if omitted', nargs='?') args = parser.parse_args(args) return dehex(pwnypack.main.string_value_or_stdin(args.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 enurlform_app(parser, cmd, args): # pragma: no cover """ encode a series of key=value pairs into a query string. """
parser.add_argument('values', help='the key=value pairs to URL encode', nargs='+') args = parser.parse_args(args) return enurlform(dict(v.split('=', 1) for v in args.values))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deurlform_app(parser, cmd, args): # pragma: no cover """ decode a query string into its key value pairs. """
parser.add_argument('value', help='the query string to decode') args = parser.parse_args(args) return ' '.join('%s=%s' % (key, value) for key, values in deurlform(args.value).items() for value in values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def frequency_app(parser, cmd, args): # pragma: no cover """ perform frequency analysis on a value. """
parser.add_argument('value', help='the value to analyse, read from stdin if omitted', nargs='?') args = parser.parse_args(args) data = frequency(six.iterbytes(pwnypack.main.binary_value_or_stdin(args.value))) return '\n'.join( '0x%02x (%c): %d' % (key, chr(key), value) if key >= 32 and...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(self, err=None): """Update the circuit breaker with an error event."""
if self.state == 'half-open': self.test_fail_count = min(self.test_fail_count + 1, 16) self.errors.append(self.clock()) if len(self.errors) > self.maxfail: time = self.clock() - self.errors.pop(0) if time < self.time_unit: if time == 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def context(self, id): """Return a circuit breaker for the given ID."""
if id not in self.circuits: self.circuits[id] = self.factory(self.clock, self.log.getChild(id), self.error_types, self.maxfail, self.reset_timeout, self.time_unit, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shell(_parser, cmd, args): # pragma: no cover """ Start an interactive python interpreter with pwny imported globally. """
parser = argparse.ArgumentParser( prog=_parser.prog, description=_parser.description, ) group = parser.add_mutually_exclusive_group() group.set_defaults(shell=have_bpython and 'bpython' or (have_IPython and 'ipython' or 'python')) if have_bpython: group.add_argument( ...
<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_sequence(self): """Return the sorted StopTimes for this trip."""
return sorted( self.stop_times(), key=lambda x:int(x.get('stop_sequence')) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getGestureAndSegments(points): """ Returns a list of tuples. The first item in the tuple is the directional integer, and the second item is a tuple of intege...
strokes, strokeSegments = _identifyStrokes(points) return list(zip(strokes, strokeSegments))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def levenshteinDistance(s1, s2): """ Returns the Levenshtein Distance between two strings, `s1` and `s2` as an integer. http://en.wikipedia.org/wiki/Levenshtein_...
singleLetterMapping = {DOWNLEFT: '1', DOWN:'2', DOWNRIGHT:'3', LEFT:'4', RIGHT:'6', UPLEFT:'7', UP:'8', UPRIGHT:'9'} len1 = len([singleLetterMapping[letter] for letter in s1]) len2 = len([singleLetterMapping[letter] for letter in s2]) matrix = lis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_localised_form(model, form, exclude=None): """ This is a factory function that creates a form for a model with internationalised field. The model should...
newfields = {} for localized_field in model.localized_fields: # get the descriptor, which contains the form field default_field_descriptor = getattr(model, localized_field) # See if we've got overridden fields in a custom form. if hasattr(form, 'declared_fie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, commit=True): """ Override save method to also save the localised fields. """
# set the localised fields for localized_field in self.instance.localized_fields: setattr(self.instance, localized_field, self.cleaned_data[localized_field]) return super(LocalisedForm, self).save(commit)
<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_unique(self): """ Validates the uniqueness of fields, but also handles the localized_fields. """
form_errors = [] try: super(LocalisedForm, self).validate_unique() except ValidationError as e: form_errors += e.messages # add unique validation for the localized fields. localized_fields_checks = self._get_localized_field_checks() bad_fields = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_localized_field_checks(self): """ Get the checks we must perform for the localized fields. """
localized_fields_checks = [] for localized_field in self.instance.localized_fields: if self.cleaned_data.get(localized_field) is None: continue f = getattr(self.instance.__class__, localized_field, None) if f and f.unique: if f.unique:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _perform_unique_localized_field_checks(self, unique_checks): """ Do the checks for the localized fields. """
bad_fields = set() form_errors = [] for (field_name, local_field_name) in unique_checks: lookup_kwargs = {} lookup_value = self.cleaned_data[field_name] # ModelChoiceField will return an object instance rather than # a raw primary ke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_missing_modules(): """ look for dependency that setuptools cannot check or that are too painful to install with setuptools """
missing_modules = [] for module in MODULES: try: __import__(module[1]) except ImportError: missing_modules.append(module) return missing_modules
<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_response(self, request, response): """ If ``request.session was modified``, or if the configuration is to save the session every time, save the chang...
try: modified = request.session.modified except AttributeError: pass else: if modified or settings.SESSION_SAVE_EVERY_REQUEST: if request.session.get_expire_at_browser_close(): max_age = None expires = N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all(cls, collection, skip=None, limit=None): """ Returns all documents of the collection :param collection Collection instance :param skip The number of docu...
kwargs = { 'skip': skip, 'limit': limit, } return cls._construct_query(name='all', collection=collection, multiple=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 update_by_example(cls, collection, example_data, new_value, keep_null=False, wait_for_sync=None, limit=None): """ This will find all documents in the collect...
kwargs = { 'newValue': new_value, 'options': { 'keepNull': keep_null, 'waitForSync': wait_for_sync, 'limit': limit, } } return cls._construct_query(name='update-by-example', ...
<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_by_example(cls, collection, example_data, wait_for_sync=None, limit=None): """ This will find all documents in the collection that match the specified...
kwargs = { 'options': { 'waitForSync': wait_for_sync, 'limit': limit, } } return cls._construct_query(name='remove-by-example', collection=collection, example=example_data, result=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 get_by_example_hash(cls, collection, index_id, example_data, allow_multiple=False, skip=None, limit=None): """ This will find all documents matching a given ...
kwargs = { 'index': index_id, 'skip': skip, 'limit': limit, } return cls._construct_query(name='by-example-hash', collection=collection, example=example_data, multiple=allow_multiple, *...
<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_by_example_skiplist(cls, collection, index_id, example_data, allow_multiple=True, skip=None, limit=None): """ This will find all documents matching a giv...
kwargs = { 'index': index_id, 'skip': skip, 'limit': limit, } return cls._construct_query(name='by-example-skiplist', collection=collection, example=example_data, multiple=allow_multiple, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def range(cls, collection, attribute, left, right, closed, index_id, skip=None, limit=None): """ This will find all documents within a given range. In order to e...
kwargs = { 'index': index_id, 'attribute': attribute, 'left': left, 'right': right, 'closed': closed, 'skip': skip, 'limit': limit, } return cls._construct_query(name='range', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fulltext(cls, collection, attribute, example_text, index_id, skip=None, limit=None): """ This will find all documents from the collection that match the full...
kwargs = { 'index': index_id, 'attribute': attribute, 'query': example_text, 'skip': skip, 'limit': limit, } return cls._construct_query(name='fulltext', collection=collection, multiple=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 near(cls, collection, latitude, longitude, index_id, distance=None, skip=None, limit=None): """ The default will find at most 100 documents near the given co...
kwargs = { 'geo': index_id, 'latitude': latitude, 'longitude': longitude, 'distance': distance, 'skip': skip, 'limit': limit, } return cls._construct_query(name='near', collection=colle...
<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_pwm_values(self, brightness=None, color=None): """ Get the pwm values for a specific state of the led. If a state argument is omitted, current value is ...
if brightness is None: brightness = self.brightness if color is None: color = self.color return [(x / 255) * brightness for x in self._rgb_to_rgbw(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 _rgb_to_rgbw(color): """ Convert a RGB color to a RGBW color. :param color: The RGB color. :return: The RGBW color. """
# Get the maximum between R, G, and B max_value = max(color) # If the maximum value is 0, immediately return pure black. if max_value == 0: return [0] * 4 # Figure out what the color with 100% hue is multiplier = 255 / max_value hue_red = color.R * ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_uri(cls, reactor, uri): """Return an AMQEndpoint instance configured with the given AMQP uri. @see: https://www.rabbitmq.com/uri-spec.html """
uri = URI.fromBytes(uri.encode(), defaultPort=5672) kwargs = {} host = uri.host.decode() if "@" in host: auth, host = uri.netloc.decode().split("@") username, password = auth.split(":") kwargs.update({"username": username, "password": password}) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _authenticate(self, client): """Perform AMQP authentication."""
yield client.authenticate( self._username, self._password, mechanism=self._auth_mechanism) returnValue(client)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _reset_plain(self): '''Create a BlockText from the captured lines and clear _text.''' if self._text: self._blocks.append(BlockText('\n'.join(self._text))) self._text.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def step(self): """Apply the current stage of the transition based on current time."""
if self.cancelled or self.finished: return if not self.pwm_stages: self._finish() return if self.duration == 0: progress = 1 else: run_time = time.time() - self._start_time progress = max(0, min(1, run_time / 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 _finish(self): """Mark transition as finished and execute callback."""
self.finished = True if self._callback: self._callback(self) self._finish_event.set()
<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(self, message, level=Level.NOTICE): "Send a syslog message to remote host using UDP or TCP" data = "<%d>%s" % (level + self.facility*8, message) if self.protocol == 'UDP': self.socket.sendto(data.encode('utf-8'), (self.host, self.port)) else: self.socket.send(data.encode('utf-8'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync(self, graph_commons): """Synchronize local and remote representations."""
if self['id'] is None: return remote_graph = graph_commons.graphs(self['id']) # TODO: less forceful, more elegant self.edges = remote_graph.edges self.nodes = remote_graph.nodes self.node_types = remote_graph.node_types self.edge_types = remote_grap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, transition): """ Queue a transition for execution. :param transition: The transition """
self._transitions.append(transition) if self._thread is None or not self._thread.isAlive(): self._thread = threading.Thread(target=self._transition_loop) self._thread.setDaemon(True) self._thread.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _transition_loop(self): """Execute all queued transitions step by step."""
while self._transitions: start = time.time() for transition in self._transitions: transition.step() if transition.finished: self._transitions.remove(transition) time_delta = time.time() - start sleep_time = max...
<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_pwm(self): """Update the pwm values of the driver regarding the current state."""
if self._is_on: values = self._get_pwm_values() else: values = [0] * len(self._driver.pins) self._driver.set_pwm(values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transition(self, duration, is_on=None, **kwargs): """ Transition to the specified state of the led. If another transition is already running, it is aborted. ...
self._cancel_active_transition() dest_state = self._prepare_transition(is_on, **kwargs) total_steps = self._transition_steps(**dest_state) state_stages = [self._transition_stage(step, total_steps, **dest_state) for step in range(total_steps)] pwm_stages ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _transition_callback(self, is_on, transition): """ Callback that is called when a transition has ended. :param is_on: The on-off state to transition to. :par...
# Update state properties if transition.state_stages: state = transition.state_stages[transition.stage_index] if self.is_on and is_on is False: # If led was turned off, set brightness to initial value # so that the brightness is restored when it 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 _interpolate(start, end, step, total_steps): """ Interpolate a value from start to end at a given progress. :param start: The start value. :param end: The en...
diff = end - start progress = step / (total_steps - 1) return start + progress * diff
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def instance(cls, hostname=None, auth=None, protocol=None, port=None, database=None): """ This method is called from everywhere in the code which accesses the da...
if cls.class_instance is None: if hostname is None and auth is None and protocol is None and port is None and database is None: cls.class_instance = Client(hostname='localhost') else: cls.class_instance = Client(hostname=hostname, auth=auth, protocol=pro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collection(self, name): """ Returns a collection with the given name :param name Collection name :returns Collection """
return Collection( name=name, api_resource=self.api.collection(name), api=self.api, )
<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(cls, name, users=None): """ Creates database and sets itself as the active database. :param name Database name :returns Database """
api = Client.instance().api database_data = { 'name': name, 'active': True, } if isinstance(users, list) or isinstance(users, tuple): database_data['users'] = users data = api.database.post(data=database_data) db = Database( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all(cls): """ Returns an array with all databases :returns Database list """
api = Client.instance().api data = api.database.get() database_names = data['result'] databases = [] for name in database_names: db = Database(name=name, api=api) databases.append(db) return databases
<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(cls, name): """ Destroys the database. """
client = Client.instance() new_current_database = None if client.database != name: new_current_database = name # Deletions are only possible from the system database client.set_database(name=SYSTEM_DATABASE) api = client.api api.database(name).de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_collection(self, name, type=2): """ Shortcut to create a collection :param name Collection name :param type Collection type (2 = document / 3 = edge) ...
return Collection.create(name=name, database=self.name, type=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 remove(cls, name): """ Destroys collection. :param name Collection name """
api = Client.instance().api api.collection(name).delete()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self): """ Updates only waitForSync and journalSize """
data = { 'waitForSync': self.waitForSync, 'journalSize': self.journalSize, } self.resource(self.name).properties.put(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self): """ Retrieves all properties again for the collection and sets the attributes. """
data = self.resource(self.name).properties.get() self.set_data(**data) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_figures(self): """ Returns figures about the collection. """
data = self.resource(self.name).figures.get() return data['figures']
<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_edge(self, from_doc, to_doc, edge_data={}): """ Creates edge document. :param from_doc Document from which the edge comes :param to_doc Document to wh...
return Edge.create( collection=self, from_doc=from_doc, to_doc=to_doc, edge_data=edge_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 documents(self): """ Returns all documents of this collection. :returns Document list """
document_list = [] document_uri_list = self.api.document.get(collection=self.name)['documents'] for document_uri in document_uri_list: splitted_uri = document_uri.split('/') document_key = splitted_uri[-1] document_id = "%s/%s" % (self.name, document_key) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(cls, collection): """ Creates document object without really creating it in the collection. :param collection Collection instance :returns Document ""...
api = Client.instance().api doc = Document( id='', key='', collection=collection.name, api=api, ) return doc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve(self): """ Retrieves all data for this document and saves it. """
data = self.resource(self.id).get() self.data = data return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self): """ If its internal state is loaded than it will only updated the set properties but otherwise it will create a new document. """
# TODO: Add option force_insert if not self.is_loaded and self.id is None or self.id == '': data = self.resource.post(data=self.data, collection=self.collection) self.id = data['_id'] self.key = data['_key'] self.revision = data['_rev'] self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key): """ Returns attribute value. :param key :returns value """
if not self.is_loaded: self.retrieve() self.is_loaded = True if self.has(key=key): return self.data[key] else: 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 _to_raw_pwm(self, values): """ Convert uniform pwm values to raw, driver-specific values. :param values: The uniform pwm values (0.0-1.0). :return: Converted...
return [self._to_single_raw_pwm(values[i]) for i in range(len(self._pins))]
<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_uniform_pwm(self, values): """ Convert raw pwm values to uniform values. :param values: The raw pwm values. :return: Converted, uniform pwm values (0.0-1...
return [self._to_single_uniform_pwm(values[i]) for i in range(len(self._pins))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def steps(self, start, end): """ Get the maximum number of steps the driver needs for a transition. :param start: The start value as uniform pwm value (0.0-1.0)....
if not 0 <= start <= 1: raise ValueError('Values must be between 0 and 1.') if not 0 <= end <= 1: raise ValueError('Values must be between 0 and 1.') raw_start = self._to_single_raw_pwm(start) raw_end = self._to_single_raw_pwm(end) return abs(raw_start -...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def numa_nodemask_to_set(mask): """ Convert NUMA nodemask to Python set. """
result = set() for i in range(0, get_max_node() + 1): if __nodemask_isset(mask, i): result.add(i) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_to_numa_nodemask(mask): """ Conver Python set to NUMA nodemask. """
result = nodemask_t() __nodemask_zero(result) for i in range(0, get_max_node() + 1): if i in mask: __nodemask_set(result, i) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_interleave_mask(): """ Get interleave mask for current thread. @return: node mask @rtype: C{set} """
nodemask = nodemask_t() bitmask = libnuma.numa_get_interleave_mask() libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask)) libnuma.numa_bitmask_free(bitmask) return numa_nodemask_to_set(nodemask)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(nodemask): """ Binds the current thread and its children to the nodes specified in nodemask. They will only run on the CPUs of the specified nodes and o...
mask = set_to_numa_nodemask(nodemask) bitmask = libnuma.numa_allocate_nodemask() libnuma.copy_nodemask_to_bitmask(byref(mask), bitmask) libnuma.numa_bind(bitmask) libnuma.numa_bitmask_free(bitmask)
<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_preferred(node): """ Sets the preferred node for the current thread to node. The preferred node is the node on which memory is preferably allocated befor...
if node < 0 or node > get_max_node(): raise ValueError(node) libnuma.numa_set_preferred(node)
<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_membind(nodemask): """ Sets the memory allocation mask. The thread will only allocate memory from the nodes set in nodemask. @param nodemask: node mask @...
mask = set_to_numa_nodemask(nodemask) tmp = bitmask_t() tmp.maskp = cast(byref(mask), POINTER(c_ulong)) tmp.size = sizeof(nodemask_t) * 8 libnuma.numa_set_membind(byref(tmp))
<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_membind(): """ Returns the mask of nodes from which memory can currently be allocated. @return: node mask @rtype: C{set} """
bitmask = libnuma.numa_get_membind() nodemask = nodemask_t() libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask)) libnuma.numa_bitmask_free(bitmask) return numa_nodemask_to_set(nodemask)
<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_run_on_node_mask(nodemask): """ Runs the current thread and its children only on nodes specified in nodemask. They will not migrate to CPUs of other node...
mask = set_to_numa_nodemask(nodemask) tmp = bitmask_t() tmp.maskp = cast(byref(mask), POINTER(c_ulong)) tmp.size = sizeof(nodemask_t) * 8 if libnuma.numa_run_on_node_mask(byref(tmp)) < 0: raise RuntimeError()
<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_run_on_node_mask(): """ Returns the mask of nodes that the current thread is allowed to run on. @return: node mask @rtype: C{set} """
bitmask = libnuma.numa_get_run_node_mask() nodemask = nodemask_t() libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask)) libnuma.numa_bitmask_free(bitmask) return numa_nodemask_to_set(nodemask)
<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_distance(node1, node2): """ Reports the distance in the machine topology between two nodes. The factors are a multiple of 10. It returns 0 when the dista...
if node1 < 0 or node1 > get_max_node(): raise ValueError(node1) if node2 < 0 or node2 > get_max_node(): raise ValueError(node2) return libnuma.numa_distance(node1, node2)
<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_affinity(pid): """ Returns the affinity mask of the process whose ID is pid. @param pid: process PID (0 == current process) @type pid: C{int} @return: se...
cpuset = cpu_set_t() result = set() libnuma.sched_getaffinity(pid, sizeof(cpu_set_t), byref(cpuset)) for i in range(0, sizeof(cpu_set_t)*8): if __CPU_ISSET(i, cpuset): result.add(i) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_affinity(pid, cpuset): """ Sets the CPU affinity mask of the process whose ID is pid to the value specified by mask. If pid is zero, then the calling pro...
_cpuset = cpu_set_t() __CPU_ZERO(_cpuset) for i in cpuset: if i in range(0, sizeof(cpu_set_t) * 8): __CPU_SET(i, _cpuset) if libnuma.sched_setaffinity(pid, sizeof(cpu_set_t), byref(_cpuset)) < 0: raise RuntimeError()
<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, namespace): '''Render template lines. Note: we only need to parse the namespace if we used variables in this part of the template. ''' return self._text.format_map(namespace.dictionary) \ if self._need_format else self._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 _assert_is_color(value): """ Assert that the given value is a valid brightness. :param value: The value to check. """
if not isinstance(value, tuple) or len(value) != 3: raise ValueError("Color must be a RGB tuple.") if not all(0 <= x <= 255 for x in value): raise ValueError("RGB values of color must be between 0 and 255.")
<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(cls, id): """ Deletes an index with id :param id string/document-handle """
api = Client.instance().api api.index(id).delete()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self): """ Creates this index in the collection if it hasn't been already created """
api = Client.instance().api index_details = { 'type': self.index_type_obj.type_name } extra_index_attributes = self.index_type_obj.get_extra_attributes() for extra_attribute_key in extra_index_attributes: extra_attribute_value = extra_index_attributes...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _compile(cls, lines): '''Return macro or block name from the current line.''' m = cls.RE_PASTE.match(lines.current) if m is None: raise MacroBlockUsageError( 'Incorrect macro or block usage at line {}, {}\nShould be ' 'something like: #my_macro'.fo...