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 _setup_sentry_client(context): """Produce and configure the sentry client."""
# get_secret will be deprecated soon dsn = os.environ.get("SENTRY_DSN") try: client = raven.Client(dsn, sample_rate=SENTRY_SAMPLE_RATE) client.user_context(_sentry_context_dict(context)) return client except: rlogger.error("Raven client error", exc_info=True) 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 _handle_processing_error(err, errstream, client): """Handle ProcessingError exceptions."""
errors = sorted(err.events, key=operator.attrgetter("index")) failed = [e.event for e in errors] silent = all(isinstance(e.error, OutOfOrderError) for e in errors) if errstream: _deliver_errored_events(errstream, failed) must_raise = False else: must_raise = True for _, event, error, tb in errors: if isinstance(error, OutOfOrderError): # Not really an error: do not log this to Sentry continue try: raise six.reraise(*tb) except Exception as err: if client: client.captureException() msg = "{}{}: {}".format(type(err).__name__, err.args, json.dumps(event, indent=4)) rlogger.error(msg, exc_info=tb) if must_raise: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _deliver_errored_events(errstream, recs): """Deliver errors to error stream."""
rlogger.info("Going to handle %s failed events", len(recs)) rlogger.info( "First failed event: %s", json.dumps(recs[0], indent=4)) kinesis_stream = errstream.get("kinesis_stream") randomkey = str(uuid.uuid4()) if kinesis_stream: send_to_kinesis_stream( recs, kinesis_stream, partition_key=errstream.get("partition_key", randomkey)) rlogger.info("Sent errors to Kinesis stream '%s'", errstream) delivery_stream = errstream.get("firehose_delivery_stream") if delivery_stream: send_to_delivery_stream(errevents, delivery_stream) rlogger.info("Sent error payload to Firehose delivery stream '%s'", delivery_stream)
<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_records(event): """Get records from an AWS Lambda trigger event."""
try: recs, _ = unpack_kinesis_event(event, deserializer=None) except KeyError: # If not a Kinesis event, just unpack the records recs = event["Records"] return recs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _search(self, query, fields=None, limit=50000, sampling=None): """ Perform the search and return raw rows :type query object :type fields list[str] or None :type limit int :type sampling int or None :arg sampling: Percentage of results to be returned (0,100) :rtype: list """
body = { "query": { "bool": { "must": [ query ] } } } # @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html if fields: body['_source'] = { "includes": fields } # add @timestamp range # @see http://stackoverflow.com/questions/40996266/elasticsearch-5-1-unknown-key-for-a-start-object-in-filters # @see https://discuss.elastic.co/t/elasticsearch-watcher-error-for-range-query/70347/2 body['query']['bool']['must'].append(self._get_timestamp_filer()) # sample the results if needed if sampling is not None: body['query']['bool']['must'].append({ 'script': { 'script': { 'lang': 'painless', 'source': "Math.abs(doc['_id'].value.hashCode()) % 100 < params.sampling", 'params': { 'sampling': sampling } } } }) self._logger.debug("Running {} query (limit set to {:d})".format(json.dumps(body), body.get('size', 0))) # use Scroll API to be able to fetch more than 10k results and prevent "search_phase_execution_exception": # "Result window is too large, from + size must be less than or equal to: [10000] but was [500000]. # See the scroll api for a more efficient way to request large data sets." # # @see http://elasticsearch-py.readthedocs.io/en/master/helpers.html#scan rows = scan( client=self._es, clear_scroll=False, # True causes "403 Forbidden: You don't have access to this resource" index=self._index, query=body, sort=["_doc"], # return the next batch of results from every shard that still has results to return. size=self._batch_size, # batch size ) # get only requested amount of entries and cast them to a list rows = islice(rows, 0, limit) rows = [entry['_source'] for entry in rows] # get data self._logger.info("{:d} rows returned".format(len(rows))) return rows
<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_rows(self, match, fields=None, limit=10, sampling=None): """ Returns raw rows that matches given query :arg match: query to be run against Kibana log messages (ex. {"@message": "Foo Bar DB queries"}) :type fields list[str] or None :arg limit: the number of results (defaults to 10) :type sampling int or None :arg sampling: Percentage of results to be returned (0,100) """
query = { "match": match, } return self._search(query, fields, limit, sampling)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_by_string(self, query, fields=None, limit=10, sampling=None): """ Returns raw rows that matches the given query string :arg query: query string to be run against Kibana log messages (ex. @message:"^PHP Fatal"). :type fields list[str] or None :arg limit: the number of results (defaults to 10) :type sampling int or None :arg sampling: Percentage of results to be returned (0,100) """
query = { "query_string": { "query": query, } } return self._search(query, fields, limit, sampling)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count(self, query): """ Returns number of matching entries :type query str :rtype: int """
body = { "query": { "bool": { "must": [{ "query_string": { "query": query, } }] } } } body['query']['bool']['must'].append(self._get_timestamp_filer()) return self._es.count(index=self._index, body=body).get('count')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_by_sql(self, sql): """ Returns entries matching given SQL query :type sql str :rtype: list[dict] """
# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest.html # https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-syntax-select.html body = {'query': sql} resp = self._es.transport.perform_request('POST', '/_xpack/sql', params={'format': 'json'}, body=body) # build key-value dictionary for each row to match results returned by query_by_string columns = [column['name'] for column in resp.get('columns')] return [dict(zip(columns, row)) for row in resp.get('rows')]
<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(self, pos, width): """Extracts a subword with a given width, starting from a given bit position. """
pos = operator.index(pos) width = operator.index(width) if width < 0: raise ValueError('width must not be negative') if pos < 0: raise ValueError('extracting out of range') return BinWord(width, self >> pos, trunc=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 blast_to_cigar(query_seq, match_seq, subject_seq, cigar_age='new'): """converts BLAST alignment into a old or new CIGAR line Args: query_seq (str): Aligned portion of query sequence match_seq (str): Alignment sequence subject_seq (str): Aligned portion of subject/reference sequence cigar_age (str): ['old', 'new'] CIGAR format to use, new is highly detailed while old is fairly minimalistic Returns: str: CIGAR string Raises: ValueError: If query_seq, match_seq, and match_seq not same length Examples: 3=2X2D2=2X3= 5M2D7M """
if not len(query_seq) == len(match_seq) \ or not len(query_seq) == len(subject_seq) \ or not len(subject_seq) == len(match_seq): raise ValueError('query_seq, match_seq, and subject_seq not same ' 'lengths.') # Translate XML alignment to CIGAR characters cigar_line_raw = [] for query, match, subject in zip(query_seq, match_seq, subject_seq): if query == '-': # Deletion cigar_line_raw.append('D') continue elif subject == '-': # Insertion cigar_line_raw.append('I') continue elif match == '+' or match == '|' or match.isalpha(): # Match if match != '+' and cigar_age == 'new': # Positive match cigar_line_raw.append('=') continue elif match == '+' and cigar_age == 'new': # Mismatch cigar_line_raw.append('X') continue else: cigar_line_raw.append('M') continue elif cigar_age == 'new': cigar_line_raw.append('X') continue else: cigar_line_raw.append('M') # Replace repeat characters with numbers cigar_line = [] last_position = '' repeats = 1 cigar_len = len(cigar_line_raw) for letter in enumerate(cigar_line_raw): if letter[1] == last_position: repeats += 1 else: if repeats != 1: cigar_line.append(str(repeats)) repeats = 1 cigar_line.append(last_position) if letter[0] == cigar_len - 1: if repeats != 1: cigar_line.append(str(repeats)) repeats = 1 cigar_line.append(letter[1]) last_position = letter[1] return ''.join(cigar_line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clean_isbn(isbn): """ Remove all non-digit and non "x" characters from given string. Args: isbn (str): isbn string, which will be cleaned. Returns: list: array of numbers (if "x" is found, it is converted to 10). """
if isinstance(isbn, basestring): isbn = list(isbn.lower()) # filter digits and "x" isbn = filter(lambda x: x.isdigit() or x == "x", isbn) # convert ISBN to numbers return map(lambda x: 10 if x == "x" else int(x), isbn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _isbn_cleaner(fn): """ Decorator for calling other functions from this module. Purpose of this decorator is to clean the ISBN string from garbage and return list of digits. Args: fn (function): function in which will be :func:`_clean_isbn(isbn)` call wrapped. """
@wraps(fn) def wrapper(isbn): return fn(_clean_isbn(isbn)) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def application(handler, adapter_cls=WerkzeugAdapter): """Converts an anillo function based handler in a wsgi compiliant application function. :param adapter_cls: the wsgi adapter implementation (default: wekrzeug) :returns: wsgi function :rtype: callable """
adapter = adapter_cls() def wrapper(environ, start_response): request = adapter.to_request(environ) response = handler(request) response_func = adapter.from_response(response) return response_func(environ, start_response) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_async(func): """Wraps an asynchronous function into a synchronous function."""
@functools.wraps(func) def wrapped(*args, **kwargs): fut = asyncio.ensure_future(func(*args, **kwargs)) cur = greenlet.getcurrent() def callback(fut): try: cur.switch(fut.result()) except BaseException as e: cur.throw(e) fut.add_done_callback(callback) return cur.parent.switch() return wrapped
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_sync(func): """Wraps a synchronous function into an asynchronous function."""
@functools.wraps(func) def wrapped(*args, **kwargs): fut = asyncio.Future() def green(): try: fut.set_result(func(*args, **kwargs)) except BaseException as e: fut.set_exception(e) greenlet.greenlet(green).switch() return fut return wrapped
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Run(self): """ Wait for clients to connect and service them :returns: None """
while True: try: events = self.poller.poll() except KeyboardInterrupt: self.context.destroy() sys.exit() self.Handle_Events(events)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Handle_Receive(self, msg): """ Handle a received message. :param msg: the received message :type msg: str :returns: The message to reply with :rtype: str """
msg = self.Check_Message(msg) msg_type = msg['type'] f_name = "Handle_{0}".format(msg_type) try: f = getattr(self, f_name) except AttributeError: f = self.Handle_ERROR(msg) reply = f(msg) return reply
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Handle_Search(self, msg): """ Handle a search. :param msg: the received search :type msg: dict :returns: The message to reply with :rtype: str """
search_term = msg['object']['searchTerm'] results = self.db.searchForItem(search_term) reply = {"status": "OK", "type": "search", "object": { "received search": msg['object']['searchTerm'], "results": results} } return json.dumps(reply)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Handle_Note(self, msg): """ Handle a new note. :param msg: the received note :type msg: dict :returns: The message to reply with :rtype: str """
note_text = msg['object']['note'] note_tags = msg['object']['tags'] if 'ID' in msg['object']: note_id = msg['object']['ID'] self.db.addItem("note", {"note": note_text, "tags": note_tags}, note_id) else: note_id = self.db.addItem("note", {"note": note_text, "tags": note_tags}) reply = {"status": "OK", "type": "Note", "object": { "received note": msg['object']['note'], "received tags": msg['object']['tags'], "ID": note_id} } return json.dumps(reply)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def after_match(self, func, full_fallback=False): """Returns an iterator for all the elements after the first match. If `full_fallback` is `True`, it will return all the messages if the function never matched. """
iterator = iter(self) for item in iterator: if func(item): return iterator if full_fallback: iterator = iter(self) return iterator
<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(correlation_id, components): """ Clears state of multiple components. To be cleaned state components must implement [[ICleanable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: the list of components that are to be cleaned. """
if components == None: return for component in components: Cleaner.clear_one(correlation_id, component)
<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_datetime(value): """Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if the input isn't well formatted. """
match = datetime_re.match(value) if match: kw = match.groupdict() if kw['microsecond']: kw['microsecond'] = kw['microsecond'].ljust(6, '0') tzinfo = kw.pop('tzinfo') if tzinfo == 'Z': tzinfo = utc elif tzinfo is not None: offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0 offset = 60 * int(tzinfo[1:3]) + offset_mins if tzinfo[0] == '-': offset = -offset tzinfo = get_fixed_timezone(offset) kw = {k: int(v) for k, v in kw.items() if v is not None} kw['tzinfo'] = tzinfo return datetime.datetime(**kw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(self): """ Check if the daemon is currently running. Requires procfs, so it will only work on POSIX compliant OS'. """
# Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: return False try: return os.path.exists("/proc/{0}".format(pid)) except OSError: 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 func(self, name: str): """return the first func defined named name"""
for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType) and f._name == name): return f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def type(self, name: str): """return the first complete definition of type 'name'"""
for f in self.body: if (hasattr(f, '_ctype') and f._ctype._storage == Storages.TYPEDEF and f._name == name): return f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def declallfuncs(self): """generator on all declaration of function"""
for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType)): yield f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def declallvars(self): """generator on all declaration of variable"""
for f in self.body: if (hasattr(f, '_ctype') and not isinstance(f._ctype, FuncType)): yield f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def declalltypes(self): """generator on all declaration of type"""
for f in self.body: if (hasattr(f, '_ctype') and f._ctype._storage == Storages.TYPEDEF): yield f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_popup(self, *args, **kwargs): """Show a popup with a textedit :returns: None :rtype: None :raises: None """
self.mw = JB_MainWindow(parent=self, flags=QtCore.Qt.Dialog) self.mw.setWindowTitle(self.popuptitle) self.mw.setWindowModality(QtCore.Qt.ApplicationModal) w = QtGui.QWidget() self.mw.setCentralWidget(w) vbox = QtGui.QVBoxLayout(w) pte = QtGui.QPlainTextEdit() pte.setPlainText(self.get_popup_text()) vbox.addWidget(pte) # move window to cursor position d = self.cursor().pos() - self.mw.mapToGlobal(self.mw.pos()) self.mw.move(d) self.mw.show()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mount(directory, lower_dir, upper_dir, mount_table=None): """Creates a mount"""
return OverlayFS.mount(directory, lower_dir, upper_dir, mount_table=mount_table)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_teams(self, teams): """Expects an iterable of team IDs"""
return [LeaderboardInstance(x) for x in self._leaderboard if x['faction']['id'] in teams]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_users(self, users): """Expects an interable of User IDs ints"""
return [LeaderboardInstance(x) for x in self._leaderboard if x['user_id'] in users]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_trainers(self, trainers): """Expects an interable of Trainer IDs ints"""
return [LeaderboardInstance(x) for x in self._leaderboard if x['id'] in trainers]
<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_path(path, filetype=FILE): """Takes a path and a filetype, verifies existence and type, and returns absolute path. """
if not path: raise ValueError('"{0}" is not a valid path.'.format(path)) if not os.path.exists(path): raise ValueError('"{0}" does not exist.'.format(path)) if filetype == FILE and not os.path.isfile(path): raise ValueError('"{0}" is not a file.'.format(path)) elif filetype == DIR and not os.path.isdir(path): raise ValueError('"{0}" is not a dir.'.format(path)) return os.path.abspath(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 err(*output, **kwargs): """Writes output to stderr. :arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap the output. """
output = 'Error: ' + ' '.join([str(o) for o in output]) if kwargs.get('wrap') is not False: output = '\n'.join(wrap(output, kwargs.get('indent', ''))) elif kwargs.get('indent'): indent = kwargs['indent'] output = indent + ('\n' + indent).join(output.splitlines()) sys.stderr.write(output + '\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 out(*output, **kwargs): """Writes output to stdout. :arg wrap: If you set ``wrap=False``, then ``out`` won't textwrap the output. """
output = ' '.join([str(o) for o in output]) if kwargs.get('wrap') is not False: output = '\n'.join(wrap(output, kwargs.get('indent', ''))) elif kwargs.get('indent'): indent = kwargs['indent'] output = indent + ('\n' + indent).join(output.splitlines()) sys.stdout.write(output + '\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 convert_rrule(rrule): """Converts icalendar rrule to dateutil rrule."""
args = {} # TODO: rrule['freq'] is a list, but I'm unclear as to why. freq = FREQ_MAP[rrule['freq'][0]] keys = ['wkst', 'until', 'bysetpos', 'interval', 'bymonth', 'bymonthday', 'byyearday', 'byweekno', 'byhour', 'byminute', 'bysecond'] def tweak(rrule, key): value = rrule.get(key) if isinstance(value, list): return value[0] return value args = dict((key, tweak(rrule, key)) for key in keys if rrule.get(key)) byweekday = rrule.get('byweekday') if byweekday: byweekday = byweekday[0] count, day = int(byweekday[0]), byweekday[1:] args['byweekday'] = WEEKDAY_MAP[day](count) return freq, args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_ics(icsfile): """Takes an icsfilename, parses it, and returns Events."""
events = [] cal = Calendar.from_ical(open(icsfile, 'rb').read()) for component in cal.walk('vevent'): dtstart = component['dtstart'].dt rrule = component['rrule'] freq, args = convert_rrule(rrule) args['dtstart'] = dtstart rrule = dateutil.rrule.rrule(freq, **args) summary = vText.from_ical(component.get('summary', u'')) description = vText.from_ical(component.get('description', u'')) organizer = vText.from_ical(component.get('organizer', u'')) # TODO: Find an event id. If it's not there, then compose one # with dtstart, summary, and organizer. event_id = "::".join((str(dtstart), summary, organizer)) events.append(Event(event_id, rrule, summary, description)) return events
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def route(cls, path): """A decorator to indicate that a method should be a routable HTTP endpoint. .. code-block:: python from compactor.process import Process class WebProcess(Process): @Process.route('/hello/world') def hello_world(self, handler): return handler.write('<html><title>hello world</title></html>') The handler passed to the method is a tornado RequestHandler. WARNING: This interface is alpha and may change in the future if or when we remove tornado as a compactor dependency. :param path: The endpoint to route to this method. :type path: ``str`` """
if not path.startswith('/'): raise ValueError('Routes must start with "/"') def wrap(fn): setattr(fn, cls.ROUTE_ATTRIBUTE, path) return fn return wrap
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(cls, mbox): """A decorator to indicate a remotely callable method on a process. .. code-block:: python from compactor.process import Process class PingProcess(Process): @Process.install('ping') def ping(self, from_pid, body): # do something The installed method should take ``from_pid`` and ``body`` parameters. ``from_pid`` is the process calling the method. ``body`` is a ``bytes`` stream that was delivered with the message, possibly empty. :param mbox: Incoming messages to this "mailbox" will be dispatched to this method. :type mbox: ``str`` """
def wrap(fn): setattr(fn, cls.INSTALL_ATTRIBUTE, mbox) return fn return wrap
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pid(self): """The pid of this process. :raises: Will raise a ``Process.UnboundProcess`` exception if the process is not bound to a context. """
self._assert_bound() return PID(self._context.ip, self._context.port, self.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def link(self, to): """Link to another process. The ``link`` operation is not guaranteed to succeed. If it does, when the other process terminates, the ``exited`` method will be called with its pid. Returns immediately. :param to: The pid of the process to send a message. :type to: :class:`PID` :raises: Will raise a ``Process.UnboundProcess`` exception if the process is not bound to a context. :return: Nothing """
self._assert_bound() self._context.link(self.pid, to)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(cls, message_type): """A decorator to indicate a remotely callable method on a process using protocol buffers. .. code-block:: python from compactor.process import ProtobufProcess from messages_pb2 import RequestMessage, ResponseMessage class PingProcess(ProtobufProcess): @ProtobufProcess.install(RequestMessage) def ping(self, from_pid, message): # do something with message, a RequestMessage # send a protocol buffer which will get serialized on the wire. self.send(from_pid, response) The installed method should take ``from_pid`` and ``message`` parameters. ``from_pid`` is the process calling the method. ``message`` is a protocol buffer of the installed type. :param message_type: Incoming messages to this message_type will be dispatched to this method. :type message_type: A generated protocol buffer stub """
def wrap(fn): @functools.wraps(fn) def wrapped_fn(self, from_pid, message_str): message = message_type() message.MergeFromString(message_str) return fn(self, from_pid, message) return Process.install(message_type.DESCRIPTOR.full_name)(wrapped_fn) return wrap
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def actions(acts, done): ''' Prepare actions pipeline. :param tuple acts: called functions :param function done: get result from actions :returns function: function that starts executio ''' def _intermediate(acc, action): result = action(acc['state']) values = concatv(acc['values'], [result['answer']]) return {'values': values, 'state': result['state']} def _actions(seed): init = {'values': [], 'state': seed} result = reduce(_intermediate, acts, init) keep = remove(lambda x: x is None, result['values']) return done(keep, result['state']) return _actions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lift(fn=None, state_fn=None): """ The lift decorator function will be used to abstract away the management of the state object used as the intermediate representation of actions. :param function answer: a function to provide the result of some action given a value :param function state: a function to provide what the new state looks like :returns function: a function suitable for use in actions """
if fn is None: return partial(lift, state_fn=state_fn) @wraps(fn) def _lift(*args, **kwargs): def _run(state): ans = fn(*cons(state, args), **kwargs) s = state_fn(state) if state_fn is not None else ans return {'answer': ans, 'state': s} return _run return _lift
<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_speed(self, motor, speed): """ Change the speed of a motor on the controller. :param motor: The motor to change. :type motor: ``int`` :param speed: Speed from -100 to +100, 0 is stop :type speed: ``int`` """
self._validate_motor(motor) en, in1, in2 = self._motors[motor-1] if speed == 0: en.pwm_stop() in1.set(False) in2.set(False) elif speed > 0: en.pwm_start(abs(speed)) in1.set(True) in2.set(False) else: en.pwm_start(abs(speed)) in1.set(False) in2.set(True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_all_params_are_keyword(method): """ Raises CooperativeError if method any parameter that is not a named keyword parameter """
args, varargs, keywords, defaults = inspect.getargspec(method) # Always have self, thus the -1 if len(args or []) - 1 != len(defaults or []): raise CooperativeError, "Init has positional parameters " + \ str(args[1:]) if varargs: raise CooperativeError, "Init has variadic positional parameters" if keywords: raise CooperativeError, "Init has variadic keyword parameters"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_keyword_extractor(method): """ Removes all keyword parameters required by 'method' from dictionary 'keys' and returns them in a separate dictionary. """
args, _1, _2, defs = inspect.getargspec(method) key_args = args[-len(defs or []):] def extractor(keys): new = {} for a in key_args: if a in keys: new[a] = keys[a] del keys[a] return new return extractor
<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_config(self, ): """Return the user config for this plugin You have to provide a configspec, put the configspec file in the same folder as your plugin. Name it like your class and put 'ini' as extension. """
# get the module of the plugin class mod = sys.modules[self.__module__] # get the file from where it was imported modfile = mod.__file__ # get the module directory specdir = os.path.dirname(modfile) # get the classname cname = self.__class__.__name__ # add the extension confname = os.extsep.join((cname, CONFIG_EXT)) specpath = os.path.join(specdir, confname) if not os.path.exists(specpath): return None confpath = os.path.join(PLUGIN_CONFIG_DIR, confname) return load_config(confpath, specpath)
<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_plugins(self, path): """Return a list with all plugins found in path :param path: the directory with plugins :type path: str :returns: list of JB_Plugin subclasses :rtype: list :raises: None """
ext = os.extsep+'py' files = [] for (dirpath, dirnames, filenames) in os.walk(path): files.extend([os.path.join(dirpath, x) for x in filenames if x.endswith(ext)]) plugins = [] for f in files: try: mod = self.__import_file(f) except Exception: tb = traceback.format_exc() log.debug("Importing plugin from %s failed!\n%s" % (f, tb)) continue # get all classes in the imported file members = inspect.getmembers(mod, lambda x: inspect.isclass(x)) # only get classes which are defined, not imported, in mod classes = [m[1] for m in members if m[1].__module__ == mod.__name__] for c in classes: # if the class is derived from a supported type append it # we test if it is a subclass of a supported type but not a supported type itself # because that might be the abstract class if any(issubclass(c, supported) for supported in self.supportedTypes)\ and c not in self.supportedTypes: plugins.append(c) return plugins
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gather_plugins(self): """Return all plugins that are found in the plugin paths Looks in the envvar ``JUKEBOX_PLUGIN_PATH``. :returns: :rtype: :raises: """
plugins = [] cfg = get_core_config() pathenv = cfg['jukebox']['pluginpaths'] pathenv = os.pathsep.join((pathenv, os.environ.get("JUKEBOX_PLUGIN_PATH", ""))) paths = pathenv.split(os.pathsep) # first find built-ins then the ones in the config, then the one from the environment # so user plugins can override built-ins for p in reversed(paths): if p and os.path.exists(p): # in case of an empty string, we do not search! plugins.extend(self.find_plugins(p)) return plugins
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_plugins(self, ): """Loads all found plugins :returns: None :rtype: None :raises: None """
for p in self.__plugins.values(): try: self.load_plugin(p) except errors.PluginInitError: log.exception('Initializing the plugin: %s failed.' % p)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_plugin(self, p): """Load the specified plugin :param p: The plugin to load :type p: Subclass of JB_Plugin :returns: None :rtype: None :raises: errors.PluginInitError """
if p.is_loaded(): return # load required plugins first reqnames = p.required reqplugins = [] for name in reqnames: try: reqplugins.append(self.__plugins[name]) except KeyError as e: log.error("Required Plugin %s not found. Cannot load %s." % (name, p)) raise errors.PluginInitError('Required Plugin %s not found. Cannot load %s. Reason: %s' % (name, p, e)) for plug in reqplugins: try: self.load_plugin(plug) except errors.PluginInitError as e: log.error("Required Plugin %s could not be loaded. Cannot load %s" % (plug, p)) raise errors.PluginInitError('Required Plugin %s could not be loaded. Cannot load %s. Reason: %s' % (plug,p, e)) # load the actual plugin p._load() log.info('Initialized the plugin: %s' % p)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unload_plugins(self, ): """ Unloads all loaded plugins :returns: None :rtype: None :raises: None """
for p in self.__plugins.values(): if p.is_loaded(): try: p._unload() log.info('Uninitialized the plugin: %s' % p) except errors.PluginUninitError: log.error('Uninitialization of the plugin: %s failed.' % p)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __import_file(self, f): """Import the specified file and return the imported module :param f: the file to import :type f: str :returns: The imported module :rtype: module :raises: None """
directory, module_name = os.path.split(f) module_name = os.path.splitext(module_name)[0] path = list(sys.path) sys.path.insert(0, directory) module = __import__(module_name) return module
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _exception_handler(self, e): """This exception handler catches should only be invoked when we need to quit the workflow prematurely. It takes in an `ApiException` which will contain the error, details of the error and status code. When the application is in testing mode, it will also return the stack trace"""
if isinstance(e.message, dict): return self._prep_response( e.message['msg'], status=e.message['status']) if e.message.find('Validation') == 0: return self._prep_response(self.validation.errors, status=400) elif e.message.find('No record') == 0: return self._prep_response(status=404) else: return self._prep_response({'message': e.message}, status=409)
<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_instance(self, **kwargs): """Loads the record specified by the `obj_id` path in the url and stores it in g._resource_instance"""
current_app.logger.info("Getting instance") current_app.logger.debug("kwargs: {}".format(kwargs)) current_app.logger.info( "Loading instance: {}".format(kwargs['obj_id'])) rec = self.db_query.get_instance(self.db_collection, kwargs['obj_id']) g._resource_instance = rec current_app.logger.debug( "g._resource_instance: {}".format(g._resource_instance)) return rec
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_record_data(self, changes, orig_record=None): """This method merges PATCH requests with the db record to ensure no data is lost. In addition, it is also a hook for other fields to be overwritten, to ensure immutable fields aren't changed by a request."""
current_app.logger.info("Merging request data with db record") current_app.logger.debug("orig_record: {}".format(orig_record)) current_app.logger.debug("Changes".format(changes)) final_record = changes if request.method == 'PATCH': final_record = dict(orig_record) final_record.update(changes) elif request.method == 'PUT': if '_id' in orig_record: final_record['_id'] = orig_record['_id'] return final_record
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repr_return(func): """ This is a decorator to give the return value a pretty print repr """
def repr_return_decorator(*args, **kwargs): ret = func(*args, **kwargs) if isinstance(ret, basestring): return ret if type(ret) in repr_map: return repr_map[type(ret)](ret) print('=' * 80 + '\n' + ' FAILED TO GET REPR RETURN for type (' + str(type(ret)) + '\n' + '=' * 80) return ret return repr_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 repr_setup(self, name=None, col_names=None, col_types=None): """ This wasn't safe to pass into init because of the inheritance """
self._name = name or self._name self._col_types = col_types or self._col_types
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_string(obj, name=None, nonempty=False): """ Raise an exception if the obj is not of type str or unicode. If name is provided it is used in the exception message. If nonempty=True, then an exception is raised if the object is the empty string. """
require_instance(obj, string_types, name, "string") if nonempty and not obj: raise ValueError( (("%s: " % name) if name else "") + "string must be nonempty.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_instance(obj, types=None, name=None, type_name=None, truncate_at=80): """ Raise an exception if obj is not an instance of one of the specified types. Similarly to isinstance, 'types' may be either a single type or a tuple of types. If name or type_name is provided, it is used in the exception message. The object's string representation is also included in the message, truncated to 'truncate_at' number of characters. """
if not isinstance(obj, types): obj_string = str(obj) if len(obj_string) > truncate_at: obj_string = obj_string[:truncate_at - 3] + "..." if type_name is None: try: type_name = "one of " + ", ".join(str(t) for t in types) except TypeError: type_name = str(types) name_string = ("%s: " % name) if name else "" error_message = "%sexpected %s. Got: '%s' of type '%s'" % ( name_string, type_name, obj_string, type(obj)) raise TypeError(error_message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_iterable_of(objs, types, name=None, type_name=None, truncate_at=80): """ Raise an exception if objs is not an iterable with each element an instance of one of the specified types. See `require_instance` for descriptions of the other parameters. """
# Fast pass for common case where all types are correct. # This avoids the more expensive loop below. A typical speedup from this # optimization is 6.6 sec -> 1.7 sec, for testing a list of size 10,000,000. try: if all(isinstance(obj, types) for obj in objs): return except TypeError: # We don't require that objs is a list in this function, just that it's # iterable. We specify 'list' below as a convenient way to throw the # desired error. require_instance(objs, list, name, "iterable", truncate_at) # Some type isn't correct. We reuse the require_instance function to raise # the exception. prefix = ("%s: " % name) if name else "" for (i, obj) in enumerate(objs): element_name = prefix + ("element at index %d" % i) require_instance(obj, types, element_name, type_name, truncate_at) assert False, "Shouldn't reach here."
<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_property(obj, name, value): """ Recursively sets value of object and its subobjects property specified by its name. The object can be a user defined object, map or array. The property name correspondently must be object property, map key or array index. If the property does not exist or introspection fails this method doesn't do anything and doesn't any throw errors. :param obj: an object to write property to. :param name: a name of the property to set. :param value: a new value for the property to set. """
if obj == None or name == None: return names = name.split(".") if names == None or len(names) == 0: return RecursiveObjectWriter._perform_set_property(obj, names, 0, 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 copy_properties(dest, src): """ Copies content of one object to another object by recursively reading all properties from source object and then recursively writing them to destination object. :param dest: a destination object to write properties to. :param src: a source object to read properties from """
if dest == None or src == None: return values = RecursiveObjectReader.get_properties(src) RecursiveObjectWriter.set_properties(dest, 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 time_range_cutter_at_time(local,time_range,time_cut=(0,0,0)): """ Given a range, return a list of DateTimes that match the time_cut between start and end. :param local: if False [default] use UTC datetime. If True use localtz :param time_range: the TimeRange object :param time_cut: HH:MM:SS of when to cut. eg: (0,0,0) for midnight """
( start, end ) = time_range.get(local) index = start.replace( hour=time_cut[0], minute=time_cut[1], second=time_cut[2] ) cuts = [] index += datetime.timedelta(days=1) while index < end: cuts.append(index) index += datetime.timedelta(days=1) if local: index = time_range.normalize(index) return cuts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hours(self,local=False): """ Returns the number of hours of difference """
delta = self.delta(local) return delta.total_seconds()/3600
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks(self,local,cutter_callback=None,*cutter_callback_args,**cutter_callback_kwargs): """ Takes a time range and returns sub timeranges based upon the cuts that cutter callback provides :param local: if False [default] use UTC datetime. If True use localtz :param cutter_callback: This should be a callback function that takes the current TimeRange and returns a list of DateTimes that denote where the next chunk should start. By default the cutter used will cut at 00:00:00 each day. """
# First we get all the slices we want to take out of this time range. if not cutter_callback: cutter_callback = time_range_cutter_at_time time_cuts = cutter_callback(local,self,*cutter_callback_args,**cutter_callback_kwargs) # Now we need to make the time range objects for the cuts time_chunks = [] time_index = self.start_time time_cuts = sorted(time_cuts) for time_cut in time_cuts: # FIXME: Better error message is probably going to be helpful if self.end_time < time_cut or self.start_time > time_cut: raise Exception('Cut time provided that is outside of time range') # Create the new tail end entry for times, combine it with the # index to craft a timerange and add it to the chunk list cut_end_time = time_cut # If the chunk is not the final chunk, we want to pull # the time back by a small smidgen if cut_end_time != self.end_time: cut_end_time -= datetime.timedelta(microseconds=1) time_ending = DateTime( data=cut_end_time, data_tz=time_index.local_tz, local_tz=time_index.local_tz ) chunk_range = TimeRange(time_index,time_ending) time_chunks.append(chunk_range) # Setup the index for the next cut (the current cut # becomes the start of the next cut) time_index = DateTime( data=time_cut, data_tz=time_index.local_tz, local_tz=time_index.local_tz ) # Add the last segment if required if time_index != self.end_time: time_chunks.append( TimeRange(time_index,self.end_time) ) return time_chunks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def str(self,local): """ Return the string representation of the time range :param local: if False [default] use UTC datetime. If True use localtz """
s = self.start_time.str(local) \ + u" to " \ + self.end_time.str(local) return 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 daily_hours(self,local=False): """ This returns a number from 0 to 24 that describes the number of hours passed in a day. This is very useful for hr.attendances """
data = self.get(local) daily_hours = (data.hour + data.minute / 60.0 + data.second / 3600.0) return round(daily_hours,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 str(self,local=False,ifempty=None): """ Returns the string representation of the datetime """
ts = self.get(local) if not ts: return ifempty return ts.strftime('%Y-%m-%d %H:%M:%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 gc_velocity_update(particle, social, state): """ Guaranteed convergence velocity update. Args: particle: cipy.algorithms.pso.Particle: Particle to update the velocity for. social: cipy.algorithms.pso.Particle: The social best for the particle. state: cipy.algorithms.pso.State: The state of the PSO algorithm. Returns: numpy.ndarray: the calculated velocity. """
gbest = state.swarm[gbest_idx(state.swarm)].position if not np.array_equal(gbest, particle.position): return std_velocity(particle, social, state) rho = state.params['rho'] inertia = state.params['inertia'] v_max = state.params['v_max'] size = particle.position.size r2 = state.rng.uniform(0.0, 1.0, size) velocity = __gc_velocity_equation__(inertia, rho, r2, particle, gbest) return __clamp__(velocity, v_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_fitness(objective_function, particle): """ Calculates and updates the fitness and best_fitness of a particle. Fitness is calculated using the 'problem.fitness' function. Args: problem: The optimization problem encapsulating the fitness function and optimization type. particle: cipy.algorithms.pso.Particle: Particle to update the fitness for. Returns: cipy.algorithms.pso.Particle: A new particle with the updated fitness. """
fitness = objective_function(particle.position) best_fitness = particle.best_fitness cmp = comparator(fitness) if best_fitness is None or cmp(fitness, best_fitness): best_position = particle.position return particle._replace(fitness=fitness, best_fitness=fitness, best_position=best_position) else: return particle._replace(fitness=fitness)
<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_particle(position_update, velocity_update, state, nbest_topology, idx_particle): """ Update function for a particle. Calculates and updates the velocity and position of a particle for a single iteration of the PSO algorithm. Social best particle is determined by the state.params['topology'] function. Args: state: cipy.algorithms.pso.State: The state of the PSO algorithm. nbest_topology: dict: Containing neighbourhood best index for each particle index. idx_particle: tuple: Tuple of the index of the particle and the particle itself. Returns: cipy.algorithms.pso.Particle: A new particle with the updated position and velocity. """
(idx, particle) = idx_particle nbest = state.swarm[nbest_topology[idx]].best_position velocity = velocity_update(particle, nbest, state) position = position_update(particle.position, velocity) return particle._replace(position=position, velocity=velocity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gbest_idx(swarm): """ gbest Neighbourhood topology function. Args: swarm: list: The list of particles. Returns: int: The index of the gbest particle. """
best = 0 cmp = comparator(swarm[best].best_fitness) for (idx, particle) in enumerate(swarm): if cmp(particle.best_fitness, swarm[best].best_fitness): best = idx return best
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lbest_idx(state, idx): """ lbest Neighbourhood topology function. Neighbourhood size is determined by state.params['n_s']. Args: state: cipy.algorithms.pso.State: The state of the PSO algorithm. idx: int: index of the particle in the swarm. Returns: int: The index of the lbest particle. """
swarm = state.swarm n_s = state.params['n_s'] cmp = comparator(swarm[0].best_fitness) indices = __lbest_indices__(len(swarm), n_s, idx) best = None for i in indices: if best is None or cmp(swarm[i].best_fitness, swarm[best].best_fitness): best = i return best
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solution(swarm): """ Determines the global best particle in the swarm. Args: swarm: iterable: an iterable that yields all particles in the swarm. Returns: cipy.algorithms.pso.Particle: The best particle in the swarm when comparing the best_fitness values of the particles. """
best = swarm[0] cmp = comparator(best.best_fitness) for particle in swarm: if cmp(particle.best_fitness, best.best_fitness): best = particle return best
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_currency_view(self, select=False): """returns the newly added view"""
v = CurrencyView() self.remove_currency_view() self['hbox_top'].pack_end(v.get_top_widget()) v.light_name(select) 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 associate_by_user_id(backend, details, response, user=None, *args, **kwargs): """ Associate current auth with a user with the same Google user_id in the DB. """
if user: return None user_id = response.get('id') if user_id: # Try to associate accounts registered with the same Google user_id. for provider in ('google-appengine-oauth', 'google-appengine-oauth2'): social = backend.strategy.storage.user.get_social_auth(provider, user_id) if social: user = social.user if user: return {'user': user}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def memoize_methodcalls(func, pickle=False, dumps=pickle.dumps): '''Cache the results of the function for each input it gets called with. ''' cache = func._memoize_cache = {} @functools.wraps(func) def memoizer(self, *args, **kwargs): if pickle: key = dumps((args, kwargs)) else: key = args if key not in cache: cache[key] = func(self, *args, **kwargs) return cache[key] return memoizer
<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_section(self, section): """ Gets parameters from specific section stored in this ConfigMap. The section name is removed from parameter keys. :param section: name of the section to retrieve configuration parameters from. :return: all configuration parameters that belong to the section named 'section'. """
result = ConfigParams() prefix = section + "." for (key, value) in self.items(): # Prevents exception on the next line if len(key) < len(prefix): continue # Perform case sensitive match key_prefix = key[: len(prefix)] if key_prefix == prefix: key = key[len(prefix): ] result[key] = value 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 add_section(self, section, section_params): """ Adds parameters into this ConfigParams under specified section. Keys for the new parameters are appended with section dot prefix. :param section: name of the section where add new parameters :param section_params: new parameters to be added. """
if section == None: raise Exception("Section name cannot be null") section = "" if self._is_shadow_name(section) else section if section_params == None or len(section_params) == 0: return for (key, value) in section_params.items(): key = "" if self._is_shadow_name(key) else key if len(key) > 0 and len(section) > 0: key = section + "." + key elif len(key) == 0: key = section self[key] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def override(self, config_params): """ Overrides parameters with new values from specified ConfigParams and returns a new ConfigParams object. :param config_params: ConfigMap with parameters to override the current values. :return: a new ConfigParams object. """
map = StringValueMap.from_maps(self, config_params) return ConfigParams(map)
<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_defaults(self, default_config_params): """ Set default values from specified ConfigParams and returns a new ConfigParams object. :param default_config_params: ConfigMap with default parameter values. :return: a new ConfigParams object. """
map = StringValueMap.from_maps(default_config_params, self) return ConfigParams(map)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(obj): """Serialize the given object into JSON. Args: obj: the object to be serialized. Returns: (str): JSON representation of the given object. """
LOGGER.debug('serialize(%s)', obj) if isinstance(obj, datetime.date): return simplejson.dumps(obj, default=encoders.as_date) elif hasattr(obj, '__dict__'): return simplejson.dumps(obj, default=encoders.as_object) return simplejson.dumps(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deserialize(json, cls=None): """Deserialize a JSON string into a Python object. Args: json (str): the JSON string. cls (:py:class:`object`): if the ``json`` is deserialized into a ``dict`` and this argument is set, the ``dict`` keys are passed as keyword arguments to the given ``cls`` initializer. Returns: Python object representation of the given JSON string. """
LOGGER.debug('deserialize(%s)', json) out = simplejson.loads(json) if isinstance(out, dict) and cls is not None: return cls(**out) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(stack_name, template, mustache_variables): 'Update or create stack' template_data = _parse_template(template, mustache_variables) params = { 'StackName': stack_name, 'TemplateBody': template_data } try: if _stack_exists(stack_name): print('Updating {}'.format(stack_name)) stack_result = cf.update_stack( **params, Capabilities=['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM']) waiter = cf.get_waiter('stack_update_complete') waiter.wait(StackName=stack_name) else: print('Creating {}'.format(stack_name)) stack_result = cf.create_stack( **params, Capabilities=['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM']) try: waiter = cf.get_waiter('stack_create_complete') waiter.wait(StackName=stack_name) except Exception as ex: print(ex) print(""" There was an error creating your stack. Please go to CloudFormation in your AWS console, click on the stack you created, resolve any errors, delete the stack and try again. You are seeing this error because your stack failed to create, when stacks fail to create they are put into a terminal ROLLBACK_COMPLETE state and the stack cannot be recovered because they have no previous state to roll back to. """
) exit(1) except botocore.exceptions.ClientError as ex: error_message = ex.response['Error']['Message'] if error_message == 'No updates are to be performed.': print("No changes") else: raise else: print(json.dumps( cf.describe_stacks(StackName=stack_result['StackId']), indent=2, default=json_serial ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_extended_help(): """ Prints an extended help message. """
# initiate TextWrapper class, which will handle all of the string formatting w = textwrap.TextWrapper() w.expand_tabs = False w.width=110 w.initial_indent = ' ' w.subsequent_indent = ' ' print('') print(textwrap.fill("<split> Complete parameter list:", initial_indent='')) print('') cmd = "--input : (required) csv file to split into training and test sets" print(w.fill(cmd)) cmd = "\t\tColumns should be as follows:" print(w.fill(cmd)) print('') cmd="\t\t id, status, receptor_1, receptor_2, ..., receptor_N" print(w.fill(cmd)) cmd="\t\t CH44, 1, -9.7, -9.3, ..., -10.2" print(w.fill(cmd)) cmd="\t\t ZN44, 0, -6.6, -6.1, ..., -6.8" print(w.fill(cmd)) print('') cmd="\t\tid is a unique molecular identifier" print(w.fill(cmd)) cmd="\t\tstatus takes a value of '1' if the molecule is active and '0' otherwise." print(w.fill(cmd)) cmd="\t\treceptor_1 through receptor_N are docking scores." print(w.fill(cmd)) print('') tfrac = "--training_fraction : (optional) The fraction of input active molecules\ allocated to the training set, e.g. 0.40. Defaults to allocate half to the training\ set." print(w.fill(tfrac)) print('') d2a = "--decoy_to_active : (optional) The decoy to active ratio to establish in the \ training and validation sets. Defaults to maintain the input file ratio." print(w.fill(d2a)) print('')
<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_float(self, input_string): """ Return float type user input """
if input_string == '--training_fraction': # was the flag set? try: index = self.args.index(input_string) + 1 except ValueError: # it wasn't, it's optional, so return the appropriate default return None # the flag was set, so check if a value was set, otherwise exit try: if self.args[index] in self.flags: print("\n {flag} was set but a value was not specified".format(flag=input_string)) print_short_help() sys.exit(1) except IndexError: print("\n {flag} was set but a value was not specified".format(flag=input_string)) print_short_help() sys.exit(1) # a value was set, so check if its the correct type try: value = float(self.args[index]) except ValueError: print("\n {flag} must be a float less than or equal to 1, e.g. 0.4".format(flag=input_string)) print_short_help() sys.exit(1) if value > 1.0 or value < 0: print("\n {flag} must be a float less than or equal to 1, e.g. 0.4".format(flag=input_string)) print_short_help() sys.exit(1) # everything checks out, so return the appropriate value return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_password(from_stdin_only=False): """ Get a password either from STDIN or by prompting the user. :return: the password. """
if not sys.stdin.isatty(): password = sys.stdin.readline().strip() elif not from_stdin_only: password = getpass.getpass('Enter the password: ') else: password = None return 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 connect_signals(self, target): """ This is deprecated. Pass your controller to connect signals the old way. """
if self.connected: raise RuntimeError("GtkBuilder can only connect signals once") self.builder.connect_signals(target) self.connected = 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 create_order_keyword_list(keywords): """ Takes a given keyword list and returns a ready-to-go list of possible ordering values. Example: ['foo'] returns [('foo', ''), ('-foo', '')] """
result = [] for keyword in keywords: result.append((keyword, '')) result.append(('-%s' % keyword, '')) 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 loads(s: str, **kwargs) -> JsonObj: """ Convert a json_str into a JsonObj :param s: a str instance containing a JSON document :param kwargs: arguments see: json.load for details :return: JsonObj representing the json string """
if isinstance(s, (bytes, bytearray)): s = s.decode(json.detect_encoding(s), 'surrogatepass') return json.loads(s, object_hook=lambda pairs: JsonObj(**pairs), **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 load(source, **kwargs) -> JsonObj: """ Deserialize a JSON source. :param source: a URI, File name or a .read()-supporting file-like object containing a JSON document :param kwargs: arguments. see: json.load for details :return: JsonObj representing fp """
if isinstance(source, str): if '://' in source: req = Request(source) req.add_header("Accept", "application/json, text/json;q=0.9") with urlopen(req) as response: jsons = response.read() else: with open(source) as f: jsons = f.read() elif hasattr(source, "read"): jsons = source.read() else: raise TypeError("Unexpected type {} for source {}".format(type(source), source)) return loads(jsons, **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 as_json(obj: JsonObj, indent: Optional[str]=' ', **kwargs) -> str: """ Convert obj to json string representation. :param obj: pseudo 'self' :param indent: indent argument to dumps :param kwargs: other arguments for dumps :return: JSON formatted string """
return obj._as_json_dumps(indent, **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(obj: JsonObj, item: str, default: JsonObjTypes=None) -> JsonObjTypes: """ Dictionary get routine """
return obj._get(item, 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 setdefault(obj: JsonObj, k: str, value: Union[Dict, JsonTypes]) -> JsonObjTypes: """ Dictionary setdefault reoutine """
return obj._setdefault(k, 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 _default(self, obj): """ return a serialized version of obj or raise a TypeError :param obj: :return: Serialized version of obj """
return obj.__dict__ if isinstance(obj, JsonObj) else json.JSONDecoder().decode(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _as_json(self, **kwargs) -> str: """ Convert a JsonObj into straight json text :param kwargs: json.dumps arguments :return: JSON formatted str """
return json.dumps(self, default=self._default, **kwargs)