text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by_tags(and_tags=None, or_tags=None, _connection=None, page_size=100, page_number=0, sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):...
err = None if not and_tags and not or_tags: err = "You must supply at least one of either and_tags or or_tags." if and_tags and not isinstance(and_tags, (tuple, list)): err = "The and_tags argument for Video.find_by_tags must an " err += "iterable" 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 find_by_text(text, _connection=None, page_size=100, page_number=0, sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER): """ List videos that ...
return connection.ItemResultSet('find_videos_by_text', Video, _connection, page_size, page_number, sort_by, sort_order, text=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 find_by_campaign(campaign_id, _connection=None, page_size=100, page_number=0, sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER): """ List a...
return connection.ItemResultSet( 'find_videos_by_campaign_id', Video, _connection, page_size, page_number, sort_by, sort_order, campaign_id=campaign_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by_user(user_id, _connection=None, page_size=100, page_number=0, sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER): """ List all video...
return connection.ItemResultSet('find_videos_by_user_id', Video, _connection, page_size, page_number, sort_by, sort_order, user_id=user_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by_reference_ids(reference_ids, _connection=None, page_size=100, page_number=0, sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER): """...
if not isinstance(reference_ids, (list, tuple)): err = "Video.find_by_reference_ids expects an iterable argument" raise exceptions.PyBrightcoveError(err) ids = ','.join(reference_ids) return connection.ItemResultSet( 'find_videos_by_reference_ids', Video, _co...
<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_by_ids(ids, _connection=None, page_size=100, page_number=0, sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER): """ List all videos ide...
if not isinstance(ids, (list, tuple)): err = "Video.find_by_ids expects an iterable argument" raise exceptions.PyBrightcoveError(err) ids = ','.join([str(i) for i in ids]) return connection.ItemResultSet('find_videos_by_ids', Video, _connection, page_size, pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __wrap(self, func): '''This decorator overrides the default arguments of a function. For each keyword argument in the function, the decorator first checks if the argument has been overridden by the caller, and uses that value instead if so. If not, the decorator consults the Preset...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sumDiceRolls(self, rollList): """convert from dice roll structure to a single integer result"""
if isinstance(rollList, RollList): self.rolls.append(rollList) return rollList.sum() else: return rollList
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotated_references(obj): """ Return known information about references held by the given object. Returns a mapping from referents to lists of descriptions....
references = KeyTransformDict(transform=id, default_factory=list) for type_ in type(obj).__mro__: if type_ in type_based_references: type_based_references[type_](obj, references) add_attr(obj, "__dict__", references) add_attr(obj, "__class__", references) if isinstance(obj, typ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def object_annotation(obj): """ Return a string to be used for Graphviz nodes. The string should be short but as informative as possible. """
# For basic types, use the repr. if isinstance(obj, BASE_TYPES): return repr(obj) if type(obj).__name__ == 'function': return "function\\n{}".format(obj.__name__) elif isinstance(obj, types.MethodType): if six.PY2: im_class = obj.im_class if im_class is 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 disttar(target, source, env): """tar archive builder"""
import tarfile env_dict = env.Dictionary() if env_dict.get("DISTTAR_FORMAT") in ["gz", "bz2"]: tar_format = env_dict["DISTTAR_FORMAT"] else: tar_format = "" # split the target directory, filename, and stuffix base_name = str(target[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 disttar_suffix(env, sources): """tar archive suffix generator"""
env_dict = env.Dictionary() if env_dict.has_key("DISTTAR_FORMAT") and env_dict["DISTTAR_FORMAT"] in ["gz", "bz2"]: return ".tar." + env_dict["DISTTAR_FORMAT"] else: return ".tar"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(env): """ Add builders and construction variables for the DistTar builder. """
disttar_action=SCons.Action.Action(disttar, disttar_string) env['BUILDERS']['DistTar'] = Builder( action=disttar_action , emitter=disttar_emitter , suffix = disttar_suffix , target_factory = env.fs.Entry ) env.AppendUnique( DISTTAR_FORMAT = 'gz...
<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_one(self, cls, id): """Find single keyed row - as per the gludb spec."""
found = self.find_by_index(cls, 'id', id) return found[0] if found else None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, obj): """Save current instance - as per the gludb spec."""
cur = self._conn().cursor() tabname = obj.__class__.get_table_name() index_names = obj.__class__.index_names() or [] col_names = ['id', 'value'] + index_names value_holders = ['%s'] * len(col_names) updates = ['%s = EXCLUDED.%s' % (cn, cn) for cn in col_names[1:]] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticated_get(username, password, url, verify=True): """ Perform an authorized query to the url, and return the result """
try: response = requests.get(url, auth=(username, password), verify=verify) if response.status_code == 401: raise BadCredentialsException( "Unable to authenticate user %s to %s with password provided!" % (username, url)) except requests.exceptions.SSL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleaned_request(request_type, *args, **kwargs): """ Perform a cleaned requests request """
s = requests.Session() # this removes netrc checking s.trust_env = False return s.request(request_type, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_to_bytesio(url): """ Return a bytesio object with a download bar """
logger.info("Downloading url: {0}".format(url)) r = cleaned_request('get', url, stream=True) stream = io.BytesIO() total_length = int(r.headers.get('content-length')) for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): if chunk: str...
<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(one, two=4, three=False): ''' This function adds two number. :param one: first number to add :param two: second number to add :rtype: int ''' s = str(int(one) + int(two)) logging.debug('logging sum from hello.py:' + s) print 'printing sum from hello.py:', s 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 queue(self): """Message queue queue."""
with self.connection_pool.acquire(block=True) as conn: return Q( self.routing_key, exchange=self.exchange, routing_key=self.routing_key )(conn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exists(self): """Test if this queue exists in the AMQP store. Note: This doesn't work with redis as declaring queues has not effect except creating the excha...
try: queue = self.queue queue.queue_declare(passive=True) except NotFound: return False except ChannelError as e: if e.reply_code == '404': return False raise e 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 create_consumer(self): """Context manager that yields an instance of ``Consumer``."""
with self.connection_pool.acquire(block=True) as conn: yield self.consumer(conn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(self, events): """Publish events."""
assert len(events) > 0 with self.create_producer() as producer: for event in events: producer.publish(event)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume(self, payload=True): """Consume events."""
with self.create_consumer() as consumer: for msg in consumer.iterqueue(): yield msg.payload if payload else msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_initial(self, *args, **kwargs): """ Gathers initial form values from user and profile objects suitable for using as form's initial data. """
initial = {} for field in self.fields: value = None if hasattr(self.user, field): value = getattr(self.user, field) if hasattr(self.profile, field): value = getattr(self.profile, field) if value: initial.upd...
<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, *args, **kwargs): """ This method should be called when is_valid is true to save relevant fields to user and profile models. """
for key, value in self.cleaned_data.items(): if value != None: if hasattr(self.user, key): setattr(self.user, key, value) if hasattr(self.profile, key): setattr(self.profile, key, value) # set password if 'pass...
<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_username(self): """ Validate that the username is alphanumeric and is not already in use. Don't fail if users username is provided. """
user = None try: user = User.objects.get(username__iexact=self.\ cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] if user: if user.username == self.user.username: return self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_body_part(self, key, data, mime_type, size=None): """Adds data to the HTTP request body. If more than one part is added, this is assumed to be a mime-mul...
if isinstance(data, str): size = len(data) if hasattr(data, "fileno"): size = os.fstat(data.fileno())[stat.ST_SIZE] if size is None: # TODO: support chunked transfer if some of the body is of unknown size. raise UnknownSize('Each part of the body must have a known size.') if 'Co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _copy(self): """Creates a deep copy of this request."""
copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port, self.uri.path, self.uri.query.copy()) new_request = HttpRequest(uri=copied_uri, method=self.method, headers=self.headers.copy()) new_request._body_parts = self._body_parts[:] return new_re...
<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_relative_path(self): """Returns the path with the query parameters escaped and appended."""
param_string = self._get_query_string() if self.path is None: path = '/' else: path = self.path if param_string: return '?'.join([path, param_string]) else: return 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 modify_request(self, http_request=None): """Sets HTTP request components based on the URI."""
if http_request is None: http_request = HttpRequest() if http_request.uri is None: http_request.uri = Uri() # Determine the correct scheme. if self.scheme: http_request.uri.scheme = self.scheme if self.port: http_request.uri.port = self.port if self.host: http_requ...
<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_uri(uri_string): """Creates a Uri object which corresponds to the URI string. This method can accept partial URIs, but it will leave missing members of...
parts = urlparse.urlparse(uri_string) uri = Uri() if parts[0]: uri.scheme = parts[0] if parts[1]: host_parts = parts[1].split(':') if host_parts[0]: uri.host = host_parts[0] if len(host_parts) > 1: uri.port = int(host_parts[1]) if parts[2]: uri.path = 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 next(self): " Move on to the next character in the text. " char = self.char if char == '\n': self.lineno += 1 self.colno = 0 else: self.colno += 1 self.index += 1 return self.char
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def readline(self): " Reads a full line from the scanner and returns it. " start = end = self.index while end < len(self.text): if self.text[end] == '\n': end += 1 break end += 1 result = self.text[start:end] self.index = end if result.endswith('\n'): self.coln...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self, *names, **kwargs): """ Extracts a token of one of the specified rule names and doesn't error if unsuccessful. Skippable tokens might still be sk...
return self.next(*names, as_accept=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 append(self, event, help=""): """Creates a new event. `event` may be iterable or string Args: event (str): Name of event to declare Kwrgs: help (str): Help...
if isinstance(event, str): self._events[event] = HookList(is_waterfall=self.is_waterfall) self._help[event] = (help, getframeinfo(stack()[1][0])) if not help: logger.warning("Great, don't say anything about your hooks and \ wait for plugin cr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hook(self, function, event, dependencies): """Tries to load the hook to the event Args: function (func): Function that will be called when the event is call...
# Hooks all events (recursively) if event is None: for e in self._events.keys(): self.hook(function, e, dependencies) return # Hook multiple, but specific events (recursively) if not isinstance(event, str) and isinstance(event, Iterable): ...
<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_message(self, message, verbosity_needed=1): """ Prints the message, if verbosity is high enough. """
if self.args.verbosity >= verbosity_needed: print(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 error(self, message, code=1): """ Prints the error, and exits with the given code. """
sys.stderr.write(message) sys.exit(code)
<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_db_settings(self, settings): """ Parse out database settings from filename or DJANGO_SETTINGS_MODULE. """
if settings == 'DJANGO_SETTINGS_MODULE': django_settings = os.environ.get('DJANGO_SETTINGS_MODULE') self.print_message("Getting settings file from DJANGO_SETTINGS_MODULE=%s" % django_settings) path_pieces = django_settings.split('.') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_db_args(self, settings, db_key): """ Initialize connection arguments for postgres commands. """
self.print_message("Initializing database settings for %s" % db_key, verbosity_needed=2) db_member = self.databases[db_key] db_name = settings.get('NAME') if db_name and not db_member['name']: db_member['name'] = db_name db_member['password'] = settings.get('PASSW...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_file(self, url, filename): """ Download file from url to filename. """
self.print_message("Downloading to file '%s' from URL '%s'" % (filename, url)) try: db_file = urllib2.urlopen(url) with open(filename, 'wb') as output: output.write(db_file.read()) db_file.close() except Exception as e: self.error(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unzip_file_if_necessary(self, source_file): """ Unzip file if zipped. """
if source_file.endswith(".gz"): self.print_message("Decompressing '%s'" % source_file) subprocess.check_call(["gunzip", "--force", source_file]) source_file = source_file[:-len(".gz")] return source_file
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_file_from_url(self, source_app, url): """ Download file from source app or url, and return local filename. """
if source_app: source_name = source_app else: source_name = urlparse.urlparse(url).netloc.replace('.', '_') filename = self.create_file_name(source_name) self.download_file(url, filename) return filename
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_database(self): """ Create dumpfile from postgres database, and return filename. """
db_file = self.create_file_name(self.databases['source']['name']) self.print_message("Dumping postgres database '%s' to file '%s'" % (self.databases['source']['name'], db_file)) self.export_pgpassword('source') args = [ "pg_dump", "-Fc"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drop_database(self): """ Drop postgres database. """
self.print_message("Dropping database '%s'" % self.databases['destination']['name']) self.export_pgpassword('destination') args = [ "dropdb", "--if-exists", self.databases['destination']['name'], ] args.extend(self.databases['destination']['ar...
<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_database(self): """ Create postgres database. """
self.print_message("Creating database '%s'" % self.databases['destination']['name']) self.export_pgpassword('destination') args = [ "createdb", self.databases['destination']['name'], ] args.extend(self.databases['destination']['args']) for arg 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 replace_postgres_db(self, file_url): """ Replace postgres database with database from specified source. """
self.print_message("Replacing postgres database") if file_url: self.print_message("Sourcing data from online backup file '%s'" % file_url) source_file = self.download_file_from_url(self.args.source_app, file_url) elif self.databases['source']['name']: self.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 capture_heroku_database(self): """ Capture Heroku database backup. """
self.print_message("Capturing database backup for app '%s'" % self.args.source_app) args = [ "heroku", "pg:backups:capture", "--app=%s" % self.args.source_app, ] if self.args.use_pgbackups: args = [ "heroku", ...
<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_heroku_database(self): """ Reset Heroku database. """
self.print_message("Resetting database for app '%s'" % self.args.destination_app) args = [ "heroku", "pg:reset", "--app=%s" % self.args.destination_app, "DATABASE_URL", ] subprocess.check_call(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 replace_heroku_db(self, file_url): """ Replace Heroku database with database from specified source. """
self.print_message("Replacing database for Heroku app '%s'" % self.args.destination_app) self.reset_heroku_database() if file_url: self.print_message("Restoring from URL '%s'" % file_url) args = [ "heroku", "pg:backups:restore", ...
<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): """ Replace a database with the data from the specified source. """
self.print_message("\nBeginning database replacement process.\n") if self.args.source_settings: settings = self.parse_db_settings(self.args.source_settings) self.initialize_db_args(settings, 'source') if self.args.settings: settings = self.parse_db_settings...
<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_task_modules(): """ Import all installed apps and add modules to registry """
top_level_modules = settings.INSTALLED_APPS module_names = [] for module in top_level_modules: #Import package mod = import_module(module) #Find all modules in package path for loader, module_name, is_pkg in pkgutil.walk_packages(mod.__path__): if not module_nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self, service_rec=None, host_rec=None, hostfilter=None): """ List a specific service or all services :param service_rec: t_services.id :param host_rec: ...
return self.send.service_list(service_rec, host_rec, hostfilter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def info(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Information about a service. :param svc_rec: t_services.id :param ipaddr: IP Address :param...
return self.send.service_info(svc_rec, ipaddr, proto, port)
<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(self, ipaddr=None, proto=None, port=None, fields=None): """ Add a service record :param ipaddr: IP Address :param proto: Protocol (tcp, udp, info) :param...
return self.send.service_add(ipaddr, proto, port, 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 delete(self, svc_rec=None, ipaddr=None, proto=None, port=None): """ Delete a t_services record :param svc_rec: t_services.id :param ipaddr: IP Address or t_h...
return self.send.service_del(svc_rec, ipaddr, proto, port)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vulns_list(self, service_id=None, service_port=None, hostfilter=None): """ List of vulnerabilities for a service :param service_id: t_services.id :param serv...
return self.send.service_vulns_list(service_id, service_port, hostfilter)
<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(nodes): ''' Connect a list of nodes. Connected nodes have an ``output`` member which is the following node in the line. The last node's ``output`` is a :class:`Queue` for easy plumbing. ''' for a, b in zip(nodes[:-1], nodes[1:]): a.output = b b.output = queues.Queue(...
<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_layout(layout_name, content, **context): """Uses a jinja template to wrap the content inside a layout. Wraps the content inside a block and adds the e...
layout_block = "content" if ":" in layout_name: layout_name, layout_block = layout_name.split(":") tpl = '{%% extends "%s" %%}{%% block %s %%}%s{%% endblock %%}' % (layout_name, layout_block, content) return render_template_string(tpl, **context)
<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_template(app, filename): """Parses the given template using the jinja environment of the given app and returns the AST. ASTs are cached in parse_templa...
if not hasattr(parse_template, "cache"): parse_template.cache = {} if filename not in parse_template.cache: source = get_template_source(app, filename) parse_template.cache[filename] = app.jinja_env.parse(source, filename=filename) return parse_template.cache[filename]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jinja_node_to_python(node): """Converts a Jinja2 node to its python equivalent """
if isinstance(node, nodes.Const): return node.value if isinstance(node, nodes.Neg): return -jinja_node_to_python(node.node) if isinstance(node, nodes.Name): return node.name if isinstance(node, (nodes.List, nodes.Tuple)): value = [] for i in node.items: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def in_group(self, group, dn=False): """Get whether or not the bound CSH LDAP member object is part of a group. Arguments: group -- the CSHGroup object (or disti...
if dn: return group in self.groups() return group.check_member(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 savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0, axis=-1, mode='interp', cval=0.0): ''' Wrapper for the scipy.signal.savgol_filter function that handles Nan values. See: https://github.com/wheeler-microfluidics/dmf-control-board-firmware/issues/3 Returns ------- y : ndarray, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def feedback_results_to_measurements_frame(feedback_result): ''' Extract measured data from `FeedbackResults` instance into `pandas.DataFrame`. ''' index = pd.Index(feedback_result.time * 1e-3, name='seconds') df_feedback = pd.DataFrame(np.column_stack([feedback_result.V_fb, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def feedback_results_to_impedance_frame(feedback_result): ''' Extract computed impedance data from `FeedbackResults` instance into `pandas.DataFrame`. ''' index = pd.Index(feedback_result.time * 1e-3, name='seconds') df_feedback = pd.DataFrame(np.column_stack([feedback_result.V_actuation() ...
<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_firmwares(): ''' Return `dmf_control_board` compiled Arduino hex file paths. This function may be used to locate firmware binaries that are available for flashing to [Arduino Mega2560][1] boards. [1]: http://arduino.cc/en/Main/arduinoBoardMega2560 ''' return OrderedDict([(board_dir...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def remote_command(function, self, *args, **kwargs): ''' Catch `RuntimeError` exceptions raised by remote control board firmware commands and re-raise as more specific `FirmwareError` exception type, which includes command code and return code. ''' try: return function(self, *args, **kwa...
<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_frame(self, filter_order=3): """ Convert data to a `pandas.DataFrame`. Parameters filter_order : int Filter order to use when filtering Z_device, capacita...
window_size = self._get_window_size() L = np.sqrt(self.area) velocity_results = self.mean_velocity(Lx=L) mean_velocity = None peak_velocity = None dx = 0 dt = 0 dxdt = np.zeros(len(self.time)) dxdt_filtered = np.zeros(len(self.time)) # 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 set_series_capacitance(self, channel, value, resistor_index=None): ''' Set the current series capacitance value for the specified channel. Parameters ---------- channel : int Analog channel index. value : float Series capacitance 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 set_series_resistance(self, channel, value, resistor_index=None): ''' Set the current series resistance value for the specified channel. Parameters ---------- channel : int Analog channel index. value : float Series resistance value. 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 persistent_write(self, address, byte, refresh_config=False): ''' Write a single byte to an address in persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). byte : int Value to write to address. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def persistent_read_multibyte(self, address, count=None, dtype=np.uint8): ''' Read a chunk of data from persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). count : int, optional Number of values to 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 persistent_write_multibyte(self, address, data, refresh_config=False): ''' Write multiple bytes to an address in persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). data : numpy.array Data to wri...
<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_files_modified(): """Get the list of modified files that are Python or Jinja2."""
cmd = "git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD" _, files_modified, _ = run(cmd) extensions = [re.escape(ext) for ext in list(SUPPORTED_FILES) + [".rst"]] test = "(?:{0})$".format("|".join(extensions)) return list(filter(lambda f: re.search(test, f), files_modified))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_git_author(): """Return the git author from the git variables."""
_, stdout, _ = run("git var GIT_AUTHOR_IDENT") git_author = stdout[0] return git_author[:git_author.find(">") + 1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_component(filename, default="global"): """Get component name from filename."""
if hasattr(filename, "decode"): filename = filename.decode() parts = filename.split(os.path.sep) if len(parts) >= 3: if parts[1] in "modules legacy ext".split(): return parts[2] if len(parts) >= 2: if parts[1] in "base celery utils".split(): return parts...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_commit_msg(tmp_file, author, files_modified=None, template=None): """Prepare the commit message in tmp_file. It will build the commit message prefil...
files_modified = files_modified or [] template = template or "{component}:\n\nSigned-off-by: {author}\n{extra}" if hasattr(template, "decode"): template = template.decode() with open(tmp_file, "r", "utf-8") as fh: contents = fh.readlines() msg = filter(lambda x: not (x.startswi...
<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_message(message, options): """Checking the message and printing the errors."""
options = options or dict() options.update(get_options()) options.update(_read_local_kwalitee_configuration()) errors = check_message(message, **options) if errors: for error in errors: print(error, file=sys.stderr) 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 _read_local_kwalitee_configuration(directory="."): """Check if the repo has a ``.kwalitee.yaml`` file."""
filepath = os.path.abspath(os.path.join(directory, '.kwalitee.yml')) data = {} if os.path.exists(filepath): with open(filepath, 'r') as file_read: data = yaml.load(file_read.read()) 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 _pre_commit(files, options): """Run the check on files of the added version. They might be different than the one on disk. Equivalent than doing a git stash,...
errors = [] tmpdir = mkdtemp() files_to_check = [] try: for (file_, content) in files: # write staged version of file to temporary directory dirname, filename = os.path.split(os.path.abspath(file_)) prefix = os.path.commonprefix([dirname, tmpdir]) ...
<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(command, raw_output=False): """Run a command using subprocess. :param command: command line to be run :type command: str :param raw_output: does not atte...
p = Popen(command.split(), stdout=PIPE, stderr=PIPE) (stdout, stderr) = p.communicate() # On python 3, subprocess.Popen returns bytes objects. if not raw_output: return ( p.returncode, [line.rstrip() for line in stdout.decode("utf-8").splitlines()], [line.rst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mpl_weight2qt(weight): """Convert a weight from matplotlib definition to a Qt weight Parameters weight: int or string Either an integer between 1 and 1000 or...
try: weight = weights_mpl2qt[weight] except KeyError: try: weight = float(weight) / 10 except (ValueError, TypeError): weight = QtGui.QFont.Normal else: try: weight = min(filter(lambda w: w >= weight, weights_qt2mpl), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def choose_font(self, font=None): """Choose a font for the label through a dialog"""
fmt_widget = self.parent() if font is None: if self.current_font: font, ok = QFontDialog.getFont( self.current_font, fmt_widget, 'Select %s font' % self.fmto_name, QFontDialog.DontUseNativeDialog) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self): """Refresh the widgets from the current font"""
font = self.current_font # refresh btn_bold self.btn_bold.blockSignals(True) self.btn_bold.setChecked(font.weight() > 50) self.btn_bold.blockSignals(False) # refresh btn_italic self.btn_italic.blockSignals(True) self.btn_italic.setChecked(font.italic())...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prettify_response(self, response): """ Prettify the HTML response. :param response: A Flask Response object. """
if response.content_type == 'text/html; charset=utf-8': ugly = response.get_data(as_text=True) soup = BeautifulSoup(ugly, 'html.parser') pretty = soup.prettify(formatter='html') response.direct_passthrough = False response.set_data(pretty) re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _call(self, params): """Call the SABnzbd API"""
if self._session.closed: raise SabnzbdApiException('Session already closed') p = {**self._default_params, **params} try: async with timeout(self._timeout, loop=self._session.loop): async with self._session.get(self._api_url, params=p) as resp: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def refresh_data(self): """Refresh the cached SABnzbd queue data"""
queue = await self.get_queue() history = await self.get_history() totals = {} for k in history: if k[-4:] == 'size': totals[k] = self._convert_size(history.get(k)) self.queue = {**totals, **queue}
<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_size(self, size_str): """Convert units to GB"""
suffix = size_str[-1] if suffix == 'K': multiplier = 1.0 / (1024.0 * 1024.0) elif suffix == 'M': multiplier = 1.0 / 1024.0 elif suffix == 'T': multiplier = 1024.0 else: multiplier = 1 try: val = float(size_str....
<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_error(self, data, params): """Handle an error response from the SABnzbd API"""
error = data.get('error', 'API call failed') mode = params.get('mode') raise SabnzbdApiException(error, mode=mode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __generate_key(self, config): """ Generate the ssh key, and return the ssh config location """
cwd = config.get('ssh_path', self._install_directory()) if config.is_affirmative('create', default="yes"): if not os.path.exists(cwd): os.makedirs(cwd) if not os.path.exists(os.path.join(cwd, config.get('keyname'))): command = "ssh-keygen -t %(typ...
<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_ssh_config(self, config): """ Install the ssh configuration """
if not config.is_affirmative('use_global_ssh', default="no"): ssh_config_injection = self._build_ssh_config(config) if not os.path.exists(ssh_config_path): if self.injections.in_noninjected_file(ssh_config_path, "Host %s" % config.get('host')): if c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_ssh_config(self, config): """ build the ssh injection configuration """
ssh_config_injection = ssh_config_template % { 'host': config.get('host'), 'hostname': config.get('hostname'), 'ssh_key_path': config.get('ssh_key_path'), 'user': config.get('user') } if config.has('port'): ssh_config_injection += " 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 extract_followups(task): """ Retrieve callbacks and errbacks from provided task instance, disables tasks callbacks. """
callbacks = task.request.callbacks errbacks = task.request.errbacks task.request.callbacks = None return {'link': callbacks, 'link_error': errbacks}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gen_procfile(ctx, wsgi, dev): """Generates Procfiles which can be used with honcho or foreman. """
if wsgi is None: if os.path.exists("wsgi.py"): wsgi = "wsgi.py" elif os.path.exists("app.py"): wsgi = "app.py" else: wsgi = "app.py" ctx.invoke(gen_apppy) def write_procfile(filename, server_process, debug): processes = [server_pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def g(self): "Hour, 12-hour format without leading zeros; i.e. '1' to '12'" if self.data.hour == 0: return 12 if self.data.hour > 12: return self.data.hour - 12 return self.data.hour
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def I(self): "'1' if Daylight Savings Time, '0' otherwise." if self.timezone and self.timezone.dst(self.data): return u'1' else: return u'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 S(self): "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'" if self.data.day in (11, 12, 13): # Special case return u'th' last = self.data.day % 10 if last == 1: return u'st' if last == 2: return u'nd' if last == 3: return u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def t(self): "Number of days in the given month; i.e. '28' to '31'" return u'%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def W(self): "ISO-8601 week number of year, weeks starting on Monday" # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt week_number = None jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1 weekday = self.data.weekday() + 1 day_of_year = self.z() if day_of_year <...