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 tree_to_graph(bbltree:BubbleTree) -> Graph or Digraph: """Compute as a graphviz.Graph instance the given graph. If given BubbleTree instance is oriented, retu...
GraphObject = Digraph if bbltree.oriented else Graph def create(name:str): """Return a graphviz graph figurating a powernode""" ret = GraphObject('cluster_' + name) # dirty hack to get links between clusters: add a blank node inside # so the subgraph don't take it's name directl...
<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_dict(self): """Returns OrderedDict whose keys are self.attrs"""
ret = OrderedDict() for attrname in self.attrs: ret[attrname] = self.__getattribute__(attrname) return ret
<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_list(self): """Returns list containing values of attributes listed in self.attrs"""
ret = OrderedDict() for attrname in self.attrs: ret[attrname] = self.__getattribute__(attrname) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def uniq(pipe): ''' this works like bash's uniq command where the generator only iterates if the next value is not the previous ''' pipe = iter(pipe) previous = next(pipe) yield previous for i in pipe: if i is not previous: previous = i yield i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_request(url, method, data, args, params, headers, cookies, timeout, is_json, verify_cert): """ Forge and send HTTP request. """
## Parse url args for p in args: url = url.replace(':' + p, str(args[p])) try: if data: if is_json: headers['Content-Type'] = 'application/json' data = json.dumps(data) request = requests.Request( method.upper(), url, data=data, params=params, headers=headers, cookies=cookies ) els...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def neighbors(self) -> List['Node']: """ The list of neighbors of the node. """
self._load_neighbors() return [edge.source if edge.source != self else edge.target for edge in self._neighbors.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 _load_neighbors(self) -> None: """ Loads all neighbors of the node from the local database and from the external data source if needed. """
if not self.are_neighbors_cached: self._load_neighbors_from_external_source() db: GraphDatabaseInterface = self._graph.database db_node: DBNode = db.Node.find_by_name(self.name) db_node.are_neighbors_cached = True db.session.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 _load_neighbors_from_database(self) -> None: """ Loads the neighbors of the node from the local database. """
self._are_neighbors_loaded = True graph: Graph = self._graph neighbors: List[DBNode] = graph.database.Node.find_by_name(self.name).neighbors nodes: NodeList = graph.nodes for db_node in neighbors: graph.add_node(db_node.name, db_node.external_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 key(self) -> Tuple[int, int]: """ The unique identifier of the edge consisting of the indexes of its source and target nodes. """
return self._source.index, self._target.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 edge_list(self) -> List[Edge]: """ The ordered list of edges in the container. """
return [edge for edge in sorted(self._edges.values(), key=attrgetter("key"))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def beforeSummaryReport(self, event): '''Output profiling results''' self.prof.disable() stats = pstats.Stats(self.prof, stream=event.stream).sort_stats( self.sort) event.stream.writeln(nose2.util.ln('Profiling results')) stats.print_stats() if self.pfile: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def separate(text): '''Takes text and separates it into a list of words''' alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: if char in alphabet or char in alphabet.upper(): news...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def eliminate_repeats(text): '''Returns a list of words that occur in the text. Eliminates stopwords.''' bannedwords = read_file('stopwords.txt') alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wordcount(text): '''Returns the count of the words in a file.''' bannedwords = read_file('stopwords.txt') wordcount = {} separated = separate(text) for word in separated: if word not in bannedwords: if not wordcount.has_key(word): wordcount[word] = 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 tuplecount(text): '''Changes a dictionary into a list of tuples.''' worddict = wordcount(text) countlist = [] for key in worddict.keys(): countlist.append((key,worddict[key])) countlist = list(reversed(sorted(countlist,key = lambda x: x[1]))) return countlist
<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_file_md5(filename): """Get a file's MD5"""
if os.path.exists(filename): blocksize = 65536 try: hasher = hashlib.md5() except BaseException: hasher = hashlib.new('md5', usedForSecurity=False) with open(filename, 'rb') as afile: buf = afile.read(blocksize) while len(buf) > 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 get_md5(string): """Get a string's MD5"""
try: hasher = hashlib.md5() except BaseException: hasher = hashlib.new('md5', usedForSecurity=False) hasher.update(string) return hasher.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy_signature(source, dest, user=None, group=None): """Deploy a signature fole"""
move(source, dest) os.chmod(dest, 0644) if user and group: try: uid = pwd.getpwnam(user).pw_uid gid = grp.getgrnam(group).gr_gid os.chown(dest, uid, gid) except (KeyError, OSError): pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_local_version(sigdir, sig): """Get the local version of a signature"""
version = None filename = os.path.join(sigdir, '%s.cvd' % sig) if os.path.exists(filename): cmd = ['sigtool', '-i', filename] sigtool = Popen(cmd, stdout=PIPE, stderr=PIPE) while True: line = sigtool.stdout.readline() if line and line.startswith('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 verify_sigfile(sigdir, sig): """Verify a signature file"""
cmd = ['sigtool', '-i', '%s/%s.cvd' % (sigdir, sig)] sigtool = Popen(cmd, stdout=PIPE, stderr=PIPE) ret_val = sigtool.wait() return ret_val == 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 check_download(obj, *args, **kwargs): """Verify a download"""
version = args[0] workdir = args[1] signame = args[2] if version: local_version = get_local_version(workdir, signame) if not verify_sigfile(workdir, signame) or version != local_version: error("[-] \033[91mFailed to verify signature: %s from: %s\033[0m" % (...
<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_sig(opts, sig, version=None): """Download signature from hostname"""
code = None downloaded = False useagent = 'ClamAV/0.101.1 (OS: linux-gnu, ARCH: x86_64, CPU: x86_64)' manager = PoolManager( headers=make_headers(user_agent=useagent), cert_reqs='CERT_REQUIRED', ca_certs=certifi.where(), timeout=Timeout(connect=10.0, read=60.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 copy_sig(sig, opts, isdiff): """Deploy a sig"""
info("[+] \033[92mDeploying signature:\033[0m %s" % sig) if isdiff: sourcefile = os.path.join(opts.workdir, '%s.cdiff' % sig) destfile = os.path.join(opts.mirrordir, '%s.cdiff' % sig) else: sourcefile = os.path.join(opts.workdir, '%s.cvd' % sig) destfile = os.path.join(opts....
<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_dns_file(opts, record): """Create the DNS record file"""
info("[+] \033[92mUpdating dns.txt file\033[0m") filename = os.path.join(opts.mirrordir, 'dns.txt') localmd5 = get_file_md5(filename) remotemd5 = get_md5(record) if localmd5 != remotemd5: create_file(filename, record) info("=> dns.txt file updated") else: info("=> No upd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_diffs(queue): """Download the cdiff files"""
while True: options, signature_type, localver, remotever = queue.get() for num in range(int(localver), int(remotever) + 1): sig_diff = '%s-%d' % (signature_type, num) filename = os.path.join(options.mirrordir, '%s.cdiff' % sig_diff) if not os.path.exists(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 work(options): """The work functions"""
# pylint: disable=too-many-locals record = get_record(options) _, mainv, dailyv, _, _, _, safebrowsingv, bytecodev = record.split(':') versions = {'main': mainv, 'daily': dailyv, 'safebrowsing': safebrowsingv, 'bytecode': bytecodev} dqueue = Queue(maxsize=0) dque...
<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_resource(src, dest): """ To copy package data to destination """
package_name = "yass" dest = (dest + "/" + os.path.basename(src)).rstrip("/") if pkg_resources.resource_isdir(package_name, src): if not os.path.isdir(dest): os.makedirs(dest) for res in pkg_resources.resource_listdir(__name__, src): copy_resource(src + "/" + res, de...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(endpoint, purge_files, rebuild_manifest, skip_upload): """Publish the site"""
print("Publishing site to %s ..." % endpoint.upper()) yass = Yass(CWD) target = endpoint.lower() sitename = yass.sitename if not sitename: raise ValueError("Missing site name") endpoint = yass.config.get("hosting.%s" % target) if not endpoint: raise ValueError("%s endpoin...
<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_dns(endpoint): """Setup site domain to route to static site"""
print("Setting up DNS...") yass = Yass(CWD) target = endpoint.lower() sitename = yass.sitename if not sitename: raise ValueError("Missing site name") endpoint = yass.config.get("hosting.%s" % target) if not endpoint: raise ValueError( "%s endpoint is missing i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_site(sitename): """Create a new site directory and init Yass"""
sitepath = os.path.join(CWD, sitename) if os.path.isdir(sitepath): print("Site directory '%s' exists already!" % sitename) else: print("Creating site: %s..." % sitename) os.makedirs(sitepath) copy_resource("skel/", sitepath) stamp_yass_current_version(sitepath) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(): """Initialize Yass in the current directory """
yass_conf = os.path.join(CWD, "yass.yml") if os.path.isfile(yass_conf): print("::ALERT::") print("It seems like Yass is already initialized here.") print("If it's a mistake, delete 'yass.yml' in this directory") else: print("Init Yass in %s ..." % CWD) copy_resource(...
<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_page(pagename): """ Create a new page Omit the extension, it will create it as .jade file """
page = pagename.lstrip("/").rstrip("/") _, _ext = os.path.splitext(pagename) # If the file doesn't have an extension, we'll just create one if not _ext or _ext == "": page += ".jade" if not page.endswith(PAGE_FORMAT): error("Can't create '%s'" % page) print("Invalid filena...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serve(port, no_livereload, open_url): """Serve the site """
engine = Yass(CWD) if not port: port = engine.config.get("local_server.port", 8000) if no_livereload is None: no_livereload = True if engine.config.get("local_server.livereload") is False else False if open_url is None: open_url = False if engine.config.get("local_server.open_u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_map_location(self): """Get the location of the player, converted to world coordinates. :return: a tuple (x, y, z). """
map_data = self.get_map() (bounds_e, bounds_n), (bounds_w, bounds_s) = map_data["continent_rect"] (map_e, map_n), (map_w, map_s) = map_data["map_rect"] assert bounds_w < bounds_e assert bounds_n < bounds_s assert map_w < map_e assert map_n < map_s meter...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CreateVertices(self, points): """ Returns a dictionary object with keys that are 2tuples represnting a point. """
gr = digraph() for z, x, Q in points: node = (z, x, Q) gr.add_nodes([node]) return gr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetFarthestNode(self, gr, node): """node is start node"""
# Remember: weights are negative distance = minmax.shortest_path_bellman_ford(gr, node)[1] # Find the farthest node, which is end of track min_key = None for key, value in distance.iteritems(): if min_key is None or value < distance[min_key]: min_key...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_success(self, fn, *args, **kwargs): """ Call the given callback if or when the connected deferred succeeds. """
self._callbacks.append((fn, args, kwargs)) result = self._resulted_in if result is not _NOTHING_YET: self._succeed(result=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 _succeed(self, result): """ Fire the success chain. """
for fn, args, kwargs in self._callbacks: fn(result, *args, **kwargs) self._resulted_in = 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 fetch_config(filename): """Fetch the Configuration schema information Finds the schema file, loads the file and reads the JSON, then converts to a dictionary...
# This trick gets the directory of *this* file Configuration.py thus # allowing to find the schema files relative to this file. dir_name = get_source_dir() # Append json filename = os.path.join('json', filename) fileobj = open(os.path.join(dir_name, filename), 'r') my_dict = json.loads(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populate_args_level(schema, parser): """Use a schema to populate a command line argument parser"""
for key, value in schema['properties'].iteritems(): if key == 'name': continue arg = '--%s' % key desc = value['description'] if 'type' in value: if value['type'] == 'string': if 'enum' in value: parser.add_argument(arg, ...
<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_json(self, config_json): """Permanently set the JSON configuration Unable to call twice."""
if self.configuration_dict is not None: raise RuntimeError("Can only set configuration once", self.configuration_dict) schema = fetch_config('ConfigurationSchema.json') validictory.validate(config_json, schema) config_json['name'] = self.name config_json['run_numb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_strip_ext( afile, skip_version=False, only_known_extensions=False, allow_subformat=True): """ Strip in the best way the extension from a filename. 'foo'...
import os afile = afile.split(';') if len(afile) > 1 and allow_subformat and not afile[-1].isdigit(): afile = afile[0:-1] if len(afile) > 1 and skip_version and afile[-1].isdigit(): afile = afile[0:-1] afile = ';'.join(afile) nextfile = _extensions.sub('', afile) if nextfile...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def guess_extension(amimetype, normalize=False): """ Tries to guess extension for a mimetype. @param amimetype: name of a mimetype @time amimetype: string @retur...
ext = _mimes.guess_extension(amimetype) if ext and normalize: # Normalize some common magic mis-interpreation ext = {'.asc': '.txt', '.obj': '.bin'}.get(ext, ext) from invenio.legacy.bibdocfile.api_normalizer import normalize_format return normalize_format(ext) return ext
<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_magic_guesses(fullpath): """ Return all the possible guesses from the magic library about the content of the file. @param fullpath: location of the file ...
if CFG_HAS_MAGIC == 1: magic_cookies = _get_magic_cookies() magic_result = [] for key in magic_cookies.keys(): magic_result.append(magic_cookies[key].file(fullpath)) return tuple(magic_result) elif CFG_HAS_MAGIC == 2: magic_result = [] for key in ({'m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mimes(self): """ Returns extended MimeTypes. """
_mimes = MimeTypes(strict=False) _mimes.suffix_map.update({'.tbz2': '.tar.bz2'}) _mimes.encodings_map.update({'.bz2': 'bzip2'}) if cfg['CFG_BIBDOCFILE_ADDITIONAL_KNOWN_MIMETYPES']: for key, value in iteritems( cfg['CFG_BIBDOCFILE_ADDITIONAL_KNOWN_MIMETYP...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extensions(self): """ Generate the regular expression to match all the known extensions. @return: the regular expression. @rtype: regular expression object "...
_tmp_extensions = self.mimes.encodings_map.keys() + \ self.mimes.suffix_map.keys() + \ self.mimes.types_map[1].keys() + \ cfg['CFG_BIBDOCFILE_ADDITIONAL_KNOWN_FILE_EXTENSIONS'] extensions = [] for ext in _tmp_extensions: if ext.startswith('.'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self, service): """ Start the service, catching and logging exceptions """
try: map(self.start_class, service.depends) if service.is_running(): return if service in self.failed: log.warning("%s previously failed to start", service) return service.start() except Exception: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_class(self, class_): """ Start all services of a given class. If this manager doesn't already have a service of that class, it constructs one and start...
matches = filter(lambda svc: isinstance(svc, class_), self) if not matches: svc = class_() self.register(svc) matches = [svc] map(self.start, matches) return matches
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stop_class(self, class_): "Stop all services of a given class" matches = filter(lambda svc: isinstance(svc, class_), self) map(self.stop, matches)
<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_more_data(self, file, timeout): """ Return data from the file, if available. If no data is received by the timeout, then raise RuntimeError. """
timeout = datetime.timedelta(seconds=timeout) timer = Stopwatch() while timer.split() < timeout: data = file.read() if data: return data raise RuntimeError("Timeout")
<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_env(self): """ Augment the current environment providing the PYTHONUSERBASE. """
env = dict(os.environ) env.update( getattr(self, 'env', {}), PYTHONUSERBASE=self.env_path, PIP_USER="1", ) self._disable_venv(env) return env
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _disable_venv(self, env): """ Disable virtualenv and venv in the environment. """
venv = env.pop('VIRTUAL_ENV', None) if venv: venv_path, sep, env['PATH'] = env['PATH'].partition(os.pathsep)
<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_env(self): """ Create a PEP-370 environment """
root = path.Path(os.environ.get('SERVICES_ROOT', 'services')) self.env_path = (root / self.name).abspath() cmd = [ self.python, '-c', 'import site; print(site.getusersitepackages())', ] out = subprocess.check_output(cmd, env=self._run_env) site_pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compaction(self, request_compaction=False): """Retrieve a report on, or request compaction for this instance. :param bool request_compaction: A boolean indic...
url = self._service_url + 'compaction/' if request_compaction: response = requests.post(url, **self._instances._default_request_kwargs) else: response = requests.get(url, **self._instances._default_request_kwargs) return response.json()
<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_authenticated_connection(self, user, passwd, db='admin', ssl=True): """Get an authenticated connection to this instance. :param str user: The username to...
# Attempt to establish an authenticated connection. try: connection = self.get_connection(ssl=ssl) connection[db].authenticate(user, passwd) return connection # Catch exception here for logging, then just re-raise. except pymongo.errors.OperationFail...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shards(self, add_shard=False): """Get a list of shards belonging to this instance. :param bool add_shard: A boolean indicating whether to add a new shard to ...
url = self._service_url + 'shards/' if add_shard: response = requests.post(url, **self._instances._default_request_kwargs) else: response = requests.get(url, **self._instances._default_request_kwargs) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_relic_stats(self): """ Get stats for this instance. """
if self._new_relic_stats is None: # if this is a sharded instance, fetch shard stats in parallel if self.type == 'mongodb_sharded': shards = [Shard(self.name, self._service_url + 'shards/', self._client, shard_doc) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rollup_shard_stats_to_instance_stats(self, shard_stats): """ roll up all shard stats to instance level stats :param shard_stats: dict of {shard_name: shard ...
instance_stats = {} opcounters_per_node = [] # aggregate replication_lag instance_stats['replication_lag'] = max(map(lambda s: s['replication_lag'], shard_stats.values())) aggregate_server_statistics = {} for shard_name, stats in shard_stats.items(): for st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compile_new_relic_stats(self, stats_this_second, stats_next_second): """ from instance 'stats_this_second' and instance 'stats_next_second', compute some pe...
server_statistics_per_second = {} opcounters_per_node_per_second = [] for subdoc in ["opcounters", "network"]: first_doc = stats_this_second['aggregate_server_statistics'][subdoc] second_doc = stats_next_second['aggregate_server_statistics'][subdoc] keys = se...
<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_stepdown_window(self): """Get information on this instance's stepdown window."""
url = self._service_url + 'stepdown/' response = requests.get(url, **self._instances._default_request_kwargs) return response.json()
<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_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True): """Set the stepdown window for this instance. Date times are assumed to be ...
# Ensure a logical start and endtime is requested. if not start < end: raise TypeError('Parameter "start" must occur earlier in time than "end".') # Ensure specified window is less than a week in length. week_delta = datetime.timedelta(days=7) if not ((end - start) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def brand(self, brand): """Sets the brand of this PaymentCard. :param brand: The brand of this PaymentCard. :type: str """
allowed_values = ["visa", "mastercard", "americanExpress", "discover"] if brand is not None and brand not in allowed_values: raise ValueError( "Invalid value for `brand` ({0}), must be one of {1}" .format(brand, allowed_values) ) self._br...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def latex_quote(s): """Quote special characters for LaTeX. (Incomplete, currently only deals with underscores, dollar and hash.) """
special = {'_':r'\_', '$':r'\$', '#':r'\#'} s = str(s) for char,repl in special.items(): new = s.replace(char, repl) s = new[:] 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 tree_to_file(tree:'BubbleTree', outfile:str): """Compute the bubble representation of given power graph, and push it into given file."""
with open(outfile, 'w') as fd: fd.write(tree_to_bubble(tree))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lines_from_tree(tree, nodes_and_set:bool=False) -> iter: """Yield lines of bubble describing given BubbleTree"""
NODE = 'NODE\t{}' INCL = 'IN\t{}\t{}' EDGE = 'EDGE\t{}\t{}\t1.0' SET = 'SET\t{}' if nodes_and_set: for node in tree.nodes(): yield NODE.format(node) for node in tree.powernodes(): yield SET.format(node) for node, includeds in tree.inclusions.items(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_formdata(self, valuelist): """Join time string."""
if valuelist: time_str = u' '.join(valuelist) try: timetuple = time.strptime(time_str, self.format) self.data = datetime.time(*timetuple[3:6]) except ValueError: self.data = None 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 validate_csrf_token(self, field): """Disable CRSF proection during testing."""
if current_app.testing: return super(InvenioBaseForm, self).validate_csrf_token(field)
<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_exchange_word_vectors( filename = "database.db", maximum_number_of_events = None ): """ Load exchange data and return dataset. """
log.info("load word vectors of database {filename}".format( filename = filename )) # Ensure that the database exists. if not os.path.isfile(filename): log.info("database {filename} nonexistent".format( filename = filename )) program.terminate() 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 load_HEP_data( ROOT_filename = "output.root", tree_name = "nominal", maximum_number_of_events = None ): """ Load HEP data and return dataset. """
ROOT_file = open_ROOT_file(ROOT_filename) tree = ROOT_file.Get(tree_name) number_of_events = tree.GetEntries() data = datavision.Dataset() progress = shijian.Progress() progress.engage_quick_calculation_mode() # counters number_of_events_loaded = 0 l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sentiment( text = None, confidence = False ): """ This function accepts a string text input. It calculates the sentiment of the text, "pos" or "neg". By defa...
try: words = text.split(" ") # Remove empty strings. words = [word for word in words if word] features = word_features(words) classification = classifier.classify(features) confidence_classification = classifier.prob_classify(features).prob(classification) except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def usernames( self ): """ This function returns the list of unique usernames corresponding to the tweets stored in self. """
try: return list(set([tweet.username for tweet in self])) except: log.error("error -- possibly a problem with tweets stored")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user_sentiments( self, username = None ): """ This function returns a list of all sentiments of the tweets of a specified user. """
try: return [tweet.sentiment for tweet in self if tweet.username == username] except: log.error("error -- possibly no username specified") 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 user_sentiments_most_frequent( self, username = None, single_most_frequent = True ): """ This function returns the most frequent calculated sentiments expres...
try: sentiment_frequencies = collections.Counter(self.user_sentiments( username = username )) if single_most_frequent: return sentiment_frequencies.most_common(1)[0][0] else: return dict(sentiment_frequencies) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def users_sentiments_single_most_frequent( self, usernames = None, ): """ This function returns the single most frequent calculated sentiment expressed by all st...
users_sentiments_single_most_frequent = dict() if usernames is None: usernames = self.usernames() try: for username in usernames: sentiment = self.user_sentiments_most_frequent( username = username, sing...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_progress(i, n): """Returns string containing a progress bar, a percentage, etc."""
if n == 0: fraction = 0 else: fraction = float(i)/n LEN_BAR = 25 num_plus = int(round(fraction*LEN_BAR)) s_plus = '+'*num_plus s_point = '.'*(LEN_BAR-num_plus) return '[{0!s}{1!s}] {2:d}/{3:d} - {4:.1f}%'.format(s_plus, s_point, i, n, fraction*100)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_exe_info(py_len, exeinfo, format, indlevel): """Renders ExeInfo object in specified format"""
ret = [] ind = " " * indlevel * NIND if format.startswith("text") else "" if format == "markdown-list": for si in exeinfo: ret.append(" - `{0!s}`: {1!s}".format(si.filename, si.description)) if format == "rest-list": for si in exeinfo: ret.append("* ``{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 _map_relation(c, language='any'): """ Map related concept or collection, leaving out the relations. :param c: the concept or collection to map :param string ...
label = c.label(language) return { 'id': c.id, 'type': c.type, 'uri': c.uri, 'label': label.label if label 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 add_indicators(self, indicators=list(), private=False, tags=list()): """Add indicators to the remote instance."""
if len(indicators) == 0: raise Exception("No indicators were identified.") self.logger.debug("Checking {} indicators".format(len(indicators))) cleaned = clean_indicators(indicators) self.logger.debug("Cleaned {} indicators".format(len(cleaned))) whitelisted = check_w...
<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_indicators(self): """List indicators available on the remote instance."""
response = self._get('', 'get-indicators') response['message'] = "%i indicators:\n%s" % ( len(response['indicators']), "\n".join(response['indicators']) ) 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: def besttype(x, encoding="utf-8", percentify=True): """Convert string x to the most useful type, i.e. int, float or unicode string. If x is a quoted string (sing...
def unicodify(x): return to_unicode(x, encoding) def percent(x): try: if x.endswith("%"): x = float(x[:-1]) / 100. else: raise ValueError except (AttributeError, ValueError): raise ValueError return x x = u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _onmessage(cls, kmsg): """ Call on received message :param kser.schemas.Message kmsg: Kafka message :return: Kafka message :rtype: kser.schemas.Message """
logger.debug( "{}.ReceivedMessage {}[{}]".format( cls.__name__, kmsg.entrypoint, kmsg.uuid ), extra=dict(kmsg=kmsg.dump()) ) return cls.onmessage(kmsg)
<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(cls, name, entrypoint): """ Register a new entrypoint :param str name: Key used by messages :param kser.entry.Entrypoint entrypoint: class to load :...
if not issubclass(entrypoint, Entrypoint): raise ValidationError( "Invalid type for entry '{}', MUST implement " "kser.entry.Entrypoint".format(name), extra=dict(entrypoint=name) ) cls.ENTRYPOINTS[name] = entrypoint logger....
<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(cls, raw_data): """description of run"""
logger.debug("{}.ReceivedFromKafka: {}".format( cls.__name__, raw_data )) try: kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data)) except Exception as exc: logger.error( "{}.ImportError: Failed to load data from kafka: {}".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 deactivate(self, node_id): """Deactivate the node identified by node_id. Deactivates the node corresponding to node_id, which means that it can never be the ...
node = self.node_list[node_id] self.node_list[node_id] = node._replace(active=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 insert(self, point, data=None): """Insert a new node in the tree. Args: point (:obj:`tuple` of float or int): Stores the position of the node. data (:obj, o...
assert len(point) == self.k if self.size == 0: if self.region is None: self.region = [[-math.inf, math.inf]] * self.k axis = 0 return self.new_node(point, self.region, axis, data) # Iteratively descends to one leaf current_id = 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 set_to_public(self, request, queryset): """ Set one or several releases to public """
queryset.update(is_public=True, modified=now())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loads(cls, json_data): """description of load"""
try: return cls(**cls.MARSHMALLOW_SCHEMA.loads(json_data)) except marshmallow.exceptions.ValidationError as exc: raise ValidationError("Failed to load message", extra=exc.args[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 format(self, response): """ Format the data. In derived classes, it is usually better idea to override ``_format_data()`` than this method. :param response: ...
res = self._prepare_response(response) res.content = self._format_data(res.content, self.charset) return self._finalize_response(res)
<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(self, data, charset=None): """ Parse the data. It is usually a better idea to override ``_parse_data()`` than this method in derived classes. :param ch...
charset = charset or self.charset return self._parse_data(data, charset)
<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_data(self, data, charset): """ Decode string data. :returns: unicode string """
try: return smart_unicode(data, charset) except UnicodeDecodeError: raise errors.BadRequest('wrong charset')
<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, data, charset): """ Parse the data :param data: the data (may be None) """
return self._decode_data(data, charset) if data else u''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _finalize_response(self, response): """ Convert the ``Response`` object into django's ``HttpResponse`` :return: django's ``HttpResponse`` """
res = HttpResponse(content=response.content, content_type=self._get_content_type()) # status_code is set separately to allow zero res.status_code = response.code return res
<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_mapper(self, mapper, content_type, shortname=None): """ Register new mapper. :param mapper: mapper object needs to implement ``parse()`` and ``forma...
self._check_mapper(mapper) cont_type_names = self._get_content_type_names(content_type, shortname) self._datamappers.update(dict([(name, mapper) for name in cont_type_names]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_formatter(self, request, resource): """ Select appropriate formatter based on the request. :param request: the HTTP request :param resource: the invok...
# 1. get from resource if resource.mapper: return resource.mapper # 2. get from url mapper_name = self._get_name_from_url(request) if mapper_name: return self._get_mapper(mapper_name) # 3. get from accept header mapper_name = self._get_na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_parser(self, request, resource): """ Select appropriate parser based on the request. :param request: the HTTP request :param resource: the invoked res...
# 1. get from resource if resource.mapper: return resource.mapper # 2. get from content type mapper_name = self._get_name_from_content_type(request) if mapper_name: return self._get_mapper(mapper_name) # 3. get from url mapper_name = self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_mapper_by_content_type(self, content_type): """ Returs mapper based on the content type. """
content_type = util.strip_charset(content_type) return self._get_mapper(content_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 _get_mapper(self, mapper_name): """ Return the mapper based on the given name. :returns: the mapper based on the given ``mapper_name`` :raises: NotAcceptable...
if mapper_name in self._datamappers: # mapper found return self._datamappers[mapper_name] else: # unsupported format return self._unknown_format(mapper_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_name_from_content_type(self, request): """ Get name from Content-Type header """
content_type = request.META.get('CONTENT_TYPE', None) if content_type: # remove the possible charset-encoding info return util.strip_charset(content_type) 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_name_from_accept(self, request): """ Process the Accept HTTP header. Find the most suitable mapper that the client wants and we support. :returns: the p...
accepts = util.parse_accept_header(request.META.get("HTTP_ACCEPT", "")) if not accepts: return None for accept in accepts: if accept[0] in self._datamappers: return accept[0] raise errors.NotAcceptable()
<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_name_from_url(self, request): """ Determine short name for the mapper based on the URL. Short name can be either in query string (e.g. ?format=json) or ...
format = request.GET.get('format', None) if not format: match = self._format_query_pattern.match(request.path) if match and match.group('format'): format = match.group('format') return format