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 summarize(df,preview_rows = 8, display_max_cols = None,display_width = None, output_path = None, output_safe = True,to_folder = False): """ Prints informatio...
assert type(df) is pd.DataFrame # Reformat displays initial_settings = pd_settings(display_max_cols, None, display_width) # --------Values of data----------- df_preview = _io.preview(df,preview_rows) df_desc_num, df_desc_cat = detailed_desc(df) percent_values = stats.percentiles(df) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def timed_pipe(generator, seconds=3): ''' This is a time limited pipeline. If you have a infinite pipeline and want it to stop yielding after a certain amount of time, use this! ''' # grab the highest precision timer # when it started start = ts() # when it will stop end = start + second...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destruct(particles, index): """Fermion annihilation operator in matrix representation for a indexed particle in a bounded N-particles fermion fock space"""
mat = np.zeros((2**particles, 2**particles)) flipper = 2**index for i in range(2**particles): ispin = btest(i, index) if ispin == 1: mat[i ^ flipper, i] = phase(i, index) return csr_matrix(mat)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_unicode_to_utf8(data): """Change all strings in a JSON structure to UTF-8."""
if isinstance(data, unicode): return data.encode('utf-8') elif isinstance(data, dict): newdict = {} for key in data: newdict[json_unicode_to_utf8( key)] = json_unicode_to_utf8(data[key]) return newdict elif isinstance(data, list): 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 json_decode_file(filename): """ Parses a textfile using json to build a python object representation """
seq = open(filename).read() # The JSON standard has no comments syntax. We have to remove them # before feeding python's JSON parser seq = json_remove_comments(seq) # Parse all the unicode stuff to utf-8 return json_unicode_to_utf8(json.loads(seq))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post_init(self): """A post init trigger"""
try: return self.postinit() except Exception as exc: return self._onerror(Result.from_exception(exc, uuid=self.uuid))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _postrun(self, result): """ To execute after exection :param kser.result.Result result: Execution result :return: Execution result :rtype: kser.result.Result...
logger.debug( "{}.PostRun: {}[{}]".format( self.__class__.__name__, self.__class__.path, self.uuid ), extra=dict( kmsg=Message( self.uuid, entrypoint=self.__class__.path, params=self.params, metadata=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 execute(self, result=None): """ Execution 'wrapper' to make sure that it return a result :return: Execution result :rtype: kser.result.Result """
try: return self.unsafe_execute(result=result) except Exception as exc: return self._onerror(Result.from_exception(exc, uuid=self.uuid))
<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_Message(self, result=None): """ Entrypoint -> Message :param kser.result.Result result: Execution result :return: Kafka message :rtype kser.schemas.Messag...
return Message( uuid=self.uuid, entrypoint=self.__class__.path, params=self.params, result=result if result else self.result, metadata=self.metadata )
<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_Message(cls, kmsg): """ Message -> Entrypoint :param kser.schemas.Message kmsg: Kafka message :return: a entrypoint :rtype kser.entry.Entrypoint """
return cls( uuid=kmsg.uuid, params=kmsg.params, result=kmsg.result, metadata=kmsg.metadata )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_as(self, filename=None): """ Dumps object contents into file on disk. Args: filename (optional): defaults to self.filename. If passed, self.filename wi...
if filename is None: filename = self.filename if filename is None: filename = self.default_filename if filename is None: raise RuntimeError("Class '{}' has no default filename".format(self.__class__.__name__)) self._do_save_as(filename) self.f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, filename=None): """Loads file and registers filename as attribute."""
assert not self.__flag_loaded, "File can be loaded only once" if filename is None: filename = self.default_filename assert filename is not None, \ "{0!s} class has no default filename".format(self.__class__.__name__) # Convention: trying to open empty file is an...
<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_default(self): """ Initializes object with its default values Tries to load self.default_filename from default data directory. For safety, filename is r...
import f311 if self.default_filename is None: raise RuntimeError("Class '{}' has no default filename".format(self.__class__.__name__)) fullpath = f311.get_default_data_path(self.default_filename, class_=self.__class__) self.load(fullpath) self.filename = 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 availability(self, availability): """Sets the availability of this Product. :param availability: The availability of this Product. :type: str """
allowed_values = ["available", "comingSoon", "retired"] if availability is not None and availability not in allowed_values: raise ValueError( "Invalid value for `availability` ({0}), must be one of {1}" .format(availability, allowed_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 stock_status(self, stock_status): """Sets the stock_status of this Product. :param stock_status: The stock_status of this Product. :type: str """
allowed_values = ["available", "alert", "unavailable"] if stock_status is not None and stock_status not in allowed_values: raise ValueError( "Invalid value for `stock_status` ({0}), must be one of {1}" .format(stock_status, allowed_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 asserts(input_value, rule, message=''): """ this function allows you to write asserts in generators since there are moments where you actually want the progr...
assert callable(rule) or type(rule)==bool, 'asserts needs rule to be a callable function or a test boolean' assert isinstance(message, str), 'asserts needs message to be a string' # if the message is empty and rule is callable, fill message with rule's source code if len(message)==0 and callable(rule):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print(*a): """ print just one that returns what you give it instead of None """
try: _print(*a) return a[0] if len(a) == 1 else a except: _print(*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 pattern2re(pattern): """Makes a unicode regular expression from a pattern. Returns ``(start, full_re, int_re)`` where: * `start` is either empty or the subdi...
pattern_segs = filter(None, pattern.split('/')) # This anchors the first component either at the start of the string or at # the start of a path component if not pattern: return '', re.compile(''), None elif '/' in pattern: full_regex = '^' # Start at beginning of path int...
<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_backend(self, p): """Converts something to the correct path representation. If given a Path, this will simply unpack it, if it's the correct type. If giv...
if isinstance(p, self._cmp_base): return p.path elif isinstance(p, self._backend): return p elif self._backend is unicode and isinstance(p, bytes): return p.decode(self._encoding) elif self._backend is bytes and isinstance(p, unicode): 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 parent(self): """The parent directory of this path. """
p = self._lib.dirname(self.path) p = self.__class__(p) return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unicodename(self): """The name of this path as unicode. """
n = self._lib.basename(self.path) if self._backend is unicode: return n else: return n.decode(self._encoding, 'replace')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rel_path_to(self, dest): """Builds a relative path leading from this one to the given `dest`. Note that these paths might be both relative, in which case the...
dest = self.__class__(dest) orig_list = self.norm_case()._components() dest_list = dest._components() i = -1 for i, (orig_part, dest_part) in enumerate(zip(orig_list, dest_list)): if orig_part != self._normcase(dest_part): up = ['..'] * (len(orig_li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lies_under(self, prefix): """Indicates if the `prefix` is a parent of this path. """
orig_list = self.norm_case()._components() pref_list = self.__class__(prefix).norm_case()._components() return (len(orig_list) >= len(pref_list) and orig_list[:len(pref_list)] == pref_list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tempfile(cls, suffix='', prefix=None, dir=None, text=False): """Returns a new temporary file. The return value is a pair (fd, path) where fd is the file desc...
if prefix is None: prefix = tempfile.template if dir is not None: # Note that this is not safe on Python 2 # There is no work around, apart from not using the tempfile module dir = str(Path(dir)) fd, filename = tempfile.mkstemp(suffix, prefix, dir...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tempdir(cls, suffix='', prefix=None, dir=None): """Returns a new temporary directory. Arguments are as for :meth:`~rpaths.Path.tempfile`, except that the `te...
if prefix is None: prefix = tempfile.template if dir is not None: # Note that this is not safe on Python 2 # There is no work around, apart from not using the tempfile module dir = str(Path(dir)) dirname = tempfile.mkdtemp(suffix, prefix, dir) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rel_path_to(self, dest): """Builds a relative path leading from this one to another. Note that these paths might be both relative, in which case they'll be a...
return super(Path, self.absolute()).rel_path_to(Path(dest).absolute())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listdir(self, pattern=None): """Returns a list of all the files in this directory. The special entries ``'.'`` and ``'..'`` will not be returned. :param patt...
files = [self / self.__class__(p) for p in os.listdir(self.path)] if pattern is None: pass elif callable(pattern): files = filter(pattern, files) else: if isinstance(pattern, backend_types): if isinstance(pattern, bytes): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recursedir(self, pattern=None, top_down=True, follow_links=False, handle_errors=None): """Recursively lists all files under this directory. :param pattern: A...
if not self.is_dir(): raise ValueError("recursedir() called on non-directory %s" % self) start = '' int_pattern = None if pattern is None: pattern = lambda p: True elif callable(pattern): pass else: if isinstance(pattern, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mkdir(self, name=None, parents=False, mode=0o777): """Creates that directory, or a directory under this one. ``path.mkdir(name)`` is a shortcut for ``(path/n...
if name is not None: return (self / name).mkdir(parents=parents, mode=mode) if self.exists(): return if parents: os.makedirs(self.path, mode) else: os.mkdir(self.path, mode) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rmdir(self, parents=False): """Removes this directory, provided it is empty. Use :func:`~rpaths.Path.rmtree` if it might still contain files. :param parents:...
if parents: os.removedirs(self.path) else: os.rmdir(self.path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename(self, new, parents=False): """Renames this path to the given new location. :param new: New path where to move this one. :param parents: If set to True...
if parents: os.renames(self.path, self._to_backend(new)) else: os.rename(self.path, self._to_backend(new))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copyfile(self, target): """Copies this file to the given `target` location. """
shutil.copyfile(self.path, self._to_backend(target))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copymode(self, target): """Copies the mode of this file on the `target` file. The owner is not copied. """
shutil.copymode(self.path, self._to_backend(target))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copystat(self, target): """Copies the permissions, times and flags from this to the `target`. The owner is not copied. """
shutil.copystat(self.path, self._to_backend(target))
<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, target): """Copies this file the `target`, which might be a directory. The permissions are copied. """
shutil.copy(self.path, self._to_backend(target))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copytree(self, target, symlinks=False): """Recursively copies this directory to the `target` location. The permissions and times are copied (like :meth:`~rpa...
shutil.copytree(self.path, self._to_backend(target), symlinks)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, target): """Recursively moves a file or directory to the given target location. """
shutil.move(self.path, self._to_backend(target))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, mode='r', name=None, **kwargs): """Opens this file, or a file under this directory. ``path.open(mode, name)`` is a shortcut for ``(path/name).open...
if name is not None: return io.open((self / name).path, mode=mode, **kwargs) else: return io.open(self.path, mode=mode, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rewrite(self, mode='r', name=None, temp=None, tempext='~', **kwargs): r"""Replaces this file with new content. This context manager gives you two file object...
if name is not None: pathr = self / name else: pathr = self for m in 'war+': mode = mode.replace(m, '') # Build options common_kwargs = {} readable_kwargs = {} writable_kwargs = {} for key, value in kwargs.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 matches(self, path): """Tests if the given path matches the pattern. Note that the unicode translation of the patch is matched, so replacement characters mig...
path = self._prepare_path(path) return self.full_regex.search(path) 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 may_contain_matches(self, path): """Tests whether it's possible for paths under the given one to match. If this method returns None, no path under the given ...
path = self._prepare_path(path) return self.int_regex.search(path) 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 tgcanrecruit(self, region=None): """Whether the nation will receive a recruitment telegram. Useful in conjunction with the Telegrams API. Parameters region :...
params = {'from': normalize(region)} if region is not None else {} @api_query('tgcanrecruit', **params) async def result(_, root): return bool(int(root.find('TGCANRECRUIT').text)) return result(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def govt(self, root): """Nation's government expenditure, as percentages. Returns ------- an :class:`ApiQuery` of :class:`collections.OrderedDict` with \ k...
elem = root.find('GOVT') result = OrderedDict() result['Administration'] = float(elem.find('ADMINISTRATION').text) result['Defense'] = float(elem.find('DEFENCE').text) # match the web UI result['Education'] = float(elem.find('EDUCATION').text) result['Environment'] = f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def sectors(self, root): """Components of the nation's economy, as percentages. Returns ------- an :class:`ApiQuery` of :class:`collections.OrderedDict` wi...
elem = root.find('SECTORS') result = OrderedDict() result['Black Market (estimated)'] = float(elem.find('BLACKMARKET').text) result['Government'] = float(elem.find('GOVERNMENT').text) result['Private Industry'] = float(elem.find('INDUSTRY').text) result['State-Owned Ind...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def deaths(self, root): """Causes of death in the nation, as percentages. Returns ------- an :class:`ApiQuery` of dict with keys of str and values of float...
return { elem.get('type'): float(elem.text) for elem in root.find('DEATHS') }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def endorsements(self, root): """Regional neighbours endorsing the nation. Returns ------- an :class:`ApiQuery` of a list of :class:`Nation` """
text = root.find('ENDORSEMENTS').text return [Nation(name) for name in text.split(',')] if text else []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def description(self): """Nation's full description, as seen on its in-game page. Returns ------- an awaitable of str """
resp = await self._call_web(f'nation={self.id}') return html.unescape( re.search( '<div class="nationsummary">(.+?)<p class="nationranktext">', resp.text, flags=re.DOTALL ) .group(1) .replace('\n', '') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self): """Accept the option. Returns ------- an awaitable of :class:`IssueResult` """
return self._issue._nation._accept_issue(self._issue.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 pip_upgrade_all(line): """Attempt to upgrade all packages"""
from pip import get_installed_distributions user = set(d.project_name for d in get_installed_distributions(user_only=True)) all = set(d.project_name for d in get_installed_distributions()) for dist in all - user: do_pip(["install", "--upgrade", dist]) for dist in user: do_pip(["ins...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enc_name_descr(name, descr, color=a99.COLOR_DESCR): """Encodes html given name and description."""
return enc_name(name, color)+"<br>"+descr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def style_checkboxes(widget): """ Iterates over widget children to change checkboxes stylesheet. The default rendering of checkboxes does not allow to tell ...
ww = widget.findChildren(QCheckBox) for w in ww: w.setStyleSheet("QCheckBox:focus {border: 1px solid #000000;}")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_table_widget(t, rowCount, colCount): """Clears and resizes a table widget."""
t.reset() t.horizontalHeader().reset() t.clear() t.sortItems(-1) t.setRowCount(rowCount) t.setColumnCount(colCount)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def place_center(window, width=None, height=None): """Places window in the center of the screen."""
screenGeometry = QApplication.desktop().screenGeometry() w, h = window.width(), window.height() if width is not None or height is not None: w = width if width is not None else w h = height if height is not None else h window.setGeometry(0, 0, w, h) x = (screenGeomet...
<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_QApplication(args=[]): """Returns the QApplication instance, creating it is does not yet exist."""
global _qapp if _qapp is None: QCoreApplication.setAttribute(Qt.AA_X11InitThreads) _qapp = QApplication(args) return _qapp
<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_frame(): """Returns a QFrame formatted in a particular way"""
ret = QFrame() ret.setLineWidth(1) ret.setMidLineWidth(0) ret.setFrameShadow(QFrame.Sunken) ret.setFrameShape(QFrame.Box) 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 add_signal(self, signal): """Adds "input" signal to connected signals. Internally connects the signal to a control slot."""
self.__signals.append(signal) if self.__connected: # Connects signal if the current state is "connected" self.__connect_signal(signal)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect_all(self): """Disconnects all signals and slots. If already in "disconnected" state, ignores the call. """
if not self.__connected: return # assert self.__connected, "disconnect_all() already in \"disconnected\" state" self.__disconnecting = True try: for signal in self.__signals: signal.disconnect(self.__signalReceived) if self.__slot is n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __signalReceived(self, *args): """Received signal. Cancel previous timer and store args to be forwarded later."""
if self.__disconnecting: return with self.__lock: self.__args = args if self.__rateLimit == 0: self.__timer.stop() self.__timer.start((self.__delay * 1000) + 1) else: now = time.time() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __flush(self): """If there is a signal queued up, send it now."""
if self.__args is None or self.__disconnecting: return False #self.emit(self.signal, *self.args) self.__sigDelayed.emit(self.__args) self.__args = None self.__timer.stop() self.__lastFlushTime = time.time() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_indicators(indicators): """Remove any extra details from indicators."""
output = list() for indicator in indicators: strip = ['http://', 'https://'] for item in strip: indicator = indicator.replace(item, '') indicator = indicator.strip('.').strip() parts = indicator.split('/') if len(parts) > 0: indicator = parts.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 hash_values(values, alg="md5"): """Hash a list of values."""
import hashlib if alg not in ['md5', 'sha1', 'sha256']: raise Exception("Invalid hashing algorithm!") hasher = getattr(hashlib, alg) if type(values) == str: output = hasher(values).hexdigest() elif type(values) == list: output = list() for item in 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 check_whitelist(values): """Check the indicators against known whitelists."""
import os import tldextract whitelisted = list() for name in ['alexa.txt', 'cisco.txt']: config_path = os.path.expanduser('~/.config/blockade') file_path = os.path.join(config_path, name) whitelisted += [x.strip() for x in open(file_path, 'r').readlines()] output = list() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_items(values): """Cache indicators that were successfully sent to avoid dups."""
import os config_path = os.path.expanduser('~/.config/blockade') file_path = os.path.join(config_path, 'cache.txt') if not os.path.isfile(file_path): file(file_path, 'w').close() written = [x.strip() for x in open(file_path, 'r').readlines()] handle = open(file_path, 'a') for item 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 prune_cached(values): """Remove the items that have already been cached."""
import os config_path = os.path.expanduser('~/.config/blockade') file_path = os.path.join(config_path, 'cache.txt') if not os.path.isfile(file_path): return values cached = [x.strip() for x in open(file_path, 'r').readlines()] output = list() for item in values: hashed = has...
<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_logger(name): """Get a logging instance we can use."""
import logging import sys logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) shandler = logging.StreamHandler(sys.stdout) fmt = "" fmt += '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():' fmt += '%(lineno)d %(asctime)s\033[0m| %(message)s' fmtr = logging.Formatter(...
<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_whitelists(): """Download approved top 1M lists."""
import csv import grequests import os import StringIO import zipfile mapping = { 'http://s3.amazonaws.com/alexa-static/top-1m.csv.zip': { 'name': 'alexa.txt' }, 'http://s3-us-west-1.amazonaws.com/umbrella-static/top-1m.csv.zip': { 'name': 'cisco.txt' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mode(self, mode): """Sets the mode of this BraintreeGateway. :param mode: The mode of this BraintreeGateway. :type: str """
allowed_values = ["test", "live"] if mode is not None and mode not in allowed_values: raise ValueError( "Invalid value for `mode` ({0}), must be one of {1}" .format(mode, allowed_values) ) self._mode = mode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diagnose(df,preview_rows = 2, display_max_cols = 0,display_width = None): """ Prints information about the DataFrame pertinent to data cleaning. Parameters d...
assert type(df) is pd.DataFrame # Diagnose problems with the data formats that can be addressed in cleaning # Get initial display settings initial_max_cols = pd.get_option('display.max_columns') initial_max_rows = pd.get_option('display.max_rows') initial_width = pd.get_option('display.wi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cut_spectrum(sp, l0, lf): """ Cuts spectrum given a wavelength interval, leaving origina intact Args: sp: Spectrum instance l0: initial wavelength lf: final ...
if l0 >= lf: raise ValueError("l0 must be lower than lf") idx0 = np.argmin(np.abs(sp.x - l0)) idx1 = np.argmin(np.abs(sp.x - lf)) out = copy.deepcopy(sp) out.x = out.x[idx0:idx1] out.y = out.y[idx0:idx1] return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def skip_first(pipe, items=1): ''' this is an alias for skip to parallel the dedicated skip_last function to provide a little more readability to the code. the action of actually skipping does not occur until the first iteration is done ''' pipe = iter(pipe) for i in skip(pipe, 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 find(self, query=None, **kwargs): """ You can pass in the appropriate model object from the queries module, or a dictionary with the keys and values for the ...
url = self.getUrl() if query is not None: if isinstance(query, queries.SlickQuery): url = url + "?" + urlencode(query.to_dict()) elif isinstance(query, dict): url = url + "?" + urlencode(query) elif len(kwargs) > 0: url = url +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findOne(self, query=None, mode=FindOneMode.FIRST, **kwargs): """ Perform a find, with the same options present, but only return a maximum of one result. If f...
results = self.find(query, **kwargs) if len(results) is 0: return None elif len(results) is 1 or mode == FindOneMode.FIRST: return results[0] elif mode == FindOneMode.LAST: return results[-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 lookup_cc_partner(nu_pid): """Lookup the charge current partner Takes as an input neutrino nu_pid is a PDG code, then returns the charged lepton partner. So ...
neutrino_type = math.fabs(nu_pid) assert neutrino_type in [12, 14, 16] cc_partner = neutrino_type - 1 # get e, mu, tau cc_partner = math.copysign( cc_partner, nu_pid) # make sure matter/antimatter cc_partner = int(cc_partner) # convert to int return cc_partner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def block_comment(solver, start, end): '''embedable block comment''' text, pos = solver.parse_state length = len(text) startlen = len(start) endlen = len(end) if pos==length: return if not text[pos:].startswith(start): return level = 1 p = pos+1 while p<length: if text[p:].starts...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pip_install(*args): ''' Run pip install ... Explicitly ignores user's config. ''' pip_cmd = os.path.join(os.path.dirname(sys.executable), 'pip') with set_env('PIP_CONFIG_FILE', os.devnull): cmd = [pip_cmd, 'install'] + list(args) print_command(cmd) subprocess.call(cm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def indent_text(text, nb_tabs=0, tab_str=" ", linebreak_input="\n", linebreak_output="\n", wrap=False): r"""Add tabs to each line of text. :param text: the text ...
if not wrap: lines = text.split(linebreak_input) tabs = nb_tabs * tab_str output = "" for line in lines: output += tabs + line + linebreak_output return output else: return wrap_text_in_a_box(body=text, style='no_border', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_user(msg=""): """ Print MSG and a confirmation prompt. Waiting for user's confirmation, unless silent '--yes-i-know' command line option was used, i...
if '--yes-i-know' in sys.argv: return print(msg) try: answer = raw_input("Please confirm by typing 'Yes, I know!': ") except KeyboardInterrupt: print() answer = '' if answer != 'Yes, I know!': sys.stderr.write("ERROR: Aborted.\n") sys.exit(1) retu...
<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_minimum_encoding(text, charsets=('ascii', 'latin1', 'utf8')): """Try to guess the minimum charset that is able to represent. Try to guess the minimum c...
text_in_unicode = text.decode('utf8', 'replace') for charset in charsets: try: return (text_in_unicode.encode(charset), charset) except (UnicodeEncodeError, UnicodeDecodeError): pass return (text_in_unicode.encode('utf8'), 'utf8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_for_xml(text, wash=False, xml_version='1.0', quote=False): """Encode special characters in a text so that it would be XML-compliant. :param text: text...
text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') if quote: text = text.replace('"', '&quot;') if wash: text = wash_for_xml(text, xml_version=xml_version) return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wash_for_xml(text, xml_version='1.0'): """Remove any character which isn't a allowed characters for XML. The allowed characters depends on the version of XML...
if xml_version == '1.0': return RE_ALLOWED_XML_1_0_CHARS.sub( '', unicode(text, 'utf-8')).encode('utf-8') else: return RE_ALLOWED_XML_1_1_CHARS.sub( '', unicode(text, 'utf-8')).encode('utf-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wash_for_utf8(text, correct=True): """Return UTF-8 encoded binary string with incorrect characters washed away. :param text: input string to wash (can be eit...
if isinstance(text, unicode): return text.encode('utf-8') errors = "ignore" if correct else "strict" return text.decode("utf-8", errors).encode("utf-8", errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nice_number(number, thousands_separator=',', max_ndigits_after_dot=None): """Return nicely printed number NUMBER in language LN. Return nicely printed number...
if isinstance(number, float): if max_ndigits_after_dot is not None: number = round(number, max_ndigits_after_dot) int_part, frac_part = str(number).split('.') return '%s.%s' % (nice_number(int(int_part), thousands_separator), frac_part) 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 nice_size(size): """Nice size. :param size: the size. :type size: int :return: a nicely printed size. :rtype: string """
unit = 'B' if size > 1024: size /= 1024.0 unit = 'KB' if size > 1024: size /= 1024.0 unit = 'MB' if size > 1024: size /= 1024.0 unit = 'GB' return '%s %s' % (nice_number(size, max_ndigits_after_dot=2), unit)
<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_line_breaks(text): """Remove line breaks from input. Including unicode 'line separator', 'paragraph separator', and 'next line' characters. """
return unicode(text, 'utf-8').replace('\f', '').replace('\n', '') \ .replace('\r', '').replace(u'\xe2\x80\xa8', '') \ .replace(u'\xe2\x80\xa9', '').replace(u'\xc2\x85', '') \ .encode('utf-8')
<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_to_unicode(text, default_encoding='utf-8'): """Decode input text into Unicode representation. Decode input text into Unicode representation by first u...
if not text: return "" try: return text.decode(default_encoding) except (UnicodeError, LookupError): pass detected_encoding = None if CHARDET_AVAILABLE: # We can use chardet to perform detection res = chardet.detect(text) if res['confidence'] >= 0.8: ...
<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_unicode(text): """Convert to unicode."""
if isinstance(text, unicode): return text if isinstance(text, six.string_types): return decode_to_unicode(text) return unicode(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_latex2unicode(text, kb_file=None): """Translate latex text to unicode. This function will take given text, presumably containing LaTeX symbols, and...
if kb_file is None: kb_file = get_kb_filename() # First decode input text to Unicode try: text = decode_to_unicode(text) except UnicodeDecodeError: text = unicode(wash_for_utf8(text)) # Load translation table, if required if CFG_LATEX_UNICODE_TRANSLATION_CONST == {}: ...
<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_latex2unicode_constants(kb_file=None): """Load LaTeX2Unicode translation table dictionary. Load LaTeX2Unicode translation table dictionary and regular ...
if kb_file is None: kb_file = get_kb_filename() try: data = open(kb_file) except IOError: # File not found or similar sys.stderr.write( "\nCould not open LaTeX to Unicode KB file. " "Aborting translation.\n") return CFG_LATEX_UNICODE_TRANSLAT...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_to_ascii(values): r"""Transliterate the string into ascii representation. Transliterate the string contents of the given sequence into ascii repres...
if not values and not isinstance(values, str): return values if isinstance(values, str): values = [values] for index, value in enumerate(values): if not value: continue unicode_text = decode_to_unicode(value) if u"[?]" in unicode_text: decode...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xml_entities_to_utf8(text, skip=('lt', 'gt', 'amp')): """Translate HTML or XML character references to UTF-8. Removes HTML or XML character references and en...
def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)).encode("utf-8") else: return unichr(int(text[2:-1])).encode("utf-8...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_accents(x): u"""Strip accents in the input phrase X. Strip accents in the input phrase X (assumed in UTF-8) by replacing accented characters with their...
x = re_latex_lowercase_a.sub("a", x) x = re_latex_lowercase_ae.sub("ae", x) x = re_latex_lowercase_oe.sub("oe", x) x = re_latex_lowercase_e.sub("e", x) x = re_latex_lowercase_i.sub("i", x) x = re_latex_lowercase_o.sub("o", x) x = re_latex_lowercase_u.sub("u", x) x = re_latex_lowercase_y...
<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_diff(original, modified, prefix='', suffix='', prefix_unchanged=' ', suffix_unchanged='', prefix_removed='-', suffix_removed='', prefix_added='+', suffix...
import difflib differ = difflib.Differ() result = [prefix] for line in differ.compare(modified.splitlines(), original.splitlines()): if line[0] == ' ': # Mark as unchanged result.append( prefix_unchanged + line[2:].strip() + suffix_unchanged) eli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escape_latex(text): r"""Escape characters of given text. This function takes the given text and escapes characters that have a special meaning in LaTeX: # $ ...
text = unicode(text.decode('utf-8')) CHARS = { '&': r'\&', '%': r'\%', '$': r'\$', '#': r'\#', '_': r'\_', '{': r'\{', '}': r'\}', '~': r'\~{}', '^': r'\^{}', '\\': r'\textbackslash{}', } escaped = "".join([CHARS.get(char, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _copy_attr(self, module, varname, cls, attrname=None): """ Copies attribute from module object to self. Raises if object not of expected class Args: module: ...
if not hasattr(module, varname): raise RuntimeError("Variable '{}' not found".format(varname)) obj = getattr(module, varname) if not isinstance(obj, cls): raise RuntimeError( "Expecting fobj to be a {}, not a '{}'".format(cls.__name__, obj.__class__.__...
<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_to_permit(self, entry_type, entry_filename): """Applying the filter rules."""
rules = self.__filter_rules[entry_type] # Should explicitly include? for pattern in rules[fss.constants.FILTER_INCLUDE]: if fnmatch.fnmatch(entry_filename, pattern): _LOGGER_FILTER.debug("Entry explicitly INCLUDED: [%s] [%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 census(self, *scales): """Current World Census data. By default returns data on today's featured World Census scale, use arguments to get results on specific...
params = {'mode': 'score+rank+rrank+prank+prrank'} if scales: params['scale'] = '+'.join(str(x) for x in scales) @api_query('census', **params) async def result(_, root): return [ CensusScaleCurrent(scale_elem) for scale_elem in 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 censushistory(self, *scales): """Historical World Census data. Was split into its own method for the sake of simplicity. By default returns data on today's f...
params = {'mode': 'history'} if scales: params['scale'] = '+'.join(str(x) for x in scales) @api_query('census', **params) async def result(_, root): return [ CensusScaleHistory(scale_elem) for scale_elem in root.find('CENSUS') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def censusranks(self, scale): """Iterate through nations ranked on the World Census scale. If the ranks change while you interate over them, they may be in...
order = count(1) for offset in count(1, 20): census_ranks = await self._get_censusranks( scale=scale, start=offset) for census_rank in census_ranks: assert census_rank.rank == next(order) yield census_rank if len(census...
<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(astring): """Decompress and deserialize string into Python object via marshal."""
try: return marshal.loads(zlib.decompress(astring)) except zlib.error as e: raise SerializerError( 'Cannot decompress object ("{}")'.format(str(e)) ) except Exception as e: # marshal module does not provide a proper Exception model...
<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(astring): """Decompress and deserialize string into Python object via pickle."""
try: return pickle.loads(zlib.decompress(astring)) except zlib.error as e: raise SerializerError( 'Cannot decompress object ("{}")'.format(str(e)) ) except pickle.UnpicklingError as e: raise SerializerError( 'Cannot...