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): """ List videos given a certain set of tags. """
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 or_tags and not isinstance(or_tags, (tuple, list)): err = "The or_tags argument for Video.find_by_tags must an " err += "iterable" if err: raise exceptions.PyBrightcoveError(err) atags = None otags = None if and_tags: atags = ','.join([str(t) for t in and_tags]) if or_tags: otags = ','.join([str(t) for t in or_tags]) return connection.ItemResultSet('find_videos_by_tags', Video, _connection, page_size, page_number, sort_by, sort_order, and_tags=atags, or_tags=otags)
<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 match the ``text`` in title or description. """
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 all videos for a given campaign. """
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 videos uploaded by a certain user. """
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): """ List all videos identified by a list of reference ids """
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, _connection, page_size, page_number, sort_by, sort_order, reference_ids=ids)
<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 identified by a list of Brightcove video ids """
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, page_number, sort_by, sort_order, video_ids=ids)
<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 object for an override value. If both of the above cases fail, the decorator reverts to the function's native default parameter value. ''' def deffunc(*args, **kwargs): '''The decorated function''' # Get the list of function arguments if hasattr(inspect, 'signature'): # Python 3.5 function_args = inspect.signature(func).parameters else: function_args = inspect.getargspec(func).args # Construct a dict of those kwargs which appear in the function filtered_kwargs = kwargs.copy() # look at all relevant keyword arguments for this function for param in function_args: if param in kwargs: # Did the user override the default? filtered_kwargs[param] = kwargs[param] elif param in self._defaults: # Do we have a clobbering value in the default dict? filtered_kwargs[param] = self._defaults[param] # Call the function with the supplied args and the filtered kwarg dict return func(*args, **filtered_kwargs) # pylint: disable=W0142 wrapped = functools.update_wrapper(deffunc, func) # force-mangle the docstring here wrapped.__doc__ = ('WARNING: this function has been modified by the Presets ' 'package.\nDefault parameter values described in the ' 'documentation below may be inaccurate.\n\n{}'.format(wrapped.__doc__)) 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 _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. Note that there may be more than one edge leading to any particular referent; hence the need for a list. Descriptions are currently strings. """
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, type): add_attr(obj, "__mro__", references) return references
<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 None: im_class_name = "<None>" else: im_class_name = im_class.__name__ try: func_name = obj.__func__.__name__ except AttributeError: func_name = "<anonymous>" return "instancemethod\\n{}.{}".format( im_class_name, func_name, ) else: try: func_name = obj.__func__.__qualname__ except AttributeError: func_name = "<anonymous>" return "instancemethod\\n{}".format(func_name) elif isinstance(obj, list): return "list[{}]".format(len(obj)) elif isinstance(obj, tuple): return "tuple[{}]".format(len(obj)) elif isinstance(obj, dict): return "dict[{}]".format(len(obj)) elif isinstance(obj, types.ModuleType): return "module\\n{}".format(obj.__name__) elif isinstance(obj, type): return "type\\n{}".format(obj.__name__) elif six.PY2 and isinstance(obj, types.InstanceType): return "instance\\n{}".format(obj.__class__.__name__) elif isinstance(obj, weakref.ref): referent = obj() if referent is None: return "weakref (dead referent)" else: return "weakref to id 0x{:x}".format(id(referent)) elif isinstance(obj, types.FrameType): filename = obj.f_code.co_filename if len(filename) > FRAME_FILENAME_LIMIT: filename = "..." + filename[-(FRAME_FILENAME_LIMIT-3):] return "frame\\n{}:{}".format( filename, obj.f_lineno, ) else: return "object\\n{}.{}".format( type(obj).__module__, type(obj).__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 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]).split('.tar')[0] (target_dir, dir_name) = os.path.split(base_name) # create the target directory if it does not exist if target_dir and not os.path.exists(target_dir): os.makedirs(target_dir) # open our tar file for writing print >> sys.stderr, 'DistTar: Writing %s' % str(target[0]) print >> sys.stderr, ' with contents: %s' % [str(s) for s in source] tar = tarfile.open(str(target[0]), "w:%s" % tar_format) # write sources to our tar file for item in source: item = str(item) sys.stderr.write(".") #print "Adding to TAR file: %s/%s" % (dir_name,item) tar.add(item,'%s/%s' % (dir_name,item)) # all done sys.stderr.write("\n") #print "Closing TAR file" tar.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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:]] if not obj.id: id = uuid() obj.id = id query = 'insert into {0} ({1}) values ({2}) on conflict(id) do update set {3};'.format( tabname, ','.join(col_names), ','.join(value_holders), ','.join(updates), ) values = [obj.id, obj.to_data()] index_vals = obj.indexes() or {} values += [index_vals.get(name, 'NULL') for name in index_names] with self._conn() as conn: with conn.cursor() as cur: cur.execute(query, tuple(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 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.SSLError: raise CertificateException("Unable to verify certificate at %s!" % url) return response.content
<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: stream.write(chunk) stream.seek(0) return 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 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 exchange. :returns: True if the queue exists, else False. :rtype: bool """
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.update({ field: value }) if hasattr(self.profile, 'dob'): dob = self.profile.dob if dob: if 'dob_day' in self.fields: initial.update({ 'dob_day': dob.day }) if 'dob_month' in self.fields: initial.update({ 'dob_month': dob.month }) if 'dob_year' in self.fields: initial.update({ 'dob_year': dob.year }) return initial
<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 'password1' in self.cleaned_data: if self.cleaned_data['password1']: self.user.set_password(self.cleaned_data['password1']) # set dob if 'dob_day' in self.cleaned_data and 'dob_month' in self.\ cleaned_data and 'dob_year' in self.cleaned_data: self.profile.dob = self._gen_dob() self.user.save() self.profile.save()
<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.cleaned_data['username'] raise forms.ValidationError(_(\ "A user with that username already exists."))
<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-multipart request. This method is designed to create MIME 1.0 requests as specified in RFC 1341. Args: data: str or a file-like object containing a part of the request body. mime_type: str The MIME type describing the data size: int Required if the data is a file like object. If the data is a string, the size is calculated so this parameter is ignored. """
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 'Content-Length' in self.headers: content_length = int(self.headers['Content-Length']) else: content_length = 0 # If this is the first part added to the body, then this is not a multipart # request. boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,) self._body_parts.append(boundary_string) content_length += len(boundary_string) + size # Include the mime type of this part. cd = 'Content-Disposition: form-data; name="%s"' % key mt = mime_type if hasattr(data, "fileno"): cd += '; filename="%s"' % data.name.split('/')[-1] mt = mimetypes.guess_type(data.name)[0] or 'application/octet-stream' cd += '\r\n' type_string = 'Content-Type: %s\r\n\r\n' % (mt) self._body_parts.append(cd) self._body_parts.append(type_string) content_length += len(type_string) + len(cd) self._body_parts.append(data) self.headers['Content-Length'] = str(content_length)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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_request
<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_request.uri.host = self.host # Set the relative uri path if self.path: http_request.uri.path = self.path if self.query: http_request.uri.query = self.query.copy() return http_request
<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 the Uri unset. """
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 = parts[2] if parts[4]: param_pairs = parts[4].split('&') for pair in param_pairs: pair_parts = pair.split('=') if len(pair_parts) > 1: uri.query[urllib.unquote_plus(pair_parts[0])] = ( urllib.unquote_plus(pair_parts[1])) elif len(pair_parts) == 1: uri.query[urllib.unquote_plus(pair_parts[0])] = None return uri
<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.colno = 0 self.lineno += 1 else: self.colno += end - start 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 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 skipped by this method. # Arguments names (str): One or more token names that are accepted. kwargs: Additional keyword arguments for #next(). # Raises ValueError: if a rule with the specified name doesn't exist. """
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 string for the event Raises: TypeError **Please** describe the event and its calling arguments in the help string. """
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 creators to figure it out.") elif isinstance(event, Iterable): # Depricated. It does not give the ability to give help string # TODO: Remove this for name in event: self.append(name) else: raise TypeError("Invalid event 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 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 called Kwargs: dependencies (str): String or Iterable with modules whose hooks should be called before this one Raises: NameError Note that the dependencies are module-wide, that means that if `parent.foo` and `parent.bar` are both subscribed to `example` event and `child` enumerates `parent` as dependcy, **both** `foo` and `bar` must be called in order for the dependcy to get resolved. """
# 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): for e in event: self.hook(function, e, dependencies) return # Hook a simple event event_list = self._events.get(event, None) if event_list is None: raise NameError( "Invalid key provided '%s'. Valid options: %s" % (event, ", ".join(self._events.keys())) ) return return event_list.hook(function, dependencies)
<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('.') path_pieces[-1] = '%s.py' % path_pieces[-1] settings = os.path.join(*path_pieces) self.print_message("Parsing settings from settings file '%s'" % settings) parser = DatabaseSettingsParser() with open(settings) as settings_file: settings_ast = ast.parse(settings_file.read()) parser.visit(settings_ast) try: return parser.database_settings['default'] except KeyError as e: self.error("Missing key or value for: %s\nSettings must be of the form: %s" % (e, self.settings_format))
<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('PASSWORD') args = [] for key in ['USER', 'HOST', 'PORT']: value = settings.get(key) if value: self.print_message("Adding parameter %s" % key.lower, verbosity_needed=2) args.append('--%s=%s' % (key.lower(), value)) db_member['args'] = 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 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(str(e)) self.print_message("File downloaded")
<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", "--no-acl", "--no-owner", "--dbname=%s" % self.databases['source']['name'], "--file=%s" % db_file, ] args.extend(self.databases['source']['args']) subprocess.check_call(args) return db_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 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']['args']) 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 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 self.databases['destination']['args']: if arg[:7] == '--user=': args.append('--owner=%s' % arg[7:]) 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_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.print_message("Sourcing data from database '%s'" % self.databases['source']['name']) source_file = self.dump_database() else: self.print_message("Sourcing data from local backup file %s" % self.args.file) source_file = self.args.file self.drop_database() self.create_database() source_file = self.unzip_file_if_necessary(source_file) self.print_message("Importing '%s' into database '%s'" % (source_file, self.databases['destination']['name'])) args = [ "pg_restore", "--no-acl", "--no-owner", "--dbname=%s" % self.databases['destination']['name'], source_file, ] args.extend(self.databases['destination']['args']) 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 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", "pgbackups:capture", "--app=%s" % self.args.source_app, "--expire", ] 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 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", file_url, "--app=%s" % self.args.destination_app, "DATABASE", "--confirm", self.args.destination_app, ] if self.args.use_pgbackups: args = [ "heroku", "pgbackups:restore", "--app=%s" % self.args.destination_app, "DATABASE_URL", "--confirm", self.args.destination_app, file_url, ] subprocess.check_call(args) else: # TODO perhaps add support for file -> heroku by piping to pg:psql self.print_message("Pushing data from database '%s'" % self.databases['source']['name']) self.print_message("NOTE: Any postgres authentication settings you passed to paragres " "will be ignored.\nIf desired, you can export PG* variables.\n" "You will be prompted for your psql password.") args = [ "heroku", "pg:push", self.databases['source']['name'], "DATABASE_URL", "--app=%s" % self.args.destination_app, ] 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 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(self.args.settings) self.initialize_db_args(settings, 'destination') if self.args.capture: self.capture_heroku_database() file_url = self.args.url if self.args.source_app: self.print_message("Sourcing data from backup for Heroku app '%s'" % self.args.source_app) file_url = self.get_file_url_for_heroku_app(self.args.source_app) if self.args.destination_app: self.replace_heroku_db(file_url) elif self.databases['destination']['name']: self.replace_postgres_db(file_url) self.print_message("\nDone.\n\nDon't forget to update the Django Site entry if necessary!")
<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_name.startswith("__"): #If the module is not __init__, add it to the registry submod_name = "{0}.{1}".format(module,module_name) module_names.append(submod_name) #Once everything is imported, the metaclass will register them automatically modules = map(import_module, module_names) return modules
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [(svc.t_services.id, svc.t_services.f_hosts_id, svc.t_hosts.f_ipaddr, svc.t_hosts.f_hostname, svc.t_services.f_proto, svc.t_services.f_number, svc.t_services.f_status, svc.t_services.f_name, """
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 proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [ service_id, host_id, ipv4, ipv6, hostname, proto, number, status, name, banner ] """
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 port: Port (0-65535) :param fields: Extra fields :return: (True/False, t_services.id or response message) """
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_hosts.id :param proto: Protocol (tcp, udp, info) :param port: Port (0-65535) :return: [True, Response Message] """
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 service_port: tcp/#, udp/# or info/# :param hostfilter: Valid hostfilter or None :return: t_services.rows.as_list() """
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 extend statement before rendering it with jinja. The block name can be specified in the layout_name after the filename separated by a colon. The default block name is "content". """
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_template.cache """
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: value.append(jinja_node_to_python(i)) return value if isinstance(node, nodes.Dict): value = {} for pair in node.items: value[pair.key.value] = jinja_node_to_python(pair.value) return value if isinstance(node, nodes.Call): if not isinstance(node.node, nodes.Name) or node.node.name not in ("_", "translate", "gettext"): raise FormDefinitionError("Cannot convert function calls from jinja to python other than translation calls") return lazy_translate(jinja_node_to_python(node.args[0])) raise Exception("Cannot convert jinja nodes to python")
<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 distinguished name) of the group to check membership for """
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, same shape as `x` The filtered data. ''' # linearly interpolate missing values before filtering x = np.ma.masked_invalid(pd.Series(x).interpolate()) try: # start filtering from the first non-zero value since these won't be addressed by # the interpolation above ind = np.isfinite(x).nonzero()[0][0] x[ind:] = signal.savgol_filter(x[ind:], window_length, polyorder, deriv, delta, axis, mode, cval) except IndexError: pass return np.ma.masked_invalid(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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, feedback_result.V_hv, feedback_result.fb_resistor, feedback_result.hv_resistor]), columns=['V_fb', 'V_hv', 'fb_resistor', 'hv_resistor'], index=index) df_feedback.insert(0, 'frequency', feedback_result.frequency) return df_feedback
<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() .filled(np.NaN), feedback_result.capacitance() .filled(np.NaN), feedback_result.Z_device() .filled(np.NaN)]), columns=['V_actuation', 'capacitance', 'impedance'], index=index) df_feedback.insert(0, 'frequency', feedback_result.frequency) df_feedback.insert(1, 'voltage', feedback_result.voltage) return df_feedback
<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.name, [f.abspath() for f in board_dir.walkfiles('*.hex')]) for board_dir in package_path().joinpath('firmware').dirs()])
<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, **kwargs) except RuntimeError, exception: error_message = str(exception) match = CRE_REMOTE_ERROR.match(error_message) if match: # Exception message matches format of remote firmware error. command_code = int(match.group('command_int')) return_code = int(match.group('return_code_int')) raise FirmwareError(command_code, return_code) match = CRE_REMOTE_COMMAND_ERROR.match(error_message) if match: # Exception message matches format of remote firmware error. command_code = int(match.group('command_int')) command_name = NAMES_BY_COMMAND_CODE[command_code] raise RuntimeError(CRE_REMOTE_COMMAND_ERROR.sub(command_name, error_message)) # Not a remote firmware error, so raise original exception. 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 to_frame(self, filter_order=3): """ Convert data to a `pandas.DataFrame`. Parameters filter_order : int Filter order to use when filtering Z_device, capacitance, x_position, and dxdt. Data is filtered using a Savitzky-Golay filter with a window size that is adjusted based on the mean velocity of the drop (see _get_window_size). Returns ------- pandas.DataFrame This DataFrame is indexed by a utc_timestamp and contains the following columns: frequency: actuation frequency (Hz) target_voltage: target voltage (V) voltage: measured voltage (V) force: actuation force (uN/mm) area: actuated area (mm^2) Z_device_filtered: filtered device impedance for actuated area (Ohms) capacitance_filtered: filtered device capacitance for actuated area (F) x_position_filtered: filtered x-position of the drop (mm) dxdt_filtered: filtered instantaneous velocity of the drop (mm/s) Z_device: device impedance for actuated area (Ohms) capacitance: device capacitance for actuated area (F) x_position: x-position of the drop (mm) dxdt: instantaneous velocity of the drop (mm/s) dx: difference in the drop's x-position over the course of the step (mm) dt: time the drop is considered to have been "moving" (s) mean_velocity: mean drop velocity (mm/s) peak_velocity: peak drop velocity calculated from filtered instantaneous velocity (mm/s) window_size: windows size used for Savitzky-Golay filter (# bins) filter_order: order used for Savitzky-Golay filter (integer) """
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)) # if the window size is too small for filtering, set filter_order to None if filter_order and window_size and window_size < filter_order + 2: filter_order = None if velocity_results and velocity_results['dx']: mean_velocity = velocity_results['p'][0] * 1e3 dx = velocity_results['dx'] dt = velocity_results['dt'] * 1e-3 # convert to seconds t, dxdt = self.dxdt(Lx=L) # interpolate dxdt to use the same time points as the impedance values. dxdt = np.interp(self.time, t, dxdt) * 1e3 # multiply by 1000 to convert to mm/s dxdt = np.ma.masked_invalid(dxdt) t, dxdt_filtered = self.dxdt(filter_order=filter_order, Lx=L) # interpolate dxdt_filtered to use the same time points as the impedance values. dxdt_filtered = np.interp(self.time, t, dxdt_filtered) * 1e3 # multiply by 1000 to convert to mm/s dxdt_filtered = np.ma.masked_invalid(dxdt_filtered) # calculate peak velocity from filtered data peak_velocity = np.max(dxdt_filtered) index = pd.Index(self.time * 1e-3, name='step_time') df = pd.DataFrame({'target_voltage': self.voltage, # V 'voltage': self.V_actuation(), # V 'force': self.force(Ly=1.0) * 1e6, # uN/mm 'Z_device_filtered': self.Z_device(filter_order=filter_order), # Ohms 'capacitance_filtered': self.capacitance(filter_order=filter_order), # F 'x_position_filtered': self.x_position(filter_order=filter_order), # mm 'dxdt_filtered': dxdt_filtered, # mm/s 'Z_device': self.Z_device(), # Ohms 'capacitance': self.capacitance(), # F 'x_position': self.x_position(), # mm 'dxdt': dxdt, # mm/s }, index=index) df['frequency'] = self.frequency df['area'] = self.area # mm^2 df['dx'] = dx # mm df['dt'] = dt # s df['mean_velocity'] = mean_velocity # mm/s df['peak_velocity'] = peak_velocity # mm/s df['window_size'] = window_size df['filter_order'] = filter_order # re-order columns return df[[u'frequency', u'target_voltage', u'voltage', u'force', u'area', u'Z_device_filtered', u'capacitance_filtered', u'x_position_filtered', u'dxdt_filtered', u'Z_device', u'capacitance', u'x_position', u'dxdt', u'dx', u'dt', u'mean_velocity', u'peak_velocity', u'window_size', u'filter_order']]
<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. resistor_index : int, optional Series resistor channel index. If :data:`resistor_index` is not specified, the resistor-index from the current context _(i.e., the result of :attr:`series_resistor_index`)_ is used. Otherwise, the series-resistor is temporarily set to the value of :data:`resistor_index` to read the resistance before restoring back to the original value. Returns ------- int Return code from embedded call. ''' if resistor_index is None: resistor_index = self.series_resistor_index(channel) try: if channel == 0: self.calibration.C_hv[resistor_index] = value else: self.calibration.C_fb[resistor_index] = value except: pass return self._set_series_capacitance(channel, 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. resistor_index : int, optional Series resistor channel index. If :data:`resistor_index` is not specified, the resistor-index from the current context _(i.e., the result of :attr:`series_resistor_index`)_ is used. Otherwise, the series-resistor is temporarily set to the value of :data:`resistor_index` to set the resistance before restoring back to the original value. See definition of :meth:`safe_series_resistor_index_read` decorator. Returns ------- int Return code from embedded call. ''' if resistor_index is None: resistor_index = self.series_resistor_index(channel) try: if channel == 0: self.calibration.R_hv[resistor_index] = value else: self.calibration.R_fb[resistor_index] = value except: pass return self._set_series_resistance(channel, 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 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. refresh_config : bool, optional Is ``True``, :meth:`load_config()` is called afterward to refresh the configuration settings. ''' self._persistent_write(address, byte) if refresh_config: self.load_config(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 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 read. If not set, read a single value of the specified :data:`dtype`. dtype : numpy.dtype, optional The type of the value(s) to read. Returns ------- dtype or numpy.array(dtype=dtype) If :data:`count` is ``None``, return single value. Otherwise, return array of values. ''' nbytes = np.dtype(dtype).itemsize if count is not None: nbytes *= count # Read enough bytes starting at specified address to match the # requested number of the specified data type. data_bytes = np.array([self.persistent_read(address + i) for i in xrange(nbytes)], dtype=np.uint8) # Cast byte array as array of specified data type. result = data_bytes.view(dtype) # If no count was specified, we return a scalar value rather than the # resultant array. if count is None: return result[0] 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 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 write. refresh_config : bool, optional Is ``True``, :meth:`load_config()` is called afterward to refresh the configuration settings. ''' for i, byte in enumerate(data.view(np.uint8)): self.persistent_write(address + i, int(byte)) if refresh_config: self.load_config(False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_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[1] if len(parts) >= 1: if parts[0] in "grunt docs".split(): return parts[0] return 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 _prepare_commit_msg(tmp_file, author, files_modified=None, template=None): """Prepare the commit message in tmp_file. It will build the commit message prefilling the component line, as well as the signature using the git author and the modified files. The file remains untouched if it is not empty. """
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.startswith("#") or x.isspace()), contents) if len(list(msg)): return component = "unknown" components = _get_components(files_modified) if len(components) == 1: component = components[0] elif len(components) > 1: component = "/".join(components) contents.append( "# WARNING: Multiple components detected - consider splitting " "commit.\r\n" ) with open(tmp_file, "w", "utf-8") as fh: fh.write(template.format(component=component, author=author, extra="".join(contents)))
<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, check, and git stash pop. """
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]) dirname = os.path.relpath(dirname, start=prefix) dirname = os.path.join(tmpdir, dirname) if not os.path.isdir(dirname): os.makedirs(dirname) filename = os.path.join(dirname, filename) with open(filename, "wb") as fh: fh.write(content) files_to_check.append((file_, filename)) for (file_, filename) in files_to_check: errors += list(map(lambda x: "{0}: {1}".format(file_, x), check_file(filename, **options) or [])) finally: shutil.rmtree(tmpdir, ignore_errors=True) return errors
<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 attempt to convert the output as unicode :type raw_output: bool :return: error code, output (``stdout``) and error (``stderr``) :rtype: tuple """
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.rstrip() for line in stderr.decode("utf-8").splitlines()] ) else: return (p.returncode, stdout, stderr)
<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 a string out of :attr:`weights_mpl2qt` Returns ------- int One type of the PyQt5.QtGui.QFont.Weight"""
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), key=lambda w: abs(w - weight)) except ValueError: weight = QtGui.QFont.Normal return weight
<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: font, ok = QFontDialog.getFont(fmt_widget) if not ok: return self.current_font = font properties = self.load_properties() properties.update(self.qfont_to_artist_props(font)) fmt_widget.set_obj(properties) self.refresh()
<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()) self.btn_italic.blockSignals(False) # refresh font size self.spin_box.blockSignals(True) self.spin_box.setValue(font.pointSize()) self.spin_box.blockSignals(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 _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) return response
<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: data = await resp.json() if data.get('status', True) is False: self._handle_error(data, params) else: return data except aiohttp.ClientError: raise SabnzbdApiException('Unable to communicate with Sabnzbd API') except asyncio.TimeoutError: raise SabnzbdApiException('SABnzbd API request timed out')
<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.split(' ')[0]) return val * multiplier except ValueError: return 0.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 _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 %(type)s -f %(keyname)s -N " % config.to_dict() lib.call(command, cwd=cwd, output_log_level=logging.DEBUG) if not config.has('ssh_path'): config.set('ssh_path', cwd) config.set('ssh_key_path', os.path.join(config.get('ssh_path'), config.get('keyname')))
<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 config.is_affirmative('override'): self.injections.inject(ssh_config_path, ssh_config_injection) else: self.injections.inject(ssh_config_path, ssh_config_injection) else: self.injections.inject(ssh_config_path, ssh_config_injection) self.injections.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 += " Port {0}\n".format(config.get('port')) return ssh_config_injection
<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_process] + current_app.processes procfile = [] for name, cmd in procfile_processes(processes, debug).iteritems(): procfile.append("%s: %s" % (name, cmd)) with open(filename, "w") as f: f.write("\n".join(procfile)) write_procfile("Procfile", ("web", ["gunicorn", wsgi]), False) if dev: write_procfile("Procfile.dev", ("web", ["frasco", "serve"]), 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 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'rd' return u'th'
<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 <= (8 - jan1_weekday) and jan1_weekday > 4: if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year-1)): week_number = 53 else: week_number = 52 else: if calendar.isleap(self.data.year): i = 366 else: i = 365 if (i - day_of_year) < (4 - weekday): week_number = 1 else: j = day_of_year + (7 - weekday) + (jan1_weekday - 1) week_number = j // 7 if jan1_weekday > 4: week_number -= 1 return week_number