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 normalize_list(self, text, cache=None):
""" Get a canonical list representation of text, with words separated and reduced to their base forms. TODO: use the cache. """ |
words = []
analysis = self.analyze(text)
for record in analysis:
if not self.is_stopword_record(record):
words.append(self.get_record_root(record))
if not words:
# Don't discard stopwords if that's all you've got
words = [self.get_record_token(record) for record in analysis]
return words |
<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_phrases(self, text):
""" Given some text, extract phrases of up to 2 content words, and map their normalized form to the complete phrase. """ |
analysis = self.analyze(text)
for pos1 in range(len(analysis)):
rec1 = analysis[pos1]
if not self.is_stopword_record(rec1):
yield self.get_record_root(rec1), rec1[0]
for pos2 in range(pos1 + 1, len(analysis)):
rec2 = analysis[pos2]
if not self.is_stopword_record(rec2):
roots = [self.get_record_root(rec1),
self.get_record_root(rec2)]
pieces = [analysis[i][0] for i in range(pos1, pos2+1)]
term = ' '.join(roots)
phrase = ''.join(pieces)
yield term, phrase
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_kana(text):
""" Use MeCab to turn any text into its phonetic spelling, as katakana separated by spaces. """ |
records = MECAB.analyze(text)
kana = []
for record in records:
if record.pronunciation:
kana.append(record.pronunciation)
elif record.reading:
kana.append(record.reading)
else:
kana.append(record.surface)
return ' '.join(k for k in kana if k) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_record_pos(self, record):
""" Given a record, get the word's part of speech. Here we're going to return MeCab's part of speech (written in Japanese), though if it's a stopword we prefix the part of speech with '~'. """ |
if self.is_stopword_record(record):
return '~' + record.pos
else:
return record.pos |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def untokenize(words):
""" Untokenizing a text undoes the tokenizing operation, restoring punctuation and spaces to the places that people expect them to be. Ideally, `untokenize(tokenize(text))` should be identical to `text`, except for line breaks. """ |
text = ' '.join(words)
step1 = text.replace("`` ", '"').replace(" ''", '"').replace('. . .', '...')
step2 = step1.replace(" ( ", " (").replace(" ) ", ") ")
step3 = re.sub(r' ([.,:;?!%]+)([ \'"`])', r"\1\2", step2)
step4 = re.sub(r' ([.,:;?!%]+)$', r"\1", step3)
step5 = step4.replace(" '", "'").replace(" n't", "n't").replace(
"can not", "cannot")
step6 = step5.replace(" ` ", " '")
return step6.strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def un_camel_case(text):
r""" Splits apart words that are written in CamelCase. Bugs: - Non-ASCII characters are treated as lowercase letters, even if they are actually capital letters. Examples: '1984 ZX Spectrum Games' 'aa Aa aa Aa A 0a A AA Aa! AAA' 'Mot\xf6r Head' 'MS Windows 3.11 For Workgroups' This should not significantly affect text that is not camel-cased: 'ACM Computing Classification System' 'Anne Blunt, 15th Baroness Wentworth' 'Hindi-Urdu' """ |
revtext = text[::-1]
pieces = []
while revtext:
match = CAMEL_RE.match(revtext)
if match:
pieces.append(match.group(1))
revtext = revtext[match.end():]
else:
pieces.append(revtext)
revtext = ''
revstr = ' '.join(piece.strip(' _') for piece in pieces
if piece.strip(' _'))
return revstr[::-1].replace('- ', '-') |
<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_badness(word):
""" Assign a heuristic to possible outputs from Morphy. Minimizing this heuristic avoids incorrect stems. """ |
if word.endswith('e'):
return len(word) - 2
elif word.endswith('ess'):
return len(word) - 10
elif word.endswith('ss'):
return len(word) - 4
else:
return len(word) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def morphy_stem(word, pos=None):
""" Get the most likely stem for a word. If a part of speech is supplied, the stem will be more accurate. Valid parts of speech are: - 'n' or 'NN' for nouns - 'v' or 'VB' for verbs - 'a' or 'JJ' for adjectives - 'r' or 'RB' for adverbs Any other part of speech will be treated as unknown. """ |
word = word.lower()
if pos is not None:
if pos.startswith('NN'):
pos = 'n'
elif pos.startswith('VB'):
pos = 'v'
elif pos.startswith('JJ'):
pos = 'a'
elif pos.startswith('RB'):
pos = 'r'
if pos is None and word.endswith('ing') or word.endswith('ed'):
pos = 'v'
if pos is not None and pos not in 'nvar':
pos = None
if word in EXCEPTIONS:
return EXCEPTIONS[word]
if pos is None:
if word in AMBIGUOUS_EXCEPTIONS:
return AMBIGUOUS_EXCEPTIONS[word]
return _morphy_best(word, pos) or word |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_list(text):
""" Get a list of word stems that appear in the text. Stopwords and an initial 'to' will be stripped, unless this leaves nothing in the stem. ['dog'] ['big', 'dog'] ['the'] """ |
pieces = [morphy_stem(word) for word in tokenize(text)]
pieces = [piece for piece in pieces if good_lemma(piece)]
if not pieces:
return [text]
if pieces[0] == 'to':
pieces = pieces[1:]
return pieces |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_topic(topic):
""" Get a canonical representation of a Wikipedia topic, which may include a disambiguation string in parentheses. Returns (name, disambig), where "name" is the normalized topic name, and "disambig" is a string corresponding to the disambiguation text or None. """ |
# find titles of the form Foo (bar)
topic = topic.replace('_', ' ')
match = re.match(r'([^(]+) \(([^)]+)\)', topic)
if not match:
return normalize(topic), None
else:
return normalize(match.group(1)), 'n/' + match.group(2).strip(' _') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def key2elements(key):
"""split key to elements""" |
# words = key.split('.')
# if len(words) == 4:
# return words
# # there is a dot in object name
# fieldword = words.pop(-1)
# nameword = '.'.join(words[-2:])
# if nameword[-1] in ('"', "'"):
# # The object name is in quotes
# nameword = nameword[1:-1]
# elements = words[:-2] + [nameword, fieldword, ]
# return elements
words = key.split('.')
first2words = words[:2]
lastword = words[-1]
namewords = words[2:-1]
namephrase = '.'.join(namewords)
if namephrase.startswith("'") and namephrase.endswith("'"):
namephrase = namephrase[1:-1]
return first2words + [namephrase] + [lastword] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateidf(idf, dct):
"""update idf using dct""" |
for key in list(dct.keys()):
if key.startswith('idf.'):
idftag, objkey, objname, field = key2elements(key)
if objname == '':
try:
idfobj = idf.idfobjects[objkey.upper()][0]
except IndexError as e:
idfobj = idf.newidfobject(objkey.upper())
else:
idfobj = idf.getobject(objkey.upper(), objname)
if idfobj == None:
idfobj = idf.newidfobject(objkey.upper(), Name=objname)
idfobj[field] = dct[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 fan_maxcfm(ddtt):
"""return the fan max cfm""" |
if str(ddtt.Maximum_Flow_Rate).lower() == 'autosize':
# str can fail with unicode chars :-(
return 'autosize'
else:
m3s = float(ddtt.Maximum_Flow_Rate)
return m3s2cfm(m3s) |
<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_paths(version=None, iddname=None):
"""Get the install paths for EnergyPlus executable and weather files. We prefer to get the install path from the IDD name but fall back to getting it from the version number for backwards compatibility and to simplify tests. Parameters version : str, optional EnergyPlus version in the format "X-X-X", e.g. "8-7-0". iddname : str, optional File path to the IDD. Returns ------- eplus_exe : str Full path to the EnergyPlus executable. eplus_weather : str Full path to the EnergyPlus weather directory. """ |
try:
eplus_exe, eplus_home = paths_from_iddname(iddname)
except (AttributeError, TypeError, ValueError):
eplus_exe, eplus_home = paths_from_version(version)
eplus_weather = os.path.join(eplus_home, 'WeatherData')
return eplus_exe, eplus_weather |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrapped_help_text(wrapped_func):
"""Decorator to pass through the documentation from a wrapped function. """ |
def decorator(wrapper_func):
"""The decorator.
Parameters
----------
f : callable
The wrapped function.
"""
wrapper_func.__doc__ = ('This method wraps the following method:\n\n' +
pydoc.text.document(wrapped_func))
return wrapper_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 prepare_run(run_id, run_data):
"""Prepare run inputs for one of multiple EnergyPlus runs. :param run_id: An ID number for naming the IDF. :param run_data: Tuple of the IDF and keyword args to pass to EnergyPlus executable. :return: Tuple of the IDF path and EPW, and the keyword args. """ |
idf, kwargs = run_data
epw = idf.epw
idf_dir = os.path.join('multi_runs', 'idf_%i' % run_id)
os.mkdir(idf_dir)
idf_path = os.path.join(idf_dir, 'in.idf')
idf.saveas(idf_path)
return (idf_path, epw), 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 run(idf=None, weather=None, output_directory='', annual=False, design_day=False, idd=None, epmacro=False, expandobjects=False, readvars=False, output_prefix=None, output_suffix=None, version=False, verbose='v', ep_version=None):
""" Wrapper around the EnergyPlus command line interface. Parameters idf : str Full or relative path to the IDF file to be run, or an IDF object. weather : str Full or relative path to the weather file. output_directory : str, optional Full or relative path to an output directory (default: 'run_outputs) annual : bool, optional If True then force annual simulation (default: False) design_day : bool, optional Force design-day-only simulation (default: False) idd : str, optional Input data dictionary (default: Energy+.idd in EnergyPlus directory) epmacro : str, optional Run EPMacro prior to simulation (default: False). expandobjects : bool, optional Run ExpandObjects prior to simulation (default: False) readvars : bool, optional Run ReadVarsESO after simulation (default: False) output_prefix : str, optional Prefix for output file names (default: eplus) output_suffix : str, optional Suffix style for output file names (default: L) L: Legacy (e.g., eplustbl.csv) C: Capital (e.g., eplusTable.csv) D: Dash (e.g., eplus-table.csv) version : bool, optional Display version information (default: False) verbose: str Set verbosity of runtime messages (default: v) v: verbose q: quiet ep_version: str EnergyPlus version, used to find install directory. Required if run() is called with an IDF file path rather than an IDF object. Returns ------- str : status Raises ------ CalledProcessError AttributeError If no ep_version parameter is passed when calling with an IDF file path rather than an IDF object. """ |
args = locals().copy()
# get unneeded params out of args ready to pass the rest to energyplus.exe
verbose = args.pop('verbose')
idf = args.pop('idf')
iddname = args.get('idd')
if not isinstance(iddname, str):
args.pop('idd')
try:
idf_path = os.path.abspath(idf.idfname)
except AttributeError:
idf_path = os.path.abspath(idf)
ep_version = args.pop('ep_version')
# get version from IDF object or by parsing the IDF file for it
if not ep_version:
try:
ep_version = '-'.join(str(x) for x in idf.idd_version[:3])
except AttributeError:
raise AttributeError(
"The ep_version must be set when passing an IDF path. \
Alternatively, use IDF.run()")
eplus_exe_path, eplus_weather_path = install_paths(ep_version, iddname)
if version:
# just get EnergyPlus version number and return
cmd = [eplus_exe_path, '--version']
check_call(cmd)
return
# convert paths to absolute paths if required
if os.path.isfile(args['weather']):
args['weather'] = os.path.abspath(args['weather'])
else:
args['weather'] = os.path.join(eplus_weather_path, args['weather'])
output_dir = os.path.abspath(args['output_directory'])
args['output_directory'] = output_dir
# store the directory we start in
cwd = os.getcwd()
run_dir = os.path.abspath(tempfile.mkdtemp())
os.chdir(run_dir)
# build a list of command line arguments
cmd = [eplus_exe_path]
for arg in args:
if args[arg]:
if isinstance(args[arg], bool):
args[arg] = ''
cmd.extend(['--{}'.format(arg.replace('_', '-'))])
if args[arg] != "":
cmd.extend([args[arg]])
cmd.extend([idf_path])
try:
if verbose == 'v':
print("\r\n" + " ".join(cmd) + "\r\n")
check_call(cmd)
elif verbose == 'q':
check_call(cmd, stdout=open(os.devnull, 'w'))
except CalledProcessError:
message = parse_error(output_dir)
raise EnergyPlusRunError(message)
finally:
os.chdir(cwd)
return 'OK' |
<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_error(output_dir):
"""Add contents of stderr and eplusout.err and put it in the exception message. :param output_dir: str :return: str """ |
sys.stderr.seek(0)
std_err = sys.stderr.read().decode('utf-8')
err_file = os.path.join(output_dir, "eplusout.err")
if os.path.isfile(err_file):
with open(err_file, "r") as f:
ep_err = f.read()
else:
ep_err = "<File not found>"
message = "\r\n{std_err}\r\nContents of EnergyPlus error file at {err_file}\r\n{ep_err}".format(**locals())
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def almostequal(first, second, places=7, printit=True):
""" Test if two values are equal to a given number of places. This is based on python's unittest so may be covered by Python's license. """ |
if first == second:
return True
if round(abs(second - first), places) != 0:
if printit:
print(round(abs(second - first), places))
print("notalmost: %s != %s to %i places" % (first, second, places))
return False
else:
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 newrawobject(data, commdct, key, block=None, defaultvalues=True):
"""Make a new object for the given key. Parameters data : Eplusdata object Data dictionary and list of objects for the entire model. commdct : list of dicts Comments from the IDD file describing each item type in `data`. key : str Object type of the object to add (in ALL_CAPS). Returns ------- list A list of field values for the new object. """ |
dtls = data.dtls
key = key.upper()
key_i = dtls.index(key)
key_comm = commdct[key_i]
# set default values
if defaultvalues:
obj = [comm.get('default', [''])[0] for comm in key_comm]
else:
obj = ['' for comm in key_comm]
if not block:
inblock = ['does not start with N'] * len(obj)
else:
inblock = block[key_i]
for i, (f_comm, f_val, f_iddname) in enumerate(zip(key_comm, obj, inblock)):
if i == 0:
obj[i] = key
else:
obj[i] = convertafield(f_comm, f_val, f_iddname)
obj = poptrailing(obj) # remove the blank items in a repeating field.
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addthisbunch(bunchdt, data, commdct, thisbunch, theidf):
"""add a bunch to model. abunch usually comes from another idf file or it can be used to copy within the idf file""" |
key = thisbunch.key.upper()
obj = copy.copy(thisbunch.obj)
abunch = obj2bunch(data, commdct, obj)
bunchdt[key].append(abunch)
return abunch |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def obj2bunch(data, commdct, obj):
"""make a new bunch object using the data object""" |
dtls = data.dtls
key = obj[0].upper()
key_i = dtls.index(key)
abunch = makeabunch(commdct, obj, key_i)
return abunch |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getobject(bunchdt, key, name):
"""get the object if you have the key and the name returns a list of objects, in case you have more than one You should not have more than one""" |
# TODO : throw exception if more than one object, or return more objects
idfobjects = bunchdt[key]
if idfobjects:
# second item in list is a unique ID
unique_id = idfobjects[0].objls[1]
theobjs = [idfobj for idfobj in idfobjects if
idfobj[unique_id].upper() == name.upper()]
try:
return theobjs[0]
except IndexError:
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 __objecthasfields(bunchdt, data, commdct, idfobject, places=7, **kwargs):
"""test if the idf object has the field values in kwargs""" |
for key, value in list(kwargs.items()):
if not isfieldvalue(
bunchdt, data, commdct,
idfobject, key, value, places=places):
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 iddofobject(data, commdct, key):
"""from commdct, return the idd of the object key""" |
dtls = data.dtls
i = dtls.index(key)
return commdct[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 getextensibleindex(bunchdt, data, commdct, key, objname):
"""get the index of the first extensible item""" |
theobject = getobject(bunchdt, key, objname)
if theobject == None:
return None
theidd = iddofobject(data, commdct, key)
extensible_i = [
i for i in range(len(theidd)) if 'begin-extensible' in theidd[i]]
try:
extensible_i = extensible_i[0]
except IndexError:
return theobject |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeextensibles(bunchdt, data, commdct, key, objname):
"""remove the extensible items in the object""" |
theobject = getobject(bunchdt, key, objname)
if theobject == None:
return theobject
theidd = iddofobject(data, commdct, key)
extensible_i = [
i for i in range(len(theidd)) if 'begin-extensible' in theidd[i]]
try:
extensible_i = extensible_i[0]
except IndexError:
return theobject
while True:
try:
popped = theobject.obj.pop(extensible_i)
except IndexError:
break
return theobject |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getfieldcomm(bunchdt, data, commdct, idfobject, fieldname):
"""get the idd comment for the field""" |
key = idfobject.obj[0].upper()
keyi = data.dtls.index(key)
fieldi = idfobject.objls.index(fieldname)
thiscommdct = commdct[keyi][fieldi]
return thiscommdct |
<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_retaincase(bunchdt, data, commdct, idfobject, fieldname):
"""test if case has to be retained for that field""" |
thiscommdct = getfieldcomm(bunchdt, data, commdct, idfobject, fieldname)
return 'retaincase' in thiscommdct |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isfieldvalue(bunchdt, data, commdct, idfobj, fieldname, value, places=7):
"""test if idfobj.field == value""" |
# do a quick type check
# if type(idfobj[fieldname]) != type(value):
# return False # takes care of autocalculate and real
# check float
thiscommdct = getfieldcomm(bunchdt, data, commdct, idfobj, fieldname)
if 'type' in thiscommdct:
if thiscommdct['type'][0] in ('real', 'integer'):
# test for autocalculate
try:
if idfobj[fieldname].upper() == 'AUTOCALCULATE':
if value.upper() == 'AUTOCALCULATE':
return True
except AttributeError:
pass
return almostequal(float(idfobj[fieldname]), float(value), places, False)
# check retaincase
if is_retaincase(bunchdt, data, commdct, idfobj, fieldname):
return idfobj[fieldname] == value
else:
return idfobj[fieldname].upper() == value.upper() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getrefnames(idf, objname):
"""get the reference names for this object""" |
iddinfo = idf.idd_info
dtls = idf.model.dtls
index = dtls.index(objname)
fieldidds = iddinfo[index]
for fieldidd in fieldidds:
if 'field' in fieldidd:
if fieldidd['field'][0].endswith('Name'):
if 'reference' in fieldidd:
return fieldidd['reference']
else:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rename(idf, objkey, objname, newname):
"""rename all the refrences to this objname""" |
refnames = getrefnames(idf, objkey)
for refname in refnames:
objlists = getallobjlists(idf, refname)
# [('OBJKEY', refname, fieldindexlist), ...]
for refname in refnames:
# TODO : there seems to be a duplication in this loop. Check.
# refname appears in both loops
for robjkey, refname, fieldindexlist in objlists:
idfobjects = idf.idfobjects[robjkey]
for idfobject in idfobjects:
for findex in fieldindexlist: # for each field
if idfobject[idfobject.objls[findex]] == objname:
idfobject[idfobject.objls[findex]] = newname
theobject = idf.getobject(objkey, objname)
fieldname = [item for item in theobject.objls if item.endswith('Name')][0]
theobject[fieldname] = newname
return theobject |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zone_height_min2max(idf, zonename, debug=False):
"""zone height = max-min""" |
zone = idf.getobject('ZONE', zonename)
surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()]
zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name]
surf_xyzs = [eppy.function_helpers.getcoords(s) for s in zone_surfs]
surf_xyzs = list(itertools.chain(*surf_xyzs))
surf_zs = [z for x, y, z in surf_xyzs]
topz = max(surf_zs)
botz = min(surf_zs)
height = topz - botz
return height |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zone_floor2roofheight(idf, zonename, debug=False):
"""zone floor to roof height""" |
zone = idf.getobject('ZONE', zonename)
surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()]
zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name]
floors = [s for s in zone_surfs if s.Surface_Type.upper() == 'FLOOR']
roofs = [s for s in zone_surfs if s.Surface_Type.upper() == 'ROOF']
ceilings = [s for s in zone_surfs if s.Surface_Type.upper() == 'CEILING']
topsurfaces = roofs + ceilings
topz = []
for topsurface in topsurfaces:
for coord in topsurface.coords:
topz.append(coord[-1])
topz = max(topz)
botz = []
for floor in floors:
for coord in floor.coords:
botz.append(coord[-1])
botz = min(botz)
height = topz - botz
return height |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setiddname(cls, iddname, testing=False):
""" Set the path to the EnergyPlus IDD for the version of EnergyPlus which is to be used by eppy. Parameters iddname : str Path to the IDD file. testing : bool Flag to use if running tests since we may want to ignore the `IDDAlreadySetError`. Raises ------ IDDAlreadySetError """ |
if cls.iddname == None:
cls.iddname = iddname
cls.idd_info = None
cls.block = None
elif cls.iddname == iddname:
pass
else:
if testing == False:
errortxt = "IDD file is set to: %s" % (cls.iddname,)
raise IDDAlreadySetError(errortxt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setidd(cls, iddinfo, iddindex, block, idd_version):
"""Set the IDD to be used by eppy. Parameters iddinfo : list Comments and metadata about fields in the IDD. block : list Field names in the IDD. """ |
cls.idd_info = iddinfo
cls.block = block
cls.idd_index = iddindex
cls.idd_version = idd_version |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initread(self, idfname):
""" Use the current IDD and read an IDF from file. If the IDD has not yet been initialised then this is done first. Parameters idf_name : str Path to an IDF file. """ |
with open(idfname, 'r') as _:
# raise nonexistent file error early if idfname doesn't exist
pass
iddfhandle = StringIO(iddcurrent.iddtxt)
if self.getiddname() == None:
self.setiddname(iddfhandle)
self.idfname = idfname
self.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initreadtxt(self, idftxt):
""" Use the current IDD and read an IDF from text data. If the IDD has not yet been initialised then this is done first. Parameters idftxt : str Text representing an IDF file. """ |
iddfhandle = StringIO(iddcurrent.iddtxt)
if self.getiddname() == None:
self.setiddname(iddfhandle)
idfhandle = StringIO(idftxt)
self.idfname = idfhandle
self.read() |
<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(self):
""" Read the IDF file and the IDD file. If the IDD file had already been read, it will not be read again. Read populates the following data structures: - idfobjects : list - model : list - idd_info : list - idd_index : dict """ |
if self.getiddname() == None:
errortxt = ("IDD file needed to read the idf file. "
"Set it using IDF.setiddname(iddfile)")
raise IDDNotSetError(errortxt)
readout = idfreader1(
self.idfname, self.iddname, self,
commdct=self.idd_info, block=self.block)
(self.idfobjects, block, self.model,
idd_info, idd_index, idd_version) = readout
self.__class__.setidd(idd_info, idd_index, block, idd_version) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initnew(self, fname):
""" Use the current IDD and create a new empty IDF. If the IDD has not yet been initialised then this is done first. Parameters fname : str, optional Path to an IDF. This does not need to be set at this point. """ |
iddfhandle = StringIO(iddcurrent.iddtxt)
if self.getiddname() == None:
self.setiddname(iddfhandle)
idfhandle = StringIO('')
self.idfname = idfhandle
self.read()
if fname:
self.idfname = fname |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def newidfobject(self, key, aname='', defaultvalues=True, **kwargs):
""" Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", Name='Interior Ceiling_class', Outside_Layer='LW Concrete', Layer_2='soundmat') Parameters key : str The type of IDF object. This must be in ALL_CAPS. aname : str, deprecated This parameter is not used. It is left there for backward compatibility. defaultvalues: boolean default is True. If True default values WILL be set. If False, default values WILL NOT be set **kwargs Keyword arguments in the format `field=value` used to set the value of fields in the IDF object when it is created. Returns ------- EpBunch object """ |
obj = newrawobject(self.model, self.idd_info,
key, block=self.block, defaultvalues=defaultvalues)
abunch = obj2bunch(self.model, self.idd_info, obj)
if aname:
warnings.warn("The aname parameter should no longer be used.", UserWarning)
namebunch(abunch, aname)
self.idfobjects[key].append(abunch)
for k, v in list(kwargs.items()):
abunch[k] = v
return abunch |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeidfobject(self, idfobject):
"""Remove an IDF object from the IDF. Parameters idfobject : EpBunch object The IDF object to remove. """ |
key = idfobject.key.upper()
self.idfobjects[key].remove(idfobject) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copyidfobject(self, idfobject):
"""Add an IDF object to the IDF. Parameters idfobject : EpBunch object The IDF object to remove. This usually comes from another idf file, or it can be used to copy within this idf file. """ |
return addthisbunch(self.idfobjects,
self.model,
self.idd_info,
idfobject, 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 getextensibleindex(self, key, name):
""" Get the index of the first extensible item. Only for internal use. # TODO : hide this Parameters key : str The type of IDF object. This must be in ALL_CAPS. name : str The name of the object to fetch. Returns ------- int """ |
return getextensibleindex(
self.idfobjects, self.model, self.idd_info,
key, 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 removeextensibles(self, key, name):
""" Remove extensible items in the object of key and name. Only for internal use. # TODO : hide this Parameters key : str The type of IDF object. This must be in ALL_CAPS. name : str The name of the object to fetch. Returns ------- EpBunch object """ |
return removeextensibles(
self.idfobjects, self.model, self.idd_info,
key, 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 idfstr(self):
"""String representation of the IDF. Returns ------- str """ |
if self.outputtype == 'standard':
astr = ''
else:
astr = self.model.__repr__()
if self.outputtype == 'standard':
astr = ''
dtls = self.model.dtls
for objname in dtls:
for obj in self.idfobjects[objname]:
astr = astr + obj.__repr__()
elif self.outputtype == 'nocomment':
return astr
elif self.outputtype == 'nocomment1':
slist = astr.split('\n')
slist = [item.strip() for item in slist]
astr = '\n'.join(slist)
elif self.outputtype == 'nocomment2':
slist = astr.split('\n')
slist = [item.strip() for item in slist]
slist = [item for item in slist if item != '']
astr = '\n'.join(slist)
elif self.outputtype == 'compressed':
slist = astr.split('\n')
slist = [item.strip() for item in slist]
astr = ' '.join(slist)
else:
raise ValueError("%s is not a valid outputtype" % self.outputtype)
return astr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, filename=None, lineendings='default', encoding='latin-1'):
""" Save the IDF as a text file with the optional filename passed, or with the current idfname of the IDF. Parameters filename : str, optional Filepath to save the file. If None then use the IDF.idfname parameter. Also accepts a file handle. lineendings : str, optional Line endings to use in the saved file. Options are 'default', 'windows' and 'unix' the default is 'default' which uses the line endings for the current system. encoding : str, optional Encoding to use for the saved file. The default is 'latin-1' which is compatible with the EnergyPlus IDFEditor. """ |
if filename is None:
filename = self.idfname
s = self.idfstr()
if lineendings == 'default':
system = platform.system()
s = '!- {} Line endings \n'.format(system) + s
slines = s.splitlines()
s = os.linesep.join(slines)
elif lineendings == 'windows':
s = '!- Windows Line endings \n' + s
slines = s.splitlines()
s = '\r\n'.join(slines)
elif lineendings == 'unix':
s = '!- Unix Line endings \n' + s
slines = s.splitlines()
s = '\n'.join(slines)
s = s.encode(encoding)
try:
with open(filename, 'wb') as idf_out:
idf_out.write(s)
except TypeError: # in the case that filename is a file handle
try:
filename.write(s)
except TypeError:
filename.write(s.decode(encoding)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def saveas(self, filename, lineendings='default', encoding='latin-1'):
""" Save the IDF as a text file with the filename passed. Parameters filename : str Filepath to to set the idfname attribute to and save the file as. lineendings : str, optional Line endings to use in the saved file. Options are 'default', 'windows' and 'unix' the default is 'default' which uses the line endings for the current system. encoding : str, optional Encoding to use for the saved file. The default is 'latin-1' which is compatible with the EnergyPlus IDFEditor. """ |
self.idfname = filename
self.save(filename, lineendings, encoding) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def savecopy(self, filename, lineendings='default', encoding='latin-1'):
"""Save a copy of the file with the filename passed. Parameters filename : str Filepath to save the file. lineendings : str, optional Line endings to use in the saved file. Options are 'default', 'windows' and 'unix' the default is 'default' which uses the line endings for the current system. encoding : str, optional Encoding to use for the saved file. The default is 'latin-1' which is compatible with the EnergyPlus IDFEditor. """ |
self.save(filename, lineendings, encoding) |
<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(self, **kwargs):
""" Run an IDF file with a given EnergyPlus weather file. This is a wrapper for the EnergyPlus command line interface. Parameters **kwargs See eppy.runner.functions.run() """ |
# write the IDF to the current directory
self.saveas('in.idf')
# if `idd` is not passed explicitly, use the IDF.iddname
idd = kwargs.pop('idd', self.iddname)
epw = kwargs.pop('weather', self.epw)
try:
run(self, weather=epw, idd=idd, **kwargs)
finally:
os.remove('in.idf') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getoneblock(astr, start, end):
"""get the block bounded by start and end doesn't work for multiple blocks""" |
alist = astr.split(start)
astr = alist[-1]
alist = astr.split(end)
astr = alist[0]
return astr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def myreplace(astr, thefind, thereplace):
"""in string astr replace all occurences of thefind with thereplace""" |
alist = astr.split(thefind)
new_s = alist.split(thereplace)
return new_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 fsliceafter(astr, sub):
"""Return the slice after at sub in string astr""" |
findex = astr.find(sub)
return astr[findex + len(sub):] |
<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_str2file(pathname, astr):
"""writes a string to file""" |
fname = pathname
fhandle = open(fname, 'wb')
fhandle.write(astr)
fhandle.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_simpletable(table):
"""test if the table has only strings in the cells""" |
tds = table('td')
for td in tds:
if td.contents != []:
td = tdbr2EOL(td)
if len(td.contents) == 1:
thecontents = td.contents[0]
if not isinstance(thecontents, NavigableString):
return False
else:
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 table2matrix(table):
"""convert a table to a list of lists - a 2D matrix""" |
if not is_simpletable(table):
raise NotSimpleTable("Not able read a cell in the table as a string")
rows = []
for tr in table('tr'):
row = []
for td in tr('td'):
td = tdbr2EOL(td) # convert any '<br>' in the td to line ending
try:
row.append(td.contents[0])
except IndexError:
row.append('')
rows.append(row)
return rows |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def table2val_matrix(table):
"""convert a table to a list of lists - a 2D matrix Converts numbers to float""" |
if not is_simpletable(table):
raise NotSimpleTable("Not able read a cell in the table as a string")
rows = []
for tr in table('tr'):
row = []
for td in tr('td'):
td = tdbr2EOL(td)
try:
val = td.contents[0]
except IndexError:
row.append('')
else:
try:
val = float(val)
row.append(val)
except ValueError:
row.append(val)
rows.append(row)
return rows |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _has_name(soup_obj):
"""checks if soup_obj is really a soup object or just a string If it has a name it is a soup object""" |
try:
name = soup_obj.name
if name == None:
return False
return True
except AttributeError:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_ntgrid(grid):
"""make a named tuple grid [["", "a b", "b c", "c d"], ["x y", 1, 2, 3 ], ["y z", 4, 5, 6 ], ["z z", 7, 8, 9 ],] will return ntcol(x_y=ntrow(a_b=1, b_c=2, c_d=3), y_z=ntrow(a_b=4, b_c=5, c_d=6), z_z=ntrow(a_b=7, b_c=8, c_d=9))""" |
hnames = [_nospace(n) for n in grid[0][1:]]
vnames = [_nospace(row[0]) for row in grid[1:]]
vnames_s = " ".join(vnames)
hnames_s = " ".join(hnames)
ntcol = collections.namedtuple('ntcol', vnames_s)
ntrow = collections.namedtuple('ntrow', hnames_s)
rdict = [dict(list(zip(hnames, row[1:]))) for row in grid[1:]]
ntrows = [ntrow(**rdict[i]) for i, name in enumerate(vnames)]
ntcols = ntcol(**dict(list(zip(vnames, ntrows))))
return ntcols |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def onlylegalchar(name):
"""return only legal chars""" |
legalchar = ascii_letters + digits + ' '
return ''.join([s for s in name[:] if s in legalchar]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intinlist(lst):
"""test if int in list""" |
for item in lst:
try:
item = int(item)
return True
except ValueError:
pass
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replaceint(fname, replacewith='%s'):
"""replace int in lst""" |
words = fname.split()
for i, word in enumerate(words):
try:
word = int(word)
words[i] = replacewith
except ValueError:
pass
return ' '.join(words) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleaniddfield(acomm):
"""make all the keys lower case""" |
for key in list(acomm.keys()):
val = acomm[key]
acomm[key.lower()] = val
for key in list(acomm.keys()):
val = acomm[key]
if key != key.lower():
acomm.pop(key)
return acomm |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makecsvdiffs(thediffs, dtls, n1, n2):
"""return the csv to be displayed""" |
def ishere(val):
if val == None:
return "not here"
else:
return "is here"
rows = []
rows.append(['file1 = %s' % (n1, )])
rows.append(['file2 = %s' % (n2, )])
rows.append('')
rows.append(theheader(n1, n2))
keys = list(thediffs.keys()) # ensures sorting by Name
keys.sort()
# sort the keys in the same order as in the idd
dtlssorter = DtlsSorter(dtls)
keys = sorted(keys, key=dtlssorter.getkey)
for key in keys:
if len(key) == 2:
rw2 = [''] + [ishere(i) for i in thediffs[key]]
else:
rw2 = list(thediffs[key])
rw1 = list(key)
rows.append(rw1 + rw2)
return rows |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def printcsv(csvdiffs):
"""print the csv""" |
for row in csvdiffs:
print(','.join([str(cell) for cell in row])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def heading2table(soup, table, row):
"""add heading row to table""" |
tr = Tag(soup, name="tr")
table.append(tr)
for attr in row:
th = Tag(soup, name="th")
tr.append(th)
th.append(attr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def row2table(soup, table, row):
"""ad a row to the table""" |
tr = Tag(soup, name="tr")
table.append(tr)
for attr in row:
td = Tag(soup, name="td")
tr.append(td)
td.append(attr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def printhtml(csvdiffs):
"""print the html""" |
soup = BeautifulSoup()
html = Tag(soup, name="html")
para1 = Tag(soup, name="p")
para1.append(csvdiffs[0][0])
para2 = Tag(soup, name="p")
para2.append(csvdiffs[1][0])
table = Tag(soup, name="table")
table.attrs.update(dict(border="1"))
soup.append(html)
html.append(para1)
html.append(para2)
html.append(table)
heading2table(soup, table, csvdiffs[3])
for row in csvdiffs[4:]:
row = [str(cell) for cell in row]
row2table(soup, table, row)
# print soup.prettify()
print(soup) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extendlist(lst, i, value=''):
"""extend the list so that you have i-th value""" |
if i < len(lst):
pass
else:
lst.extend([value, ] * (i - len(lst) + 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 addfunctions(abunch):
"""add functions to epbunch""" |
key = abunch.obj[0].upper()
#-----------------
# TODO : alternate strategy to avoid listing the objkeys in snames
# check if epbunch has field "Zone_Name" or "Building_Surface_Name"
# and is in group u'Thermal Zones and Surfaces'
# then it is likely to be a surface.
# of course we need to recode for surfaces that do not have coordinates :-(
# or we can filter those out since they do not have
# the field "Number_of_Vertices"
snames = [
"BuildingSurface:Detailed",
"Wall:Detailed",
"RoofCeiling:Detailed",
"Floor:Detailed",
"FenestrationSurface:Detailed",
"Shading:Site:Detailed",
"Shading:Building:Detailed",
"Shading:Zone:Detailed", ]
snames = [sname.upper() for sname in snames]
if key in snames:
func_dict = {
'area': fh.area,
'height': fh.height, # not working correctly
'width': fh.width, # not working correctly
'azimuth': fh.azimuth,
'tilt': fh.tilt,
'coords': fh.getcoords, # needed for debugging
}
abunch.__functions.update(func_dict)
#-----------------
# print(abunch.getfieldidd )
names = [
"CONSTRUCTION",
"MATERIAL",
"MATERIAL:AIRGAP",
"MATERIAL:INFRAREDTRANSPARENT",
"MATERIAL:NOMASS",
"MATERIAL:ROOFVEGETATION",
"WINDOWMATERIAL:BLIND",
"WINDOWMATERIAL:GLAZING",
"WINDOWMATERIAL:GLAZING:REFRACTIONEXTINCTIONMETHOD",
"WINDOWMATERIAL:GAP",
"WINDOWMATERIAL:GAS",
"WINDOWMATERIAL:GASMIXTURE",
"WINDOWMATERIAL:GLAZINGGROUP:THERMOCHROMIC",
"WINDOWMATERIAL:SCREEN",
"WINDOWMATERIAL:SHADE",
"WINDOWMATERIAL:SIMPLEGLAZINGSYSTEM",
]
if key in names:
func_dict = {
'rvalue': fh.rvalue,
'ufactor': fh.ufactor,
'rvalue_ip': fh.rvalue_ip, # quick fix for Santosh. Needs to thought thru
'ufactor_ip': fh.ufactor_ip, # quick fix for Santosh. Needs to thought thru
'heatcapacity': fh.heatcapacity,
}
abunch.__functions.update(func_dict)
names = [
'FAN:CONSTANTVOLUME',
'FAN:VARIABLEVOLUME',
'FAN:ONOFF',
'FAN:ZONEEXHAUST',
'FANPERFORMANCE:NIGHTVENTILATION',
]
if key in names:
func_dict = {
'f_fanpower_bhp': fh.fanpower_bhp,
'f_fanpower_watts': fh.fanpower_watts,
'f_fan_maxcfm': fh.fan_maxcfm,
}
abunch.__functions.update(func_dict)
# =====
# code for references
#-----------------
# add function zonesurfaces
if key == 'ZONE':
func_dict = {'zonesurfaces':fh.zonesurfaces}
abunch.__functions.update(func_dict)
#-----------------
# add function subsurfaces
# going to cheat here a bit
# check if epbunch has field "Zone_Name"
# and is in group u'Thermal Zones and Surfaces'
# then it is likely to be a surface attached to a zone
fields = abunch.fieldnames
try:
group = abunch.getfieldidd('key')['group']
except KeyError as e: # some pytests don't have group
group = None
if group == u'Thermal Zones and Surfaces':
if "Zone_Name" in fields:
func_dict = {'subsurfaces':fh.subsurfaces}
abunch.__functions.update(func_dict)
return abunch |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getrange(bch, fieldname):
"""get the ranges for this field""" |
keys = ['maximum', 'minimum', 'maximum<', 'minimum>', 'type']
index = bch.objls.index(fieldname)
fielddct_orig = bch.objidd[index]
fielddct = copy.deepcopy(fielddct_orig)
therange = {}
for key in keys:
therange[key] = fielddct.setdefault(key, None)
if therange['type']:
therange['type'] = therange['type'][0]
if therange['type'] == 'real':
for key in keys[:-1]:
if therange[key]:
therange[key] = float(therange[key][0])
if therange['type'] == 'integer':
for key in keys[:-1]:
if therange[key]:
therange[key] = int(therange[key][0])
return therange |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkrange(bch, fieldname):
"""throw exception if the out of range""" |
fieldvalue = bch[fieldname]
therange = bch.getrange(fieldname)
if therange['maximum'] != None:
if fieldvalue > therange['maximum']:
astr = "Value %s is not less or equal to the 'maximum' of %s"
astr = astr % (fieldvalue, therange['maximum'])
raise RangeError(astr)
if therange['minimum'] != None:
if fieldvalue < therange['minimum']:
astr = "Value %s is not greater or equal to the 'minimum' of %s"
astr = astr % (fieldvalue, therange['minimum'])
raise RangeError(astr)
if therange['maximum<'] != None:
if fieldvalue >= therange['maximum<']:
astr = "Value %s is not less than the 'maximum<' of %s"
astr = astr % (fieldvalue, therange['maximum<'])
raise RangeError(astr)
if therange['minimum>'] != None:
if fieldvalue <= therange['minimum>']:
astr = "Value %s is not greater than the 'minimum>' of %s"
astr = astr % (fieldvalue, therange['minimum>'])
raise RangeError(astr)
return fieldvalue
"""get the idd dict for this field
Will return {} if the fieldname 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 getfieldidd_item(bch, fieldname, iddkey):
"""return an item from the fieldidd, given the iddkey will return and empty list if it does not have the iddkey or if the fieldname does not exist""" |
fieldidd = getfieldidd(bch, fieldname)
try:
return fieldidd[iddkey]
except KeyError as e:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isequal(bch, fieldname, value, places=7):
"""return True if the field is equal to value""" |
def equalalphanumeric(bch, fieldname, value):
if bch.get_retaincase(fieldname):
return bch[fieldname] == value
else:
return bch[fieldname].upper() == value.upper()
fieldidd = bch.getfieldidd(fieldname)
try:
ftype = fieldidd['type'][0]
if ftype in ['real', 'integer']:
return almostequal(bch[fieldname], float(value), places=places)
else:
return equalalphanumeric(bch, fieldname, value)
except KeyError as e:
return equalalphanumeric(bch, fieldname, 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_referenced_object(referring_object, fieldname):
""" Get an object referred to by a field in another object. For example an object of type Construction has fields for each layer, each of which refers to a Material. This functions allows the object representing a Material to be fetched using the name of the layer. Returns the first item found since if there is more than one matching item, it is a malformed IDF. Parameters referring_object : EpBunch The object which contains a reference to another object, fieldname : str The name of the field in the referring object which contains the reference to another object. Returns ------- EpBunch """ |
idf = referring_object.theidf
object_list = referring_object.getfieldidd_item(fieldname, u'object-list')
for obj_type in idf.idfobjects:
for obj in idf.idfobjects[obj_type]:
valid_object_lists = obj.getfieldidd_item("Name", u'reference')
if set(object_list).intersection(set(valid_object_lists)):
referenced_obj_name = referring_object[fieldname]
if obj.Name == referenced_obj_name:
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isequal(self, fieldname, value, places=7):
"""return True if the field == value Will retain case if get_retaincase == True for real value will compare to decimal 'places' """ |
return isequal(self, fieldname, value, places=places) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makename2refdct(commdct):
"""make the name2refs dict in the idd_index""" |
refdct = {}
for comm in commdct: # commdct is a list of dict
try:
idfobj = comm[0]['idfobj'].upper()
field1 = comm[1]
if 'Name' in field1['field']:
references = field1['reference']
refdct[idfobj] = references
except (KeyError, IndexError) as e:
continue # not the expected pattern for reference
return refdct |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makeref2namesdct(name2refdct):
"""make the ref2namesdct in the idd_index""" |
ref2namesdct = {}
for key, values in name2refdct.items():
for value in values:
ref2namesdct.setdefault(value, set()).add(key)
return ref2namesdct |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ref2names2commdct(ref2names, commdct):
"""embed ref2names into commdct""" |
for comm in commdct:
for cdct in comm:
try:
refs = cdct['object-list'][0]
validobjects = ref2names[refs]
cdct.update({'validobjects':validobjects})
except KeyError as e:
continue
return commdct |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def area(poly):
"""Calculation of zone area""" |
poly_xy = []
num = len(poly)
for i in range(num):
poly[i] = poly[i][0:2] + (0,)
poly_xy.append(poly[i])
return surface.area(poly) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prevnode(edges, component):
"""get the pervious component in the loop""" |
e = edges
c = component
n2c = [(a, b) for a, b in e if type(a) == tuple]
c2n = [(a, b) for a, b in e if type(b) == tuple]
node2cs = [(a, b) for a, b in e if b == c]
c2nodes = []
for node2c in node2cs:
c2node = [(a, b) for a, b in c2n if b == node2c[0]]
if len(c2node) == 0:
# return []
c2nodes = []
break
c2nodes.append(c2node[0])
cs = [a for a, b in c2nodes]
# test for connections that have no nodes
# filter for no nodes
nonodes = [(a, b) for a, b in e if type(a) != tuple and type(b) != tuple]
for a, b in nonodes:
if b == component:
cs.append(a)
return cs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getcoords(ddtt):
"""return the coordinates of the surface""" |
n_vertices_index = ddtt.objls.index('Number_of_Vertices')
first_x = n_vertices_index + 1 # X of first coordinate
pts = ddtt.obj[first_x:]
return list(grouper(3, pts)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buildingname(ddtt):
"""return building name""" |
idf = ddtt.theidf
building = idf.idfobjects['building'.upper()][0]
return building.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 cleanupversion(ver):
"""massage the version number so it matches the format of install folder""" |
lst = ver.split(".")
if len(lst) == 1:
lst.extend(['0', '0'])
elif len(lst) == 2:
lst.extend(['0'])
elif len(lst) > 2:
lst = lst[:3]
lst[2] = '0' # ensure the 3rd number is 0
cleanver = '.'.join(lst)
return cleanver |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getiddfile(versionid):
"""find the IDD file of the E+ installation""" |
vlist = versionid.split('.')
if len(vlist) == 1:
vlist = vlist + ['0', '0']
elif len(vlist) == 2:
vlist = vlist + ['0']
ver_str = '-'.join(vlist)
eplus_exe, _ = eppy.runner.run_functions.install_paths(ver_str)
eplusfolder = os.path.dirname(eplus_exe)
iddfile = '{}/Energy+.idd'.format(eplusfolder, )
return iddfile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initdict(self, fname):
"""create a blank dictionary""" |
if isinstance(fname, Idd):
self.dt, self.dtls = fname.dt, fname.dtls
return self.dt, self.dtls
astr = mylib2.readfile(fname)
nocom = removecomment(astr, '!')
idfst = nocom
alist = idfst.split(';')
lss = []
for element in alist:
lst = element.split(',')
lss.append(lst)
for i in range(0, len(lss)):
for j in range(0, len(lss[i])):
lss[i][j] = lss[i][j].strip()
dt = {}
dtls = []
for element in lss:
if element[0] == '':
continue
dt[element[0].upper()] = []
dtls.append(element[0].upper())
self.dt, self.dtls = dt, dtls
return dt, dtls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makedict(self, dictfile, fnamefobject):
"""stuff file data into the blank dictionary""" |
#fname = './exapmlefiles/5ZoneDD.idf'
#fname = './1ZoneUncontrolled.idf'
if isinstance(dictfile, Idd):
localidd = copy.deepcopy(dictfile)
dt, dtls = localidd.dt, localidd.dtls
else:
dt, dtls = self.initdict(dictfile)
# astr = mylib2.readfile(fname)
astr = fnamefobject.read()
try:
astr = astr.decode('ISO-8859-2')
except AttributeError:
pass
fnamefobject.close()
nocom = removecomment(astr, '!')
idfst = nocom
# alist = string.split(idfst, ';')
alist = idfst.split(';')
lss = []
for element in alist:
# lst = string.split(element, ',')
lst = element.split(',')
lss.append(lst)
for i in range(0, len(lss)):
for j in range(0, len(lss[i])):
lss[i][j] = lss[i][j].strip()
for element in lss:
node = element[0].upper()
if node in dt:
# stuff data in this key
dt[node.upper()].append(element)
else:
# scream
if node == '':
continue
print('this node -%s-is not present in base dictionary' %
(node))
self.dt, self.dtls = dt, dtls
return dt, dtls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replacenode(self, othereplus, node):
"""replace the node here with the node from othereplus""" |
node = node.upper()
self.dt[node.upper()] = othereplus.dt[node.upper()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add2node(self, othereplus, node):
"""add the node here with the node from othereplus this will potentially have duplicates""" |
node = node.upper()
self.dt[node.upper()] = self.dt[node.upper()] + \
othereplus.dt[node.upper()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getrefs(self, reflist):
""" reflist is got from getobjectref in parse_idd.py getobjectref returns a dictionary. reflist is an item in the dictionary getrefs gathers all the fields refered by reflist """ |
alist = []
for element in reflist:
if element[0].upper() in self.dt:
for elm in self.dt[element[0].upper()]:
alist.append(elm[element[1]])
return alist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dropnodes(edges):
"""draw a graph without the nodes""" |
newedges = []
added = False
for edge in edges:
if bothnodes(edge):
newtup = (edge[0][0], edge[1][0])
newedges.append(newtup)
added = True
elif firstisnode(edge):
for edge1 in edges:
if edge[0] == edge1[1]:
newtup = (edge1[0], edge[1])
try:
newedges.index(newtup)
except ValueError as e:
newedges.append(newtup)
added = True
elif secondisnode(edge):
for edge1 in edges:
if edge[1] == edge1[0]:
newtup = (edge[0], edge1[1])
try:
newedges.index(newtup)
except ValueError as e:
newedges.append(newtup)
added = True
# gets the hanging nodes - nodes with no connection
if not added:
if firstisnode(edge):
newedges.append((edge[0][0], edge[1]))
if secondisnode(edge):
newedges.append((edge[0], edge[1][0]))
added = False
return newedges |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edges2nodes(edges):
"""gather the nodes from the edges""" |
nodes = []
for e1, e2 in edges:
nodes.append(e1)
nodes.append(e2)
nodedict = dict([(n, None) for n in nodes])
justnodes = list(nodedict.keys())
# justnodes.sort()
justnodes = sorted(justnodes, key=lambda x: str(x[0]))
return justnodes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makediagram(edges):
"""make the diagram with the edges""" |
graph = pydot.Dot(graph_type='digraph')
nodes = edges2nodes(edges)
epnodes = [(node,
makeanode(node[0])) for node in nodes if nodetype(node)=="epnode"]
endnodes = [(node,
makeendnode(node[0])) for node in nodes if nodetype(node)=="EndNode"]
epbr = [(node, makeabranch(node)) for node in nodes if not istuple(node)]
nodedict = dict(epnodes + epbr + endnodes)
for value in list(nodedict.values()):
graph.add_node(value)
for e1, e2 in edges:
graph.add_edge(pydot.Edge(nodedict[e1], nodedict[e2]))
return graph |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makebranchcomponents(data, commdct, anode="epnode"):
"""return the edges jointing the components of a branch""" |
alledges = []
objkey = 'BRANCH'
cnamefield = "Component %s Name"
inletfield = "Component %s Inlet Node Name"
outletfield = "Component %s Outlet Node Name"
numobjects = len(data.dt[objkey])
cnamefields = loops.repeatingfields(data, commdct, objkey, cnamefield)
inletfields = loops.repeatingfields(data, commdct, objkey, inletfield)
outletfields = loops.repeatingfields(data, commdct, objkey, outletfield)
inlts = loops.extractfields(data, commdct,
objkey, [inletfields] * numobjects)
cmps = loops.extractfields(data, commdct,
objkey, [cnamefields] * numobjects)
otlts = loops.extractfields(data, commdct,
objkey, [outletfields] * numobjects)
zipped = list(zip(inlts, cmps, otlts))
tzipped = [transpose2d(item) for item in zipped]
for i in range(len(data.dt[objkey])):
tt = tzipped[i]
# branchname = data.dt[objkey][i][1]
edges = []
for t0 in tt:
edges = edges + [((t0[0], anode), t0[1]), (t0[1], (t0[2], anode))]
alledges = alledges + edges
return alledges |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getedges(fname, iddfile):
"""return the edges of the idf file fname""" |
data, commdct, _idd_index = readidf.readdatacommdct(fname, iddfile=iddfile)
edges = makeairplantloop(data, commdct)
return edges |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeblanklines(astr):
"""remove the blank lines in astr""" |
lines = astr.splitlines()
lines = [line for line in lines if line.strip() != ""]
return "\n".join(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 _readfname(fname):
"""copied from extractidddata below. It deals with all the types of fnames""" |
try:
if isinstance(fname, (file, StringIO)):
astr = fname.read()
else:
astr = open(fname, 'rb').read()
except NameError:
if isinstance(fname, (FileIO, StringIO)):
astr = fname.read()
else:
astr = mylib2.readfile(fname)
return astr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_idd_index(extract_func, fname, debug):
"""generate the iddindex""" |
astr = _readfname(fname)
# fname is exhausted by the above read
# reconstitute fname as a StringIO
fname = StringIO(astr)
# glist = iddgroups.iddtxt2grouplist(astr.decode('ISO-8859-2'))
blocklst, commlst, commdct = extract_func(fname)
name2refs = iddindex.makename2refdct(commdct)
ref2namesdct = iddindex.makeref2namesdct(name2refs)
idd_index = dict(name2refs=name2refs, ref2names=ref2namesdct)
commdct = iddindex.ref2names2commdct(ref2namesdct, commdct)
return blocklst, commlst, commdct, idd_index |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def embedgroupdata(extract_func, fname, debug):
"""insert group info into extracted idd""" |
astr = _readfname(fname)
# fname is exhausted by the above read
# reconstitute fname as a StringIO
fname = StringIO(astr)
try:
astr = astr.decode('ISO-8859-2')
except Exception as e:
pass # for python 3
glist = iddgroups.iddtxt2grouplist(astr)
blocklst, commlst, commdct = extract_func(fname)
# add group information to commlst and commdct
# glist = getglist(fname)
commlst = iddgroups.group2commlst(commlst, glist)
commdct = iddgroups.group2commdct(commdct, glist)
return blocklst, commlst, commdct |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extractfields(data, commdct, objkey, fieldlists):
"""get all the objects of objkey. fieldlists will have a fieldlist for each of those objects. return the contents of those fields""" |
# TODO : this assumes that the field list identical for
# each instance of the object. This is not true.
# So we should have a field list for each instance of the object
# and map them with a zip
objindex = data.dtls.index(objkey)
objcomm = commdct[objindex]
objfields = []
# get the field names of that object
for dct in objcomm[0:]:
try:
thefieldcomms = dct['field']
objfields.append(thefieldcomms[0])
except KeyError as err:
objfields.append(None)
fieldindexes = []
for fieldlist in fieldlists:
fieldindex = []
for item in fieldlist:
if isinstance(item, int):
fieldindex.append(item)
else:
fieldindex.append(objfields.index(item) + 0)
# the index starts at 1, not at 0
fieldindexes.append(fieldindex)
theobjects = data.dt[objkey]
fieldcontents = []
for theobject, fieldindex in zip(theobjects, fieldindexes):
innerlst = []
for item in fieldindex:
try:
innerlst.append(theobject[item])
except IndexError as err:
break
fieldcontents.append(innerlst)
# fieldcontents.append([theobject[item] for item in fieldindex])
return fieldcontents |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.