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 __visit_index_model_instance(self, models, p, k, v): """ Called during model research on merged data """
# print 'model visit {} on {}'.format(model, v) cp = p + (k,) for model in models: try: if model.validator(v): if cp in self.path_index: # if self.path_index[cp].val != v: # raise ValueError(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_edge_reduction(self) -> float: """Compute the edge reduction. Costly computation"""
nb_init_edge = self.init_edge_number() nb_poweredge = self.edge_number() return (nb_init_edge - nb_poweredge) / (nb_init_edge)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_edge_number(self) -> int: """Return the number of edges present in the non-compressed graph"""
return len(frozenset(frozenset(edge) for edge in self.initial_edges()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_powernode(self, name:str) -> None or ValueError: """Do nothing if given name refers to a powernode in given graph. Raise a ValueError in any other case...
if name not in self.inclusions: raise ValueError("Powernode '{}' does not exists.".format(name)) if self.is_node(name): raise ValueError("Given name '{}' is a node.".format(name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def powernode_data(self, name:str) -> Powernode: """Return a Powernode object describing the given powernode"""
self.assert_powernode(name) contained_nodes = frozenset(self.nodes_in(name)) return Powernode( size=len(contained_nodes), contained=frozenset(self.all_in(name)), contained_pnodes=frozenset(self.powernodes_in(name)), contained_nodes=contained_nodes...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def node_number(self, *, count_pnode=True) -> int: """Return the number of node"""
return (sum(1 for n in self.nodes()) + (sum(1 for n in self.powernodes()) if count_pnode else 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 write_bubble(self, filename:str): """Write in given filename the lines of bubble describing this instance"""
from bubbletools import converter converter.tree_to_bubble(self, filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_bubble_file(bblfile:str, oriented:bool=False, symmetric_edges:bool=True) -> 'BubbleTree': """Extract data from given bubble file, then call from_bubble_d...
return BubbleTree.from_bubble_data(utils.data_from_bubble(bblfile), oriented=bool(oriented), symmetric_edges=symmetric_edges)
<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_from_tree(root:str, graph:dict) -> frozenset: """Return a recursive structure describing given tree"""
Node = namedtuple('Node', 'id succs') succs = graph[root] if succs: return (len(succs), sorted(tuple(set_from_tree(succ, graph) for succ in succs))) else: return 0, ()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_suitable_vis_classes(obj): """Retuns a list of Vis classes that can handle obj."""
ret = [] for class_ in classes_vis(): if isinstance(obj, class_.input_classes): ret.append(class_) 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 get_suitable_vis_list_classes(objs): """Retuns a list of VisList classes that can handle a list of objects."""
from f311 import explorer as ex ret = [] for class_ in classes_vis(): if isinstance(class_, ex.VisList): flag_can = True for obj in objs: if not isinstance(obj, class_.item_input_classes): flag_can = False 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 _get_programs_dict(): """ Builds and returns programs dictionary This will have to import the packages in COLLABORATORS_S in order to get their absolute path...
global __programs_dict if __programs_dict is not None: return __programs_dict d = __programs_dict = OrderedDict() for pkgname in COLLABORATORS_S: try: package = importlib.import_module(pkgname) except ImportError: # I think it is better to be silent wh...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_url(*args, **kwargs) -> str: """ Return a valid url. """
resource_url = API_RESOURCES_URLS for key in args: resource_url = resource_url[key] if kwargs: resource_url = resource_url.format(**kwargs) return urljoin(URL, resource_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 _get(url:str, headers:dict) -> dict: """ Make a GET call. """
response = requests.get(url, headers=headers) data = response.json() if response.status_code != 200: raise GoogleApiError({"status_code": response.status_code, "error": data.get("error", "")}) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post(url:str, params:dict, headers:dict) -> dict: """ Make a POST call. """
response = requests.post(url, params=params, headers=headers) data = response.json() if response.status_code != 200 or "error" in data: raise GoogleApiError({"status_code": response.status_code, "error": data.get("error", "")}) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dims_knight(self, move): '''Knight on the rim is dim''' if self.board.piece_type_at(move.from_square) == chess.KNIGHT: rim = SquareSet( chess.BB_RANK_1 | \ chess.BB_RANK_8 | \ chess.BB_FILE_A | \ chess.BB_FILE_H) return move.to_square in rim
<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_comment_collection(cmt_id): """ Extract the collection where the comment is written """
query = """SELECT id_bibrec FROM "cmtRECORDCOMMENT" WHERE id=%s""" recid = run_sql(query, (cmt_id,)) record_primary_collection = guess_primary_collection_of_a_record( recid[0][0]) return record_primary_collection
<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_collection_moderators(collection): """ Return the list of comment moderators for the given collection. """
from invenio_access.engine import acc_get_authorized_emails res = list( acc_get_authorized_emails( 'moderatecomments', collection=collection)) if not res: return [CFG_WEBCOMMENT_DEFAULT_MODERATOR, ] return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_reply_order_cache_data(comid): """ Prepare a representation of the comment ID given as parameter so that it is suitable for byte ordering in MySQL. """
return "%s%s%s%s" % (chr((comid >> 24) % 256), chr((comid >> 16) % 256), chr((comid >> 8) % 256), chr(comid % 256))
<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_attached_files_to_storage(attached_files, recID, comid): """ Move the files that were just attached to a new comment to their final location. :param att...
for filename, filepath in iteritems(attached_files): dest_dir = os.path.join(CFG_COMMENTSDIR, str(recID), str(comid)) try: os.makedirs(dest_dir) except: # Dir most probably already existed pass shutil.move(filepath, os.path.joi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subscribe_user_to_discussion(recID, uid): """ Subscribe a user to a discussion, so the she receives by emails all new new comments for this record. :param re...
query = """INSERT INTO "cmtSUBSCRIPTION" (id_bibrec, id_user, creation_time) VALUES (%s, %s, %s)""" params = (recID, uid, convert_datestruct_to_datetext(time.localtime())) try: run_sql(query, params) except: return 0 return 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 unsubscribe_user_from_discussion(recID, uid): """ Unsubscribe users from a discussion. :param recID: record ID corresponding to the discussion we want to uns...
query = """DELETE FROM "cmtSUBSCRIPTION" WHERE id_bibrec=%s AND id_user=%s""" params = (recID, uid) try: res = run_sql(query, params) except: return 0 if res > 0: return 1 return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_users_subscribed_to_discussion(recID, check_authorizations=True): """ Returns the lists of users subscribed to a given discussion. Two lists are returned...
subscribers_emails = {} # Get users that have subscribed to this discussion query = """SELECT id_user FROM "cmtSUBSCRIPTION" WHERE id_bibrec=%s""" params = (recID,) res = run_sql(query, params) for row in res: uid = row[0] if check_authorizations: user_info = UserIn...
<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_record_status(recid): """ Returns the current status of the record, i.e. current restriction to apply for newly submitted comments, and current commentin...
collections_with_rounds = CFG_WEBCOMMENT_ROUND_DATAFIELD.keys() commenting_round = "" for collection in collections_with_rounds: # Find the first collection defines rounds field for this # record if recid in get_collection_reclist(collection): commenting_rounds = get_fie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def group_comments_by_round(comments, ranking=0): """ Group comments by the round to which they belong """
comment_rounds = {} ordered_comment_round_names = [] for comment in comments: comment_round_name = ranking and comment[11] or comment[7] if comment_round_name not in comment_rounds: comment_rounds[comment_round_name] = [] ordered_comment_round_names.append(comment_ro...
<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_mini_reviews(recid, ln=CFG_SITE_LANG): """ Returns the web controls to add reviews to a record from the detailed record pages mini-panel. :param recid: t...
if CFG_WEBCOMMENT_ALLOW_SHORT_REVIEWS: action = 'SUBMIT' else: action = 'DISPLAY' reviews = query_retrieve_comments_or_remarks(recid, ranking=1) return webcomment_templates.tmpl_mini_review( recid, ln, action=action, avg_score=calculate_avg_score(review...
<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_user_can_view_comments(user_info, recid): """Check if the user is authorized to view comments for given recid. Returns the same type as acc_authorize_a...
# Check user can view the record itself first (auth_code, auth_msg) = check_user_can_view_record(user_info, recid) if auth_code: return (auth_code, auth_msg) # Check if user can view the comments # But first can we find an authorization for this case action, # for this collection? ...
<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_user_can_view_comment(user_info, comid, restriction=None): """Check if the user is authorized to view a particular comment, given the comment restricti...
if restriction is None: comment = query_get_comment(comid) if comment: restriction = comment[11] else: return (1, 'Comment %i does not exist' % comid) if restriction == "": return (0, '') return acc_authorize_action( user_info, 'viewrestrcomme...
<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_user_can_send_comments(user_info, recid): """Check if the user is authorized to comment the given recid. This function does not check that user can vie...
# First can we find an authorization for this case, action + collection record_primary_collection = guess_primary_collection_of_a_record(recid) return acc_authorize_action( user_info, 'sendcomment', authorized_if_no_roles=True, collection=record_primary_collection)
<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_user_can_attach_file_to_comments(user_info, recid): """Check if the user is authorized to attach a file to comments for given recid. This function does...
# First can we find an authorization for this case action, for # this collection? record_primary_collection = guess_primary_collection_of_a_record(recid) return acc_authorize_action( user_info, 'attachcommentfile', authorized_if_no_roles=False, collection=record_primary_...
<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_user_collapsed_comments_for_record(uid, recid): """ Get the comments collapsed for given user on given recid page """
# Collapsed state is not an attribute of cmtRECORDCOMMENT table # (vary per user) so it cannot be found when querying for the # comment. We must therefore provide a efficient way to retrieve # the collapsed state for a given discussion page and user. query = """SELECT "id_cmtRECORDCOMMENT" from "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 is_comment_deleted(comid): """ Return True of the comment is deleted. Else False :param comid: ID of comment to check """
query = """SELECT status from "cmtRECORDCOMMENT" WHERE id=%s""" params = (comid,) res = run_sql(query, params) if res and res[0][0] != 'ok': return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fix_time(self, dt): """Stackdistiller converts all times to utc. We store timestamps as utc datetime. However, the explicit UTC timezone on incoming datetim...
if dt.tzinfo is not None: dt = dt.replace(tzinfo=None) return dt
<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_leading_comments(text): """Strips the leading whitespaces and % from the given text. Adapted from textwrap.dedent """
# Look for the longest leading string of spaces and tabs common to # all lines. margin = None text = _whitespace_only_re.sub('', text) indents = _leading_whitespace_re.findall(text) for indent in indents: if margin is None: margin = indent # Current line more deeply...
<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(target, trace=False, **kwargs): """Parse the given target. If it is a file-like object, then parse its contents. If given a string, perform one of the ...
# Beware! This function, that actually is the core of all the # business, is written to minimize the responsibilities of each # chunk of code, keeping things simple. Performance may degrade # because of this, but without actual measurements the simplest # choice is the best one. if hasattr(ta...
<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(name, app=None, components=None, raw=False): """ Discover any named attributes, modules, or packages and coalesces the results. Looks in any module or p...
if components is None: if app is None: from flask import current_app as app components = app.config.get('COMPONENTS', []) items = [] for key in components: # Attempt to import the component and access the specified name # as an attribute. module = impo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auto_clear_shopping_cart(self, auto_clear_shopping_cart): """Sets the auto_clear_shopping_cart of this CartSettings. :param auto_clear_shopping_cart: The aut...
allowed_values = ["never", "orderCreated", "orderCompleted"] # noqa: E501 if auto_clear_shopping_cart is not None and auto_clear_shopping_cart not in allowed_values: raise ValueError( "Invalid value for `auto_clear_shopping_cart` ({0}), must be one of {1}" # noqa: E501 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getView(self, lv): """Determine the detector view starting with a G4LogicalVolume"""
view = None if str(lv.GetName())[-1] == 'X': return 'X' elif str(lv.GetName())[-1] == 'Y': return 'Y' self.log.error('Cannot determine view for %s', lv.GetName()) raise 'Cannot determine view for %s' % lv.GetName() return view
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def RenderWidget(self): """Returns a QWidget subclass instance. Exact class depends on self.type"""
t = self.type if t == int: ret = QSpinBox() ret.setMaximum(999999999) ret.setValue(self.value) elif t == float: ret = QLineEdit() ret.setText(str(self.value)) elif t == bool: ret = QCheckBox() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ScreenGenerator(nfft, r0, nx, ny): """Generate an infinite series of rectangular phase screens Uses an FFT screen generator to make a large screen and then r...
while 1: layers = GenerateTwoScreens(nfft, r0) for iLayer in range(2): for iy in range(int(nfft/ny)): for ix in range(int(nfft/nx)): yield layers[iLayer][iy*ny:iy*ny+ny, ix*nx:ix*nx+nx]
<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_dates(d, default='today'): """ Parses one or more dates from d """
if default == 'today': default = datetime.datetime.today() if d is None: return default elif isinstance(d, _parsed_date_types): return d elif is_number(d): # Treat as milliseconds since 1970 d = d if isinstance(d, float) else float(d) return datetime....
<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_with_classes(filename, classes): """Attempts to load file by trial-and-error using a given list of classes. Arguments: filename -- full path to file cla...
ok = False for class_ in classes: obj = class_() try: obj.load(filename) ok = True # # cannot let IOError through because pyfits raises IOError!! # except IOError: # raise # # also cannot let OSError through because astropy.io.fits ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_any_file(filename): """ Attempts to load filename by trial-and-error Returns: file: A DataFile descendant, whose specific class depends on the file form...
import f311 # Splits attempts using ((binary X text) file) criterion if a99.is_text_file(filename): return load_with_classes(filename, f311.classes_txt()) else: return load_with_classes(filename, f311.classes_bin())
<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_spectrum(filename): """ Attempts to load spectrum as one of the supported types. Returns: a Spectrum, or None """
import f311 f = load_with_classes(filename, f311.classes_sp()) if f: return f.spectrum return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_spectrum_fits_messed_x(filename, sp_ref=None): """Loads FITS file spectrum that does not have the proper headers. Returns a Spectrum"""
import f311.filetypes as ft # First tries to load as usual f = load_with_classes(filename, (ft.FileSpectrumFits,)) if f is not None: ret = f.spectrum else: hdul = fits.open(filename) hdu = hdul[0] if not hdu.header.get("CDELT1"): hdu.header["CDELT1"] =...
<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_filetypes_info(editor_quote="`", flag_leaf=True): """ Reports available data types Args: editor_quote: character to enclose the name of the editor script...
NONE_REPL = "" import f311 data = [] # [FileTypeInfo, ...] for attr in f311.classes_file(flag_leaf): description = a99.get_obj_doc0(attr) def_ = NONE_REPL if attr.default_filename is None else attr.default_filename ee = attr.editors if ee is None: ee = NON...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tabulate_filetypes_rest(attrnames=None, header=None, flag_wrap_description=True, description_width=40, flag_leaf=True): """ Generates a reST multirow table A...
infos = get_filetypes_info(editor_quote="``", flag_leaf=flag_leaf) rows, header = filetypes_info_to_rows_header(infos, attrnames, header, flag_wrap_description, description_width) ret = a99.rest_table(rows, header) 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 return_action(self, return_action): """Sets the return_action of this ReturnSettings. :param return_action: The return_action of this ReturnSettings. :type: ...
allowed_values = ["refund", "storeCredit"] # noqa: E501 if return_action is not None and return_action not in allowed_values: raise ValueError( "Invalid value for `return_action` ({0}), must be one of {1}" # noqa: E501 .format(return_action, 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 show_config(config): """Show the current configuration."""
print("\nCurrent Configuration:\n") for k, v in sorted(config.config.items()): print("{0:15}: {1}".format(k, v))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_cloud_user(cfg, args): """Attempt to create the user on the cloud node."""
url = cfg['api_server'] + "admin/add-user" params = {'user_email': args.user_email, 'user_name': args.user_name, 'user_role': args.user_role, 'email': cfg['email'], 'api_key': cfg['api_key']} headers = {'Content-Type': 'application/json'} response = requests.post(url, data=j...
<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_store(name, min_length=4, **kwargs): """\ Creates a store with a reasonable keygen. .. deprecated:: 2.0.0 Instantiate stores directly e.g. ``shorten.Mem...
if name not in stores: raise ValueError('valid stores are {0}'.format(', '.join(stores))) if name == 'memcache': store = MemcacheStore elif name == 'memory': store = MemoryStore elif name == 'redis': store = RedisStore return store(min_length=min_length, **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 do_copy(self, line): ''' Copy packages between repos copy SOURCE DESTINATION Where SOURCE can be either LOCAL-FILE or REPO:PACKAGE-SPEC DESTINATION can be either a REPO: or a directory. ''' words = line.split() source, destination = words 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 do_work_on(self, repo): ''' Make repo the active one. Commands working on a repo will use it as default for repo parameter. ''' self.abort_on_nonexisting_repo(repo, 'work_on') self.network.active_repo = repo
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_status(self, line): ''' Show python packaging configuration status ''' # Pyrene version print('{} {}'.format(bold('Pyrene version'), green(get_version()))) # .pip/pip.conf - Pyrene repo name | exists or not pip_conf = os.path.expanduser('~/.pip/pip.conf') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_forget(self, repo): ''' Drop definition of a repo. forget REPO ''' self.abort_on_nonexisting_repo(repo, 'forget') self.network.forget(repo)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_set(self, line): ''' Set repository attributes on the active repo. set attribute=value # intended use: # directory repos: work_on developer-repo set type=directory set directory=package-directory # http repos: work_on company-pri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_list(self, line): ''' List known repos ''' repo_names = self.network.repo_names print('Known repos:') print(' ' + '\n '.join(repo_names))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_show(self, repo): ''' List repo attributes ''' self.abort_on_nonexisting_effective_repo(repo, 'show') repo = self.network.get_repo(repo) repo.print_attributes()
<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(filename, num_questions=None, solution=False, pages_per_q=DEFAULT_PAGES_PER_Q, folder='question_pdfs', output='gradescope.pdf', zoom=1): """ Public m...
check_for_wkhtmltohtml() save_notebook(filename) nb = read_nb(filename, solution=solution) pdf_names = create_question_pdfs(nb, pages_per_q=pages_per_q, folder=folder, zoom=zoom) merge_pd...
<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_for_wkhtmltohtml(): """ Checks to see if the wkhtmltohtml binary is installed. Raises error if not. """
locator = 'where' if sys.platform == 'win32' else 'which' wkhtmltopdf = (subprocess.Popen([locator, 'wkhtmltopdf'], stdout=subprocess.PIPE) .communicate()[0].strip()) if not os.path.exists(wkhtmltopdf): logging.error( 'No wkhtmlto...
<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_nb(filename, solution) -> nbformat.NotebookNode: """ Takes in a filename of a notebook and returns a notebook object containing only the cell outputs to ...
with open(filename, 'r') as f: nb = nbformat.read(f, as_version=4) email = find_student_email(nb) preamble = nbformat.v4.new_markdown_cell( source='# ' + email, metadata={'tags': ['q_email']}) tags_to_check = TAGS if not solution else SOL_TAGS cells = ([preamble] + [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 nb_to_html_cells(nb) -> list: """ Converts notebook to an iterable of BS4 HTML nodes. Images are inline. """
html_exporter = HTMLExporter() html_exporter.template_file = 'basic' (body, resources) = html_exporter.from_notebook_node(nb) return BeautifulSoup(body, 'html.parser').findAll('div', class_='cell')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nb_to_q_nums(nb) -> list: """ Gets question numbers from each cell in the notebook """
def q_num(cell): assert cell.metadata.tags return first(filter(lambda t: 'q' in t, cell.metadata.tags)) return [q_num(cell) for cell in nb['cells']]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad_pdf_pages(pdf_name, pages_per_q) -> None: """ Checks if PDF has the correct number of pages. If it has too many, warns the user. If it has too few, adds b...
pdf = PyPDF2.PdfFileReader(pdf_name) output = PyPDF2.PdfFileWriter() num_pages = pdf.getNumPages() if num_pages > pages_per_q: logging.warning('{} has {} pages. Only the first ' '{} pages will get output.' .format(pdf_name, num_pages, pages_per_q)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_question_pdfs(nb, pages_per_q, folder, zoom) -> list: """ Converts each cells in tbe notebook to a PDF named something like 'q04c.pdf'. Places PDFs in ...
html_cells = nb_to_html_cells(nb) q_nums = nb_to_q_nums(nb) os.makedirs(folder, exist_ok=True) pdf_options = PDF_OPTS.copy() pdf_options['zoom'] = ZOOM_FACTOR * zoom pdf_names = [] for question, cell in zip(q_nums, html_cells): # Create question PDFs pdf_name = os.path.jo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_pdfs(pdf_names, output) -> None: """ Merges all pdfs together into a single long PDF. """
merger = PyPDF2.PdfFileMerger() for filename in pdf_names: merger.append(filename) merger.write(output) merger.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connection_count(self): """Number of currently open connections to the database. (Stored in table sqlarray_master.) """
return self.sql("SELECT value FROM %(master)s WHERE name = 'connection_counter'" % vars(self), cache=False, asrecarray=False)[0][0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sql_select(self,fields,*args,**kwargs): """Execute a simple SQL ``SELECT`` statement and returns values as new numpy rec array. The arguments *fields* and th...
SQL = "SELECT "+str(fields)+" FROM __self__ "+ " ".join(args) return self.sql(SQL,**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 sql(self,SQL,parameters=None,asrecarray=True,cache=True): """Execute sql statement. :Arguments: SQL : string Full SQL command; can contain the ``?`` place ho...
SQL = SQL.replace('__self__',self.name) # Cache the last N (query,result) tuples using a 'FIFO-dict' # of length N, where key = SQL; if we can use the cache # (cache=True) and if query in dict (AND cache # valid, ie it hasn't been emptied (??)) just return cache 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 limits(self,variable): """Return minimum and maximum of variable across all rows of data."""
(vmin,vmax), = self.SELECT('min(%(variable)s), max(%(variable)s)' % vars()) return vmin,vmax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selection(self, SQL, parameters=None, **kwargs): """Return a new SQLarray from a SELECT selection. This method is useful to build complicated selections and ...
# TODO: under development # - could use VIEW force = kwargs.pop('force', False) # pretty unsafe... I hope the user knows what they are doing # - only read data to first semicolon # - here should be input scrubbing... safe_sql = re.match(r'(?P<SQL>[^;]*)',SQL).g...
<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_sqlite_functions(self): """additional SQL functions to the database"""
self.connection.create_function("sqrt", 1,sqlfunctions._sqrt) self.connection.create_function("sqr", 1,sqlfunctions._sqr) self.connection.create_function("periodic", 1,sqlfunctions._periodic) self.connection.create_function("pow", 2,sqlfunctions._pow) self.connection.create_fun...
<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(self): """Primitive way to keep dict in sync with RB."""
delkeys = [k for k in self.keys() if k not in self.__ringbuffer] for k in delkeys: # necessary because dict is changed during iterations super(KRingbuffer,self).__delitem__(k)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def chunk_on(pipeline, new_chunk_signal, output_type=tuple): ''' split the stream into seperate chunks based on a new chunk signal ''' assert iterable(pipeline), 'chunks needs pipeline to be iterable' assert callable(new_chunk_signal), 'chunks needs new_chunk_signal to be callable' assert callable(outpu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def center_image(self, img): """Sets an image's anchor point to its center"""
img.anchor_x = img.width // 2 # int img.anchor_y = img.height // 2
<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_persons(self): """ Returns list of strings which represents persons being chated with """
cs = self.data["to"]["data"] res = [] for c in cs: res.append(c["name"]) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_messages(self): """ Returns list of Message objects which represents messages being transported. """
cs = self.data["comments"]["data"] res = [] for c in cs: res.append(Message(c,self)) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """ Returns next paging """
c = Conversation(self.data, requests.get(self.data["comments"]["paging"]["next"]).json()) if "error" in c.data["comments"] and c.data["comments"]["error"]["code"] == 613: raise LimitExceededException() return 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 _subset_table(full_table, subset): """ Return subtable matching all conditions in subset Parameters full_table : dataframe Entire data table subset : str Str...
if not subset: return full_table # TODO: Figure out syntax for logical or conditions = subset.replace(' ','').split(';') valid = np.ones(len(full_table), dtype=bool) for condition in conditions: col = re.split("[<>=!]", condition)[0] comp = condition.replace(col, "") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _subset_meta(full_meta, subset, incremented=False): """ Return metadata reflecting all conditions in subset Parameters full_meta : ConfigParser obj Metadata ...
if not subset: return full_meta, False meta = {} # Make deepcopy of entire meta (all section dicts in meta dict) for key, val in full_meta.iteritems(): meta[key] = copy.deepcopy(dict(val)) conditions = subset.replace(' ','').split(';') inc = False for condition in conditions...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sad(patch, cols, splits, clean=True): """ Calculates an empirical species abundance distribution Parameters {0} clean : bool If True, all species with zero a...
(spp_col, count_col), patch = \ _get_cols(['spp_col', 'count_col'], cols, patch) full_spp_list = np.unique(patch.table[spp_col]) # Loop through each split result_list = [] for substring, subpatch in _yield_subpatches(patch, splits): # Get abundance for each species sad_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ssad(patch, cols, splits): """ Calculates an empirical intra-specific spatial abundance distribution Parameters {0} Returns ------- {1} Result has one column...
# Get and check SAD sad_results = sad(patch, cols, splits, clean=False) # Create dataframe with col for spp name and numbered col for each split for i, sad_result in enumerate(sad_results): if i == 0: # For first result, create dataframe fulldf = sad_result[1] fulldf....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sar(patch, cols, splits, divs, ear=False): """ Calculates an empirical species area or endemics area relationship Parameters {0} divs : str Description of ho...
def sar_y_func(spatial_table, all_spp): return np.mean(spatial_table['n_spp']) def ear_y_func(spatial_table, all_spp): endemic_counter = 0 for spp in all_spp: spp_in_cell = [spp in x for x in spatial_table['spp_set']] spp_n_cells = np.sum(spp_in_cell) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sar_ear_inner(patch, cols, splits, divs, y_func): """ y_func is function calculating the mean number of species or endemics, respectively, for the SAR or EA...
(spp_col, count_col, x_col, y_col), patch = \ _get_cols(['spp_col', 'count_col', 'x_col', 'y_col'], cols, patch) # Loop through each split result_list = [] for substring, subpatch in _yield_subpatches(patch, splits): # Get A0 A0 = _patch_area(subpatch, x_col, y_col) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comm_grid(patch, cols, splits, divs, metric='Sorensen'): """ Calculates commonality as a function of distance for a gridded patch Parameters {0} divs : str D...
(spp_col, count_col, x_col, y_col), patch = \ _get_cols(['spp_col', 'count_col', 'x_col', 'y_col'], cols, patch) # Loop through each split result_list = [] for substring, subpatch in _yield_subpatches(patch, splits): # Get spatial table and break out columns spatial_table = _...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _yield_spatial_table(patch, div, spp_col, count_col, x_col, y_col): """ Calculates an empirical spatial table Yields ------- DataFrame Spatial table for each...
# Catch error if you don't use ; after divs in comm_grid in MacroecoDesktop try: div_split_list = div.replace(';','').split(',') except AttributeError: div_split_list = str(div).strip("()").split(',') div_split = (x_col + ':' + div_split_list[0] + ';' + y_col + ':' + ...
<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_cols(special_col_names, cols, patch): """ Retrieve values of special_cols from cols string or patch metadata """
# If cols not given, try to fall back on cols from metadata if not cols: if 'cols' in patch.meta['Description'].keys(): cols = patch.meta['Description']['cols'] else: raise NameError, ("cols argument not given, spp_col at a minimum " "must ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _yield_subpatches(patch, splits, name='split'): """ Iterator for subtables defined by a splits string Parameters patch : obj Patch object containing data to ...
if splits: subset_list = _parse_splits(patch, splits) for subset in subset_list: logging.info('Analyzing subset %s: %s' % (name, subset)) subpatch = copy.copy(patch) subpatch.table = _subset_table(patch.table, subset) subpatch.meta, subpatch.incremen...
<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_splits(patch, splits): """ Parse splits string to get list of all associated subset strings. Parameters patch : obj Patch object containing data to su...
split_list = splits.replace(' ','').split(';') subset_list = [] # List of all subset strings for split in split_list: col, val = split.split(':') if val == 'split': uniques = [] for level in patch.table[col]: if level not in uniques: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _product(*args, **kwds): """ Generates cartesian product of lists given as arguments From itertools.product documentation """
pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] 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 empirical_cdf(data): """ Generates an empirical cdf from data Parameters data : iterable Empirical data Returns -------- DataFrame Columns 'data' and 'ecdf'....
vals = pd.Series(data).value_counts() ecdf = pd.DataFrame(data).set_index(keys=0) probs = pd.DataFrame(vals.sort_index().cumsum() / np.float(len(data))) ecdf = ecdf.join(probs) ecdf = ecdf.reset_index() ecdf.columns = ['data', 'ecdf'] return ecdf
<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_table(self, metadata_path, data_path): """ Load data table, taking subset if needed Parameters metadata_path : str Path to metadata file data_path : st...
metadata_dir = os.path.dirname(os.path.expanduser(metadata_path)) data_path = os.path.normpath(os.path.join(metadata_dir, data_path)) extension = data_path.split('.')[-1] if extension == 'csv': full_table = pd.read_csv(data_path, index_col=False) table = _subs...
<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_db_table(self, data_path, extension): """ Query a database and return query result as a recarray Parameters data_path : str Path to the database file ex...
# TODO: This is probably broken raise NotImplementedError, "SQL and db file formats not yet supported" # Load table if extension == 'sql': con = lite.connect(':memory:') con.row_factory = lite.Row cur = con.cursor() with open(data_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 doc_sub(*sub): """ Decorator for performing substitutions in docstrings. Using @doc_sub(some_note, other_note) on a function with {0} and {1} in the docstrin...
def dec(obj): obj.__doc__ = obj.__doc__.format(*sub) return obj return dec
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_start_end(f): """ Decorator to log start and end of function Use of decorator module here ensures that argspec will inspect wrapped function, not the dec...
def inner(f, *args, **kwargs): logging.info('Starting %s' % f.__name__) res = f(*args, **kwargs) logging.info('Finished %s' % f.__name__) return res return decorator.decorator(inner, 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 check_parameter_file(filename): """ Function does a rudimentary check whether the cols, splits and divs columns in the parameter files are formatted properly...
# Load file with open(filename, "r") as fin: content = fin.read() # Check cols and splits strings bad_names = [] line_numbers = [] strs = ["cols", "splits", "divs"] for tstr in strs: start = content.find(tstr) while start != -1: cols_str = "".join...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_starttag(self, tag, attrs): """Function called for new opening tags"""
if tag.lower() in self.allowed_tag_whitelist: if tag.lower() == 'ol': # we need a list to store the last # number used in the previous ordered lists self.previous_nbs.append(self.nb) self.nb = 0 # we need to know which...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_entityref(self, name): """Process a general entity reference of the form "&name;". Transform to text whenever possible."""
char_code = html_entities.name2codepoint.get(name, None) if char_code is not None: try: self.result += unichr(char_code).encode("utf-8") except: 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 bethe_lattice(energy, hopping): """Bethe lattice in inf dim density of states"""
energy = np.asarray(energy).clip(-2*hopping, 2*hopping) return np.sqrt(4*hopping**2 - energy**2) / (2*np.pi*hopping**2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bethe_fermi(energy, quasipart, shift, hopping, beta): """product of the bethe lattice dos, fermi distribution"""
return fermi_dist(quasipart * energy - shift, beta) \ * bethe_lattice(energy, hopping)