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 _preprocess(self, filehandle, metadata): "Runs all attached preprocessors on the provided filehandle." for process in self._preprocessors: filehandle = process(filehandle, metadata) return filehandle
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _postprocess(self, filehandle, metadata): "Runs all attached postprocessors on the provided filehandle." for process in self._postprocessors: filehandle = process(filehandle, metadata) return filehandle
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, filehandle, destination=None, metadata=None, validate=True, catch_all_errors=False, *args, **kwargs): """Saves the filehandle to the provided dest...
destination = destination or self._destination if destination is None: raise RuntimeError("Destination for filehandle must be provided.") elif destination is not self._destination: destination = _make_destination_callable(destination) if metadata is 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 choose_palette(stream=sys.stdout, basic_palette=None): ''' Make a best effort to automatically determine whether to enable ANSI sequences, and if so, which color palettes are available. This is the main function of the module—meant to be used unless something more specific is needed. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def detect_palette_support(basic_palette=None): ''' Returns whether we think the terminal supports basic, extended, or truecolor. None if not able to tell. Returns: None or str: 'basic', 'extended', 'truecolor' ''' result = col_init = win_enabled = None TERM = env.TERM or '...
<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_basic_palette(result): ''' Find the platform-dependent 16-color basic palette. This is used for "downgrading to the nearest color" support. ''' pal_name = 'default (xterm)' basic_palette = color_tables.xterm_palette4 if env.SSH_CLIENT: # fall back to xterm over ssh, info often wr...
<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_available_palettes(chosen_palette): ''' Given a chosen palette, returns tuple of those available, or None when not found. Because palette support of a particular level is almost always a superset of lower levels, this should return all available palettes. Returns: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def is_a_tty(stream=sys.stdout): ''' Detect terminal or something else, such as output redirection. Returns: Boolean, None: is tty or None if not found. ''' result = stream.isatty() if hasattr(stream, 'isatty') else None log.debug(result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_x11_color_map(paths=X11_RGB_PATHS): ''' Load and parse X11's rgb.txt. Loads: x11_color_map: { name_lower: ('R', 'G', 'B') } ''' if type(paths) is str: paths = (paths,) x11_color_map = color_tables.x11_color_map for path in paths: try: with o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse_vtrgb(path='/etc/vtrgb'): ''' Parse the color table for the Linux console. ''' palette = () table = [] try: with open(path) as infile: for i, line in enumerate(infile): row = tuple(int(val) for val in line.split(',')) table.append(row) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _read_until(infile=sys.stdin, maxchars=20, end=RS): ''' Read a terminal response of up to a few characters from stdin. ''' chars = [] read = infile.read if not isinstance(end, tuple): end = (end,) # count down, stopping at 0 while maxchars: char = read(1) if char in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_color(name, number=None): ''' Query the default terminal, for colors, etc. Direct queries supported on xterm, iTerm, perhaps others. Arguments: str: name, one of ('foreground', 'fg', 'background', 'bg', or 'index') # index grabs a palette ind...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_position(fallback=CURSOR_POS_FALLBACK): ''' Return the current column number of the terminal cursor. Used to figure out if we need to print an extra newline. Returns: tuple(int): (x, y), (,) - empty, if an error occurred. TODO: needs non-ansi mode for Windows 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 get_theme(): ''' Checks system for theme information. First checks for the environment variable COLORFGBG. Next, queries terminal, supported on Windows and xterm, perhaps others. See notes on get_color(). Returns: str, None: 'dark', 'light', None if no information. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def really_bad_du(path): "Don't actually use this, it's just an example." return sum([os.path.getsize(fp) for fp in list_files(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 check_disk_usage(filehandle, meta): """Checks the upload directory to see if the uploaded file would exceed the total disk allotment. Meant as a quick and di...
# limit it at twenty kilobytes if no default is provided MAX_DISK_USAGE = current_app.config.get('MAX_DISK_USAGE', 20 * 1024) CURRENT_USAGE = really_bad_du(current_app.config['UPLOAD_PATH']) filehandle.seek(0, os.SEEK_END) if CURRENT_USAGE + filehandle.tell() > MAX_DISK_USAGE: filehandle.c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_version(filename, version='1.00'): ''' Read version as text to avoid machinations at import time. ''' with open(filename) as infile: for line in infile: if line.startswith('__version__'): try: version = line.split("'")[1] except Ind...
<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_nearest_color_index(r, g, b, color_table=None, method='euclid'): ''' Given three integers representing R, G, and B, return the nearest color index. Arguments: r: int - of range 0…255 g: int - of range 0…255 b: int - of range 0…255 Retur...
<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_nearest_color_hexstr(hexdigits, color_table=None, method='euclid'): ''' Given a three or six-character hex digit string, return the nearest color index. Arguments: hexdigits: a three/6 digit hex string, e.g. 'b0b', '123456' Returns: int, None: index, or No...
<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_interval(self, start, end, data=None): ''' Inserts an interval to the tree. Note that when inserting we do not maintain appropriate sorting of the "mid" data structure. This should be done after all intervals are inserted. ''' # Ignore intervals of 0 or negative ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _query(self, x, result): ''' Same as self.query, but uses a provided list to accumulate results into. ''' if self.single_interval is None: # Empty return elif self.single_interval != 0: # Single interval, just check whether x is in it if self.single_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 dfa_complementation(dfa: dict) -> dict: """ Returns a DFA that accepts any word but he ones accepted by the input DFA. Let A be a completed DFA, :math:`Ā = (Σ...
dfa_complement = dfa_completion(deepcopy(dfa)) dfa_complement['accepting_states'] = \ dfa_complement['states'].difference(dfa_complement['accepting_states']) return dfa_complement
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict: """ Returns a DFA accepting the intersection of the DFAs in input. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1...
intersection = { 'alphabet': dfa_1['alphabet'].intersection(dfa_2['alphabet']), 'states': {(dfa_1['initial_state'], dfa_2['initial_state'])}, 'initial_state': (dfa_1['initial_state'], dfa_2['initial_state']), 'accepting_states': set(), 'transitions': dict() } bounda...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfa_union(dfa_1: dict, dfa_2: dict) -> dict: """ Returns a DFA accepting the union of the input DFAs. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :ma...
dfa_1 = deepcopy(dfa_1) dfa_2 = deepcopy(dfa_2) dfa_1['alphabet'] = dfa_2['alphabet'] = dfa_1['alphabet'].union( dfa_2['alphabet']) # to complete the DFAs over all possible transition dfa_1 = dfa_completion(dfa_1) dfa_2 = dfa_completion(dfa_2) union = { 'alphabet': dfa_1['alph...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfa_minimization(dfa: dict) -> dict: """ Returns the minimization of the DFA in input through a greatest fix-point method. Given a completed DFA :math:`A = (Σ...
dfa = dfa_completion(deepcopy(dfa)) ################################################################ ### Greatest-fixpoint z_current = set() z_next = set() # First bisimulation condition check (can be done just once) # s ∈ F iff t ∈ F for state_s in dfa['states']: for state_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfa_reachable(dfa: dict) -> dict: """ Side effects on input! Removes unreachable states from a DFA and returns the pruned DFA. It is possible to remove from a...
reachable_states = set() # set of reachable states from root boundary = set() reachable_states.add(dfa['initial_state']) boundary.add(dfa['initial_state']) while boundary: s = boundary.pop() for a in dfa['alphabet']: if (s, a) in dfa['transitions']: if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfa_co_reachable(dfa: dict) -> dict: """ Side effects on input! Removes from the DFA all states that do not reach a final state and returns the pruned DFA. It...
co_reachable_states = dfa['accepting_states'].copy() boundary = co_reachable_states.copy() # inverse transition function inverse_transitions = dict() for key, value in dfa['transitions'].items(): inverse_transitions.setdefault(value, set()).add(key) while boundary: s = bounda...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfa_trimming(dfa: dict) -> dict: """ Side effects on input! Returns the DFA in input trimmed, so both reachable and co-reachable. Given a DFA A, the correspon...
# Reachable DFA dfa = dfa_reachable(dfa) # Co-reachable DFA dfa = dfa_co_reachable(dfa) # trimmed DFA return dfa
<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_chains(f): ''' Loads all LiftOverChain objects from a file into an array. Returns the result. ''' chains = [] while True: line = f.readline() if not line: break if line.startswith(b'#') or line.startswith(b'\n') or lin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checksum(string): """ Compute the Luhn checksum for the provided string of digits. Note this assumes the check digit is in place. """
digits = list(map(int, string)) odd_sum = sum(digits[-1::-2]) even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]]) return (odd_sum + even_sum) % 10
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_blocked(self, ip): """Determine if an IP address should be considered blocked."""
blocked = True if ip in self.allowed_admin_ips: blocked = False for allowed_range in self.allowed_admin_ip_ranges: if ipaddress.ip_address(ip) in ipaddress.ip_network(allowed_range): blocked = False return blocked
<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(args): """Start a server which will watch .md and .rst files for changes. If a md file changes, the Home Documentation is rebuilt. If a .rst file chang...
# Sever's parameters port = args.serve_port or PORT host = "0.0.0.0" # Current working directory dir_path = Path().absolute() web_dir = dir_path / "site" # Update routes utils.set_routes() # Offline mode if args.offline: os.environ["MKINX_OFFLINE"] = "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 train(self, X_train, Y_train, X_test, Y_test): """Train and validate the LR on a train and test dataset Args: X_train (np.array): Training data Y_train (np....
while True: print(1) time.sleep(1) if random.randint(0, 9) >= 5: break
<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(url, path, kind='file', progressbar=True, replace=False, timeout=10., verbose=True): """Download a URL. This will download a file and store it in a ...
if kind not in ALLOWED_KINDS: raise ValueError('`kind` must be one of {}, got {}'.format( ALLOWED_KINDS, kind)) # Make sure we have directories to dump files path = op.expanduser(path) if len(path) == 0: raise ValueError('You must specify a path. For current directory use ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_url_to_downloadable(url): """Convert a url to the proper style depending on its website."""
if 'drive.google.com' in url: # For future support of google drive file_id = url.split('d/')[1].split('/')[0] base_url = 'https://drive.google.com/uc?export=download&id=' out = '{}{}'.format(base_url, file_id) elif 'dropbox.com' in url: if url.endswith('.png'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def md5sum(fname, block_size=1048576): # 2 ** 20 """Calculate the md5sum for a file. Parameters fname : str Filename. block_size : int Block size to use when rea...
md5 = hashlib.md5() with open(fname, 'rb') as fid: while True: data = fid.read(block_size) if not data: break md5.update(data) return md5.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 _chunk_write(chunk, local_file, progress): """Write a chunk to file and update the progress bar."""
local_file.write(chunk) if progress is not None: progress.update(len(chunk))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sizeof_fmt(num): """Turn number of bytes into human-readable str. Parameters num : int The number of bytes. Returns ------- size : str The size in human-read...
units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'] decimals = [0, 0, 1, 2, 2, 2] if num > 1: exponent = min(int(log(num, 1024)), len(units) - 1) quotient = float(num) / 1024 ** exponent unit = units[exponent] num_decimals = decimals[exponent] format_string = '{0:.%sf} {...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None, retry_log_level=logging.INFO, retry_log_message="Connection broken in '{f}' (error: '{e}'); " "retrying...
exc_classes = tuple(exc_classes) @wraps(f) def deco(*args, **kwargs): failures = 0 while True: try: return f(*args, **kwargs) except exc_classes as e: if logger is not None: logger.log(retry_log_level, ...
<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(self): """ Get a connection from the pool, to make and receive traffic. If the connection fails for any reason (socket.error), it is dropped and a new on...
self.lock.acquire() try: c = self.conn.popleft() yield c except self.exc_classes: # The current connection has failed, drop it and create a new one gevent.spawn_later(1, self._addOne) raise except: self.conn.append(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eff_default_transformer(fills=EFF_DEFAULT_FILLS): """ Return a simple transformer function for parsing EFF annotations. N.B., ignores all but the first effec...
def _transformer(vals): if len(vals) == 0: return fills else: # ignore all but first effect match_eff_main = _prog_eff_main.match(vals[0]) if match_eff_main is None: logging.warning( 'match_eff_main is None: vals={}...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ann_default_transformer(fills=ANN_DEFAULT_FILLS): """ Return a simple transformer function for parsing ANN annotations. N.B., ignores all but the first effec...
def _transformer(vals): if len(vals) == 0: return fills else: # ignore all but first effect ann = vals[0].split(b'|') ann = ann[:11] + _ann_split2(ann[11]) + _ann_split2(ann[12]) + \ _ann_split2(ann[13]) + ann[14:] 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 overloaded(func): """ Introduces a new overloaded function and registers its first implementation. """
fn = unwrap(func) ensure_function(fn) def dispatcher(*args, **kwargs): resolved = None if dispatcher.__complex_parameters: cache_key_pos = [] cache_key_kw = [] for argset in (0, 1) if kwargs else (0,): if argset == 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 register(dispatcher, func, *, hook=None): """ Registers `func` as an implementation on `dispatcher`. """
wrapper = None if isinstance(func, (classmethod, staticmethod)): wrapper = type(func) func = func.__func__ ensure_function(func) if isinstance(dispatcher, (classmethod, staticmethod)): wrapper = None dp = unwrap(dispatcher) try: dp.__functions except Attribut...
<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(dispatcher, args, kwargs): """ Given the arguments contained in `args` and `kwargs`, returns the best match from the list of implementations registered ...
matches = [] full_args = args full_kwargs = kwargs for func, sig in dispatcher.__functions: params = sig.parameters param_count = len(params) # Filter out arguments that will be consumed by catch-all parameters # or by keyword-only parameters. if sig.has_varargs:...
<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_signature(func): """ Gathers information about the call signature of `func`. """
code = func.__code__ # Names of regular parameters parameters = tuple(code.co_varnames[:code.co_argcount]) # Flags has_varargs = bool(code.co_flags & inspect.CO_VARARGS) has_varkw = bool(code.co_flags & inspect.CO_VARKEYWORDS) has_kwonly = bool(code.co_kwonlyargcount) # A mapping of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_type(type_, level=0): """ Reduces an arbitrarily complex type declaration into something manageable. """
if not typing or not isinstance(type_, typing.TypingMeta) or type_ is AnyType: return type_ if isinstance(type_, typing.TypeVar): if type_.__constraints__ or type_.__bound__: return type_ else: return AnyType if issubclass(type_, typing.Union): if not...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def type_complexity(type_): """Computes an indicator for the complexity of `type_`. If the return value is 0, the supplied type is not parameterizable. Otherwise...
if (not typing or not isinstance(type_, (typing.TypingMeta, GenericWrapperMeta)) or type_ is AnyType): return 0 if issubclass(type_, typing.Union): return reduce(operator.or_, map(type_complexity, type_.__union_params__)) if issubclass(type_, typing.Tuple): if type_.__tu...
<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_base_generic(type_): """Locates the underlying generic whose structure and behavior are known. For example, the base generic of a type that inherits fro...
for t in type_.__mro__: if t.__module__ == typing.__name__: return first_origin(t)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_generic_bases(type_): """Iterates over all generics `type_` derives from, including origins. This function is only necessary because, in typing 3.5.0, a...
for t in type_.__mro__: if not isinstance(t, typing.GenericMeta): continue yield t t = t.__origin__ while t: yield t t = t.__origin__
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sig_cmp(sig1, sig2): """ Compares two normalized type signatures for validation purposes. """
types1 = sig1.required types2 = sig2.required if len(types1) != len(types2): return False dup_pos = [] dup_kw = {} for t1, t2 in zip(types1, types2): match = type_cmp(t1, t2) if match: dup_pos.append(match) else: break else: re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_void(func): """ Determines if a function is a void function, i.e., one whose body contains nothing but a docstring or an ellipsis. A void function can be ...
try: source = dedent(inspect.getsource(func)) except (OSError, IOError): return False fdef = next(ast.iter_child_nodes(ast.parse(source))) return ( type(fdef) is ast.FunctionDef and len(fdef.body) == 1 and type(fdef.body[0]) is ast.Expr and type(fdef.body[0].value) in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def derive_configuration(cls): """ Collect the nearest type variables and effective parameters from the type, its bases, and their origins as necessary. """
base_params = cls.base.__parameters__ if hasattr(cls.type, '__args__'): # typing as of commit abefbe4 tvars = {p: p for p in base_params} types = {} for t in iter_generic_bases(cls.type): if t is cls.base: type_vars = t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nfa_intersection(nfa_1: dict, nfa_2: dict) -> dict: """ Returns a NFA that reads the intersection of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)...
intersection = { 'alphabet': nfa_1['alphabet'].intersection(nfa_2['alphabet']), 'states': set(), 'initial_states': set(), 'accepting_states': set(), 'transitions': dict() } for init_1 in nfa_1['initial_states']: for init_2 in nfa_2['initial_states']: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nfa_union(nfa_1: dict, nfa_2: dict) -> dict: """ Returns a NFA that reads the union of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A...
union = { 'alphabet': nfa_1['alphabet'].union(nfa_2['alphabet']), 'states': nfa_1['states'].union(nfa_2['states']), 'initial_states': nfa_1['initial_states'].union(nfa_2['initial_states']), 'accepting_states': nfa_1['accepting_states'].union(nfa_2['accepting_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nfa_determinization(nfa: dict) -> dict: """ Returns a DFA that reads the same language of the input NFA. Let A be an NFA, then there exists a DFA :math:`A_d` ...
def state_name(s): return str(set(sorted(s))) dfa = { 'alphabet': nfa['alphabet'].copy(), 'initial_state': None, 'states': set(), 'accepting_states': set(), 'transitions': dict() } if len(nfa['initial_states']) > 0: dfa['initial_state'] = state_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nfa_complementation(nfa: dict) -> dict: """ Returns a DFA reading the complemented language read by input NFA. Complement a nondeterministic automaton is poss...
determinized_nfa = nfa_determinization(nfa) return DFA.dfa_complementation(determinized_nfa)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nfa_word_acceptance(nfa: dict, word: list) -> bool: """ Checks if a given word is accepted by a NFA. The word w is accepted by a NFA if exists at least an acc...
current_level = set() current_level = current_level.union(nfa['initial_states']) next_level = set() for action in word: for state in current_level: if (state, action) in nfa['transitions']: next_level.update(nfa['transitions'][state, action]) if len(next_leve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overwrite_view_source(project, dir_path): """In the project's index.html built file, replace the top "source" link with a link to the documentation's home, w...
project_html_location = dir_path / project / HTML_LOCATION if not project_html_location.exists(): return files_to_overwrite = [ f for f in project_html_location.iterdir() if "html" in f.suffix ] for html_file in files_to_overwrite: with open(html_file, "r") as 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 get_listed_projects(): """Find the projects listed in the Home Documentation's index.md file Returns: set(str): projects' names, with the '/' in their begin...
index_path = Path().resolve() / "docs" / "index.md" with open(index_path, "r") as index_file: lines = index_file.readlines() listed_projects = set() project_section = False for _, l in enumerate(lines): idx = l.find(PROJECT_KEY) if idx >= 0: project_section = Tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_offline(): """Deletes references to the external google fonts in the Home Documentation's index.html file """
dir_path = Path(os.getcwd()).absolute() css_path = dir_path / "site" / "assets" / "stylesheets" material_css = css_path / "material-style.css" if not material_css.exists(): file_path = Path(__file__).resolve().parent copyfile(file_path / "material-style.css", material_css) copy...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filenames_from_arg(filename): """Utility function to deal with polymorphic filenames argument."""
if isinstance(filename, string_types): filenames = [filename] elif isinstance(filename, (list, tuple)): filenames = filename else: raise Exception('filename argument must be string, list or tuple') for fn in filenames: if not os.path.exists(fn): raise ValueEr...
<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_cache(vcf_fn, array_type, region, cachedir, compress, log): """Utility function to obtain a cache file name and determine whether or not a fresh cache f...
# guard condition if isinstance(vcf_fn, (list, tuple)): raise Exception( 'caching only supported when loading from a single VCF file' ) # create cache file name cache_fn = _mk_cache_fn(vcf_fn, array_type=array_type, region=region, cachedir=cache...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _variants_fields(fields, exclude_fields, info_ids): """Utility function to determine which fields to extract when loading variants."""
if fields is None: # no fields specified by user # by default extract all standard and INFO fields fields = config.STANDARD_VARIANT_FIELDS + info_ids else: # fields have been specified for f in fields: # check for non-standard fields not declared in INFO head...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _variants_fills(fields, fills, info_types): """Utility function to determine fill values for variants fields with missing values."""
if fills is None: # no fills specified by user fills = dict() for f, vcf_type in zip(fields, info_types): if f == 'FILTER': fills[f] = False elif f not in fills: if f in config.STANDARD_VARIANT_FIELDS: fills[f] = config.DEFAULT_VARIANT_FIL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _info_transformers(fields, transformers): """Utility function to determine transformer functions for variants fields."""
if transformers is None: # no transformers specified by user transformers = dict() for f in fields: if f not in transformers: transformers[f] = config.DEFAULT_TRANSFORMER.get(f, None) return tuple(transformers[f] for f in fields)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _variants_dtype(fields, dtypes, arities, filter_ids, flatten_filter, info_types): """Utility function to build a numpy dtype for a variants array, given user...
dtype = list() for f, n, vcf_type in zip(fields, arities, info_types): if f == 'FILTER' and flatten_filter: # split FILTER into multiple boolean fields for flt in filter_ids: nm = 'FILTER_' + flt dtype.append((nm, 'b1')) elif f == 'FILTER'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fromiter(it, dtype, count, progress, log): """Utility function to load an array from an iterator."""
if progress > 0: it = _iter_withprogress(it, progress, log) if count is not None: a = np.fromiter(it, dtype=dtype, count=count) else: a = np.fromiter(it, dtype=dtype) return 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 _iter_withprogress(iterable, progress, log): """Utility function to load an array from an iterator, reporting progress as we go."""
before_all = time.time() before = before_all n = 0 for i, o in enumerate(iterable): yield o n = i+1 if n % progress == 0: after = time.time() log('%s rows in %.2fs; batch in %.2fs (%d rows/s)' % (n, after-before_all, after-before, progress...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calldata(vcf_fn, region=None, samples=None, ploidy=2, fields=None, exclude_fields=None, dtypes=None, arities=None, fills=None, vcf_types=None, count=None, pro...
# flake8: noqa loader = _CalldataLoader(vcf_fn, region=region, samples=samples, ploidy=ploidy, fields=fields, exclude_fields=exclude_fields, dtypes=dtypes, arities=arities, fills=fills, vcf_types=vcf_types, ...
<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_datetimenow(self): """ get datetime now according to USE_TZ and default time """
value = timezone.datetime.utcnow() if settings.USE_TZ: value = timezone.localtime( timezone.make_aware(value, timezone.utc), timezone.get_default_timezone() ) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_default_timezone_datetime(self, value): """ convert to default timezone datetime """
return timezone.localtime(self.to_utc_datetime(value), timezone.get_default_timezone())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfa_json_importer(input_file: str) -> dict: """ Imports a DFA from a JSON file. :param str input_file: path + filename to json file; :return: *(dict)* represe...
file = open(input_file) json_file = json.load(file) transitions = {} # key [state ∈ states, action ∈ alphabet] # value [arriving state ∈ states] for (origin, action, destination) in json_file['transitions']: transitions[origin, action] = destination dfa = { ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfa_to_json(dfa: dict, name: str, path: str = './'): """ Exports a DFA to a JSON file. If *path* do not exists, it will be created. :param dict dfa: DFA to e...
out = { 'alphabet': list(dfa['alphabet']), 'states': list(dfa['states']), 'initial_state': dfa['initial_state'], 'accepting_states': list(dfa['accepting_states']), 'transitions': list() } for t in dfa['transitions']: out['transitions'].append( [t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dfa_dot_importer(input_file: str) -> dict: """ Imports a DFA from a DOT file. Of DOT files are recognized the following attributes: • nodeX shape=doublecircle...
# pyDot Object g = pydot.graph_from_dot_file(input_file)[0] states = set() initial_state = None accepting_states = set() replacements = {'"': '', "'": '', '(': '', ')': '', ' ': ''} for node in g.get_nodes(): if node.get_name() == 'fake' \ or node.get_name() == '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 nfa_json_importer(input_file: str) -> dict: """ Imports a NFA from a JSON file. :param str input_file: path+filename to JSON file; :return: *(dict)* represent...
file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alphabet] # value [Set of arriving states in states] for p in json_file['transitions']: transitions.setdefault((p[0], p[1]), set()).add(p[2]) nfa = { 'alph...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nfa_to_json(nfa: dict, name: str, path: str = './'): """ Exports a NFA to a JSON file. :param dict nfa: NFA to export; :param str name: name of the output fi...
transitions = list() # key[state in states, action in alphabet] # value [Set of arriving states in states] for p in nfa['transitions']: for dest in nfa['transitions'][p]: transitions.append([p[0], p[1], dest]) out = { 'alphabet': list(nfa['alphabet'])...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nfa_dot_importer(input_file: str) -> dict: """ Imports a NFA from a DOT file. Of .dot files are recognized the following attributes • nodeX shape=doublecircle...
# pyDot Object g = pydot.graph_from_dot_file(input_file)[0] states = set() initial_states = set() accepting_states = set() replacements = {'"': '', "'": '', '(': '', ')': '', ' ': ''} for node in g.get_nodes(): attributes = node.get_attributes() if node.get_name() == 'fa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def afw_json_importer(input_file: str) -> dict: """ Imports a AFW from a JSON file. :param str input_file: path+filename to input JSON file; :return: *(dict)* rep...
file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alphabet] # value [string representing boolean expression] for p in json_file['transitions']: transitions[p[0], p[1]] = p[2] # return map afw = { 'alphabet': set(json_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 __recursive_acceptance(afw, state, remaining_word): """ Recursive call for word acceptance. :param dict afw: input AFW; :param str state: current state; :par...
# the word is accepted only if all the final states are # accepting states if len(remaining_word) == 0: if state in afw['accepting_states']: return True else: return False action = remaining_word[0] if (state, action) not in afw['transitions']: retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def afw_completion(afw): """ Side effect on input! Complete the afw adding not present transitions and marking them as False. :param dict afw: input AFW. """
for state in afw['states']: for a in afw['alphabet']: if (state, a) not in afw['transitions']: afw['transitions'][state, a] = 'False' return afw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nfa_to_afw_conversion(nfa: dict) -> dict: """ Returns a AFW reading the same language of input NFA. Let :math:`A = (Σ,S,S^0, ρ,F)` be an nfa. Then we define t...
afw = { 'alphabet': nfa['alphabet'].copy(), 'states': nfa['states'].copy(), 'initial_state': 'root', 'accepting_states': nfa['accepting_states'].copy(), 'transitions': dict() } # Make sure "root" node doesn't already exists, in case rename it i = 0 while afw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def afw_to_nfa_conversion(afw: dict) -> dict: """ Returns a NFA reading the same language of input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )` be an afw. Then we def...
nfa = { 'alphabet': afw['alphabet'].copy(), 'initial_states': {(afw['initial_state'],)}, 'states': {(afw['initial_state'],)}, 'accepting_states': set(), 'transitions': dict() } # State of the NFA are composed by the union of more states of the AFW boundary = d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formula_dual(input_formula: str) -> str: """ Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :...
conversion_dictionary = { 'and': 'or', 'or': 'and', 'True': 'False', 'False': 'True' } return re.sub( '|'.join(re.escape(key) for key in conversion_dictionary.keys()), lambda k: conversion_dictionary[k.group(0)], input_formula)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def afw_complementation(afw: dict) -> dict: """ Returns a AFW reading the complemented language read by input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )`. Define :ma...
completed_input = afw_completion(deepcopy(afw)) complemented_afw = { 'alphabet': completed_input['alphabet'], 'states': completed_input['states'], 'initial_state': completed_input['initial_state'], 'accepting_states': completed_input['states'].difference(afw['accept...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def afw_union(afw_1: dict, afw_2: dict) -> dict: """ Returns a AFW that reads the union of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1...
# make sure new root state is unique initial_state = 'root' i = 0 while initial_state in afw_1['states'] or initial_state in afw_2['states']: initial_state = 'root' + str(i) i += 1 union = { 'alphabet': afw_1['alphabet'].union(afw_2['alphabet']), 'states': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def afw_intersection(afw_1: dict, afw_2: dict) -> dict: """ Returns a AFW that reads the intersection of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_...
# make sure new root state is unique initial_state = 'root' i = 0 while initial_state in afw_1['states'] or initial_state in afw_2['states']: initial_state = 'root' + str(i) i += 1 intersection = { 'alphabet': afw_1['alphabet'].union(afw_2['alphabet']), 'states': ...
<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_dbus_type(typeof, value): """ Helper function to map values from their native Python types to Dbus types. :param type typeof: Target for type co...
if ((isinstance(value, types.UnicodeType) or isinstance(value, str)) and typeof is not dbus.String): # FIXME: This is potentially dangerous since it evaluates # a string in-situ return typeof(eval(value)) else: return typeof(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def signal_handler(self, *args): """ Method to call in order to invoke the user callback. :param args: list of signal-dependent arguments :return: """
self.user_callback(self.signal, self.user_arg, *args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_property(self, name=None): """ Helper to get a property value by name or all properties as a dictionary. See also :py:meth:`set_property` :param str name...
if (name): return self._interface.GetProperties()[name] else: return self._interface.GetProperties()
<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_property(self, name, value): """ Helper to set a property value by name, translating to correct dbus type See also :py:meth:`get_property` :param str nam...
typeof = type(self.get_property(name)) self._interface.SetProperty(name, translate_to_dbus_type(typeof, value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default(self, o): """ Encode JSON. :return str: A JSON encoded string """
if isinstance(o, (datetime.datetime, datetime.date, datetime.time)): return o.isoformat() if isinstance(o, decimal.Decimal): return float(o) return json.JSONEncoder.default(self, o)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_document(cls, instance, fields_own=None, fields_to_many=None): """ Get document for model_instance. redefine dump rule for field x: def dump_document_x ...
if fields_own is not None: fields_own = {f.name for f in fields_own} else: fields_own = { f.name for f in instance._meta.fields if f.rel is None and f.serialize } fields_own.add('id') fields_own = (fields_own | set(cls...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cached(f): """ Decorator that makes a method cached."""
attr_name = '_cached_' + f.__name__ def wrapper(obj, *args, **kwargs): if not hasattr(obj, attr_name): setattr(obj, attr_name, f(obj, *args, **kwargs)) return getattr(obj, attr_name) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _filter_child_model_fields(cls, fields): """ Keep only related model fields. Example: Inherited models: A -> B -> C B has one-to-many relationship to BMany. ...
indexes_to_remove = set([]) for index1, field1 in enumerate(fields): for index2, field2 in enumerate(fields): if index1 < index2 and index1 not in indexes_to_remove and\ index2 not in indexes_to_remove: if issubclass(field1.related...
<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_session(): """ This endpoint appears to be required in order to keep pubnub updates flowing for some user. This just posts a random nonce to the /users/...
url_string = "{}/users/me/session".format(WinkApiInterface.BASE_URL) nonce = ''.join([str(random.randint(0, 9)) for i in range(9)]) _json = {"nonce": str(nonce)} try: arequest = requests.post(url_string, data=json.dumps(_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_device_state(self, device, state, id_override=None, type_override=None): """ Set device state via online API. Args: device (WinkDevice): The device the ...
_LOGGER.info("Setting state via online API") object_id = id_override or device.object_id() object_type = type_override or device.object_type() url_string = "{}/{}s/{}".format(self.BASE_URL, object_type, obje...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def local_set_state(self, device, state, id_override=None, type_override=None): """ Set device state via local API, and fall back to online API. Args: device (Wi...
if ALLOW_LOCAL_CONTROL: if device.local_id() is not None: hub = HUBS.get(device.hub_id()) if hub is None or hub["token"] is None: return self.set_device_state(device, state, id_override, type_override) else: 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 get_device_state(self, device, id_override=None, type_override=None): """ Get device state via online API. Args: device (WinkDevice): The device the change ...
_LOGGER.info("Getting state via online API") object_id = id_override or device.object_id() object_type = type_override or device.object_type() url_string = "{}/{}s/{}".format(self.BASE_URL, object_type, object_id) arequest = requests.get(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 local_get_state(self, device, id_override=None, type_override=None): """ Get device state via local API, and fall back to online API. Args: device (WinkDevic...
if ALLOW_LOCAL_CONTROL: if device.local_id() is not None: hub = HUBS.get(device.hub_id()) if hub is not None and hub["token"] is not None: ip = hub["ip"] access_token = hub["token"] else: ret...