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 decode_response(content: bytes) -> set: """ adb response text -> device set """
content = content[4:].decode(config.ENCODING) if '\t' not in content and '\n' not in content: return set() connected_devices = set() device_list = [i for i in content.split('\n') if i] for each_device in device_list: device_id, device_status = each_device.split('\t') if dev...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(requirements_file, skip_requirements_file, pipfile, skip_pipfile): # type: (str, bool, str, bool) -> None """Update the requirements.txt file and reform...
pipfile_path = path.Path(pipfile) pf = load_pipfile(pipfile_path) if not skip_requirements_file: requirements_file_path = path.Path(requirements_file) update_requirements(requirements_file_path, pf) if not skip_pipfile: dump_pipfile(pipfile_path, pf)
<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_file(self): """Analyse the uploaded file, and return the parsed lines. Returns: tuple of tuples of cells content (as text). """
data = self.cleaned_data['file'] available_parsers = self.get_parsers() for parser in available_parsers: try: return parser.parse_file(data) except parsers.ParserError: pass raise forms.ValidationError( "No parser 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 clean(self): """Global cleanup."""
super(LineFormSet, self).clean() if any(self.errors): # Already seen errors, let's skip. return self.clean_unique_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 clean_unique_fields(self): """Ensure 'unique fields' are unique among entered data."""
if not self.unique_fields: return keys = set() duplicates = [] for form in self.forms: key = tuple(form.cleaned_data[field] for field in self.unique_fields) if key in keys: duplicates.append(",".join(key)) 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 run(itf): """ Run optimize functions. """
if not itf: return 1 # access user input options = SplitInput(itf) # read input inputpath = os.path.abspath(options.inputpath) print(" Reading input file ...") molecules = csv_interface.read_csv(inputpath, options) if not molecules: print("\n '{flag}' was unable to be...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optimizor(molecules, sort_order, ensemble_size, options): """ Evaluate the performance of all ensembles of fixed size. """
# set variables ncpu = options.ncpu score_field = options.score_field # generate an exhaustive list of all possible ensembles ensemble_list = make_ensemble_list(molecules, score_field, ensemble_size) # set number of processors. if not ncpu: ncpu = multiprocessing.cpu_count() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate(molecules, ensemble_chunk, sort_order, options, output_queue=None): """ Evaluate VS performance of each ensemble in ensemble_chunk """
results = {} # {('receptor_1', ..., 'receptor_n') : ensemble storage object} for ensemble in ensemble_chunk: results[ensemble] = calculate_performance(molecules, ensemble, sort_order, options) if output_queue is not None: output_queue.put(results) else: return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_ensemble_list(molecules, score_field, ensemble_size): """ Construct ensemble list """
# generate list of queries queryList = molecules[0].scores.keys() # nchoosek ensemble_iterator = itertools.combinations(queryList, ensemble_size) # list of tuples: [(query1, query2), ... (queryN-1, queryN) ensembleList = [] for ensemble in ensemble_iterator: ensembleList.append(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunker(ensemble_list, ncpu): """ Generate successive chunks of ensemble_list. """
# determine sublist lengths length = int(len(ensemble_list) / ncpu) # generator for i in range(0, len(ensemble_list), length): yield ensemble_list[i:i + 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 fasta_verifier(entries, ambiguous=False): """Raises error if invalid FASTA format detected Args: entries (list): A list of FastaEntry instances ambiguous (b...
if ambiguous: regex = r'^>.+{0}[ACGTURYKMSWBDHVNX]+{0}$'.format(os.linesep) else: regex = r'^>.+{0}[ACGTU]+{0}$'.format(os.linesep) delimiter = r'{0}'.format(os.linesep) for entry in entries: try: entry_verifier([entry.write()], regex, delimiter) except For...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def guard(params, guardian, error_class=GuardError, message=''): ''' A guard function - check parameters with guardian function on decorated function :param tuple or string params: guarded function parameter/s :param function guardian: verifying the conditions for the selected parameter :param ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(dimension, iterations): """ Main function for PSO optimizer example. Instantiate PSOOptimizer to optimize 30-dimensional spherical function. """
optimizer = PSOOptimizer() solution = optimizer.minimize(sphere, -5.12, 5.12, dimension, max_iterations(iterations)) return solution, optimizer
<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_last_commit_message(self): """ Gets the last commit message on the active branch Returns None if not in a git repo """
# Check if we are currently in a repo try: branch = self.active_branch return self.commit(branch).message except InvalidGitRepositoryError: print "Not in a git repo" return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_last_modified_timestamp(self): """ Looks at the files in a git root directory and grabs the last modified timestamp """
cmd = "find . -print0 | xargs -0 stat -f '%T@ %p' | sort -n | tail -1 | cut -f2- -d' '" ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) output = ps.communicate()[0] print output
<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_config_root(path=sys.argv[0]): """ Finds config root relative to the given file path """
dirname = os.path.dirname(path) lastdirname = None while dirname != lastdirname: config_root = os.path.join(dirname, 'config') if os.path.exists(config_root): return config_root lastdirname, dirname = dirname, os.path.dirname(dirname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_default(self, index): """Set the value of the given index row to its default :param index: :type index: :returns: :rtype: :raises: """
spec = self.get_configspec_str(index) if spec is None or isinstance(spec, Section): return try: default = self._vld.get_default_value(spec) defaultstr = self._val_to_str(default) self.setData(index, defaultstr) except KeyError: ...
<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_value(self, index): """ Return the value of the given index The index stores the section as internal pointer. The row of the index determines the key. Th...
p = index.internalPointer() k = self.get_key(p, index.row()) return p[k]
<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_configspec_str(self, index): """ Return the config spec string of the given index The index stores the section as internal pointer. The row of the index ...
p = index.internalPointer() if p is None: return spec = p.configspec if spec is None: return None k = self.get_key(p, index.row()) try: return spec[k] except KeyError: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _val_to_str(self, value): """Converts the value to a string that will be handled correctly by the confobj :param value: the value to parse :type value: somet...
# might be a list value # then represent it 'nicer' so that when we edit it, the same value will return if isinstance(value, list): # so we have a list value. the default str(v) would produce something like: ['a', 'b'] # handling such a value is not possible. it should b...
<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_index_edited(self, index, edited): """Set whether the conf was edited or not. Edited files will be displayed with a \'*\' :param index: the index that wa...
self.__edited[index.row()] = edited self.dataChanged.emit(index, index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_edited(self, ): """Return all indices that were modified :returns: list of indices for modified confs :rtype: list of QModelIndex :raises: None """
modified = [] for i in range(len(self.__edited)): if self.__edited[i]: modified.append(self.__configs[i]) return 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 validate(self, index): """Validate the conf for the given index :param index: the index of the model to validate :type index: QModelIndex :returns: True if p...
c = self.__configs[index.row()] if c.configspec is None: return True else: return c.validate(self.vld)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metapolicy(request, permitted, domains=None): """ Serves a cross-domain policy which can allow other policies to exist on the same domain. Note that this vie...
if domains is None: domains = [] policy = policies.Policy(*domains) policy.metapolicy(permitted) return serve(request, policy)
<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_popen(command, print_output=False): """ subprocess has the most terrible interface ever. Envoy is an option but too heavyweight for this. This is a conv...
output = '' po = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) fcntl.fcntl( po.stdout.fileno(), fcntl.F_SETFL, fcntl.fcntl(po.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK, ) while po.poll() is None: stre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perimeter(patch, world_size=(60, 60), neighbor_func=get_rook_neighbors_toroidal): """ Count cell faces in patch that do not connect to part of patch. This pr...
edge = 0 patch = set([tuple(i) for i in patch]) for cell in patch: neighbors = neighbor_func(cell, world_size) neighbors = [n for n in neighbors if n not in patch] edge += len(neighbors) return edge
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def traverse_core(core_area, world_size=(60, 60), neighbor_func=get_moore_neighbors_toroidal): """ Treat cells in core_area like a graph and traverse it to see h...
if not core_area: return [] core_area = [tuple(i) for i in core_area] curr = core_area[0] core_area = set(core_area[1:]) to_explore = [] cores = [[curr]] while core_area: neighbors = neighbor_func(curr, world_size) for n in neighbors: if n in core_area...
<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_command_line_args(): """parse command line args"""
parser = argparse.ArgumentParser(description='PipApp. {}'.format(DESCRIPTION)) parser.add_argument( '-d', '--dir', metavar='DIR', help='Root directory where to create new project files and dirs. Default is current directory.' ) parser.add_argument( '-v,', '--version', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def requirements(collector): """Just print out the requirements"""
out = sys.stdout artifact = collector.configuration['dashmat'].artifact if artifact not in (None, "", NotSpecified): if isinstance(artifact, six.string_types): out = open(artifact, 'w') else: out = artifact for active in collector.configuration['__imported__'].v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_checks(collector): """Just run the checks for our modules"""
artifact = collector.configuration["dashmat"].artifact chosen = artifact if chosen in (None, "", NotSpecified): chosen = None dashmat = collector.configuration["dashmat"] modules = collector.configuration["__active_modules__"] config_root = collector.configuration["config_root"] mo...
<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_npm_modules(collector, no_print=False): """List the npm modules that get installed in a docker image for the react server"""
default = ReactServer().default_npm_deps() for _, module in sorted(collector.configuration["__active_modules__"].items()): default.update(module.npm_deps()) if not no_print: print(json.dumps(default, indent=4, sort_keys=True)) 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 collect_dashboard_js(collector): """Generate dashboard javascript for each dashboard"""
dashmat = collector.configuration["dashmat"] modules = collector.configuration["__active_modules__"] compiled_static_prep = dashmat.compiled_static_prep compiled_static_folder = dashmat.compiled_static_folder npm_deps = list_npm_modules(collector, no_print=True) react_server = ReactServer() ...
<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_file(file, filename='<input>'): """This is a generator that yields all top-level S-expression nodes from a given file object."""
reader = Reader(filename) for line in file: yield from reader.feed_line(line) reader.finish()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _feed_node(self, value, loc): """A helper method called when an S-expression has been recognized. Like feed_line, this is a generator that yields newly recog...
node = GenericNode(value, loc) if not self.stack: yield node else: top = self.stack[-1] if isinstance(top, StackEntryList): top.items.append(node) elif isinstance(top, StackEntryComment): self.stack.pop() ...
<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_until_complete(self): """Run loop until all futures are done. Schedule futures for execution and wait until all are done. Return value from future, or li...
try: result = self.loop.run_until_complete(self.futures) except asyncio.futures.CancelledError: return None else: if self.ft_count == 1: 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 get_irregular_vertex(bgedge): """ This method is called only in irregular edges in current implementation, thus at least one edge will be irregular """
if not bgedge.is_irregular_edge: raise Exception("trying to retrieve an irregular vertex from regular edge") return bgedge.vertex1 if bgedge.vertex1.is_irregular_vertex else bgedge.vertex2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_coordinates(cls, ra=None, dec=None, distance=None, pm_ra_cosdec=None, pm_dec=None, radial_velocity=None, obstime=2000.0*u.year, id=None, mag=None, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_text(self, filename=None, overwrite=True): ''' Write this catalog out to a text file. ''' table = self.standardized #table = hstack([self.identifiers, # self._coordinate_table(), # self.magnitudes, # sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def plot(self, sizescale=10, color=None, alpha=0.5, label=None, edgecolor='none', **kw): ''' Plot the ra and dec of the coordinates, at a given epoch, scaled by their magnitude. (This does *not* create a new empty figure.) Parameters ---------- sizescale : (opti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def animate(self, filename='constellation.mp4', epochs=[1900,2100], dt=5, dpi=300, fps=10, **kw): ''' Animate a finder chart. ''' scatter = self.finder(**kw) plt.tight_layout() figure = plt.gcf() if '.gif' in filename: try: writer = a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_gitdir(self): """Determine the git repository for this request"""
if self.gitlookup is None: raise tornado.web.HTTPError(500, 'no git lookup configured') gitdir = self.gitlookup(self.request) if gitdir is None: raise tornado.web.HTTPError(404, 'unable to find repository') logger.debug("Accessing git at: %s", gitdir) 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 get_last_data(self, uuid, period=0, average_by=0): """ Get the data from one device for period till now. :param uuid: Id of the device :type uuid: str :param...
return self.parse_data((yield from self._get( LAST_DATA_URL.format(uuid= uuid, period= trunc(period), average_by= trunc(average_by)))))
<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_historical_data(self, uuid, start, end, average_by=0): """ Get the data from one device for a specified time range. .. note:: Can fetch a maximum of 42 d...
return self.parse_data((yield from self._get( HISTORICAL_DATA_URL.format(uuid= uuid, start = trunc(start.replace(tzinfo=timezone.utc).timestamp()), end = trunc(end.replace(tzinfo=timezone.utc).timestamp()), average_by= trunc(average_by)))))
<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_data(self, response): """ Convert the weird list format used for datapoints to a more usable dictionnary one :param response: dictionnary from API json...
parsed = [] try: items = response['sensors'] for datapoint in response['datapoints']: line = {} for index, data in enumerate(datapoint): line[items[index]] = data parsed.append(line) return parsed ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metaclass(self): """Get a metaclass configured to use this registry."""
if '_metaclass' not in self.__dict__: self._metaclass = type('PermissionsMeta', (PermissionsMeta,), {'registry': self}) return self._metaclass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, perm_func=None, model=None, allow_staff=None, allow_superuser=None, allow_anonymous=None, unauthenticated_handler=None, request_types=None, nam...
allow_staff = _default(allow_staff, self._allow_staff) allow_superuser = _default(allow_superuser, self._allow_superuser) allow_anonymous = _default(allow_anonymous, self._allow_anonymous) unauthenticated_handler = _default(unauthenticated_handler, self._unauthenticated_handler) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require(self, perm_name, **kwargs): """Use as a decorator on a view to require a permission. Optional args: - ``field`` The name of the model field to use fo...
view_decorator = self._get_entry(perm_name).view_decorator return view_decorator(**kwargs) if kwargs else view_decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entry_for_view(self, view, perm_name): """Get registry entry for permission if ``view`` requires it. In other words, if ``view`` requires the permission spec...
view_name = self._get_view_name(view) entry = self._get_entry(perm_name) if view_name in entry.views: return entry return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_importer(self): """ Resolve importer from TRACK_IMPORTER_CLASS setting. """
try: importer_path = settings.TRACK_IMPORTER_CLASS except AttributeError: raise ImproperlyConfigured('No TRACK_IMPORTER_CLASS setting found.') try: dot = importer_path.rindex('.') except ValueError: raise ImproperlyConfigured('%s isn\'t a ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lookup_track(self, track): """ Looks up Django Track object for provided raw importing track object. """
tracks = Track.objects.filter(title__iexact=track.title) for track_obj in tracks: for contributor in track_obj.get_primary_contributors(permitted=False): if contributor.title == track.artist: return track_obj return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Run import. """
latest_track = Track.objects.all().order_by('-last_played') latest_track = latest_track[0] if latest_track else None importer = self.get_importer() tracks = importer.run() # Create/update Django Track objects for importer tracks. for track in tracks: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_value_by_name(expected_type, actual_value): """ Matches expected type to a type of a value. :param expected_type: an expected type name to match. :para...
if expected_type == None: return True if actual_value == None: raise Exception("Actual value cannot be null") return TypeMatcher.match_type_by_name(expected_type, type(actual_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 match_type_by_name(expected_type, actual_type): """ Matches expected type to an actual type. :param expected_type: an expected type name to match. :param act...
if expected_type == None: return True if actual_type == None: raise Exception("Actual type cannot be null") expected_type = expected_type.lower() if actual_type.__name__.lower() == expected_type: return True elif expected_type == "o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blob(self, request, pk=None): """ fetch large object from pg and gives it back to user via HTTP 1.1 request :param request: django request instance :param pk...
obj = self.get_object_or_none() if obj: blob = obj.get_blob_data() content_type = 'octet/stream' response = HttpResponse(blob, content_type=content_type, status=status.HTTP_200_OK) response['Content-Disposition'] = ( ...
<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_github(self): """Creates an instance of github.Github to interact with the repos via the API interface in pygithub. """
from github import Github vms("Querying github with user '{}'.".format(self.username)) g = Github(self.username, self.apikey) self._user = g.get_user() if self._user is None: raise ValueError("Can't authenticate to github with '{}'.".format(self.username)) #T...
<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_xml(self): """Extracts the XML settings into class instances that can operate on the settings to perform the testing functions. """
import xml.etree.ElementTree as ET from os import path #This dict has the keys of XML tags that are required in order for the #CI server to run the repo. When each one is parsed, we change its value #to True and then check that they are all true at the end. required = {"...
<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_xml(self, xml): """Extracts the attributes from the XMLElement instance."""
from re import split vms("Parsing <cron> XML child tag.", 2) self.frequency = get_attrib(xml, "frequency", default=5, cast=int) self.emails = split(",\s*", get_attrib(xml, "emails", default="")) self.notify = split(",\s*", get_attrib(xml, "notify", 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 _parse_xml(self, xml): """Extracts objects representing and interacting with the settings in the xml tag. """
vms("Parsing <static> XML child tag.", 2) for child in xml: if "path" in child.attrib and "target" in child.attrib: if child.tag == "file": self.files.append({"source": child.attrib["path"], "target": child.attrib["t...
<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, repodir): """Copies the static files and folders specified in these settings into the locally-cloned repository directory. :arg repodir: the full ...
#Instead of using the built-in shell copy, we make shell calls to rsync. #This allows us to copy only changes across between runs of pull-requests. from os import system, path vms("Running static file copy locally.", 2) for file in self.files: fullpath = path.expandu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serial(self): """Returns true if the CI server should run in serial mode. """
serial = self.property_get("SERIAL", False) if isinstance(serial, str): return serial.lower() == "true" else: return serial
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def var_replace(self, text): """Replaces all instances of @VAR with their values in the specified text. """
result = text for var in self._vardict: result = result.replace("@{}".format(var), self._vardict[var]) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_or_create_iobject(identifier_uid, identifier_namespace_uri, iobject_type_name, iobject_type_namespace_uri, iobject_type_revision_name, iobject_family_name...
# create or retrieve the iobject type and revision # create or retrieve identifier if not timestamp: raise StandardError("You must supply a timestamp.") id_namespace, created = dingos_class_map['IdentifierNameSpace'].objects.get_or_create(uri=identifier_namespace_uri) if created and 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 get_or_create_fact(fact_term, fact_dt_name='String', fact_dt_namespace_uri=DINGOS_NAMESPACE_URI, values=None, value_iobject_id=None, value_iobject_ts=None, ):...
if not values: values = [] vocab_namespace, created = dingos_class_map['DataTypeNameSpace'].objects.get_or_create(uri=fact_dt_namespace_uri) fact_data_type, created = dingos_class_map['FactDataType'].objects.get_or_create(name=fact_dt_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 get_or_create_fact_term(iobject_family_name, fact_term_name, fact_term_attribute, iobject_type_name, iobject_type_namespace_uri, fact_dt_name=DINGOS_DEFAULT_F...
if not fact_term_attribute: fact_term_attribute = '' # create or retrieve the enrichment type and revision iobject_family, created = dingos_class_map['InfoObjectFamily'].objects.get_or_create(name=iobject_family_name) # create or retrieve namespace of data type fact_dt_namespace, creat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def marking_thru(self): """ Return the back-pointer to markings that may have been attached via Django's content type mechanism. """
self_django_type = ContentType.objects.get_for_model(self) return Marking2X.objects.filter(content_type__pk=self_django_type.id, object_id=self.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 embedded_in(self): """ Used in the view for the InfoObject (in order to be able to use the standard class-based object view. Should be removed from here and ...
return self._DCM['InfoObject2Fact']. \ objects. \ filter(fact__value_iobject_id=self.identifier). \ filter(iobject__timestamp=F('iobject__identifier__latest__timestamp')). \ order_by('-iobject__timestamp') \ .values_list( 'iobject', ...
<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_name(self,name=None): """ Set the name of the object. If no name is given, the name is extracted via the extract_name method. """
if name: self.name = name[:254] else: self.name = self.extract_name()[:254] self.save() return self.name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_relation(self, target_id=None, relation_types=None, fact_dt_namespace_name=None, fact_dt_namespace_uri=DINGOS_NAMESPACE_URI, fact_dt_kind=FactDataType.UNK...
if not markings: markings = [] if relation_types == None: relation_types = [] # Create fact-term for relation types relation_type_ft, created = get_or_create_fact_term(iobject_family_name=self.iobject_family.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 _load_data(self): """ Load data from raw_data or file_path """
if self.raw_data is None and self.data_format is not FormatType.PYTHON: if self.file_path is None: raise ArgumentInvalid('One of "raw_data" or "file_path" should be set!') if not os.path.isfile(self.file_path) or not os.access(self.file_path, os.R_OK): ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate(self): """ Validate the input data. """
if self.data_format is FormatType.PYTHON: self.data = self.raw_data elif self.data_format is FormatType.JSON: self._validate_json() elif self.data_format is FormatType.YAML: self._validate_yaml()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(pattern, text, no_escape=False, path_name=True, wild_star=True, period=False, case_fold=False): u""" Matches text against the supplied wildmatch patter...
regex = translate(pattern, no_escape=no_escape, path_name=path_name, wild_star=wild_star, period=period, case_fold=case_fold, closed_regex=True) return regex.match(text) is not 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 filter(self, texts): u""" Returns a generator yielding the elements of `texts` matching this pattern. :type texts: typing.Iterable[text_type] :param texts: A...
return (text for text in texts if self.regex.match(text) is not 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 imagesc(data, title=None, fig='current', ax=None): '''Simple alias for a Matlab-like imshow function.''' ax = _get_axis(fig, ax, False) ax.imshow(data, interpolation='nearest', aspect='auto') if title: ax.set_title(title) return plt.show
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def vector_field(points, directions, title=None, fig='current', ax=None, edge_style='k-', vertex_style='o'): '''Plots vectors that start at 'points', and move along 'directions'.''' assert points.shape[1] in (2,3) and directions.shape == points.shape ax = _get_axis(fig, ax, points.shape[1] == 3) ...
<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_passwd_file(pass_file): """Read password from external file and retrun as string. The file should contain just single line. Prevents hard-coding passwor...
with open(pass_file) as fin: passwd = fin.read().strip() return passwd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_mail(to_addr, subj_msg, body_msg, attach_path, serv_addr, serv_port, from_addr, passwd): """Send an e-mail message using smtplib and email standard pyth...
msg = MIMEMultipart() if attach_path is not None: with open(attach_path, "rb") as fin: part = MIMEBase("application", "octet-stream") part.set_payload(fin.read()) encoders.encode_base64(part) part.add_header("Content-Disposition", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roc_calculator(screened_molecules, status_field, active_label, decoy_label): """ Calculates ROC curve """
P = 0 # Total no. of actives N = 0 # Total no. of decoys tpf = []; tpf.append(0) # true positive fraction list fpf = []; fpf.append(0) # false positive fraction list fpindex = [] # indeces where decoys are found are labeled '1' # Tally the # of positives & negatives at each thres...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listen(identifier): """ Launch a listener and return the compactor context. """
context = Context() process = WebProcess(identifier) context.spawn(process) log.info("Launching PID %s", process.pid) return process, 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 history(self): """Get the latest 10 files uploaded to the account. Return a list of Puush File objects. """
res = self._api_request('hist') if res[0][0] == '-1': raise PuushError("History retrieval failed.") files = [] for line in res[1:]: id, upload_time, url, filename, views, _ = line files.append(self._File(id, url, filename, upload_time, views)...
<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_value(self, value): """ To avoid evaluating the lazysorted callable more than necessary to establish a potential initial value for the field, we do i...
if value is None and self.required: choices =list(self.choices) if len(choices) == 1: value = choices[0][0] return super(TemplateChoiceField, self).prepare_value(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 to_float_with_default(value, default_value): """ Converts value into float or returns default when conversion is not possible. :param value: the value to con...
result = FloatConverter.to_nullable_float(value) return result if result != None else default_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 run(self): """This method is run by a separated thread"""
self.busy = True for i in range(9): self.counter += 1 time.sleep(0.5) pass self.counter += 1 self.busy = False return
<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_info_field(prop): """ Return the info attribute of the given property """
if isinstance(prop, ColumnProperty): column = prop.columns[0] elif isinstance(prop, RelationshipProperty): column = prop return column.info
<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_item(self, sqla_col_type, item, key_specific=None): """ Add an item to the registry """
if key_specific is not None: self.setdefault(key_specific, {})[sqla_col_type] = item else: self[sqla_col_type] = item
<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_formatter(self, sqla_col_type, formatter, key_specific=None): """ Add a formatter to the registry if key_specific is provided, this formatter will only b...
self.add_item(sqla_col_type, formatter, key_specific)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_layout(self, orientation=None): """Setup the layout for the tooltip in the given orientation :param layout: the orentation of the layout :type layout: ...
if orientation == QtCore.Qt.Horizontal or orientation is None: layout = QtGui.QHBoxLayout() elif orientation == QtCore.Qt.Vertical: layout = QtGui.QVBoxLayout() else: raise TypeError('Orientation is of wrong type! Allowed is QtCore.Qt.Horizontal and QtCore.Qt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_size(self, width, height): """Set the width and height for one cell in the tooltip This is inderectly acomplished by setting the iconsizes for the butt...
self._iconw = max(0, width - 7) self._iconh = max(0, height - 6) self.update_all_buttons()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_cyatimer(self, interval): """Setup the timer that will close the widget after the mouse left the widget for the time of interval :param interval: the t...
self.cyatimer = QtCore.QTimer(self) self.cyatimer.setSingleShot(True) self.cyatimer.timeout.connect(self.hide) self._interval = interval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def event(self, event): """Reimplementation of QWidget.event The widget is closed, when the window is deactivated. The widget is closed after the set interval if...
if event.type() == QtCore.QEvent.WindowDeactivate: # hide the tooltip self.cyatimer.stop() self.hide() return True if event.type() == QtCore.QEvent.Leave: # start timer self.cyatimer.start(self._interval) return True if event.type() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_button(self, widget): """Create a button that has the given widget rendered as an icon :param widget: the widget to render as icon :type widget: QtGui...
btn = QtGui.QToolButton(self) btn.setIconSize(QtCore.QSize(self._iconw, self._iconh)) self.update_button(btn, widget) return btn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_button(self, button, widget): """Update the icon of the button with the given widget if the widget does not is invalid, it is deleted from the tooltip...
if not shiboken.isValid(widget): self.remove_widget(widget) return button.setIconSize(QtCore.QSize(self._iconw, self._iconh)) pix = QtGui.QPixmap(widget.size()) widget.render(pix) icon = QtGui.QIcon(pix) button.setIcon(icon)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_all_buttons(self, ): """Update all buttons :returns: None :rtype: None :raises: None """
for widget, button in self._buttons.items(): self.update_button(button, widget) self.adjustSize()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def focus_widget(self, checked=None, w=None): """Focus the given widget. Checked is ignored and only used as a slot for QAbstractButton.clicked. :param checked: ...
if w is None: return if w.isMinimized(): w.showNormal() else: w.show() w.activateWindow() w.setFocus()
<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_widget(self, widget): """Add the given widget to the tooltip :param widget: the widget to add :type widget: QtGui.QWidget :returns: None :rtype: None :ra...
if self._buttons.get(widget): return btn = self.create_button(widget) cb = partial(self.focus_widget, w=widget) btn.clicked.connect(cb) self.layout().addWidget(btn) self._buttons[widget] = btn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_widget(self, widget): """Remove the given widget from the tooltip :param widget: the widget to remove :type widget: QtGui.QWidget :returns: None :rtyp...
button = self._buttons.pop(widget) self.layout().removeWidget(button) button.deleteLater()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eventFilter(self, watched, event): """Filter ToolTip events and display this tooltip widget, if watched requests a tooltip. :param watched: The watched objec...
if event.type() == self._triggerevent: self.show() return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_position(self, ): """Return a recommended position for this widget to appear This implemenation returns a position so that the widget is vertically cente...
pos = QtGui.QCursor.pos() if self._alignment & QtCore.Qt.AlignLeft == QtCore.Qt.AlignLeft: pos.setX(pos.x() - self._offset) elif self._alignment & QtCore.Qt.AlignRight == QtCore.Qt.AlignRight: pos.setX(pos.x() - self.frameGeometry().width() + self._offset) elif 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 show(self, ): """Reimplementation that moves the tooltip and updates the buttons :returns: None :rtype: None :raises: None """
self.update_all_buttons() pos = self.get_position() self.move(pos) super(WidgetToolTip, self).show()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(self, ): """Reimplementation of show to update all currently available JB_MainWindows :returns: None :rtype: None :raises: None """
wins = set(JB_MainWindow.instances()) widgets = set(self.get_widgets()) for w in wins - widgets: self.add_widget(w) super(JB_WindowToolTip, self).show()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_issue(self, branch): """ Gets the JIRA issue associated with the branch name. Returns None if no issue with this branch name. """
if branch: try: issue = self.issue(branch, expand='changelog') return issue except jira.exceptions.JIRAError as ex: if ex.status_code == 404: print "No JIRA issue found for branch %s" % branch else: ...