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 is_resource_class_member_attribute(rc, attr_name):
""" Checks if the given attribute name is a member attribute of the given registered resource. """
|
attr = get_resource_class_attribute(rc, attr_name)
return attr.kind == RESOURCE_ATTRIBUTE_KINDS.MEMBER
|
<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_resource_class_collection_attribute(rc, attr_name):
""" Checks if the given attribute name is a collection attribute of the given registered resource. """
|
attr = get_resource_class_attribute(rc, attr_name)
return attr.kind == RESOURCE_ATTRIBUTE_KINDS.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_joke():
"""Return a Ron Swanson quote. Returns None if unable to retrieve a quote. """
|
page = requests.get("http://ron-swanson-quotes.herokuapp.com/v2/quotes")
if page.status_code == 200:
jokes = []
jokes = json.loads(page.content.decode(page.encoding))
return '"' + jokes[0] + '" - Ron Swanson'
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 window(iterable, n=2, cast=tuple):
""" This function passes a running window along the length of the given iterable. By default, the return value is a tuple, but the cast parameter can be used to change the final result. """
|
it = iter(iterable)
win = deque((next(it) for _ in repeat(None, n)), maxlen=n)
if len(win) < n:
raise ValueError('Window size was greater than iterable length')
yield cast(win)
append = win.append
for e in it:
append(e)
yield cast(win)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Command line interface for the ``update-dotdee`` program."""
|
# Initialize logging to the terminal and system log.
coloredlogs.install(syslog=True)
# Parse the command line arguments.
context_opts = {}
program_opts = {}
try:
options, arguments = getopt.getopt(sys.argv[1:], 'fur:vqh', [
'force', 'use-sudo', 'remote-host=',
'verbose', 'quiet', 'help',
])
for option, value in options:
if option in ('-f', '--force'):
program_opts['force'] = True
elif option in ('-u', '--use-sudo'):
context_opts['sudo'] = True
elif option in ('-r', '--remote-host'):
context_opts['ssh_alias'] = value
elif option in ('-v', '--verbose'):
coloredlogs.increase_verbosity()
elif option in ('-q', '--quiet'):
coloredlogs.decrease_verbosity()
elif option in ('-h', '--help'):
usage(__doc__)
sys.exit(0)
else:
# Programming error...
assert False, "Unhandled option!"
if not arguments:
usage(__doc__)
sys.exit(0)
if len(arguments) != 1:
raise Exception("Expected a filename as the first and only argument!")
program_opts['filename'] = arguments[0]
except Exception as e:
warning("Error: %s", e)
sys.exit(1)
# Run the program.
try:
# Initialize the execution context.
program_opts['context'] = create_context(**context_opts)
# Initialize the program and update the file.
UpdateDotDee(**program_opts).update_file()
except Exception as e:
logger.exception("Encountered unexpected exception, aborting!")
sys.exit(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 add_months(self, value: int) -> datetime: """ Add a number of months to the given date """
|
self.value = self.value + relativedelta(months=value)
return self.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 from_date(self, value: date) -> datetime: """ Initializes from the given date value """
|
assert isinstance(value, date)
#self.value = datetime.combine(value, time.min)
self.value = datetime(value.year, value.month, value.day)
return self.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 get_day_name(self) -> str: """ Returns the day name """
|
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday]
|
<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_iso_string(self) -> str: """ Returns full ISO string for the given date """
|
assert isinstance(self.value, datetime)
return datetime.isoformat(self.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 end_of_day(self) -> datetime: """ End of day """
|
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.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 end_of_month(self) -> datetime: """ Provides end of the month for the given date """
|
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.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 is_end_of_month(self) -> bool: """ Checks if the date is at the end of the month """
|
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.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 set_day(self, day: int) -> datetime: """ Sets the day value """
|
self.value = self.value.replace(day=day)
return self.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 set_value(self, value: datetime):
""" Sets the current value """
|
assert isinstance(value, datetime)
self.value = value
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_of_day(self) -> datetime: """ Returns start of day """
|
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.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 subtract_days(self, days: int) -> datetime: """ Subtracts dates from the given value """
|
self.value = self.value - relativedelta(days=days)
return self.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 subtract_weeks(self, weeks: int) -> datetime: """ Subtracts number of weeks from the current value """
|
self.value = self.value - timedelta(weeks=weeks)
return self.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 subtract_months(self, months: int) -> datetime: """ Subtracts a number of months from the current value """
|
self.value = self.value - relativedelta(months=months)
return self.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 yesterday(self) -> datetime: """ Set the value to yesterday """
|
self.value = datetime.today() - timedelta(days=1)
return self.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 get_uuid_string(low=None, high=None, **x):
"""This method parses a UUID protobuf message type from its component 'high' and 'low' longs into a standard formatted UUID string Args: x (dict):
containing keys, 'low' and 'high' corresponding to the UUID protobuf message type Returns: str: UUID formatted string """
|
if low is None or high is None:
return None
x = ''.join([parse_part(low), parse_part(high)])
return '-'.join([x[:8], x[8:12], x[12:16], x[16:20], x[20:32]])
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, search):
"""search Zenodo record for string `search` :param search: string to search :return: Record[] results """
|
search = search.replace('/', ' ') # zenodo can't handle '/' in search query
params = {'q': search}
return self._get_records(params)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qdict_get_list(qdict, k):
""" get list from QueryDict and remove blank date from list. """
|
pks = qdict.getlist(k)
return [e for e in pks if e]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_get_next(request, default_next):
""" get next url form request order: POST.next GET.next HTTP_REFERER, default_next """
|
next_url = request.POST.get('next')\
or request.GET.get('next')\
or request.META.get('HTTP_REFERER')\
or default_next
return next_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 upload_progress(request):
""" AJAX view adapted from django-progressbarupload Return the upload progress and total length values """
|
if 'X-Progress-ID' in request.GET:
progress_id = request.GET['X-Progress-ID']
elif 'X-Progress-ID' in request.META:
progress_id = request.META['X-Progress-ID']
if 'logfilename' in request.GET:
logfilename = request.GET['logfilename']
elif 'logfilename' in request.META:
logfilename = request.META['logfilename']
cache_key = "%s_%s" % (request.META['REMOTE_ADDR'], progress_id)
data = cache.get(cache_key)
if not data:
data = cache.get(logfilename.replace(' ','_'))
return HttpResponse(json.dumps(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 set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):
"""Set foreground- and background colors and intensity."""
|
raise NotImplementedError
|
<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(self, entity):
""" Adds the given entity to this cache. :param entity: Entity to add. :type entity: Object implementing :class:`everest.interfaces.IEntity`. :raises ValueError: If the ID of the entity to add is ``None`` (unless the `allow_none_id` constructor argument was set). """
|
do_append = self.__check_new(entity)
if do_append:
self.__entities.append(entity)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, entity):
""" Removes the given entity from this cache. :param entity: Entity to remove. :type entity: Object implementing :class:`everest.interfaces.IEntity`. :raises KeyError: If the given entity is not in this cache. :raises ValueError: If the ID of the given entity is `None`. """
|
self.__id_map.pop(entity.id, None)
self.__slug_map.pop(entity.slug, None)
self.__entities.remove(entity)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retrieve(self, filter_expression=None, order_expression=None, slice_key=None):
""" Retrieve entities from this cache, possibly after filtering, ordering and slicing. """
|
ents = iter(self.__entities)
if not filter_expression is None:
ents = filter_expression(ents)
if not order_expression is None:
# Ordering always involves a copy and conversion to a list, so
# we have to wrap in an iterator.
ents = iter(order_expression(ents))
if not slice_key is None:
ents = islice(ents, slice_key.start, slice_key.stop)
return ents
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_user_keywords_generator(twitter_lists_gen, lemmatizing="wordnet"):
""" Based on the user-related lists I have downloaded, annotate the users. Inputs: - twitter_lists_gen: A python generator that yields a user Twitter id and a generator of Twitter lists. - lemmatizing: A string containing one of the following: "porter", "snowball" or "wordnet". Yields: - user_twitter_id: A Twitter user id. - user_annotation: A python dictionary that contains two dicts: * bag_of_lemmas: Maps emmas to multiplicity. * lemma_to_keywordbag: A python dictionary that maps stems/lemmas to original topic keywords. """
|
####################################################################################################################
# Extract keywords serially.
####################################################################################################################
for user_twitter_id, twitter_lists_list in twitter_lists_gen:
if twitter_lists_list is not None:
if "lists" in twitter_lists_list.keys():
twitter_lists_list = twitter_lists_list["lists"]
bag_of_lemmas, lemma_to_keywordbag = user_twitter_list_bag_of_words(twitter_lists_list, lemmatizing)
for lemma, keywordbag in lemma_to_keywordbag.items():
lemma_to_keywordbag[lemma] = dict(keywordbag)
lemma_to_keywordbag = dict(lemma_to_keywordbag)
user_annotation = dict()
user_annotation["bag_of_lemmas"] = bag_of_lemmas
user_annotation["lemma_to_keywordbag"] = lemma_to_keywordbag
yield user_twitter_id, user_annotation
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def form_user_label_matrix(user_twitter_list_keywords_gen, id_to_node, max_number_of_labels):
""" Forms the user-label matrix to be used in multi-label classification. Input: - user_twitter_list_keywords_gen: - id_to_node: A Twitter id to node map as a python dictionary. Outputs: - user_label_matrix: A user-to-label matrix in scipy sparse matrix format. - annotated_nodes: A numpy array containing graph nodes. - label_to_lemma: A python dictionary that maps a numerical label to a string topic lemma. - lemma_to_keyword: A python dictionary that maps a lemma to the original keyword. """
|
user_label_matrix, annotated_nodes, label_to_lemma, node_to_lemma_tokeywordbag = form_user_term_matrix(user_twitter_list_keywords_gen,
id_to_node,
None)
# write_terms_and_frequencies("/home/georgerizos/Documents/term_matrix.txt", user_label_matrix, label_to_lemma)
user_label_matrix, annotated_nodes, label_to_lemma = filter_user_term_matrix(user_label_matrix,
annotated_nodes,
label_to_lemma,
max_number_of_labels)
# write_terms_and_frequencies("/home/georgerizos/Documents/label_matrix.txt", user_label_matrix, label_to_lemma)
lemma_to_keyword = form_lemma_tokeyword_map(annotated_nodes, node_to_lemma_tokeywordbag)
return user_label_matrix, annotated_nodes, label_to_lemma, lemma_to_keyword
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def form_user_term_matrix(user_twitter_list_keywords_gen, id_to_node, lemma_set=None, keyword_to_topic_manual=None):
""" Forms a user-term matrix. Input: - user_twitter_list_keywords_gen: A python generator that yields a user Twitter id and a bag-of-words. - id_to_node: A Twitter id to node map as a python dictionary. - lemma_set: For the labelling, we use only lemmas in this set. Default: None Outputs: - user_term_matrix: A user-to-term matrix in scipy sparse matrix format. - annotated_nodes: A numpy array containing graph nodes. - label_to_topic: A python dictionary that maps a numerical label to a string topic/keyword. - node_to_lemma_tokeywordbag: A python dictionary that maps nodes to lemma-to-keyword bags. """
|
# Prepare for iteration.
term_to_attribute = dict()
user_term_matrix_row = list()
user_term_matrix_col = list()
user_term_matrix_data = list()
append_user_term_matrix_row = user_term_matrix_row.append
append_user_term_matrix_col = user_term_matrix_col.append
append_user_term_matrix_data = user_term_matrix_data.append
annotated_nodes = list()
append_node = annotated_nodes.append
node_to_lemma_tokeywordbag = dict()
invalid_terms = list()
counter = 0
if keyword_to_topic_manual is not None:
manual_keyword_list = list(keyword_to_topic_manual.keys())
for user_twitter_id, user_annotation in user_twitter_list_keywords_gen:
counter += 1
# print(counter)
bag_of_words = user_annotation["bag_of_lemmas"]
lemma_to_keywordbag = user_annotation["lemma_to_keywordbag"]
if lemma_set is not None:
bag_of_words = {lemma: multiplicity for lemma, multiplicity in bag_of_words.items() if lemma in lemma_set}
lemma_to_keywordbag = {lemma: keywordbag for lemma, keywordbag in lemma_to_keywordbag.items() if lemma in lemma_set}
node = id_to_node[user_twitter_id]
append_node(node)
node_to_lemma_tokeywordbag[node] = lemma_to_keywordbag
for term, multiplicity in bag_of_words.items():
if term == "news":
continue
if keyword_to_topic_manual is not None:
keyword_bag = lemma_to_keywordbag[term]
term = max(keyword_bag.keys(), key=(lambda key: keyword_bag[key]))
found_list_of_words = simple_word_query(term, manual_keyword_list, edit_distance=1)
if len(found_list_of_words) > 0:
term = found_list_of_words[0]
try:
term = keyword_to_topic_manual[term]
except KeyError:
print(term)
vocabulary_size = len(term_to_attribute)
attribute = term_to_attribute.setdefault(term, vocabulary_size)
append_user_term_matrix_row(node)
append_user_term_matrix_col(attribute)
append_user_term_matrix_data(multiplicity)
annotated_nodes = np.array(list(set(annotated_nodes)), dtype=np.int64)
user_term_matrix_row = np.array(user_term_matrix_row, dtype=np.int64)
user_term_matrix_col = np.array(user_term_matrix_col, dtype=np.int64)
user_term_matrix_data = np.array(user_term_matrix_data, dtype=np.float64)
user_term_matrix = sparse.coo_matrix((user_term_matrix_data,
(user_term_matrix_row, user_term_matrix_col)),
shape=(len(id_to_node), len(term_to_attribute)))
label_to_topic = dict(zip(term_to_attribute.values(), term_to_attribute.keys()))
# print(user_term_matrix.shape)
# print(len(label_to_topic))
# print(invalid_terms)
return user_term_matrix, annotated_nodes, label_to_topic, node_to_lemma_tokeywordbag
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_twitter_lists_for_user_ids_generator(twitter_app_key, twitter_app_secret, user_id_list):
""" Collects at most 500 Twitter lists for each user from an input list of Twitter user ids. Inputs: - twitter_app_key: What is says on the tin. - twitter_app_secret: Ditto. - user_id_list: A python list of Twitter user ids. Yields: - user_twitter_id: A Twitter user id. - twitter_lists_list: A python list containing Twitter lists in dictionary (json) format. """
|
####################################################################################################################
# Log into my application.
####################################################################################################################
twitter = login(twitter_app_key,
twitter_app_secret)
####################################################################################################################
# For each user, gather at most 500 Twitter lists.
####################################################################################################################
get_list_memberships_counter = 0
get_list_memberships_time_window_start = time.perf_counter()
for user_twitter_id in user_id_list:
# Make safe twitter request.
try:
twitter_lists_list, get_list_memberships_counter, get_list_memberships_time_window_start\
= safe_twitter_request_handler(twitter_api_func=twitter.get_list_memberships,
call_rate_limit=15,
call_counter=get_list_memberships_counter,
time_window_start=get_list_memberships_time_window_start,
max_retries=5,
wait_period=2,
user_id=user_twitter_id,
count=500,
cursor=-1)
# If the call is succesful, yield the list of Twitter lists.
yield user_twitter_id, twitter_lists_list
except twython.TwythonError:
# If the call is unsuccesful, we do not have any Twitter lists to store.
yield user_twitter_id, None
except URLError:
# If the call is unsuccesful, we do not have any Twitter lists to store.
yield user_twitter_id, None
except BadStatusLine:
# If the call is unsuccesful, we do not have any Twitter lists to store.
yield user_twitter_id, 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 decide_which_users_to_annotate(centrality_vector, number_to_annotate, already_annotated, node_to_id):
""" Sorts a centrality vector and returns the Twitter user ids that are to be annotated. Inputs: - centrality_vector: A numpy array vector, that contains the centrality values for all users. - number_to_annotate: The number of users to annotate. - already_annotated: A python set of user twitter ids that have already been annotated. - node_to_id: A python dictionary that maps graph nodes to user twitter ids. Output: - user_id_list: A python list of Twitter user ids. """
|
# Sort the centrality vector according to decreasing centrality.
centrality_vector = np.asarray(centrality_vector)
ind = np.argsort(np.squeeze(centrality_vector))
if centrality_vector.size > 1:
reversed_ind = ind[::-1]
else:
reversed_ind = list()
reversed_ind = reversed_ind.append(ind)
# Get the sublist of Twitter user ids to return.
user_id_list = list()
append_user_id = user_id_list.append
counter = 0
for node in reversed_ind:
user_twitter_id = node_to_id[node]
if user_twitter_id not in already_annotated:
append_user_id(user_twitter_id)
counter += 1
if counter >= number_to_annotate:
break
return user_id_list
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_demand_annotation(twitter_app_key, twitter_app_secret, user_twitter_id):
""" A service that leverages twitter lists for on-demand annotation of popular users. TODO: Do this. """
|
####################################################################################################################
# Log into my application
####################################################################################################################
twitter = login(twitter_app_key, twitter_app_secret)
twitter_lists_list = twitter.get_list_memberships(user_id=user_twitter_id, count=1000)
for twitter_list in twitter_lists_list:
print(twitter_list)
return twitter_lists_list
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_member_class(resource):
""" Returns the registered member class for the given resource. :param resource: registered resource :type resource: class implementing or instance providing or subclass of a registered resource interface. """
|
reg = get_current_registry()
if IInterface in provided_by(resource):
member_class = reg.getUtility(resource, name='member-class')
else:
member_class = reg.getAdapter(resource, IMemberResource,
name='member-class')
return member_class
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_collection_class(resource):
""" Returns the registered collection resource class for the given marker interface or member resource class or instance. :param rc: registered resource :type rc: class implementing or instance providing or subclass of a registered resource interface. """
|
reg = get_current_registry()
if IInterface in provided_by(resource):
coll_class = reg.getUtility(resource, name='collection-class')
else:
coll_class = reg.getAdapter(resource, ICollectionResource,
name='collection-class')
return coll_class
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_member(entity, parent=None):
""" Adapts an object to a location aware member resource. :param entity: a domain object for which a resource adapter has been registered :type entity: an object implementing :class:`everest.entities.interfaces.IEntity` :param parent: optional parent collection resource to make the new member a child of :type parent: an object implementing :class:`everest.resources.interfaces.ICollectionResource` :returns: an object implementing :class:`everest.resources.interfaces.IMemberResource` """
|
reg = get_current_registry()
rc = reg.getAdapter(entity, IMemberResource)
if not parent is None:
rc.__parent__ = parent # interface method pylint: disable=E1121
return rc
|
<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_resource_url(resource):
""" Returns the URL for the given resource. """
|
path = model_path(resource)
parsed = list(urlparse.urlparse(path))
parsed[1] = ""
return urlparse.urlunparse(parsed)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_registered_collection_resources():
""" Returns a list of all registered collection resource classes. """
|
reg = get_current_registry()
return [util.component
for util in reg.registeredUtilities()
if util.name == 'collection-class']
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_to_url(resource, request=None, quote=False):
""" Converts the given resource to a URL. :param request: Request object (required for the host name part of the URL). If this is not given, the current request is used. :param bool quote: If set, the URL returned will be quoted. """
|
if request is None:
request = get_current_request()
# cnv = request.registry.getAdapter(request, IResourceUrlConverter)
reg = get_current_registry()
cnv = reg.getAdapter(request, IResourceUrlConverter)
return cnv.resource_to_url(resource, quote=quote)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url_to_resource(url, request=None):
""" Converts the given URL to a resource. :param request: Request object (required for the host name part of the URL). If this is not given, the current request is used. """
|
if request is None:
request = get_current_request()
# cnv = request.registry.getAdapter(request, IResourceUrlConverter)
reg = get_current_registry()
cnv = reg.getAdapter(request, IResourceUrlConverter)
return cnv.url_to_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_entity_class(resource):
""" Returns the entity class registered for the given registered resource. :param resource: registered resource :type collection: class implementing or instance providing a registered resource interface. :return: entity class (class implementing `everest.entities.interfaces.IEntity`) """
|
reg = get_current_registry()
if IInterface in provided_by(resource):
ent_cls = reg.getUtility(resource, name='entity-class')
else:
ent_cls = reg.getAdapter(resource, IEntity, name='entity-class')
return ent_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 install_board_with_programmer(mcu, programmer, f_cpu=16000000, core='arduino', replace_existing=False, ):
"""install board with programmer."""
|
bunch = AutoBunch()
board_id = '{mcu}_{f_cpu}_{programmer}'.format(f_cpu=f_cpu,
mcu=mcu,
programmer=programmer,
)
bunch.name = '{mcu}@{f} Prog:{programmer}'.format(f=strfreq(f_cpu),
mcu=mcu,
programmer=programmer,
)
bunch.upload.using = programmer
bunch.build.mcu = mcu
bunch.build.f_cpu = str(f_cpu) + 'L'
bunch.build.core = core
install_board(board_id, bunch, replace_existing=replace_existing)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logMsg(self, msg, printMsg=True):
""" logs a message and prints it to the screen """
|
time = datetime.datetime.now().strftime('%I:%M %p')
self.log = '{0}\n{1} | {2}'.format(self.log, time, msg)
if printMsg:
print msg
if self.addLogsToArcpyMessages:
from arcpy import AddMessage
AddMessage(msg)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logGPMsg(self, printMsg=True):
""" logs the arcpy messages and prints them to the screen """
|
from arcpy import GetMessages
msgs = GetMessages()
try:
self.logMsg(msgs, printMsg)
except:
self.logMsg('error getting arcpy message', printMsg)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writeLogToFile(self):
""" writes the log to a """
|
if not os.path.exists(self.logFolder):
os.mkdir(self.logFolder)
with open(self.logFile, mode='a') as f:
f.write('\n\n' + self.log)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logError(self):
""" gets traceback info and logs it """
|
# got from http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Error_handling_with_Python
import traceback
self.logMsg('ERROR!!!')
errMsg = traceback.format_exc()
self.logMsg(errMsg)
return errMsg
|
<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_random_giphy(phrase):
"""Return the URL of a random GIF related to the phrase, if possible"""
|
with warnings.catch_warnings():
warnings.simplefilter('ignore')
giphy = giphypop.Giphy()
results = giphy.search_list(phrase=phrase, limit=100)
if not results:
raise ValueError('There were no results for that phrase')
return random.choice(results).media_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 handle_command_line():
"""Display an image for the phrase in sys.argv, if possible"""
|
phrase = ' '.join(sys.argv[1:]) or 'random'
try:
giphy = get_random_giphy(phrase)
except ValueError:
sys.stderr.write('Unable to find any GIFs for {!r}\n'.format(phrase))
sys.exit(1)
display(fetch_image(giphy))
|
<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_required_folders(self):
"""Makes all folders declared in the config if they do not exist. """
|
for folder in [
self.pending_folder,
self.usb_incoming_folder,
self.outgoing_folder,
self.incoming_folder,
self.archive_folder,
self.tmp_folder,
self.log_folder,
]:
if not os.path.exists(folder):
os.makedirs(folder)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, filename, offset):
"""Loads HFS+ volume information"""
|
try:
self.offset = offset
self.fd = open(filename, 'rb')
# 1024 - temporary, need to find out actual volume header size
self.fd.seek(self.offset + VOLUME_HEADER_OFFSET)
data = self.fd.read(1024)
self.vol_header = VolumeHeader(data)
self.fd.close()
except IOError as e:
print(e)
|
<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_interfaces(self):
""" Return a list of sham.network.interfaces.NetworkInterface describing all the interfaces this VM has """
|
interfaces = self.xml.find('devices').iter('interface')
iobjs = []
for interface in interfaces:
_type = interface.attrib['type']
mac = interface.find('mac').attrib['address']
source = interface.find('source').attrib[_type]
model = interface.find('model').attrib['type']
iobjs.append(NetworkInterface(_type, mac, source, model))
return iobjs
|
<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_disks(self):
""" Return a list of all the Disks attached to this VM The disks are returned in a sham.storage.volumes.Volume object """
|
disks = [disk for disk in self.xml.iter('disk')]
disk_objs = []
for disk in disks:
source = disk.find('source')
if source is None:
continue
path = source.attrib['file']
diskobj = self.domain.connect().storageVolLookupByPath(path)
disk_objs.append(diskobj)
return [Volume(d, StoragePool(d.storagePoolLookupByVolume())) for d in disk_objs]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" Delete this VM, and remove all its disks """
|
disks = self.get_disks()
self.domain.undefine()
for disk in disks:
disk.wipe()
disk.delete()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
""" Return the values contained in this object as a dict """
|
return {'domain_type': self.domain_type,
'max_memory': self.max_memory,
'current_memory': self.current_memory,
'num_cpus': self.num_cpus,
'running': self.is_running(),
'name': self.name,
}
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def guess_url_vcs(url):
""" Given a url, try to guess what kind of VCS it's for. Return None if we can't make a good guess. """
|
parsed = urllib.parse.urlsplit(url)
if parsed.scheme in ('git', 'svn'):
return parsed.scheme
elif parsed.path.endswith('.git'):
return 'git'
elif parsed.hostname == 'github.com':
return 'git'
# If it's an http url, we can try requesting it and guessing from the
# contents.
if parsed.scheme in ('http', 'https'):
resp = requests.get(url)
if re.match('basehttp.*python.*', resp.headers.get('server').lower()):
# It's the mercurial http server
return 'hg'
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 guess_folder_vcs(folder):
""" Given a path for a folder on the local filesystem, see what kind of vcs repo it is, if any. """
|
try:
contents = os.listdir(folder)
vcs_folders = ['.git', '.hg', '.svn']
found = next((x for x in vcs_folders if x in contents), None)
# Chop off the dot if we got a string back
return found[1:] if found else None
except OSError:
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 basename(url):
""" Return the name of the folder that you'd get if you cloned 'url' into the current working directory. """
|
# It's easy to accidentally have whitespace on the beginning or end of the
# url.
url = url.strip()
url, _sep, _fragment = url.partition('#')
# Remove trailing slash from url if present
if url.endswith('/'):
url = url[:-1]
# Also strip .git from url if it ends in that.
return re.sub(r'\.git$', '', url.split('/')[-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 get_url(self):
""" Assuming that the repo has been cloned locally, get its default upstream URL. """
|
cmd = {
'hg': 'hg paths default',
'git': 'git config --local --get remote.origin.url',
}[self.vcs_type]
with chdir(self.folder):
r = self.run(cmd)
return r.output.replace('\n', '')
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fburl(parser, token):
""" Returns an absolute URL matching given view with its parameters. This is a way to define links that aren't tied to a particular URL configuration:: {% url path.to.some_view arg1,arg2,name1=value1 %} The first argument is a path to a view. It can be an absolute python path or just ``app_name.view_name`` without the project name if the view is located inside the project. Other arguments are comma-separated values that will be filled in place of positional and keyword arguments in the URL. All arguments for the URL should be present. For example if you have a view ``app_name.client`` taking client's id and the corresponding line in a URLconf looks like this:: ('^client/(\d+)/$', 'app_name.client') and this app's URLconf is included into the project's URLconf under some path:: ('^clients/', include('project_name.app_name.urls')) then in a template you can create a link for a certain client like this:: {% url app_name.client client.id %} The URL will look like ``/clients/client/123/``. """
|
bits = token.contents.split(' ')
if len(bits) < 2:
raise template.TemplateSyntaxError("'%s' takes at least one argument"
" (path to a view)" % bits[0])
viewname = bits[1]
args = []
kwargs = {}
asvar = None
if len(bits) > 2:
bits = iter(bits[2:])
for bit in bits:
if bit == 'as':
asvar = bits.next()
break
else:
for arg in bit.split(","):
if '=' in arg:
k, v = arg.split('=', 1)
k = k.strip()
kwargs[k] = parser.compile_filter(v)
elif arg:
args.append(parser.compile_filter(arg))
return URLNode(viewname, args, kwargs, asvar)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chdir(method):
"""Decorator executing method in directory 'dir'. """
|
def wrapper(self, dir, *args, **kw):
dirstack = ChdirStack()
dirstack.push(dir)
try:
return method(self, dir, *args, **kw)
finally:
dirstack.pop()
return functools.wraps(method)(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 push(self, dir):
"""Push cwd on stack and change to 'dir'. """
|
self.stack.append(os.getcwd())
os.chdir(dir or os.getcwd())
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop(self):
"""Pop dir off stack and change to it. """
|
if len(self.stack):
os.chdir(self.stack.pop())
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_matching(self, source_id):
""" Returns a matching target object for the given source ID. """
|
value = self._accessor.get_by_id(source_id)
if not value is None:
reg = get_current_registry()
prx_fac = reg.getUtility(IDataTraversalProxyFactory)
prx = prx_fac.make_proxy(value,
self._accessor,
self.relationship_direction,
self.relation_operation)
else:
prx = None
return prx
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_attribute_value_items(self):
""" Returns an iterator of items for an attribute value map to use for an UPDATE operation. The iterator ignores collection attributes as these are processed implicitly by the traversal algorithm. :returns: iterator yielding tuples with objects implementing :class:`everest.resources.interfaces.IResourceAttribute` as the first and the proxied attribute value as the second argument. """
|
for attr in self._attribute_iterator():
if attr.kind != RESOURCE_ATTRIBUTE_KINDS.COLLECTION:
try:
attr_val = self._get_proxied_attribute_value(attr)
except AttributeError:
continue
else:
yield (attr, attr_val)
|
<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_entity(self):
""" Returns the entity converted from the proxied data. """
|
if self._accessor is None:
if self.__converted_entity is None:
self.__converted_entity = self._convert_to_entity()
else:
# If we have an accessor, we can get the proxied entity by ID.
# FIXME: This is a hack that is only used for REMOVE operations
# with data elements.
self.__converted_entity = \
self.get_matching(self.get_id()).get_entity()
return self.__converted_entity
|
<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_traverser(cls, source_data, target_data, relation_operation, accessor=None, manage_back_references=True):
""" Factory method to create a tree traverser depending on the input source and target data combination. :param source_data: Source data. :param target_target: Target data. :param str relation_operation: Relation operation. On of the constants defined in :class:`everest.constants.RELATION_OPERATIONS`. :param accessor: Accessor for looking up target nodes for update operations. :param bool manage_back_references: If set, backreferences will automatically be updated in the target data. """
|
reg = get_current_registry()
prx_fac = reg.getUtility(IDataTraversalProxyFactory)
if relation_operation == RELATION_OPERATIONS.ADD \
or relation_operation == RELATION_OPERATIONS.UPDATE:
if relation_operation == RELATION_OPERATIONS.ADD \
and not target_data is None:
raise ValueError('Must not provide target data with '
'relation operation ADD.')
source_proxy = prx_fac.make_proxy(source_data,
None,
RELATIONSHIP_DIRECTIONS.NONE,
relation_operation)
source_is_sequence = \
source_proxy.proxy_for == RESOURCE_KINDS.COLLECTION
if not source_is_sequence:
source_id = source_proxy.get_id()
else:
source_proxy = None
source_is_sequence = False
if relation_operation == RELATION_OPERATIONS.REMOVE \
or relation_operation == RELATION_OPERATIONS.UPDATE:
rel_dir = RELATIONSHIP_DIRECTIONS.BIDIRECTIONAL
if not manage_back_references:
rel_dir &= ~RELATIONSHIP_DIRECTIONS.REVERSE
if relation_operation == RELATION_OPERATIONS.REMOVE:
if not source_data is None:
raise ValueError('Must not provide source data with '
'relation operation REMOVE.')
target_proxy = prx_fac.make_proxy(target_data,
accessor,
rel_dir,
relation_operation)
else: # UPDATE
if accessor is None:
raise ValueError('Need to provide an accessor when '
'performing UPDATE operations.')
if not target_data is None:
target_root = target_data
elif not source_is_sequence:
# Look up the (single) target to update.
target_root = accessor.get_by_id(source_id)
if target_root is None:
raise ValueError('Entity with ID %s to update not '
'found.' % source_id)
else:
# Look up collection of targets to update.
target_root = []
for src_prx in source_proxy:
tgt_ent_id = src_prx.get_id()
if tgt_ent_id is None:
continue
tgt_ent = accessor.get_by_id(tgt_ent_id)
if tgt_ent is None:
continue
target_root.append(tgt_ent)
target_proxy = prx_fac.make_proxy(target_root,
accessor,
rel_dir,
relation_operation)
target_is_sequence = \
target_proxy.proxy_for == RESOURCE_KINDS.COLLECTION
else:
target_proxy = None
target_is_sequence = False
if not source_proxy is None and not target_proxy is None:
# Check for source/target consistency.
if not ((source_is_sequence and target_is_sequence) or
(not source_is_sequence and not target_is_sequence)):
raise ValueError('When both source and target root nodes are '
'given, they can either both be sequences '
'or both not be sequences.')
return cls(source_proxy, target_proxy)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
async def info(self, obj_id=None):
'''Get info about object id
|coro|
Parameters
----------
obj_id : str, list
if not provided, server info is retured(as a dict).
Otherwise, an object with that id is returned
(or objects if `obj_id` is a list).
'''
if obj_id:
try:
return await self.process(obj_id)
except JSONDecodeError:
raise LookupError('Error object with that id does not exist', obj_id)
else:
return await self.connector.getJson('/system/info/public', remote=False)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
async def search(self, query,
sort_map = {'BoxSet':0,'Series':1,'Movie':2,'Audio':3,'Person':4},
strict_sort = False):
'''Sends a search request to emby, returns results
|coro|
Parameters
----------
query : str
the search string to send to emby
sort_map : dict
is a dict of strings to ints. Strings should be item types, and
the ints are the priority of those types(for sorting).
lower valued(0) will appear first.
strict_sort : bool
if True, then only item types in the keys of sortmap will be
included in the results
Returns
-------
list
list of emby objects
'''
search_params = {
'remote' : False,
'searchTerm' : query
}
if strict_sort:
search_params['IncludeItemTypes'] = ','.join(sort_map.keys())
json = await self.connector.getJson('/Search/Hints/', **search_params)
items = await self.process(json["SearchHints"])
m_size = len(sort_map)
items = sorted(items, key = lambda x : sort_map.get(x.type, m_size))
return items
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
async def nextUp(self, userId=None):
'''returns list of items marked as `next up`
|coro|
Parameters
----------
userId : str
if provided, then the list returned is
the one that that use will see.
Returns
-------
list
the itmes that will appear as next up
(for user if id was given)
'''
json = await self.connector.getJson('/Shows/NextUp',
pass_uid=True,
remote=False,
userId=userId
)
return await self.process(json)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
async def update(self):
'''
reload all cached information
|coro|
Notes
-----
This is a slow process, and will remove the cache before updating.
Thus it is recomended to use the `*_force` properties, which will
only update the cache after data is retrived.
'''
keys = self.extras.keys()
self.extras = {}
for key in keys:
try:
func = getattr(self, key, None)
if callable(func):
func()
except:
pass
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
async def create_playlist(self, name, *songs):
'''create a new playlist
|coro|
Parameters
----------
name : str
name of new playlist
songs : array_like
list of song ids to add to playlist
'''
data = {'Name': name}
ids = [i.id for i in (await self.process(songs))]
if ids:
data['Ids'] = ','.join(ids)
# TODO - return playlist not status
return await self.connector.post('/Playlists',
data=data,
pass_uid=True,
remote=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 load_all(self, group):
""" Loads all plugins advertising entry points with the given group name. The specified plugin needs to be a callable that accepts the everest configurator as single argument. """
|
for ep in iter_entry_points(group=group):
plugin = ep.load()
plugin(self.__config)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gui():
"""remove libraries by GUI."""
|
sel = psidialogs.multi_choice(libraries(),
'select libraries to remove from %s!' % libraries_dir(),
title='remove boards')
print('%s selected' % sel)
if sel:
if psidialogs.ask_yes_no('Do you really want to remove selected libraries?\n' + '\n'.join(sel)):
for x in sel:
remove_lib(x)
print('%s was removed' % x)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def src2ast(src: str) -> Expression: """Return ast.Expression created from source code given in `src`."""
|
try:
return ast.parse(src, mode='eval')
except SyntaxError:
raise ValueError("Not a valid expression.") from 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 names(expr: AST) -> Set[str]: """Names of globals in `expr`."""
|
nodes = [node for node in ast.walk(expr) if isinstance(node, ast.Name)]
loaded = {node.id for node in nodes if isinstance(node.ctx, ast.Load)}
stored = {node.id for node in nodes if isinstance(node.ctx, ast.Store)}
return loaded - stored
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace_name(expr: AST, old_name: str, new_name: str) -> AST: """Replace all Name nodes named `old_name` with nodes named `new_name`."""
|
return _NameReplacer(old_name, new_name).visit(deepcopy(expr))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Negation(expr: Expression) -> Expression: """Return expression which is the negation of `expr`."""
|
expr = Expression(_negate(expr.body))
return ast.fix_missing_locations(expr)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Conjunction(expr1: Expression, expr2: Expression) -> Expression: """Return expression which is the conjunction of `expr1` and `expr2`."""
|
expr = Expression(ast.BoolOp(ast.And(), [expr1.body, expr2.body]))
return ast.fix_missing_locations(expr)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Disjunction(expr1: Expression, expr2: Expression) -> Expression: """Return expression which is the disjunction of `expr1` and `expr2`."""
|
expr = Expression(ast.BoolOp(ast.Or(), [expr1.body, expr2.body]))
return ast.fix_missing_locations(expr)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Contradiction(expr1: Expression, expr2: Expression) -> Expression: """Return expression which is the contradiction of `expr1` and `expr2`."""
|
expr = Disjunction(Conjunction(expr1, Negation(expr2)),
Conjunction(Negation(expr1), expr2))
return ast.fix_missing_locations(expr)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diff_binding(self) -> int: """Return the difference betweens the binding levels of the current and the previous operator. """
|
try:
prev_op, prev_op_binding = self.nested_ops[-2]
except IndexError:
prev_op, prev_op_binding = None, 0
try:
curr_op, curr_op_binding = self.nested_ops[-1]
except IndexError:
curr_op, curr_op_binding = None, 0
# special case
if prev_op is ast.Pow and isinstance(curr_op, (ast.Invert, ast.USub)):
return 1
# print(prev_op, prev_op_binding, curr_op, curr_op_binding)
return curr_op_binding - prev_op_binding
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_expr(self, src: str, dfltChaining: bool) -> str: """Wrap `src` in parentheses if neccessary."""
|
diff_binding = self.op_man.diff_binding()
if diff_binding < 0 or diff_binding == 0 and not dfltChaining:
return self.parenthesize(src)
else:
return src
|
<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(self, node: AST, dfltChaining: bool = True) -> str: """Process `node` by dispatching to a handler."""
|
# print(node.__class__.__name__)
if node is None:
return ''
if isinstance(node, ast.Expression):
return self.visit(node.body)
# dispatch to specific or generic method
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node, dfltChaining)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generic_visit(self, node: AST, dfltChaining: bool = True) -> str: """Default handler, called if no explicit visitor function exists for a node. """
|
for field, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, AST):
self.visit(item)
elif isinstance(value, AST):
self.visit(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 visit_NameConstant(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s name as string."""
|
return str(node.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 visit_Num(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s number as string."""
|
return str(node.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 visit_Str(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s string representation."""
|
return repr(node.s)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_FormattedValue(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s value formatted according to its format spec."""
|
format_spec = node.format_spec
return f"{{{self.visit(node.value)}" \
f"{self.CONV_MAP.get(node.conversion, '')}" \
f"{':'+self._nested_str(format_spec) if format_spec else ''}}}"
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Tuple(self, node: AST, dfltChaining: bool = True) -> str: """Return tuple representation of `node`s elements."""
|
elems = (self.visit(elt) for elt in node.elts)
return f"({', '.join(elems)}{')' if len(node.elts) != 1 else ',)'}"
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Set(self, node: AST, dfltChaining: bool = True) -> str: """Return set representation of `node`s elements."""
|
return '{' + ', '.join([self.visit(elt) for elt in node.elts]) + '}'
|
<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_Dict(self, node: AST, dfltChaining: bool = True) -> str: """Return dict representation of `node`s elements."""
|
items = (': '.join((self.visit(key), self.visit(value)))
for key, value in zip(node.keys, node.values))
return f"{{{', '.join(items)}}}"
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Name(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s id."""
|
return node.id
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Starred(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of starred expresssion."""
|
with self.op_man(node):
return f"*{self.visit(node.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 visit_Expr(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of nested expression."""
|
return self.visit(node.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 visit_UnaryOp(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of `node`s operator and operand."""
|
op = node.op
with self.op_man(op):
return self.visit(op) + self.visit(node.operand)
|
<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_Div(self, node: AST, dfltChaining: bool = True) -> str: """Return division sign."""
|
return '/' if self.compact else ' / '
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Compare(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s operators and operands as inlined expression."""
|
# all comparison operators have the same precedence,
# we just take the first one as representative
first_op = node.ops[0]
with self.op_man(first_op):
cmps = [' '.join((self.visit(op),
self.visit(cmp, dfltChaining=False)))
for op, cmp in zip(node.ops, node.comparators)]
src = ' '.join((self.visit(node.left), ' '.join(cmps)))
return self.wrap_expr(src, dfltChaining)
|
<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_keyword(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of `node` as keyword arg."""
|
arg = node.arg
if arg is None:
return f"**{self.visit(node.value)}"
else:
return f"{arg}={self.visit(node.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 visit_Call(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as function call."""
|
args = node.args
try:
kwds = node.keywords
except AttributeError:
kwds = []
self.compact = True
args_src = (self.visit(arg) for arg in args)
kwds_src = (self.visit(kwd) for kwd in kwds)
param_src = ', '.join(chain(args_src, kwds_src))
src = f"{self.visit(node.func)}({param_src})"
self.compact = False
return src
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.