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 restoreWCS(self,prepend=None):
""" Resets the WCS values to the original values stored in the backup keywords recorded in self.backup. """ |
# Open header for image
image = self.rootname
if prepend: _prepend = prepend
elif self.prepend: _prepend = self.prepend
else: _prepend = None
# Open image as writable FITS object
fimg = fileutil.openImage(image, mode='update')
# extract the extension 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 createReferenceWCS(self,refname,overwrite=yes):
""" Write out the values of the WCS keywords to the NEW specified image 'fitsname'. """ |
hdu = self.createWcsHDU()
# If refname already exists, delete it to make way for new file
if os.path.exists(refname):
if overwrite==yes:
# Remove previous version and re-create with new header
os.remove(refname)
hdu.writeto(refname)
... |
<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_jd(year, month, day, method=None):
'''Obtain Julian day from a given French Revolutionary calendar date.'''
method = method or 'equinox'
if day < 1 or day > 30:
raise ValueError("Invalid day for this calendar")
if month > 13:
raise ValueError("Invalid month for this calendar")
... |
<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_jd_schematic(year, month, day, method):
'''Calculate JD using various leap-year calculation methods'''
y0, y1, y2, y3, y4, y5 = 0, 0, 0, 0, 0, 0
intercal_cycle_yrs, over_cycle_yrs, leap_suppression_yrs = None, None, None
# Use the every-four-years method below year 16 (madler) or below 15 (ro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def from_jd(jd, method=None):
'''Calculate date in the French Revolutionary
calendar from Julian day. The five or six
"sansculottides" are considered a thirteenth
month in the results of this function.'''
method = method or 'equinox'
if method == 'equinox':
return _from_jd_equinox(jd)
... |
<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_jd_schematic(jd, method):
'''Convert from JD using various leap-year calculation methods'''
if jd < EPOCH:
raise ValueError("Can't convert days before the French Revolution")
# days since Epoch
J = trunc(jd) + 0.5 - EPOCH
y0, y1, y2, y3, y4, y5 = 0, 0, 0, 0, 0, 0
intercal_cyc... |
<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_jd_equinox(jd):
'''Calculate the FR day using the equinox as day 1'''
jd = trunc(jd) + 0.5
equinoxe = premier_da_la_annee(jd)
an = gregorian.from_jd(equinoxe)[0] - YEAR_EPOCH
mois = trunc((jd - equinoxe) / 30.) + 1
jour = int((jd - equinoxe) % 30) + 1
return (an, mois, jour) |
<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_jd(year, month, day):
'''Obtain Julian day for Indian Civil date'''
gyear = year + 78
leap = isleap(gyear)
# // Is this a leap year ?
# 22 - leap = 21 if leap, 22 non-leap
start = gregorian.to_jd(gyear, 3, 22 - leap)
if leap:
Caitra = 31
else:
Caitra = 30
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 from_jd(jd):
'''Calculate Indian Civil date from Julian day
Offset in years from Saka era to Gregorian epoch'''
start = 80
# Day offset between Saka and Gregorian
jd = trunc(jd) + 0.5
greg = gregorian.from_jd(jd) # Gregorian date for Julian day
leap = isleap(greg[0]) # Is this a leap... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_stack(skip=0, length=6, _sep=os.path.sep):
""" Returns a one-line string with the current callstack. """ |
return ' < '.join("%s:%s:%s" % (
'/'.join(f.f_code.co_filename.split(_sep)[-2:]),
f.f_lineno,
f.f_code.co_name
) for f in islice(frame_iterator(sys._getframe(1 + skip)), length)) |
<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, deviceId):
""" lists all known active measurements. """ |
measurementsByName = self.measurements.get(deviceId)
if measurementsByName is None:
return []
else:
return list(measurementsByName.values()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, deviceId, measurementId):
""" details the specific measurement. """ |
record = self.measurements.get(deviceId)
if record is not None:
return record.get(measurementId)
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 clicked(self):
""" Called when this button is clicked. Execute code from .cfgspc """ |
try:
from . import teal
except:
teal = None
try:
# start drilling down into the tpo to get the code
tealGui = self._mainGuiObj
tealGui.showStatus('Clicked "'+self.getButtonLabel()+'"', keep=1)
pscope = self.paramInfo.scope
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tobytes(s, encoding='ascii'):
""" Convert string s to the 'bytes' type, in all Pythons, even back before Python 2.6. What 'str' means varies by PY3K or not. ... |
# NOTE: after we abandon 2.5, we might simply instead use "bytes(s)"
# NOTE: after we abandon all 2.*, del this and prepend byte strings with 'b'
if PY3K:
if isinstance(s, bytes):
return s
else:
return s.encode(encoding)
else:
# for py2.6 on (before 3.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 tostr(s, encoding='ascii'):
""" Convert string-like-thing s to the 'str' type, in all Pythons, even back before Python 2.6. What 'str' means varies by PY3K o... |
if PY3K:
if isinstance(s, str): # str == unicode in PY3K
return s
else: # s is type bytes
return s.decode(encoding)
else:
# for py2.6 on (before 3.0), bytes is same as str; 2.5 has no bytes
# but handle if unicode is passed
if isinstance(s, unico... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retry(func=None, retries=5, backoff=None, exceptions=(IOError, OSError, EOFError), cleanup=None, sleep=time.sleep):
""" Decorator that retries the call ``ret... |
@Aspect(bind=True)
def retry_aspect(cutpoint, *args, **kwargs):
for count in range(retries + 1):
try:
if count and cleanup:
cleanup(*args, **kwargs)
yield
break
except exceptions as exc:
if coun... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eparOptionFactory(master, statusBar, param, defaultParam, doScroll, fieldWidths, plugIn=None, editedCallbackObj=None, helpCallbackObj=None, mainGuiObj=None, d... |
# Allow passed-in overrides
if plugIn is not None:
eparOption = plugIn
# If there is an enumerated list, regardless of datatype use EnumEparOption
elif param.choice is not None:
eparOption = EnumEparOption
else:
# Use String for types not in the dictionary
eparOpt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def popupChoices(self, event=None):
"""Popup right-click menu of special parameter operations Relies on browserEnabled, clearEnabled, unlearnEnabled, helpEnabled... |
# don't bother if all items are disabled
if NORMAL not in (self.browserEnabled, self.clearEnabled,
self.unlearnEnabled, self.helpEnabled):
return
self.menu = Menu(self.entry, tearoff = 0)
if self.browserEnabled != DISABLED:
# Handle fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fileBrowser(self):
"""Invoke a tkinter file dialog""" |
if capable.OF_TKFD_IN_EPAR:
fname = askopenfilename(parent=self.entry, title="Select File")
else:
from . import filedlg
self.fd = filedlg.PersistLoadFileDialog(self.entry,
"Select File", "*")
if self.fd.Show() != 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 dirBrowser(self):
"""Invoke a tkinter directory dialog""" |
if capable.OF_TKFD_IN_EPAR:
fname = askdirectory(parent=self.entry, title="Select Directory")
else:
raise NotImplementedError('Fix popupChoices() logic.')
if not fname:
return # canceled
self.choice.set(fname)
# don't select when we go back ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forceValue(self, newVal, noteEdited=False):
"""Force-set a parameter entry to the given value""" |
if newVal is None:
newVal = ""
self.choice.set(newVal)
if noteEdited:
self.widgetEdited(val=newVal, skipDups=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 unlearnValue(self):
"""Unlearn a parameter value by setting it back to its default""" |
defaultValue = self.defaultParamInfo.get(field = "p_filename",
native = 0, prompt = 0)
self.choice.set(defaultValue) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keypress(self, event):
"""Allow keys typed in widget to select items""" |
try:
self.choice.set(self.shortcuts[event.keysym])
except KeyError:
# key not found (probably a bug, since we intend to catch
# only events from shortcut keys, but ignore it anyway)
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def postcmd(self):
"""Make sure proper entry is activated when menu is posted""" |
value = self.choice.get()
try:
index = self.paramInfo.choice.index(value)
self.entry.menu.activate(index)
except ValueError:
# initial null value may not be in list
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convertToNative(self, aVal):
""" Convert to native bool; interpret certain strings. """ |
if aVal is None:
return None
if isinstance(aVal, bool): return aVal
# otherwise interpret strings
return str(aVal).lower() in ('1','on','yes','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 toggle(self, event=None):
"""Toggle value between Yes and No""" |
if self.choice.get() == "yes":
self.rbno.select()
else:
self.rbyes.select()
self.widgetEdited() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def entryCheck(self, event = None, repair = True):
""" Ensure any INDEF entry is uppercase, before base class behavior """ |
valupr = self.choice.get().upper()
if valupr.strip() == 'INDEF':
self.choice.set(valupr)
return EparOption.entryCheck(self, event, repair = repair) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setSampleSizeBytes(self):
""" updates the current record of the packet size per sample and the relationship between this and the fifo reads. """ |
self.sampleSizeBytes = self.getPacketSize()
if self.sampleSizeBytes > 0:
self.maxBytesPerFifoRead = (32 // self.sampleSizeBytes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def easter(year):
'''Calculate western easter'''
# formula taken from http://aa.usno.navy.mil/faq/docs/easter.html
c = trunc(year / 100)
n = year - 19 * trunc(year / 19)
k = trunc((c - 17) / 25)
i = c - trunc(c / 4) - trunc((c - k) / 3) + (19 * n) + 15
i = i - 30 * trunc(i / 30)
i = i ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(input, width=132, output=None, keep=False):
"""Input ASCII trailer file "input" will be read. The contents will then be written out to a FITS file in... |
# open input trailer file
trl = open(input)
# process all lines
lines = np.array([i for text in trl.readlines() for i in textwrap.wrap(text,width=width)])
# close ASCII trailer file now that we have processed all the lines
trl.close()
if output is None:
# create fits file
... |
<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_extra_values(conf, _prepend=()):
""" Find all the values and sections not in the configspec from a validated ConfigObj. ``get_extra_values`` returns a li... |
out = []
out.extend([(_prepend, name) for name in conf.extra_values])
for name in conf.sections:
if name not in conf.extra_values:
out.extend(get_extra_values(conf[name], _prepend + (name,)))
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fetch(self, key):
"""Helper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found. """ |
# switch off interpolation before we try and fetch anything !
save_interp = self.section.main.interpolation
self.section.main.interpolation = False
# Start at section that "owns" this InterpolationEngine
current_section = self.section
while True:
# try the c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dict(self):
""" Return a deepcopy of self as a dictionary. All members that are ``Section`` instances are recursively turned to ordinary dictionaries - by ca... |
newdict = {}
for entry in self:
this_entry = self[entry]
if isinstance(this_entry, Section):
this_entry = this_entry.dict()
elif isinstance(this_entry, list):
# create a copy rather than a reference
this_entry = list(th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(self, indict):
""" A recursive update - useful for merging config files. ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'Fa... |
for key, val in list(indict.items()):
if (key in self and isinstance(self[key], dict) and
isinstance(val, dict)):
self[key].merge(val)
else:
self[key] = 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 rename(self, oldkey, newkey):
""" Change a keyname to another, without changing position in sequence. Implemented so that transformations can be made on keys... |
if oldkey in self.scalars:
the_list = self.scalars
elif oldkey in self.sections:
the_list = self.sections
else:
raise KeyError('Key "%s" not found.' % oldkey)
pos = the_list.index(oldkey)
#
val = self[oldkey]
dict.__delitem__(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 walk(self, function, raise_errors=True, call_on_sections=False, **keywargs):
""" Walk every member and call a function on the keyword and value. Return a dic... |
out = {}
# scalars first
for i in range(len(self.scalars)):
entry = self.scalars[i]
try:
val = function(self, entry, **keywargs)
# bound again in case name has changed
entry = self.scalars[i]
out[entry] = va... |
<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_list(self, key):
""" A convenience method which fetches the specified value, guaranteeing that it is a list. [1] [1] [1] """ |
result = self[key]
if isinstance(result, (tuple, list)):
return list(result)
return [result] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_defaults(self):
""" Recursively restore default values to all members that have them. This method will only work for a ConfigObj that was created wit... |
for key in self.default_values:
self.restore_default(key)
for section in self.sections:
self[section].restore_defaults() |
<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_bom(self, infile):
""" Handle any BOM, and decode if necessary. If an encoding is specified, that *must* be used - but the BOM should still be remove... |
if ((self.encoding is not None) and
(self.encoding.lower() not in BOM_LIST)):
# No need to check for a BOM
# the encoding specified doesn't have one
# just decode
return self._decode(infile, self.encoding)
if isinstance(infile, (list, tuple))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode(self, infile, encoding):
""" Decode infile to unicode. Using the specified encoding. if is a string, it also needs converting to a list. """ |
if isinstance(infile, string_types):
# can't be unicode
# NOTE: Could raise a ``UnicodeDecodeError``
return infile.decode(encoding).splitlines(True)
for i, line in enumerate(infile):
# NOTE: The isinstance test here handles mixed lists of unicode/string
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode_element(self, line):
"""Decode element to unicode if necessary.""" |
if not self.encoding:
return line
if isinstance(line, str) and self.default_encoding:
return line.decode(self.default_encoding)
return line |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match_depth(self, sect, depth):
""" Given a section and a depth level, walk back through the sections parents to see if the depth level matches a previous s... |
while depth < sect.depth:
if sect is sect.parent:
# we've reached the top level already
raise SyntaxError()
sect = sect.parent
if sect.depth == depth:
return sect
# shouldn't get here
raise SyntaxError() |
<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_error(self, text, ErrorClass, infile, cur_index):
""" Handle an error according to the error settings. Either raise the error or store it. The error ... |
line = infile[cur_index]
cur_index += 1
message = text % cur_index
error = ErrorClass(message, cur_index, line)
if self.raise_errors:
# raise the error - parsing stops here
raise error
# store the error
# reraise when parsing has finished
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unquote(self, value):
"""Return an unquoted version of a value""" |
if not value:
# should only happen during parsing of lists
raise SyntaxError
if (value[0] == value[-1]) and (value[0] in ('"', "'")):
value = value[1:-1]
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _quote(self, value, multiline=True):
""" Return a safely quoted version of a value. Raise a ConfigObjError if the value cannot be safely quoted. If multiline... |
if multiline and self.write_empty_values and value == '':
# Only if multiline is set, so that it is used for values not
# keys, and not values that are part of a list
return ''
if multiline and isinstance(value, (list, tuple)):
if not 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 _multiline(self, value, infile, cur_index, maxline):
"""Extract the value, where we are in a multiline situation.""" |
quot = value[:3]
newvalue = value[3:]
single_line = self._triple_quote[quot][0]
multi_line = self._triple_quote[quot][1]
mat = single_line.match(value)
if mat is not None:
retval = list(mat.groups())
retval.append(cur_index)
return ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_configspec(self, configspec):
"""Parse the configspec.""" |
# FIXME: Should we check that the configspec was created with the
# correct settings ? (i.e. ``list_values=False``)
if not isinstance(configspec, ConfigObj):
try:
configspec = ConfigObj(configspec,
raise_errors=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 _write_line(self, indent_string, entry, this_entry, comment):
"""Write an individual line, for the write method""" |
# NOTE: the calls to self._quote here handles non-StringType values.
if not self.unrepr:
val = self._decode_element(self._quote(this_entry))
else:
val = repr(this_entry)
return '%s%s%s%s%s' % (indent_string,
self._decode_element(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 _write_marker(self, indent_string, depth, entry, comment):
"""Write a section marker line""" |
return '%s%s%s%s%s' % (indent_string,
self._a_to_u('[' * depth),
self._quote(self._decode_element(entry), multiline=False),
self._a_to_u(']' * depth),
self._decode_element(comment)) |
<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_comment(self, comment):
"""Deal with a comment.""" |
if not comment:
return ''
start = self.indent_type
if not comment.startswith('#'):
start += self._a_to_u(' # ')
return (start + comment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
"""Clear ConfigObj instance and restore to 'freshly created' state.""" |
self.clear()
self._initialise()
# FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
# requires an empty dictionary
self.configspec = None
# Just to be sure ;-)
self._original_configspec = 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 reload(self):
""" Reload a ConfigObj from file. This method raises a ``ReloadError`` if the ConfigObj doesn't have a filename attribute pointing to a file. "... |
if not isinstance(self.filename, string_types):
raise ReloadError()
filename = self.filename
current_options = {}
for entry in OPTION_DEFAULTS:
if entry == 'configspec':
continue
current_options[entry] = getattr(self, entry)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self, check, member, missing=False):
"""A dummy check method, always returns the value unchanged.""" |
if missing:
raise self.baseErrorClass()
return 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 _verify(waiveredHdul):
""" Verify that the input HDUList is for a waivered FITS file. Parameters: waiveredHdul HDUList object to be verified Returns: None Ex... |
if len(waiveredHdul) == 2:
#
# There must be exactly 2 HDU's
#
if waiveredHdul[0].header['NAXIS'] > 0:
#
# The Primary HDU must have some data
#
if isinstance(waiveredHdul[1], fits.TableHDU):
#
# The Al... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convertwaiveredfits(waiveredObject, outputFileName=None, forceFileOutput=False, convertTo='multiExtension', verbose=False):
""" Convert the input waivered FI... |
if convertTo == 'multiExtension':
func = toMultiExtensionFits
else:
raise ValueError('Conversion type ' + convertTo + ' unknown')
return func(*(waiveredObject,outputFileName,forceFileOutput,verbose)) |
<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_jd(year, month, day):
'''Determine Julian day from Persian date'''
if year >= 0:
y = 474
else:
y = 473
epbase = year - y
epyear = 474 + (epbase % 2820)
if month <= 7:
m = (month - 1) * 31
else:
m = (month - 1) * 30 + 6
return day + m + trunc(((ep... |
<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_jd(jd):
'''Calculate Persian date from Julian day'''
jd = trunc(jd) + 0.5
depoch = jd - to_jd(475, 1, 1)
cycle = trunc(depoch / 1029983)
cyear = (depoch % 1029983)
if cyear == 1029982:
ycycle = 2820
else:
aux1 = trunc(cyear / 366)
aux2 = cyear % 366
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def teardown_global_logging():
"""Disable global logging of stdio, warnings, and exceptions.""" |
global global_logging_started
if not global_logging_started:
return
stdout_logger = logging.getLogger(__name__ + '.stdout')
stderr_logger = logging.getLogger(__name__ + '.stderr')
if sys.stdout is stdout_logger:
sys.stdout = sys.stdout.stream
if sys.stderr is stderr_logger:
... |
<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_logger(name, format='%(levelname)s: %(message)s', datefmt=None, stream=None, level=logging.INFO, filename=None, filemode='w', filelevel=None, propagate... |
# Get a logger for the specified name
logger = logging.getLogger(name)
logger.setLevel(level)
fmt = logging.Formatter(format, datefmt)
logger.propagate = propagate
# Remove existing handlers, otherwise multiple handlers can accrue
for hdlr in logger.handlers:
logger.removeHandler(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _post_login_page(self, login_url):
"""Login to HydroQuebec website.""" |
data = {"login": self.username,
"_58_password": self.password}
try:
raw_res = yield from self._session.post(login_url,
data=data,
timeout=self._timeout,
... |
<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_p_p_id_and_contract(self):
"""Get id of consumption profile.""" |
contracts = {}
try:
raw_res = yield from self._session.get(PROFILE_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can not get profile page")
# Parse html
content = yield from raw_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 _get_lonely_contract(self):
"""Get contract number when we have only one contract.""" |
contracts = {}
try:
raw_res = yield from self._session.get(MAIN_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can not get main page")
# Parse html
content = yield from raw_res.text... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_balances(self):
"""Get all balances. .. todo:: IT SEEMS balances are shown (MAIN_URL) in the same order that contracts in profile page (PROFILE_URL). Ma... |
balances = []
try:
raw_res = yield from self._session.get(MAIN_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can not get main page")
# Parse html
content = yield from raw_res.text(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_contract_page(self, contract_url):
"""Load the profile page of a specific contract when we have multiple contracts.""" |
try:
yield from self._session.get(contract_url,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can not get profile page for a "
"specific contract") |
<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_annual_data(self, p_p_id):
"""Get annual data.""" |
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationAnnuelles"}
try:
raw_res = yield from self._session.get(PROFILE_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_monthly_data(self, p_p_id):
"""Get monthly data.""" |
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_resource_id": ("resourceObtenirDonnees"
"PeriodesConsommation")}
try:
raw_res = yield from self._session.get(PROFILE_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_hourly_data(self, day_date, p_p_id):
"""Get Hourly Data.""" |
params = {"p_p_id": p_p_id,
"p_p_lifecycle": 2,
"p_p_state": "normal",
"p_p_mode": "view",
"p_p_resource_id": "resourceObtenirDonneesConsommationHoraires",
"p_p_cacheability": "cacheLevelPage",
"p_p_col_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_data_detailled_energy_use(self, start_date=None, end_date=None):
"""Get detailled energy use from a specific contract.""" |
if start_date is None:
start_date = datetime.datetime.now(HQ_TIMEZONE) - datetime.timedelta(days=1)
if end_date is None:
end_date = datetime.datetime.now(HQ_TIMEZONE)
# Get http session
yield from self._get_httpsession()
# Get login page
login_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 fetch_data(self):
"""Get the latest data from HydroQuebec.""" |
# Get http session
yield from self._get_httpsession()
# Get login page
login_url = yield from self._get_login_page()
# Post login page
yield from self._post_login_page(login_url)
# Get p_p_id and contracts
p_p_id, contracts = yield from self._get_p_p_id_a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_data(self, contract=None):
"""Return collected data.""" |
if contract is None:
return self._data
if contract in self._data.keys():
return {contract: self._data[contract]}
raise PyHydroQuebecError("Contract {} not found".format(contract)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_argument(self, arg):
"""Validate a type or matcher argument to the constructor.""" |
if arg is None:
return arg
if isinstance(arg, type):
return InstanceOf(arg)
if not isinstance(arg, BaseMatcher):
raise TypeError(
"argument of %s can be a type or a matcher (got %r)" % (
self.__class__.__name__, type(arg))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _initialize(self, *args, **kwargs):
"""Initiaize the mapping matcher with constructor arguments.""" |
self.items = None
self.keys = None
self.values = None
if args:
if len(args) != 2:
raise TypeError("expected exactly two positional arguments, "
"got %s" % len(args))
if kwargs:
raise TypeError(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def docs(ctx, output='html', rebuild=False, show=True, verbose=True):
"""Build the docs and show them in default web browser.""" |
sphinx_build = ctx.run(
'sphinx-build -b {output} {all} {verbose} docs docs/_build'.format(
output=output,
all='-a -E' if rebuild else '',
verbose='-v' if verbose else ''))
if not sphinx_build.ok:
fatal("Failed to build the docs", cause=sphinx_build)
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 upload(ctx, yes=False):
"""Upload the package to PyPI.""" |
import callee
version = callee.__version__
# check the packages version
# TODO: add a 'release' to automatically bless a version as release one
if version.endswith('-dev'):
fatal("Can't upload a development version (%s) to PyPI!", version)
# run the upload if it has been confirmed by ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fatal(*args, **kwargs):
"""Log an error message and exit. Following arguments are keyword-only. :param exitcode: Optional exit code to use :param cause: Opti... |
# determine the exitcode to return to the operating system
exitcode = None
if 'exitcode' in kwargs:
exitcode = kwargs.pop('exitcode')
if 'cause' in kwargs:
cause = kwargs.pop('cause')
if not isinstance(cause, Result):
raise TypeError(
"invalid cause o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_request_parameters(func):
"""Adds the ratelimit and request timeout parameters to a function.""" |
# The function the decorator returns
async def decorated_func(*args, handle_ratelimit=None, max_tries=None, request_timeout=None, **kwargs):
return await func(*args, handle_ratelimit=handle_ratelimit, max_tries=max_tries,
request_timeout=request_timeout, **kwa... |
<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 _base_request(self, battle_tag: str, endpoint_name: str, session: aiohttp.ClientSession, *, platform=None, handle_ratelimit=None, max_tries=None, reques... |
# We check the different optional arguments, and if they're not passed (are none) we set them to the default for the client object
if platform is None:
platform = self.default_platform
if handle_ratelimit is None:
handle_ratelimit = self.default_handle_ratelimit
... |
<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_method(arg, min_arity=None, max_arity=None):
"""Check if argument is a method. Optionally, we can also check if minimum or maximum arities (number of acce... |
if not callable(arg):
return False
if not any(is_(arg) for is_ in (inspect.ismethod,
inspect.ismethoddescriptor,
inspect.isbuiltin)):
return False
try:
argnames, varargs, kwargs, defaults = getargspec(arg)
... |
<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_readable(self, obj):
"""Check if the argument is a readable file-like object.""" |
try:
read = getattr(obj, 'read')
except AttributeError:
return False
else:
return is_method(read, max_arity=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 _is_writable(self, obj):
"""Check if the argument is a writable file-like object.""" |
try:
write = getattr(obj, 'write')
except AttributeError:
return False
else:
return is_method(write, min_arity=1, max_arity=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 run(time: datetime, altkm: float, glat: Union[float, np.ndarray], glon: Union[float, np.ndarray], *, f107a: float = None, f107: float = None, Ap: int = None) ... |
glat = np.atleast_2d(glat)
glon = np.atleast_2d(glon) # has to be here
# %% altitude 1-D
if glat.size == 1 and glon.size == 1 and isinstance(time, (str, date, datetime, np.datetime64)):
atmos = rungtd1d(time, altkm, glat.squeeze()[()], glon.squeeze()[()],
f107a=f107a, f107... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loopalt_gtd(time: datetime, glat: Union[float, np.ndarray], glon: Union[float, np.ndarray], altkm: Union[float, List[float], np.ndarray], *, f107a: float = No... |
glat = np.atleast_2d(glat)
glon = np.atleast_2d(glon)
assert glat.ndim == glon.ndim == 2
times = np.atleast_1d(time)
assert times.ndim == 1
atmos = xarray.Dataset()
for k, t in enumerate(times):
print('computing', t)
for i in range(glat.shape[0]):
for j in ran... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_desc(self, desc):
"""Validate the predicate description.""" |
if desc is None:
return desc
if not isinstance(desc, STRING_TYPES):
raise TypeError(
"predicate description for Matching must be a string, "
"got %r" % (type(desc),))
# Python 2 mandates __repr__ to be an ASCII string,
# so if Un... |
<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_email(self):
""" Raise ValidationError if the contact exists. """ |
contacts = self.api.lists.contacts(id=self.list_id)['result']
for contact in contacts:
if contact['email'] == self.cleaned_data['email']:
raise forms.ValidationError(
_(u'This email is already subscribed'))
return self.cleaned_data['email'] |
<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_contact(self):
""" Create a contact with using the email on the list. """ |
self.api.lists.addcontact(
contact=self.cleaned_data['email'], id=self.list_id, method='POST') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_id(self):
""" Get or create the list id. """ |
list_id = getattr(self, '_list_id', None)
if list_id is None:
for l in self.api.lists.all()['lists']:
if l['name'] == self.list_name:
self._list_id = l['id']
if not getattr(self, '_list_id', None):
self._list_id = self.api.li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_tags(filename):
"""Reads values of "magic tags" defined in the given Python file. :param filename: Python filename to read the tags from :return: Dictio... |
with open(filename) as f:
ast_tree = ast.parse(f.read(), filename)
res = {}
for node in ast.walk(ast_tree):
if type(node) is not ast.Assign:
continue
target = node.targets[0]
if type(target) is not ast.Name:
continue
if not (target.id.starts... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def word_tokenize(text, stopwords=_stopwords, ngrams=None, min_length=0, ignore_numeric=True):
""" Parses the given text and yields tokens which represent words ... |
if ngrams is None:
ngrams = 1
text = re.sub(re.compile('\'s'), '', text) # Simple heuristic
text = re.sub(_re_punctuation, '', text)
matched_tokens = re.findall(_re_token, text.lower())
for tokens in get_ngrams(matched_tokens, ngrams):
for i in range(len(tokens)):
tok... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmake_setup():
""" attempt to build using CMake >= 3 """ |
cmake_exe = shutil.which('cmake')
if not cmake_exe:
raise FileNotFoundError('CMake not available')
wopts = ['-G', 'MinGW Makefiles', '-DCMAKE_SH="CMAKE_SH-NOTFOUND'] if os.name == 'nt' else []
subprocess.check_call([cmake_exe] + wopts + [str(SRCDIR)],
cwd=BINDIR)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def meson_setup():
""" attempt to build with Meson + Ninja """ |
meson_exe = shutil.which('meson')
ninja_exe = shutil.which('ninja')
if not meson_exe or not ninja_exe:
raise FileNotFoundError('Meson or Ninja not available')
if not (BINDIR / 'build.ninja').is_file():
subprocess.check_call([meson_exe, str(SRCDIR)], cwd=BINDIR)
ret = subprocess.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 add_term_occurrence(self, term, document):
""" Adds an occurrence of the term in the specified document. """ |
if document not in self._documents:
self._documents[document] = 0
if term not in self._terms:
if self._freeze:
return
else:
self._terms[term] = collections.Counter()
if document not in self._terms[term]:
self._ter... |
<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_total_term_frequency(self, term):
""" Gets the frequency of the specified term in the entire corpus added to the HashedIndex. """ |
if term not in self._terms:
raise IndexError(TERM_DOES_NOT_EXIST)
return sum(self._terms[term].values()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_term_frequency(self, term, document, normalized=False):
""" Returns the frequency of the term specified in the document. """ |
if document not in self._documents:
raise IndexError(DOCUMENT_DOES_NOT_EXIST)
if term not in self._terms:
raise IndexError(TERM_DOES_NOT_EXIST)
result = self._terms[term].get(document, 0)
if normalized:
result /= self.get_document_length(document)
... |
<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_document_frequency(self, term):
""" Returns the number of documents the specified term appears in. """ |
if term not in self._terms:
raise IndexError(TERM_DOES_NOT_EXIST)
else:
return len(self._terms[term]) |
<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_document_length(self, document):
""" Returns the number of terms found within the specified document. """ |
if document in self._documents:
return self._documents[document]
else:
raise IndexError(DOCUMENT_DOES_NOT_EXIST) |
<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_documents(self, term):
""" Returns all documents related to the specified term in the form of a Counter object. """ |
if term not in self._terms:
raise IndexError(TERM_DOES_NOT_EXIST)
else:
return self._terms[term] |
<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_tfidf(self, term, document, normalized=False):
""" Returns the Term-Frequency Inverse-Document-Frequency value for the given term in the specified docume... |
tf = self.get_term_frequency(term, document)
# Speeds up performance by avoiding extra calculations
if tf != 0.0:
# Add 1 to document frequency to prevent divide by 0
# (Laplacian Correction)
df = 1 + self.get_document_frequency(term)
n = 2 + len... |
<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_feature_matrix(self, mode='tfidf'):
""" Returns a feature matrix in the form of a list of lists which represents the terms and documents in this Inv... |
result = []
for doc in self._documents:
result.append(self.generate_document_vector(doc, mode))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_class_in_list(klass, lst):
""" Returns the first occurrence of an instance of type `klass` in the given list, or None if no such instance is present. ""... |
filtered = list(filter(lambda x: x.__class__ == klass, lst))
if filtered:
return filtered[0]
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 _build_parmlist(self, parameters):
""" Converts a dictionary of name and value pairs into a PARMLIST string value acceptable to the Payflow Pro API. """ |
args = []
for key, value in parameters.items():
if not value is None:
# We always use the explicit-length keyname format, to reduce the chance
# of requests failing due to unusual characters in parameter values.
try:
clas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.