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 add(self, interval, offset):
""" The added interval must be overlapping or beyond the last stored interval ie. added in sorted order. :param interval: interv... |
start, stop = self.get_start_stop(interval)
if len(self.starts) > 0:
if start < self.starts[-1] or offset <= self.offsets[-1][1]:
raise ValueError('intervals and offsets must be added in-order')
self.offsets[-1][1] = offset
self.offsets[-1][2] += 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_sum(qs, field):
""" get sum for queryset. ``qs``: queryset ``field``: The field name to sum. """ |
sum_field = '%s__sum' % field
qty = qs.aggregate(Sum(field))[sum_field]
return qty if qty 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 get_max(qs, field):
""" get max for queryset. qs: queryset field: The field name to max. """ |
max_field = '%s__max' % field
num = qs.aggregate(Max(field))[max_field]
return num if num 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 do_filter(qs, qdata, quick_query_fields=[], int_quick_query_fields=[]):
""" auto filter queryset by dict. qs: queryset need to filter. qdata: quick_query_fie... |
try:
qs = qs.filter(
__gen_quick_query_params(
qdata.get('q_quick_search_kw'), quick_query_fields,
int_quick_query_fields)
)
q, kw_query_params = __gen_query_params(qdata)
qs = qs.filter(q, **kw_query_params)
except:
import tra... |
<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_gcvs(filename):
""" Reads variable star data in `GCVS format`_. :param filename: path to GCVS data file (usually ``iii.dat``) .. _`GCVS format`: http://... |
with open(filename, 'r') as fp:
parser = GcvsParser(fp)
for star in parser:
yield star |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dict_to_body(star_dict):
""" Converts a dictionary of variable star data to a `Body` instance. Requires `PyEphem <http://rhodesmill.org/pyephem/>`_ to be ins... |
if ephem is None: # pragma: no cover
raise NotImplementedError("Please install PyEphem in order to use dict_to_body.")
body = ephem.FixedBody()
body.name = star_dict['name']
body._ra = ephem.hours(str(star_dict['ra']))
body._dec = ephem.degrees(str(star_dict['dec']))
body._epoch = ephe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tempfile(self):
"write the docx to a named tmpfile and return the tmpfile filename"
tf = tempfile.NamedTemporaryFile()
tfn = tf.name
tf.close()
os.remove(tf.name)
shutil.copy(self.fn, tfn)
return tfn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sheets(self):
"""return the sheets of data.""" |
data = Dict()
for src in [src for src in self.zipfile.namelist() if 'xl/worksheets/' in src]:
name = os.path.splitext(os.path.basename(src))[0]
xml = self.xml(src)
data[name] = xml
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 workbook_data(self):
"""return a readable XML form of the data.""" |
document = XML(
fn=os.path.splitext(self.fn)[0]+'.xml',
root=Element.workbook())
shared_strings = [
str(t.text) for t in
self.xml('xl/sharedStrings.xml')
.root.xpath(".//xl:t", namespaces=self.NS)]
for key in self.sheets.keys():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, event):
"""Put and process tasks in queue. """ |
logger.info(f"{self}: put {event.src_path}")
self.queue.put(os.path.basename(event.src_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 main():
""" Scrapes Apple's iCal feed for Australian public holidays and generates per- state listings. """ |
print "Downloading Holidays from Apple's server..."
r = requests.get('http://files.apple.com/calendars/Australian32Holidays.ics')
cal = Calendar.from_ical(r.text)
print "Processing calendar data..."
valid_states = ['ACT', 'NSW', 'NT', 'QLD', 'SA', 'TAS', 'VIC', 'WA']
state_cal = {}
all_cal = make_calend... |
<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_editing_mode(self, e): # (M-C-j)
'''Initialize vi editingmode'''
self.show_all_if_ambiguous = 'on'
self.key_dispatch = {}
self.__vi_insert_mode = None
self._vi_command = None
self._vi_command_edit = None
self._vi_key_find_char = None
self._vi_key_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_collection_documents_generator(client, database_name, collection_name, spec, latest_n, sort_key):
""" This is a python generator that yields tweets store... |
mongo_database = client[database_name]
collection = mongo_database[collection_name]
collection.create_index(sort_key)
if latest_n is not None:
skip_n = collection.count() - latest_n
if collection.count() - latest_n < 0:
skip_n = 0
cursor = collection.find(filter=spe... |
<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_connected_components(graph, connectivity_type, node_to_id):
""" Extract the largest connected component from a graph. Inputs: - graph: An adjacency m... |
# Get a networkx graph.
nx_graph = nx.from_scipy_sparse_matrix(graph, create_using=nx.DiGraph())
# Calculate all connected components in graph.
if connectivity_type == "weak":
largest_connected_component_list = nxalgcom.weakly_connected_component_subgraphs(nx_graph)
elif connectivity_type ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendEmail(self, subject, body, toAddress=False):
""" sends an email using the agrcpythonemailer@gmail.com account """ |
if not toAddress:
toAddress = self.toAddress
toAddress = toAddress.split(';')
message = MIMEText(body)
message['Subject'] = subject
message['From'] = self.fromAddress
message['To'] = ','.join(toAddress)
if not self.testing:
s = SMTP(sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_completions(self):
"""Return a list of possible completions for the string ending at the point.
Also set begidx and endidx in the process.""" |
completions = []
self.begidx = self.l_buffer.point
self.endidx = self.l_buffer.point
buf=self.l_buffer.line_buffer
if self.completer:
# get the string to complete
while self.begidx > 0:
self.begidx -= 1
if buf[self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complete(self, e):
# (TAB)
u"""Attempt to perform completion on the text before point. The
actual completion performed is application-specific. The default... |
completions = self._get_completions()
if completions:
cprefix = commonprefix(completions)
if len(cprefix) > 0:
rep = [ c for c in cprefix ]
point=self.l_buffer.point
self.l_buffer[self.begidx:self.endidx] = rep
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def possible_completions(self, e):
# (M-?)
u"""List the possible completions of the text before point. """ |
completions = self._get_completions()
self._display_completions(completions)
self.finalize() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_completions(self, e):
# (M-*)
u"""Insert all completions of the text before point that would have
been generated by possible-completions.""" |
completions = self._get_completions()
b = self.begidx
e = self.endidx
for comp in completions:
rep = [ c for c in comp ]
rep.append(' ')
self.l_buffer[b:e] = rep
b += len(rep)
e = b
self.line_cursor = b
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_text(self, string):
u"""Insert text into the command line.""" |
self.l_buffer.insert_text(string, self.argument_reset)
self.finalize() |
<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_char(self, e):
# (C-d)
u"""Delete the character at point. If point is at the beginning of
the line, there are no characters in the line, and the las... |
self.l_buffer.delete_char(self.argument_reset)
self.finalize() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
u"""Insert yourself. """ |
if e.char and ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys.
self.insert_text(e.char)
self.finalize() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paste(self,e):
u"""Paste windows clipboard.
Assume single line strip other lines and end of line markers and trailing spaces""" | #(Control-v)
if self.enable_win32_clipboard:
txt=clipboard.get_clipboard_text_and_convert(False)
txt=txt.split("\n")[0].strip("\r").strip("\n")
log("paste: >%s<"%map(ord,txt))
self.insert_text(txt)
self.finalize() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_functions(self, e):
# ()
u"""Print all of the functions and their key bindings to the Readline
output stream. If a numeric argument is supplied, the o... |
print
txt="\n".join(self.rl_settings_to_string())
print txt
self._print_prompt()
self.finalize() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit(self, X, y=None):
"""Calls the ctmc.ctmc function Parameters X : list of lists (see ctmc function 'data') y not used, present for API consistence purpose... |
self.transmat, self.genmat, self.transcount, self.statetime = ctmc(
X, self.numstates, self.transintv, self.toltime, self.debug)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RV_1(self):
"""Instantaneous RV of star 1 with respect to system center-of-mass """ |
return self.orbpop_long.RV * (self.orbpop_long.M2 / (self.orbpop_long.M1 + self.orbpop_long.M2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RV_2(self):
"""Instantaneous RV of star 2 with respect to system center-of-mass """ |
return -self.orbpop_long.RV * (self.orbpop_long.M1 /
(self.orbpop_long.M1 + self.orbpop_long.M2)) +\
self.orbpop_short.RV_com1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RV_3(self):
"""Instantaneous RV of star 3 with respect to system center-of-mass """ |
return -self.orbpop_long.RV * (self.orbpop_long.M1 / (self.orbpop_long.M1 + self.orbpop_long.M2)) +\
self.orbpop_short.RV_com2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_hdf(self,filename,path=''):
"""Save to .h5 file. """ |
self.orbpop_long.save_hdf(filename,'{}/long'.format(path))
self.orbpop_short.save_hdf(filename,'{}/short'.format(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 Rsky(self):
"""Projected sky separation of stars """ |
return np.sqrt(self.position.x**2 + self.position.y**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 RV_com1(self):
"""RVs of star 1 relative to center-of-mass """ |
return self.RV * (self.M2 / (self.M1 + self.M2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RV_com2(self):
"""RVs of star 2 relative to center-of-mass """ |
return -self.RV * (self.M1 / (self.M1 + self.M2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_hdf(self,filename,path=''):
"""Saves all relevant data to .h5 file; so state can be restored. """ |
self.dataframe.to_hdf(filename,'{}/df'.format(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 add_pii_permissions(self, group, view_only=None):
"""Adds PII model permissions. """ |
pii_model_names = [m.split(".")[1] for m in self.pii_models]
if view_only:
permissions = Permission.objects.filter(
(Q(codename__startswith="view") | Q(codename__startswith="display")),
content_type__model__in=pii_model_names,
)
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 get_attribute_cardinality(attribute):
""" Returns the cardinality of the given resource attribute. :returns: One of the constants defined in :class:`evererst... |
if attribute.kind == RESOURCE_ATTRIBUTE_KINDS.MEMBER:
card = CARDINALITY_CONSTANTS.ONE
elif attribute.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION:
card = CARDINALITY_CONSTANTS.MANY
else:
raise ValueError('Can not determine cardinality for non-terminal '
'att... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(path_config="~/.config/scalar/config.yaml", configuration_name=None):
""" Load a configuration from a default or specified configuration file, accessin... |
global config
global client
global token
global room
# config file
path_config = Path(path_config).expanduser()
log.debug("load config {path}".format(path = path_config))
if not path_config.exists():
log.error("no config {path} found".format(path = path_config))
sys.exit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def worker_wrapper(worker_instance, pid_path):
""" A wrapper to start RQ worker as a new process. :param worker_instance: RQ's worker instance :param pid_path: A... |
def exit_handler(*args):
"""
Remove pid file on exit
"""
if len(args) > 0:
print("Exit py signal {signal}".format(signal=args[0]))
remove(pid_path)
atexit.register(exit_handler)
signal.signal(signal.SIGINT, exit_handler)
signal.signal(signal.SIGTERM,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collection(self):
"""Return the redis-collection instance.""" |
if not self.include_collections:
return None
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, 'redislite_collection'):
ctx.redislite_collection = Collection(redis=self.connection)
return ctx.redislite_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 queue(self):
"""The queue property. Return rq.Queue instance.""" |
if not self.include_rq:
return None
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, 'redislite_queue'):
ctx.redislite_queue = {}
for queue_name in self.queues:
ctx.redislite_queue[queue_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 start_worker(self):
"""Trigger new process as a RQ worker.""" |
if not self.include_rq:
return None
worker = Worker(queues=self.queues,
connection=self.connection)
worker_pid_path = current_app.config.get(
"{}_WORKER_PID".format(self.config_prefix), 'rl_worker.pid'
)
try:
worker_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def image_save_buffer_fix(maxblock=1048576):
""" Contextmanager that change MAXBLOCK in ImageFile. """ |
before = ImageFile.MAXBLOCK
ImageFile.MAXBLOCK = maxblock
try:
yield
finally:
ImageFile.MAXBLOCK = before |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upgrade_many(upgrade=True, create_examples_all=True):
"""upgrade many libs. source: http://arduino.cc/playground/Main/LibraryList you can set your arduino pa... |
urls = set()
def inst(url):
print('upgrading %s' % url)
assert url not in urls
urls.add(url)
try:
lib = install_lib(url, upgrade)
print(' -> %s' % lib)
except Exception as e:
print(e)
############################
# github.com... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confirm(self, batch_id=None, filename=None):
"""Flags the batch as confirmed by updating confirmation_datetime on the history model for this batch. """ |
if batch_id or filename:
export_history = self.history_model.objects.using(self.using).filter(
Q(batch_id=batch_id) | Q(filename=filename),
sent=True,
confirmation_code__isnull=True,
)
else:
export_history = self.histor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_single_word(word, lemmatizing="wordnet"):
""" Performs stemming or lemmatizing on a single word. If we are to search for a word in a clean bag-of-words... |
if lemmatizing == "porter":
porter = PorterStemmer()
lemma = porter.stem(word)
elif lemmatizing == "snowball":
snowball = SnowballStemmer('english')
lemma = snowball.stem(word)
elif lemmatizing == "wordnet":
wordnet = WordNetLemmatizer()
lemma = wordnet.lemma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_document(document, sent_tokenize, _treebank_word_tokenize, tagger, lemmatizer, lemmatize, stopset, first_cap_re, all_cap_re, digits_punctuation_whitespa... |
####################################################################################################################
# Tokenizing text
####################################################################################################################
# start_time = time.perf_counter()
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_corpus_serial(corpus, lemmatizing="wordnet"):
""" Extracts a bag-of-words from each document in a corpus serially. Inputs: - corpus: A python list of p... |
list_of_bags_of_words = list()
append_bag_of_words = list_of_bags_of_words.append
lemma_to_keywordbag_total = defaultdict(lambda: defaultdict(int))
for document in corpus:
word_list, lemma_to_keywordbag = clean_document(document=document, lemmatizing=lemmatizing) # TODO: Alter this.
... |
<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_bag_of_words_from_corpus_parallel(corpus, lemmatizing="wordnet"):
""" This extracts one bag-of-words from a list of strings. The documents are mapped... |
####################################################################################################################
# Map and reduce document cleaning.
####################################################################################################################
# Build a pool of processes.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def middleware(func):
""" Executes routes.py route middleware """ |
@wraps(func)
def parse(*args, **kwargs):
""" get middleware from route, execute middleware in order """
middleware = copy.deepcopy(kwargs['middleware'])
kwargs.pop('middleware')
if request.method == "OPTIONS":
# return 200 json response for CORS
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 progress_bar_media():
""" progress_bar_media simple tag return rendered script tag for javascript used by progress_bar """ |
if PROGRESSBARUPLOAD_INCLUDE_JQUERY:
js = ["http://code.jquery.com/jquery-1.8.3.min.js",]
else:
js = []
js.append("js/progress_bar.js")
m = Media(js=js)
return m.render() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(MESSAGE, SOCKET, MESSAGE_ID=None, CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None, **kwargs):
r"""Send a message to the journal. Value of the MESSAGE arg... |
args = ['MESSAGE=' + MESSAGE]
if MESSAGE_ID is not None:
id = getattr(MESSAGE_ID, 'hex', MESSAGE_ID)
args.append('MESSAGE_ID=' + id)
if CODE_LINE == CODE_FILE == CODE_FUNC == None:
CODE_FILE, CODE_LINE, CODE_FUNC = \
_traceback.extract_stack(limit=2)[0][:3]
if COD... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self):
""" Checks if item already exists in database """ |
self_object = self.query.filter_by(id=self.id).first()
if self_object is None:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" Easy delete for db models """ |
try:
if self.exists() is False:
return None
self.db.session.delete(self)
self.db.session.commit()
except (Exception, BaseException) as error:
# fail silently
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 row_to_dict(self, row):
""" Converts a raw GCVS record to a dictionary of star data. """ |
constellation = self.parse_constellation(row[0])
name = self.parse_name(row[1])
ra, dec = self.parse_coordinates(row[2])
variable_type = row[3].strip()
max_magnitude, symbol = self.parse_magnitude(row[4])
min_magnitude, symbol = self.parse_magnitude(row[5])
if sy... |
<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_magnitude(self, magnitude_str):
""" Converts magnitude field to a float value, or ``None`` if GCVS does not list the magnitude. Returns a tuple (magnit... |
symbol = magnitude_str[0].strip()
magnitude = magnitude_str[1:6].strip()
return float(magnitude) if magnitude else None, symbol |
<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_period(self, period_str):
""" Converts period field to a float value or ``None`` if there is no period in GCVS record. """ |
period = period_str.translate(TRANSLATION_MAP)[3:14].strip()
return float(period) if period else None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_hwpack_dir(root):
"""search for hwpack dir under root.""" |
root = path(root)
log.debug('files in dir: %s', root)
for x in root.walkfiles():
log.debug(' %s', x)
hwpack_dir = None
for h in (root.walkfiles('boards.txt')):
assert not hwpack_dir
hwpack_dir = h.parent
log.debug('found hwpack: %s', hwpack_dir)
assert hwpack_... |
<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_hwpack(url, replace_existing=False):
"""install hwpackrary from web or local files system. :param url: web address or file path :param replace_existi... |
d = tmpdir(tmpdir())
f = download(url)
Archive(f).extractall(d)
clean_dir(d)
src_dhwpack = find_hwpack_dir(d)
targ_dhwpack = hwpack_dir() / src_dhwpack.name
doaction = 0
if targ_dhwpack.exists():
log.debug('hwpack already exists: %s', targ_dhwpack)
if 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 create(self, volume_id, vtype, size, affinity):
""" create a volume """ |
volume_id = volume_id or str(uuid.uuid4())
params = {'volume_type_name': vtype,
'size': size,
'affinity': affinity}
return self.http_put('/volumes/%s' % volume_id,
params=self.unused(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 restore(self, volume_id, **kwargs):
""" restore a volume from a backup """ |
# These arguments are required
self.required('create', kwargs, ['backup', 'size'])
# Optional Arguments
volume_id = volume_id or str(uuid.uuid4())
kwargs['volume_type_name'] = kwargs['volume_type_name'] or 'vtype'
kwargs['size'] = kwargs['size'] or 1
# Make the 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 create(self, volume_id, backup_id):
""" create a backup """ |
backup_id = backup_id or str(uuid.uuid4())
return self.http_put('/backups/%s' % backup_id,
params={'volume': volume_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 delete(self, volume_id, force=False):
""" delete an export """ |
return self.http_delete('/volumes/%s/export'
% volume_id, params={'force': force}) |
<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(self, volume_id, **kwargs):
""" update an export """ |
# These arguments are allowed
self.allowed('update', kwargs,
['status', 'instance_id',
'mountpoint', 'ip', 'initiator', 'session_ip',
'session_initiator'])
# Remove parameters that are None
params = self.unused(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 proto_refactor(proto_filename, namespace, namespace_path):
"""This method refactors a Protobuf file to import from a namespace that will map to the desired p... |
with open(proto_filename) as f:
data = f.read()
if not re.search('syntax = "proto2"', data):
insert_syntax = 'syntax = "proto2";\n'
data = insert_syntax + data
substitution = 'import "{}/\\1";'.format(namespace_path)
data = re.sub('import\s+"([^"]+\.proto)"\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 proto_refactor_files(dest_dir, namespace, namespace_path):
"""This method runs the refactoring on all the Protobuf files in the Dropsonde repo. Args: dest_di... |
for dn, dns, fns in os.walk(dest_dir):
for fn in fns:
fn = os.path.join(dn, fn)
if fnmatch.fnmatch(fn, '*.proto'):
data = proto_refactor(fn, namespace, namespace_path)
with open(fn, 'w') as f:
f.write(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 clone_source_dir(source_dir, dest_dir):
"""Copies the source Protobuf files into a build directory. Args: source_dir (str):
source directory of the Protobuf... |
if os.path.isdir(dest_dir):
print('removing', dest_dir)
shutil.rmtree(dest_dir)
shutil.copytree(source_dir, dest_dir) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def are_budget_data_package_fields_filled_in(self, resource):
""" Check if the budget data package fields are all filled in because if not then this can't be a b... |
fields = ['country', 'currency', 'year', 'status']
return all([self.in_resource(f, resource) for f in fields]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_budget_data_package(self, resource):
""" Try to grab a budget data package schema from the resource. The schema only allows fields which are defined... |
# Return if the budget data package fields have not been filled in
if not self.are_budget_data_package_fields_filled_in(resource):
return
try:
resource['schema'] = self.data.schema
except exceptions.NotABudgetDataPackageException:
log.debug('Resourc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def before_update(self, context, current, resource):
""" If the resource has changed we try to generate a budget data package, but if it hasn't then we don't do ... |
# Return if the budget data package fields have not been filled in
if not self.are_budget_data_package_fields_filled_in(resource):
return
if resource.get('upload', '') == '':
# If it isn't an upload we check if it's the same url
if current['url'] == resourc... |
<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_directory_contents(input_dict, environment_dict):
"""This function serves to upload every file in a user-supplied source directory to all of the vesse... |
# Check user input and seash state:
# 1, Make sure there is an active user key.
if environment_dict["currentkeyname"] is None:
raise seash_exceptions.UserError("""Error: Please set an identity before using 'uploaddir'!
Example:
!> loadkeys your_user_name
!> as your_user_name
your_user_name@ !>
""")
# 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 __load_file(self, key_list) -> str:
""" Load a translator file """ |
file = str(key_list[0]) + self.extension
key_list.pop(0)
file_path = os.path.join(self.path, file)
if os.path.exists(file_path):
return Json.from_file(file_path)
else:
raise FileNotFoundError(file_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 remove_programmer(programmer_id):
"""remove programmer. :param programmer_id: programmer id (e.g. 'avrisp') :rtype: None """ |
log.debug('remove %s', programmer_id)
lines = programmers_txt().lines()
lines = filter(
lambda x: not x.strip().startswith(programmer_id + '.'), lines)
programmers_txt().write_lines(lines) |
<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, entity_class, entity):
""" Load the given repository entity into the session and return a clone. If it was already loaded before, look up the load... |
if self.__needs_flushing:
self.flush()
if entity.id is None:
raise ValueError('Can not load entity without an ID.')
cache = self.__get_cache(entity_class)
sess_ent = cache.get_by_id(entity.id)
if sess_ent is None:
if self.__clone_on_load:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def onStart(self, event):
""" Display the environment of a started container """ |
c = event.container
print '+' * 5, 'started:', c
kv = lambda s: s.split('=', 1)
env = {k: v for (k, v) in (kv(s) for s in c.attrs['Config']['Env'])}
print env |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _identifier_data(self):
"""Return a unique identifier for the folder data""" |
# Use only file names
data = [ff.name for ff in self.files]
data.sort()
# also use the folder name
data.append(self.path.name)
# add meta data
data += self._identifier_meta()
return hash_obj(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 _search_files(path):
"""Search a folder for data files .. versionchanged:: 0.6.0 `path` is not searched recursively anymore """ |
path = pathlib.Path(path)
fifo = []
for fp in path.glob("*"):
if fp.is_dir():
continue
for fmt in formats:
# series data is not supported in SeriesFolder
if not fmt.is_series and fmt.verify(fp):
fifo.ap... |
<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_identifier(self, idx):
"""Return an identifier for the data at index `idx` .. versionchanged:: 0.4.2 indexing starts at 1 instead of 0 """ |
name = self._get_cropped_file_names()[idx]
return "{}:{}:{}".format(self.identifier, name, idx + 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 verify(path):
"""Verify folder file format The folder file format is only valid when there is only one file format present. """ |
valid = True
fifo = SeriesFolder._search_files(path)
# dataset size
if len(fifo) == 0:
valid = False
# number of different file formats
fifmts = [ff[1] for ff in fifo]
if len(set(fifmts)) != 1:
valid = False
return valid |
<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_file(path):
'''Load a txt data file'''
path = pathlib.Path(path)
data = path.open().readlines()
# remove comments and empty lines
data = [l for l in data if len(l.strip()) and not l.startswith("#")]
# determine data shape
n = len(data)
m = len(data[0].strip().split())
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 emit(self, record):
"""Write record as journal event. MESSAGE is taken from the message provided by the user, and PRIORITY, LOGGER, THREAD_NAME, CODE_{FILE,L... |
if record.args and isinstance(record.args, collections.Mapping):
extra = dict(self._extra, **record.args) # Merge metadata from handler and record
else:
extra = self._extra
try:
msg = self.format(record)
pri = self.mapPriority(record.levelno)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mapPriority(levelno):
"""Map logging levels to journald priorities. Since Python log level numbers are "sparse", we have to map numbers in between the standa... |
if levelno <= _logging.DEBUG:
return LOG_DEBUG
elif levelno <= _logging.INFO:
return LOG_INFO
elif levelno <= _logging.WARNING:
return LOG_WARNING
elif levelno <= _logging.ERROR:
return LOG_ERR
elif levelno <= _logging.CRITICAL:
... |
<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_args(self, func):
""" Get the arguments of a method and return it as a dictionary with the supplied defaults, method arguments with no default are assign... |
def reverse(iterable):
if iterable:
iterable = list(iterable)
while len(iterable):
yield iterable.pop()
args, varargs, varkw, defaults = inspect.getargspec(func)
result = {}
for default in reverse(defaults):
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def guess_format(path):
"""Determine the file format of a folder or a file""" |
for fmt in formats:
if fmt.verify(path):
return fmt.__name__
else:
msg = "Undefined file format: '{}'".format(path)
raise UnknownFileFormatError(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 load_data(path, fmt=None, bg_data=None, bg_fmt=None, meta_data={}, holo_kw={}, as_type="float32"):
"""Load experimental data Parameters path: str Path to exp... |
path = pathlib.Path(path).resolve()
# sanity checks
for kk in meta_data:
if kk not in qpimage.meta.DATA_KEYS:
msg = "Meta data key not allowed: {}".format(kk)
raise ValueError(msg)
# ignore None or nan values in meta_data
for kk in list(meta_data.keys()):
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def duration(seconds):
"""Return a string of the form "1 hr 2 min 3 sec" representing the given number of seconds.""" |
if seconds < 1:
return 'less than 1 sec'
seconds = int(round(seconds))
components = []
for magnitude, label in ((3600, 'hr'), (60, 'min'), (1, 'sec')):
if seconds >= magnitude:
components.append('{} {}'.format(seconds // magnitude, label))
seconds %= magnitude
... |
<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_shortcut_prefix(self, user_agent, standart_prefix):
""" Returns the shortcut prefix of browser. :param user_agent: The user agent of browser. :type user... |
# pylint: disable=no-self-use
if user_agent is not None:
user_agent = user_agent.lower()
opera = 'opera' in user_agent
mac = 'mac' in user_agent
konqueror = 'konqueror' in user_agent
spoofer = 'spoofer' in user_agent
safari = 'app... |
<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_role_description(self, role):
""" Returns the description of role. :param role: The role. :type role: str :return: The description of role. :rtype: str ... |
parameter = 'role-' + role.lower()
if self.configure.has_parameter(parameter):
return self.configure.get_parameter(parameter)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_language_description(self, language_code):
""" Returns the description of language. :param language_code: The BCP 47 code language. :type language_code:... |
language = language_code.lower()
parameter = 'language-' + language
if self.configure.has_parameter(parameter):
return self.configure.get_parameter(parameter)
elif '-' in language:
codes = re.split(r'\-', language)
parameter = 'language-' + codes[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_description(self, element):
""" Returns the description of element. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDO... |
description = None
if element.has_attribute('title'):
description = element.get_attribute('title')
elif element.has_attribute('aria-label'):
description = element.get_attribute('aria-label')
elif element.has_attribute('alt'):
description = element.ge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_list_shortcuts(self):
""" Generate the list of shortcuts of page. """ |
id_container_shortcuts_before = (
AccessibleDisplayImplementation.ID_CONTAINER_SHORTCUTS_BEFORE
)
id_container_shortcuts_after = (
AccessibleDisplayImplementation.ID_CONTAINER_SHORTCUTS_AFTER
)
local = self.parser.find('body').first_result()
if 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 _insert(self, element, new_element, before):
""" Insert a element before or after other element. :param element: The reference element. :type element: hatemi... |
tag_name = element.get_tag_name()
append_tags = [
'BODY',
'A',
'FIGCAPTION',
'LI',
'DT',
'DD',
'LABEL',
'OPTION',
'TD',
'TH'
]
controls = ['INPUT', 'SELECT', 'TEXTARE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _force_read_simple(self, element, text_before, text_after, data_of):
""" Force the screen reader display an information of element. :param element: The refer... |
self.id_generator.generate_id(element)
identifier = element.get_attribute('id')
selector = '[' + data_of + '="' + identifier + '"]'
reference_before = self.parser.find(
'.'
+ AccessibleDisplayImplementation.CLASS_FORCE_READ_BEFORE
+ selector
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _force_read( self, element, value, text_prefix_before, text_suffix_before, text_prefix_after, text_suffix_after, data_of ):
""" Force the screen reader displ... |
if (text_prefix_before) or (text_suffix_before):
text_before = text_prefix_before + value + text_suffix_before
else:
text_before = ''
if (text_prefix_after) or (text_suffix_after):
text_after = text_prefix_after + value + text_suffix_after
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 provider(func=None, *, singleton=False, injector=None):
""" Decorator to mark a function as a provider. Args: singleton (bool):
The returned value should be... |
def decorator(func):
wrapped = _wrap_provider_func(func, {'singleton': singleton})
if injector:
injector.register_provider(wrapped)
return wrapped
if func:
return decorator(func)
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inject(*args, **kwargs):
""" Mark a class or function for injection, meaning that a DI container knows that it should inject dependencies into it. Normally y... |
def wrapper(obj):
if inspect.isclass(obj) or callable(obj):
_inject_object(obj, *args, **kwargs)
return obj
raise DiayException("Don't know how to inject into %r" % obj)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_plugin(self, plugin: Plugin):
""" Register a plugin. """ |
if isinstance(plugin, Plugin):
lazy = False
elif issubclass(plugin, Plugin):
lazy = True
else:
msg = 'plugin %r must be an object/class of type Plugin' % plugin
raise DiayException(msg)
predicate = inspect.isfunction if lazy else inspect.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_provider(self, func):
""" Register a provider function. """ |
if 'provides' not in getattr(func, '__di__', {}):
raise DiayException('function %r is not a provider' % func)
self.factories[func.__di__['provides']] = func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_lazy_provider_method(self, cls, method):
""" Register a class method lazily as a provider. """ |
if 'provides' not in getattr(method, '__di__', {}):
raise DiayException('method %r is not a provider' % method)
@functools.wraps(method)
def wrapper(*args, **kwargs):
return getattr(self.get(cls), method.__name__)(*args, **kwargs)
self.factories[method.__di__['... |
<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_factory(self, thing: type, value, overwrite=False):
""" Set the factory for something. """ |
if thing in self.factories and not overwrite:
raise DiayException('factory for %r already exists' % thing)
self.factories[thing] = 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_instance(self, thing: type, value, overwrite=False):
""" Set an instance of a thing. """ |
if thing in self.instances and not overwrite:
raise DiayException('instance for %r already exists' % thing)
self.instances[thing] = 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(self, thing: type):
""" Get an instance of some type. """ |
if thing in self.instances:
return self.instances[thing]
if thing in self.factories:
fact = self.factories[thing]
ret = self.get(fact)
if hasattr(fact, '__di__') and fact.__di__['singleton']:
self.instances[thing] = ret
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.