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 rename(self, new_folder_name): """Renames the Folder to the provided name. Args: new_folder_name: A string of the replacement name. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Returns: A new Folder representing the folder with the new name on Outlook. """
headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id payload = '{ "DisplayName": "' + new_folder_name + '"}' r = requests.patch(endpoint, headers=headers, data=payload) if check_response(r): return_folder = r.json() return self._json_to_folder(self.account, return_folder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_subfolders(self): """Retrieve all child Folders inside of this Folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Returns: List[:class:`Folder <pyOutlook.core.folder.Folder>`] """
headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/childfolders' r = requests.get(endpoint, headers=headers) if check_response(r): return self._json_to_folders(self.account, r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """Deletes this Folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. """
headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id r = requests.delete(endpoint, headers=headers) check_response(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 move_into(self, destination_folder): # type: (Folder) -> None """Move the Folder into a different folder. This makes the Folder provided a child folder of the destination_folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Args: destination_folder: A :class:`Folder <pyOutlook.core.folder.Folder>` that should become the parent Returns: A new :class:`Folder <pyOutlook.core.folder.Folder>` that is now inside of the destination_folder. """
headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/move' payload = '{ "DestinationId": "' + destination_folder.id + '"}' r = requests.post(endpoint, headers=headers, data=payload) if check_response(r): return_folder = r.json() return self._json_to_folder(self.account, return_folder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_child_folder(self, folder_name): """Creates a child folder within the Folder it is called from and returns the new Folder object. Args: folder_name: The name of the folder to create Returns: :class:`Folder <pyOutlook.core.folder.Folder>` """
headers = self.headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self.id + '/childfolders' payload = '{ "DisplayName": "' + folder_name + '"}' r = requests.post(endpoint, headers=headers, data=payload) if check_response(r): return_folder = r.json() return self._json_to_folder(self.account, return_folder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gformat(val, length=11): """Format a number with '%g'-like format, except that a) the length of the output string will be the requested length. b) positive numbers will have a leading blank. b) the precision will be as high as possible. c) trailing zeros will not be trimmed. The precision will typically be length-7. Arguments --------- val value to be formatted length length of output string Returns ------- string of specified length. Notes ------ Positive values will have leading blank. """
try: expon = int(log10(abs(val))) except (OverflowError, ValueError): expon = 0 length = max(length, 7) form = 'e' prec = length - 7 if abs(expon) > 99: prec -= 1 elif ((expon > 0 and expon < (prec+4)) or (expon <= 0 and -expon < (prec-1))): form = 'f' prec += 4 if expon > 0: prec -= expon fmt = '{0: %i.%i%s}' % (length, prec, form) return fmt.format(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 pack(window, sizer, expand=1.1): "simple wxPython pack function" tsize = window.GetSize() msize = window.GetMinSize() window.SetSizer(sizer) sizer.Fit(window) nsize = (10*int(expand*(max(msize[0], tsize[0])/10)), 10*int(expand*(max(msize[1], tsize[1])/10.))) window.SetSize(nsize)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Setup(self, event=None): """set up figure for printing. Using the standard wx Printer Setup Dialog. """
if hasattr(self, 'printerData'): data = wx.PageSetupDialogData() data.SetPrintData(self.printerData) else: data = wx.PageSetupDialogData() data.SetMarginTopLeft( (15, 15) ) data.SetMarginBottomRight( (15, 15) ) dlg = wx.PageSetupDialog(None, data) if dlg.ShowModal() == wx.ID_OK: data = dlg.GetPageSetupData() tl = data.GetMarginTopLeft() br = data.GetMarginBottomRight() self.printerData = wx.PrintData(data.GetPrintData()) dlg.Destroy()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Preview(self, title=None, event=None): """ generate Print Preview with wx Print mechanism"""
if title is None: title = self.title if self.canvas is None: self.canvas = self.parent.canvas po1 = PrintoutWx(self.parent.canvas, title=title, width=self.pwidth, margin=self.pmargin) po2 = PrintoutWx(self.parent.canvas, title=title, width=self.pwidth, margin=self.pmargin) self.preview = wx.PrintPreview(po1, po2, self.printerData) if ((is_wxPhoenix and self.preview.IsOk()) or (not is_wxPhoenix and self.preview.Ok())): self.preview.SetZoom(85) frameInst= self.parent while not isinstance(frameInst, wx.Frame): frameInst= frameInst.GetParent() frame = wx.PreviewFrame(self.preview, frameInst, "Preview") frame.Initialize() frame.SetSize((850, 650)) frame.Centre(wx.BOTH) frame.Show(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 set_float(val): """ utility to set a floating value, useful for converting from strings """
out = None if not val in (None, ''): try: out = float(val) except ValueError: return None if numpy.isnan(out): out = default 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 SetAction(self, action, **kws): "set callback action" if hasattr(action,'__call__'): self.__action = Closure(action, **kws)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __GetMark(self): " keep track of cursor position within text" try: self.__mark = min(wx.TextCtrl.GetSelection(self)[0], len(wx.TextCtrl.GetValue(self).strip())) except: self.__mark = 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 __SetMark(self, mark=None): "set mark for later" if mark is None: mark = self.__mark self.SetSelection(mark, mark)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def SetValue(self, value=None, act=True): " main method to set value " if value is None: value = wx.TextCtrl.GetValue(self).strip() self.__CheckValid(value) self.__GetMark() if value is not None: wx.TextCtrl.SetValue(self, self.format % set_float(value)) if self.is_valid and hasattr(self.__action, '__call__') and act: self.__action(value=self.__val) elif not self.is_valid and self.bell_on_invalid: wx.Bell() self.__SetMark()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def OnChar(self, event): """ on Character event"""
key = event.GetKeyCode() entry = wx.TextCtrl.GetValue(self).strip() pos = wx.TextCtrl.GetSelection(self) # really, the order here is important: # 1. return sends to ValidateEntry if key == wx.WXK_RETURN: if not self.is_valid: wx.TextCtrl.SetValue(self, self.format % set_float(self.__bound_val)) else: self.SetValue(entry) return # 2. other non-text characters are passed without change if (key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255): event.Skip() return # 3. check for multiple '.' and out of place '-' signs and ignore these # note that chr(key) will now work due to return at #2 has_minus = '-' in entry ckey = chr(key) if ((ckey == '.' and (self.__prec == 0 or '.' in entry) ) or (ckey == '-' and (has_minus or pos[0] != 0)) or (ckey != '-' and has_minus and pos[0] == 0)): return # 4. allow digits, but not other characters if chr(key) in self.__digits: event.Skip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __CheckValid(self, value): "check for validity of value" val = self.__val self.is_valid = True try: val = set_float(value) if self.__min is not None and (val < self.__min): self.is_valid = False val = self.__min if self.__max is not None and (val > self.__max): self.is_valid = False val = self.__max except: self.is_valid = False self.__bound_val = self.__val = val fgcol, bgcol = self.fgcol_valid, self.bgcol_valid if not self.is_valid: fgcol, bgcol = self.fgcol_invalid, self.bgcol_invalid self.SetForegroundColour(fgcol) self.SetBackgroundColour(bgcol) self.Refresh()
<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_text(self, text, x, y, side='left', size=None, rotation=None, ha='left', va='center', family=None, **kws): """add text at supplied x, y position"""
axes = self.axes if side == 'right': axes = self.get_right_axes() dynamic_size = False if size is None: size = self.conf.legendfont.get_size() dynamic_size = True t = axes.text(x, y, text, ha=ha, va=va, size=size, rotation=rotation, family=family, **kws) self.conf.added_texts.append((dynamic_size, t)) self.draw()
<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_arrow(self, x1, y1, x2, y2, side='left', shape='full', color='black', width=0.01, head_width=0.03, overhang=0, **kws): """add arrow supplied x, y position"""
dx, dy = x2-x1, y2-y1 axes = self.axes if side == 'right': axes = self.get_right_axes() axes.arrow(x1, y1, dx, dy, shape=shape, length_includes_head=True, fc=color, edgecolor=color, width=width, head_width=head_width, overhang=overhang, **kws) self.draw()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_xylims(self, limits, axes=None, side='left'): "set user-defined limits and apply them" if axes is None: axes = self.axes if side == 'right': axes = self.get_right_axes() self.conf.user_limits[axes] = limits self.unzoom_all()
<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_deriv(self, evt=None, value=None): "toggle derivative of data" if value is None: self.conf.data_deriv = not self.conf.data_deriv expr = self.conf.data_expr or '' if self.conf.data_deriv: expr = "deriv(%s)" % expr self.write_message("plotting %s" % expr, panel=0) self.conf.process_data()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def toggle_legend(self, evt=None, show=None): "toggle legend display" if show is None: show = not self.conf.show_legend self.conf.show_legend = show self.conf.draw_legend()
<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_grid(self, evt=None, show=None): "toggle grid display" if show is None: show = not self.conf.show_grid self.conf.enable_grid(show)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(self, event=None): """show configuration frame"""
if self.win_config is not None: try: self.win_config.Raise() except: self.win_config = None if self.win_config is None: self.win_config = PlotConfigFrame(parent=self, config=self.conf, trace_color_callback=self.trace_color_callback) self.win_config.Raise()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _updateCanvasDraw(self): """ Overload of the draw function that update axes position before each draw"""
fn = self.canvas.draw def draw2(*a,**k): self._updateGridSpec() return fn(*a,**k) self.canvas.draw = draw2
<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_default_margins(self): """get default margins"""
trans = self.fig.transFigure.inverted().transform # Static margins l, t, r, b = self.axesmargins (l, b), (r, t) = trans(((l, b), (r, t))) # Extent dl, dt, dr, db = 0, 0, 0, 0 for i, ax in enumerate(self.fig.get_axes()): (x0, y0),(x1, y1) = ax.get_position().get_points() try: (ox0, oy0), (ox1, oy1) = ax.get_tightbbox(self.canvas.get_renderer()).get_points() (ox0, oy0), (ox1, oy1) = trans(((ox0 ,oy0),(ox1 ,oy1))) dl = min(0.2, max(dl, (x0 - ox0))) dt = min(0.2, max(dt, (oy1 - y1))) dr = min(0.2, max(dr, (ox1 - x1))) db = min(0.2, max(db, (y0 - oy0))) except: pass return (l + dl, t + dt, r + dr, b + db)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_line(self, trace, xdata, ydata, side='left', draw=False, update_limits=True): """ update a single trace, for faster redraw """
x = self.conf.get_mpl_line(trace) x.set_data(xdata, ydata) datarange = [xdata.min(), xdata.max(), ydata.min(), ydata.max()] self.conf.set_trace_datarange(datarange, trace=trace) axes = self.axes if side == 'right': axes = self.get_right_axes() if update_limits: self.set_viewlimits() if draw: self.draw()
<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_userid_by_email(self, email): ''' get userid by email ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, email=email ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_user_id_by_user(self, username): ''' get user id by username ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, username=username ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_user_by_userid(self, userid): ''' get user by user id ''' response, status_code = self.__pod__.Users.get_v2_user( sessionToken=self.__session__, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_user_presence(self, userid): ''' check on presence of a user ''' response, status_code = self.__pod__.Presence.get_v2_user_uid_presence( sessionToken=self.__session__, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_user_presence(self, userid, presence): ''' set presence of user ''' response, status_code = self.__pod__.Presence.post_v2_user_uid_presence( sessionToken=self.__session__, uid=userid, presence=presence ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<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_features(self): ''' list features the pod supports ''' response, status_code = self.__pod__.System.get_v1_admin_system_features_list( sessionToken=self.__session__ ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def user_feature_update(self, userid, payload): ''' update features by user id ''' response, status_code = self.__pod__.User.post_v1_admin_user_uid_features_update( sessionToken=self.__session__, uid=userid, payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_user_avatar(self, userid): ''' get avatar by user id ''' response, status_code = self.__pod__.User.get_v1_admin_user_uid_avatar( sessionToken=self.__session, uid=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def user_avatar_update(self, userid, payload): ''' updated avatar by userid ''' response, status_code = self.__pod__.User.post_v1_admin_user_uid_avatar_update( sessionToken=self.__session, uid=userid, payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stream_members(self, stream_id): ''' get stream members ''' response, status_code = self.__pod__.Streams.get_v1_admin_stream_id_membership_list( sessionToken=self.__session__, id=stream_id ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def connection_status(self, userid): ''' get connection status ''' response, status_code = self.__pod__.Connection.get_v1_connection_user_userId_info( sessionToken=self.__session__, userId=userid ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ib_group_member_list(self, group_id): ''' ib group member list ''' req_hook = 'pod/v1/admin/group/' + group_id + '/membership/list' req_args = None status_code, response = self.__rest__.GET_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ib_group_member_add(self, group_id, userids): ''' ib group member add ''' req_hook = 'pod/v1/admin/group/' + group_id + '/membership/add' req_args = {'usersListId': userids} req_args = json.dumps(req_args) status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ib_group_policy_list(self): ''' ib group policy list ''' req_hook = 'pod/v1/admin/policy/list' req_args = None status_code, response = self.__rest__.GET_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_monitoring(self): """Enable periodically monitoring. """
if self.__monitoring is False: self.__monitoring = True self.__monitoring_action()
<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_MML(self, mml): ''' parse the MML structure ''' hashes_c = [] mentions_c = [] soup = BeautifulSoup(mml, "lxml") hashes = soup.find_all('hash', {"tag": True}) for hashe in hashes: hashes_c.append(hashe['tag']) mentions = soup.find_all('mention', {"uid": True}) for mention in mentions: mentions_c.append(mention['uid']) msg_string = soup.messageml.text.strip() self.logger.debug('%s : %s : %s' % (hashes_c, mentions_c, msg_string)) return hashes_c, mentions_c, msg_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 create_room(self, payload): ''' create a stream in a non-inclusive manner ''' response, status_code = self.__pod__.Streams.post_v2_room_create( # V2RoomAttributes payload=payload ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stream_info(self, stream_id): ''' get stream info ''' response, status_code = self.__pod__.Streams.get_v2_room_id_info( sessionToken=self.__session__, id=stream_id ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<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_stream(self, uidList=[]): ''' create a stream ''' req_hook = 'pod/v1/im/create' req_args = json.dumps(uidList) status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update_room(self, stream_id, room_definition): ''' update a room definition ''' req_hook = 'pod/v2/room/' + str(stream_id) + '/update' req_args = json.dumps(room_definition) status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def room_members(self, stream_id): ''' get list of room members ''' req_hook = 'pod/v2/room/' + str(stream_id) + '/membership/list' req_args = None status_code, response = self.__rest__.GET_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def promote_owner(self, stream_id, user_id): ''' promote user to owner in stream ''' req_hook = 'pod/v1/room/' + stream_id + '/membership/promoteOwner' req_args = '{ "id": %s }' % user_id status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<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_streams(self, types=[], inactive=False): ''' list user streams ''' req_hook = 'pod/v1/streams/list' json_query = { "streamTypes": types, "includeInactiveStreams": inactive } req_args = json.dumps(json_query) status_code, response = self.__rest__.POST_query(req_hook, req_args) self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
<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_unverified_claims(token): """Returns the decoded claims without verification of any kind. Args: token (str): A signed JWT to decode the headers from. Returns: dict: The dict representation of the token claims. Raises: JWTError: If there is an exception decoding the token. """
try: claims = jws.get_unverified_claims(token) except: raise JWTError('Error decoding token claims.') try: claims = json.loads(claims.decode('utf-8')) except ValueError as e: raise JWTError('Invalid claims string: %s' % e) if not isinstance(claims, Mapping): raise JWTError('Invalid claims string: must be a json object') return claims
<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_at_hash(claims, access_token, algorithm): """ Validates that the 'at_hash' parameter included in the claims matches with the access_token returned alongside the id token as part of the authorization_code flow. Args: claims (dict): The claims dictionary to validate. access_token (str): The access token returned by the OpenID Provider. algorithm (str): The algorithm used to sign the JWT, as specified by the token headers. """
if 'at_hash' not in claims and not access_token: return elif 'at_hash' in claims and not access_token: msg = 'No access_token provided to compare against at_hash claim.' raise JWTClaimsError(msg) elif access_token and 'at_hash' not in claims: msg = 'at_hash claim missing from token.' raise JWTClaimsError(msg) try: expected_hash = calculate_at_hash(access_token, ALGORITHMS.HASHES[algorithm]) except (TypeError, ValueError): msg = 'Unable to calculate at_hash to verify against token claims.' raise JWTClaimsError(msg) if claims['at_hash'] != expected_hash: raise JWTClaimsError('at_hash claim does not match access_token.')
<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_session_token(self): ''' get session token ''' # HTTP POST query to session authenticate API try: response = requests.post(self.__session_url__ + 'sessionauth/v1/authenticate', cert=(self.__crt__, self.__key__), verify=True) except requests.exceptions.RequestException as err: self.logger.error(err) raise if response.status_code == 200: # load json response as list data = json.loads(response.text) self.logger.debug(data) # grab token from list session_token = data['token'] else: raise Exception('BAD HTTP STATUS: %s' % str(response.status_code)) # return the token self.logger.debug(session_token) return session_token
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solar_spectrum(model='SOLAR-ISS'): r'''Returns the solar spectrum of the sun according to the specified model. Only the 'SOLAR-ISS' model is supported. Parameters ---------- model : str, optional The model to use; 'SOLAR-ISS' is the only model available, [-] Returns ------- wavelengths : ndarray The wavelengths of the solar spectra, [m] SSI : ndarray The solar spectral irradiance of the sun, [W/(m^2*m)] uncertainties : ndarray The estimated absolute uncertainty of the measured spectral irradiance of the sun, [W/(m^2*m)] Notes ----- The power of the sun changes as the earth gets closer or further away. In [1]_, the UV and VIS data come from observations in 2008; the IR comes from measurements made from 2010-2016. There is a further 28 W/m^2 for the 3 micrometer to 160 micrometer range, not included in this model. All data was corrected to a standard distance of one astronomical unit from the Sun, as is the resultant spectrum. The variation of the spectrum as a function of distance from the sun should alter only the absolute magnitudes. [2]_ contains another dataset. Examples -------- >>> wavelengths, SSI, uncertainties = solar_spectrum() Calculate the minimum and maximum values of the wavelengths (0.5 nm/3000nm) and SSI: >>> min(wavelengths), max(wavelengths), min(SSI), max(SSI) (5e-10, 2.9999000000000003e-06, 1330.0, 2256817820.0) Integration - calculate the solar constant, in untis of W/m^2 hitting earth's atmosphere. >>> np.trapz(SSI, wavelengths) 1344.802978238 References ---------- .. [1] Meftah, M., L. Damé, D. Bolsée, A. Hauchecorne, N. Pereira, D. Sluse, G. Cessateur, et al. "SOLAR-ISS: A New Reference Spectrum Based on SOLAR/SOLSPEC Observations." Astronomy & Astrophysics 611 (March 1, 2018): A1. https://doi.org/10.1051/0004-6361/201731316. .. [2] Woods Thomas N., Chamberlin Phillip C., Harder Jerald W., Hock Rachel A., Snow Martin, Eparvier Francis G., Fontenla Juan, McClintock William E., and Richard Erik C. "Solar Irradiance Reference Spectra (SIRS) for the 2008 Whole Heliosphere Interval (WHI)." Geophysical Research Letters 36, no. 1 (January 1, 2009). https://doi.org/10.1029/2008GL036373. ''' if model == 'SOLAR-ISS': pth = os.path.join(folder, 'solar_iss_2018_spectrum.dat') data = np.loadtxt(pth) wavelengths, SSI, uncertainties = data[:, 0], data[:, 1], data[:, 2] wavelengths = wavelengths*1E-9 SSI = SSI*1E9 # Convert -1 uncertainties to nans uncertainties[uncertainties == -1] = np.nan uncertainties = uncertainties*1E9 return wavelengths, SSI, uncertainties
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def qmax_boiling(rhol=None, rhog=None, sigma=None, Hvap=None, D=None, P=None, Pc=None, Method=None, AvailableMethods=False): r'''This function handles the calculation of nucleate boiling critical heat flux and chooses the best method for performing the calculation. Preferred methods are 'Serth-HEDH' when a tube diameter is specified, and 'Zuber' otherwise. Parameters ---------- rhol : float, optional Density of the liquid [kg/m^3] rhog : float, optional Density of the produced gas [kg/m^3] sigma : float, optional Surface tension of liquid [N/m] Hvap : float, optional Heat of vaporization of the fluid at T, [J/kg] D : float, optional Diameter of tubes [m] P : float, optional Saturation pressure of fluid, [Pa] Pc : float, optional Critical pressure of fluid, [Pa] Returns ------- q : float Nucleate boiling critical heat flux [W/m^2] methods : list, only returned if AvailableMethods == True List of methods which can be used to calculate qmax with the given inputs Other Parameters ---------------- Method : string, optional A string of the function name to use; one of ('Serth-HEDH', 'Zuber', or 'HEDH-Montinsky') AvailableMethods : bool, optional If True, function will consider which methods which can be used to calculate `qmax` with the given inputs Examples -------- >>> qmax_boiling(D=0.0127, sigma=8.2E-3, Hvap=272E3, rhol=567, rhog=18.09) 351867.46522901946 ''' def list_methods(): methods = [] if all((sigma, Hvap, rhol, rhog, D)): methods.append('Serth-HEDH') if all((sigma, Hvap, rhol, rhog)): methods.append('Zuber') if all((P, Pc)): methods.append('HEDH-Montinsky') return methods if AvailableMethods: return list_methods() if not Method: methods = list_methods() if methods == []: raise Exception('Insufficient property or geometry data for any ' 'method.') Method = methods[0] if Method == 'Serth-HEDH': return Serth_HEDH(D=D, sigma=sigma, Hvap=Hvap, rhol=rhol, rhog=rhog) elif Method == 'Zuber': return Zuber(sigma=sigma, Hvap=Hvap, rhol=rhol, rhog=rhog) elif Method == 'HEDH-Montinsky': return HEDH_Montinsky(P=P, Pc=Pc) else: raise Exception("Correlation name not recognized; options are " "'Serth-HEDH', 'Zuber' and 'HEDH-Montinsky'")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Nu_vertical_cylinder(Pr, Gr, L=None, D=None, Method=None, AvailableMethods=False): r'''This function handles choosing which vertical cylinder free convection correlation is used. Generally this is used by a helper class, but can be used directly. Will automatically select the correlation to use if none is provided; returns None if insufficient information is provided. Preferred functions are 'Popiel & Churchill' for fully defined geometries, and 'McAdams, Weiss & Saunders' otherwise. Examples -------- >>> Nu_vertical_cylinder(0.72, 1E7) 30.562236756513943 Parameters ---------- Pr : float Prandtl number [-] Gr : float Grashof number with respect to cylinder height [-] L : float, optional Length of vertical cylinder, [m] D : float, optional Diameter of cylinder, [m] Returns ------- Nu : float Nusselt number, [-] methods : list, only returned if AvailableMethods == True List of methods which can be used to calculate Nu with the given inputs Other Parameters ---------------- Method : string, optional A string of the function name to use, as in the dictionary vertical_cylinder_correlations AvailableMethods : bool, optional If True, function will consider which methods which can be used to calculate Nu with the given inputs ''' def list_methods(): methods = [] for key, values in vertical_cylinder_correlations.items(): if values[4] or all((L, D)): methods.append(key) if 'Popiel & Churchill' in methods: methods.remove('Popiel & Churchill') methods.insert(0, 'Popiel & Churchill') elif 'McAdams, Weiss & Saunders' in methods: methods.remove('McAdams, Weiss & Saunders') methods.insert(0, 'McAdams, Weiss & Saunders') return methods if AvailableMethods: return list_methods() if not Method: Method = list_methods()[0] if Method in vertical_cylinder_correlations: if vertical_cylinder_correlations[Method][4]: return vertical_cylinder_correlations[Method][0](Pr=Pr, Gr=Gr) else: return vertical_cylinder_correlations[Method][0](Pr=Pr, Gr=Gr, L=L, D=D) else: raise Exception("Correlation name not recognized; see the " "documentation for the available options.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Nu_horizontal_cylinder(Pr, Gr, Method=None, AvailableMethods=False): r'''This function handles choosing which horizontal cylinder free convection correlation is used. Generally this is used by a helper class, but can be used directly. Will automatically select the correlation to use if none is provided; returns None if insufficient information is provided. Prefered functions are 'Morgan' when discontinuous results are acceptable and 'Churchill-Chu' otherwise. Parameters ---------- Pr : float Prandtl number [-] Gr : float Grashof number [-] Returns ------- Nu : float Nusselt number, [-] methods : list, only returned if AvailableMethods == True List of methods which can be used to calculate Nu with the given inputs Other Parameters ---------------- Method : string, optional A string of the function name to use, as in the dictionary horizontal_cylinder_correlations AvailableMethods : bool, optional If True, function will consider which methods which can be used to calculate Nu with the given inputs Examples -------- >>> Nu_horizontal_cylinder(0.72, 1E7) 24.864192615468973 ''' def list_methods(): methods = [] for key, values in horizontal_cylinder_correlations.items(): methods.append(key) if 'Morgan' in methods: methods.remove('Morgan') methods.insert(0, 'Morgan') return methods if AvailableMethods: return list_methods() if not Method: Method = list_methods()[0] if Method in horizontal_cylinder_correlations: return horizontal_cylinder_correlations[Method](Pr=Pr, Gr=Gr) else: raise Exception("Correlation name not recognized; see the " "documentation for the available options.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calc_Cmin(mh, mc, Cph, Cpc): r'''Returns the heat capacity rate for the minimum stream having flows `mh` and `mc`, with averaged heat capacities `Cph` and `Cpc`. .. math:: C_c = m_cC_{p,c} C_h = m_h C_{p,h} C_{min} = \min(C_c, C_h) Parameters ---------- mh : float Mass flow rate of hot stream, [kg/s] mc : float Mass flow rate of cold stream, [kg/s] Cph : float Averaged heat capacity of hot stream, [J/kg/K] Cpc : float Averaged heat capacity of cold stream, [J/kg/K] Returns ------- Cmin : float The heat capacity rate of the smaller fluid, [W/K] Notes ----- Used with the effectiveness method for heat exchanger design. Technically, it doesn't matter if the hot and cold streams are in the right order for the input, but it is easiest to use this function when the order is specified. Examples -------- >>> calc_Cmin(mh=22., mc=5.5, Cph=2200, Cpc=4400.) 24200.0 References ---------- .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011. ''' Ch = mh*Cph Cc = mc*Cpc return min(Ch, Cc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calc_Cmax(mh, mc, Cph, Cpc): r'''Returns the heat capacity rate for the maximum stream having flows `mh` and `mc`, with averaged heat capacities `Cph` and `Cpc`. .. math:: C_c = m_cC_{p,c} C_h = m_h C_{p,h} C_{max} = \max(C_c, C_h) Parameters ---------- mh : float Mass flow rate of hot stream, [kg/s] mc : float Mass flow rate of cold stream, [kg/s] Cph : float Averaged heat capacity of hot stream, [J/kg/K] Cpc : float Averaged heat capacity of cold stream, [J/kg/K] Returns ------- Cmax : float The heat capacity rate of the larger fluid, [W/K] Notes ----- Used with the effectiveness method for heat exchanger design. Technically, it doesn't matter if the hot and cold streams are in the right order for the input, but it is easiest to use this function when the order is specified. Examples -------- >>> calc_Cmax(mh=22., mc=5.5, Cph=2200, Cpc=4400.) 48400.0 References ---------- .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011. ''' Ch = mh*Cph Cc = mc*Cpc return max(Ch, Cc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calc_Cr(mh, mc, Cph, Cpc): r'''Returns the heat capacity rate ratio for a heat exchanger having flows `mh` and `mc`, with averaged heat capacities `Cph` and `Cpc`. .. math:: C_r=C^*=\frac{C_{min}}{C_{max}} Parameters ---------- mh : float Mass flow rate of hot stream, [kg/s] mc : float Mass flow rate of cold stream, [kg/s] Cph : float Averaged heat capacity of hot stream, [J/kg/K] Cpc : float Averaged heat capacity of cold stream, [J/kg/K] Returns ------- Cr : float The heat capacity rate ratio, of the smaller fluid to the larger fluid, [W/K] Notes ----- Used with the effectiveness method for heat exchanger design. Technically, it doesn't matter if the hot and cold streams are in the right order for the input, but it is easiest to use this function when the order is specified. Examples -------- >>> calc_Cr(mh=22., mc=5.5, Cph=2200, Cpc=4400.) 0.5 References ---------- .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011. ''' Ch = mh*Cph Cc = mc*Cpc Cmin = min(Ch, Cc) Cmax = max(Ch, Cc) return Cmin/Cmax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Pc(x, y): r'''Basic helper calculator which accepts a transformed R1 and NTU1 as inputs for a common term used in the calculation of the P-NTU method for plate exchangers. Returns a value which is normally used in other calculations before the actual P1 is calculated. Nominally used in counterflow calculations .. math:: P_c(x, y) = \frac{1 - \exp[-x(1 - y)]}{1 - y\exp[-x(1 - y)]} Parameters ---------- x : float A modification of NTU1, the Thermal Number of Transfer Units [-] y : float A modification of R1, the thermal effectiveness [-] Returns ------- z : float Just another term in the calculation, [-] Notes ----- Used with the P-NTU plate method for heat exchanger design. At y =-1, this function has a ZeroDivisionError but can be evaluated at the limit to be :math:`z = \frac{x}{1+x}`. Examples -------- >>> Pc(5, .7) 0.9206703686051108 References ---------- .. [1] Shah, Ramesh K., and Dusan P. Sekulic. Fundamentals of Heat Exchanger Design. 1st edition. Hoboken, NJ: Wiley, 2002. .. [2] Rohsenow, Warren and James Hartnett and Young Cho. Handbook of Heat Transfer, 3E. New York: McGraw-Hill, 1998. ''' try: term = exp(-x*(1. - y)) return (1. - term)/(1. - y*term) except ZeroDivisionError: return x/(1. + x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _NTU_from_P_solver(P1, R1, NTU_min, NTU_max, function, **kwargs): '''Private function to solve the P-NTU method backwards, given the function to use, the upper and lower NTU bounds for consideration, and the desired P1 and R1 values. ''' P1_max = _NTU_from_P_objective(NTU_max, R1, 0, function, **kwargs) P1_min = _NTU_from_P_objective(NTU_min, R1, 0, function, **kwargs) if P1 > P1_max: raise ValueError('No solution possible gives such a high P1; maximum P1=%f at NTU1=%f' %(P1_max, NTU_max)) if P1 < P1_min: raise ValueError('No solution possible gives such a low P1; minimum P1=%f at NTU1=%f' %(P1_min, NTU_min)) # Construct the function as a lambda expression as solvers don't support kwargs to_solve = lambda NTU1: _NTU_from_P_objective(NTU1, R1, P1, function, **kwargs) return ridder(to_solve, NTU_min, NTU_max)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _NTU_max_for_P_solver(data, R1): '''Private function to calculate the upper bound on the NTU1 value in the P-NTU method. This value is calculated via a pade approximation obtained on the result of a global minimizer which calculated the maximum P1 at a given R1 from ~1E-7 to approximately 100. This should suffice for engineering applications. This value is needed to bound the solver. ''' offset_max = data['offset'][-1] for offset, p, q in zip(data['offset'], data['p'], data['q']): if R1 < offset or offset == offset_max: x = R1 - offset return _horner(p, x)/_horner(q, x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Ntubes_VDI(DBundle=None, Ntp=None, Do=None, pitch=None, angle=30.): r'''A rough equation presented in the VDI Heat Atlas for estimating the number of tubes in a tube bundle of differing geometries and tube sizes. No accuracy estimation given. Parameters ---------- DBundle : float Outer diameter of tube bundle, [m] Ntp : float Number of tube passes, [-] Do : float Tube outer diameter, [m] pitch : float Pitch; distance between two orthogonal tube centers, [m] angle : float The angle the tubes are positioned; 30, 45, 60 or 90, [degrees] Returns ------- N : float Number of tubes, [-] Notes ----- No coefficients for this method with Ntp=6 are available in [1]_. For consistency, estimated values were added to support 6 tube passes, f2 = 90.. This equation is a rearranged form of that presented in [1]_. The calculated tube count is rounded down to an integer. Examples -------- >>> Ntubes_VDI(DBundle=1.184, Ntp=2, Do=.028, pitch=.036, angle=30) 966 References ---------- .. [1] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition. Berlin; New York:: Springer, 2010. ''' if Ntp == 1: f2 = 0. elif Ntp == 2: f2 = 22. elif Ntp == 4: f2 = 70. elif Ntp == 8: f2 = 105. elif Ntp == 6: f2 = 90. # Estimated! else: raise Exception('Only 1, 2, 4 and 8 passes are supported') if angle == 30 or angle == 60: f1 = 1.1 elif angle == 45 or angle == 90: f1 = 1.3 else: raise Exception('Only 30, 60, 45 and 90 degree layouts are supported') DBundle, Do, pitch = DBundle*1000, Do*1000, pitch*1000 # convert to mm, equation is dimensional. t = pitch Ntubes = (-(-4*f1*t**4*f2**2*Do + 4*f1*t**4*f2**2*DBundle**2 + t**4*f2**4)**0.5 - 2*f1*t**2*Do + 2*f1*t**2*DBundle**2 + t**2*f2**2) / (2*f1**2*t**4) return int(Ntubes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def D_for_Ntubes_VDI(N, Ntp, Do, pitch, angle=30): r'''A rough equation presented in the VDI Heat Atlas for estimating the size of a tube bundle from a given number of tubes, number of tube passes, outer tube diameter, pitch, and arrangement. No accuracy estimation given. .. math:: OTL = \sqrt{f_1 z t^2 + f_2 t \sqrt{z} - d_o} Parameters ---------- N : float Number of tubes, [-] Ntp : float Number of tube passes, [-] Do : float Tube outer diameter, [m] pitch : float Pitch; distance between two orthogonal tube centers, [m] angle : float The angle the tubes are positioned; 30, 45, 60 or 90 Returns ------- DBundle : float Outer diameter of tube bundle, [m] Notes ----- f1 = 1.1 for triangular, 1.3 for square patterns f2 is as follows: 1 pass, 0; 2 passes, 22; 4 passes, 70; 8 passes, 105. 6 tube passes is not officially supported, only 1, 2, 4 and 8. However, an estimated constant has been added to support it. f2 = 90. Examples -------- >>> D_for_Ntubes_VDI(N=970, Ntp=2., Do=0.00735, pitch=0.015, angle=30.) 0.5003600119829544 References ---------- .. [1] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition. Berlin; New York:: Springer, 2010. ''' if Ntp == 1: f2 = 0. elif Ntp == 2: f2 = 22. elif Ntp == 4: f2 = 70. elif Ntp == 6: f2 = 90. elif Ntp == 8: f2 = 105. else: raise Exception('Only 1, 2, 4 and 8 passes are supported') if angle == 30 or angle == 60: f1 = 1.1 elif angle == 45 or angle == 90: f1 = 1.3 else: raise Exception('Only 30, 60, 45 and 90 degree layouts are supported') Do, pitch = Do*1000, pitch*1000 # convert to mm, equation is dimensional. Dshell = (f1*N*pitch**2 + f2*N**0.5*pitch +Do)**0.5 return Dshell/1000.
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Ntubes_HEDH(DBundle=None, Do=None, pitch=None, angle=30): r'''A rough equation presented in the HEDH for estimating the number of tubes in a tube bundle of differing geometries and tube sizes. No accuracy estimation given. Only 1 pass is supported. .. math:: N = \frac{0.78(D_{bundle} - D_o)^2}{C_1(\text{pitch})^2} C1 = 0.866 for 30° and 60° layouts, and 1 for 45 and 90° layouts. Parameters ---------- DBundle : float Outer diameter of tube bundle, [m] Do : float Tube outer diameter, [m] pitch : float Pitch; distance between two orthogonal tube centers, [m] angle : float The angle the tubes are positioned; 30, 45, 60 or 90, [degrees] Returns ------- N : float Number of tubes, [-] Notes ----- Seems reasonably accurate. Examples -------- >>> Ntubes_HEDH(DBundle=1.184, Do=.028, pitch=.036, angle=30) 928 References ---------- .. [1] Schlunder, Ernst U, and International Center for Heat and Mass Transfer. Heat Exchanger Design Handbook. Washington: Hemisphere Pub. Corp., 1983. ''' if angle == 30 or angle == 60: C1 = 13/15. elif angle == 45 or angle == 90: C1 = 1. else: raise Exception('Only 30, 60, 45 and 90 degree layouts are supported') Dctl = DBundle - Do N = 0.78*Dctl**2/C1/pitch**2 return int(N)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def DBundle_for_Ntubes_HEDH(N, Do, pitch, angle=30): r'''A rough equation presented in the HEDH for estimating the tube bundle diameter necessary to fit a given number of tubes. No accuracy estimation given. Only 1 pass is supported. .. math:: D_{bundle} = (D_o + (\text{pitch})\sqrt{\frac{1}{0.78}}\cdot \sqrt{C_1\cdot N}) C1 = 0.866 for 30° and 60° layouts, and 1 for 45 and 90° layouts. Parameters ---------- N : float Number of tubes, [-] Do : float Tube outer diameter, [m] pitch : float Pitch; distance between two orthogonal tube centers, [m] angle : float The angle the tubes are positioned; 30, 45, 60 or 90, [degrees] Returns ------- DBundle : float Outer diameter of tube bundle, [m] Notes ----- Easily reversed from the main formulation. Examples -------- >>> DBundle_for_Ntubes_HEDH(N=928, Do=.028, pitch=.036, angle=30) 1.1839930795640605 References ---------- .. [1] Schlunder, Ernst U, and International Center for Heat and Mass Transfer. Heat Exchanger Design Handbook. Washington: Hemisphere Pub. Corp., 1983. ''' if angle == 30 or angle == 60: C1 = 13/15. elif angle == 45 or angle == 90: C1 = 1. else: raise Exception('Only 30, 60, 45 and 90 degree layouts are supported') return (Do + (1./.78)**0.5*pitch*(C1*N)**0.5)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setup(self, data, view='hypergrid', schema=None, columns=None, rowpivots=None, columnpivots=None, aggregates=None, sort=None, index='', limit=-1, computedcolumns=None, settings=True, embed=False, dark=False, *args, **kwargs): '''Setup perspective base class Arguments: data : dataframe/list/dict The static or live datasource Keyword Arguments: view : str or View what view to use. available in the enum View (default: {'hypergrid'}) columns : list of str what columns to display rowpivots : list of str what names to use as rowpivots columnpivots : list of str what names to use as columnpivots aggregates: dict(str: str or Aggregate) dictionary of name to aggregate type (either string or enum Aggregate) index : str columns to use as index limit : int row limit computedcolumns : list of dict computed columns to set on the perspective viewer settings : bool display settings settings : bool embedded mode dark : bool use dark theme ''' self.view = validate_view(view) self.schema = schema or {} self.sort = validate_sort(sort) or [] self.index = index self.limit = limit self.settings = settings self.embed = embed self.dark = dark self.rowpivots = validate_rowpivots(rowpivots) or [] self.columnpivots = validate_columnpivots(columnpivots) or [] self.aggregates = validate_aggregates(aggregates) or {} self.columns = validate_columns(columns) or [] self.computedcolumns = validate_computedcolumns(computedcolumns) or [] self.load(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def R_cylinder(Di, Do, k, L): r'''Returns the thermal resistance `R` of a cylinder of constant thermal conductivity `k`, of inner and outer diameter `Di` and `Do`, and with a length `L`. .. math:: (hA)_{\text{cylinder}}=\frac{k}{\ln(D_o/D_i)} \cdot 2\pi L\\ R_{\text{cylinder}}=\frac{1}{(hA)_{\text{cylinder}}}= \frac{\ln(D_o/D_i)}{2\pi Lk} Parameters ---------- Di : float Inner diameter of the cylinder, [m] Do : float Outer diameter of the cylinder, [m] k : float Thermal conductivity of the cylinder, [W/m/K] L : float Length of the cylinder, [m] Returns ------- R : float Thermal resistance [K/W] Examples -------- >>> R_cylinder(0.9, 1., 20, 10) 8.38432343682705e-05 References ---------- .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011. ''' hA = k*2*pi*L/log(Do/Di) return 1./hA
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def S_isothermal_pipe_to_isothermal_pipe(D1, D2, W, L=1.): r'''Returns the Shape factor `S` of a pipe of constant outer temperature and of outer diameter `D1` which is `w` distance from another infinite pipe of outer diameter`D2`. Length `L` must be provided, but can be set to 1 to obtain a dimensionless shape factor used in some sources. .. math:: S = \frac{2\pi L}{\cosh^{-1}\left(\frac{4w^2-D_1^2-D_2^2}{2D_1D_2}\right)} Parameters ---------- D1 : float Diameter of one pipe, [m] D2 : float Diameter of the other pipe, [m] W : float Distance from the middle of one pipe to the middle of the other, [m] L : float, optional Length of the pipe, [m] Returns ------- S : float Shape factor [m] Examples -------- >>> S_isothermal_pipe_to_isothermal_pipe(.1, .2, 1, 1) 1.188711034982268 Notes ----- L should be much larger than both diameters. L should be larger than W. .. math:: Q = Sk(T_1 - T_2) \\ R_{\text{shape}}=\frac{1}{Sk} References ---------- .. [1] Kreith, Frank, Raj Manglik, and Mark Bohn. Principles of Heat Transfer. Cengage, 2010. .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011. ''' return 2.*pi*L/acosh((4*W**2 - D1**2 - D2**2)/(2.*D1*D2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def S_isothermal_pipe_to_two_planes(D, Z, L=1.): r'''Returns the Shape factor `S` of a pipe of constant outer temperature and of outer diameter `D` which is `Z` distance from two infinite isothermal planes of equal temperatures, parallel to each other and enclosing the pipe. Length `L` must be provided, but can be set to 1 to obtain a dimensionless shape factor used in some sources. .. math:: S = \frac{2\pi L}{\ln\frac{8z}{\pi D}} Parameters ---------- D : float Diameter of the pipe, [m] Z : float Distance from the middle of the pipe to either of the planes, [m] L : float, optional Length of the pipe, [m] Returns ------- S : float Shape factor [m] Examples -------- >>> S_isothermal_pipe_to_two_planes(.1, 5, 1) 1.2963749299921428 Notes ----- L should be much larger than both diameters. L should be larger than W. .. math:: Q = Sk(T_1 - T_2) \\ R_{\text{shape}}=\frac{1}{Sk} References ---------- .. [1] Shape Factors for Heat Conduction Through Bodies with Isothermal or Convective Boundary Conditions, J. E. Sunderland, K. R. Johnson, ASHRAE Transactions, Vol. 70, 1964. .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011. ''' return 2.*pi*L/log(8.*Z/(pi*D))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def S_isothermal_pipe_eccentric_to_isothermal_pipe(D1, D2, Z, L=1.): r'''Returns the Shape factor `S` of a pipe of constant outer temperature and of outer diameter `D1` which is `Z` distance from the center of another pipe of outer diameter`D2`. Length `L` must be provided, but can be set to 1 to obtain a dimensionless shape factor used in some sources. .. math:: S = \frac{2\pi L}{\cosh^{-1} \left(\frac{D_2^2 + D_1^2 - 4Z^2}{2D_1D_2}\right)} Parameters ---------- D1 : float Diameter of inner pipe, [m] D2 : float Diameter of outer pipe, [m] Z : float Distance from the middle of inner pipe to the center of the other, [m] L : float, optional Length of the pipe, [m] Returns ------- S : float Shape factor [m] Examples -------- >>> S_isothermal_pipe_eccentric_to_isothermal_pipe(.1, .4, .05, 10) 47.709841915608976 Notes ----- L should be much larger than both diameters. D2 should be larger than D1. .. math:: Q = Sk(T_1 - T_2) \\ R_{\text{shape}}=\frac{1}{Sk} References ---------- .. [1] Kreith, Frank, Raj Manglik, and Mark Bohn. Principles of Heat Transfer. Cengage, 2010. .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011. ''' return 2.*pi*L/acosh((D2**2 + D1**2 - 4.*Z**2)/(2.*D1*D2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def LMTD(Thi, Tho, Tci, Tco, counterflow=True): r'''Returns the log-mean temperature difference of an ideal counterflow or co-current heat exchanger. .. math:: \Delta T_{LMTD}=\frac{\Delta T_1-\Delta T_2}{\ln(\Delta T_1/\Delta T_2)} \text{For countercurrent: } \\ \Delta T_1=T_{h,i}-T_{c,o}\\ \Delta T_2=T_{h,o}-T_{c,i} \text{Parallel Flow Only:} \\ {\Delta T_1=T_{h,i}-T_{c,i}}\\ {\Delta T_2=T_{h,o}-T_{c,o}} Parameters ---------- Thi : float Inlet temperature of hot fluid, [K] Tho : float Outlet temperature of hot fluid, [K] Tci : float Inlet temperature of cold fluid, [K] Tco : float Outlet temperature of cold fluid, [K] counterflow : bool, optional Whether the exchanger is counterflow or co-current Returns ------- LMTD : float Log-mean temperature difference [K] Notes ----- Any consistent set of units produces a consistent output. Examples -------- Example 11.1 in [1]_. >>> LMTD(100., 60., 30., 40.2) 43.200409294131525 >>> LMTD(100., 60., 30., 40.2, counterflow=False) 39.75251118049003 References ---------- .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011. ''' if counterflow: dTF1 = Thi-Tco dTF2 = Tho-Tci else: dTF1 = Thi-Tci dTF2 = Tho-Tco return (dTF2 - dTF1)/log(dTF2/dTF1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def k2g(kml_path, output_dir, separate_folders, style_type, style_filename): """ Given a path to a KML file, convert it to a a GeoJSON FeatureCollection file and save it to the given output directory. If ``--separate_folders``, then create several GeoJSON files, one for each folder in the KML file that contains geodata or that has a descendant node that contains geodata. Warning: this can produce GeoJSON files with the same geodata in case the KML file has nested folders with geodata. If ``--style_type`` is specified, then also build a JSON style file of the given style type and save it to the output directory under the file name given by ``--style_filename``. """
m.convert(kml_path, output_dir, separate_folders, style_type, style_filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disambiguate(names, mark='1'): """ Given a list of strings ``names``, return a new list of names where repeated names have been disambiguated by repeatedly appending the given mark. EXAMPLE:: ['sing', 'song', 'sing1', 'sing11'] """
names_seen = set() new_names = [] for name in names: new_name = name while new_name in names_seen: new_name += mark new_names.append(new_name) names_seen.add(new_name) return new_names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_rgb_and_opacity(s): """ Given a KML color string, return an equivalent RGB hex color string and an opacity float rounded to 2 decimal places. EXAMPLE:: ('#221100', 0.93) """
# Set defaults color = '000000' opacity = 1 if s.startswith('#'): s = s[1:] if len(s) == 8: color = s[6:8] + s[4:6] + s[2:4] opacity = round(int(s[0:2], 16)/256, 2) elif len(s) == 6: color = s[4:6] + s[2:4] + s[0:2] elif len(s) == 3: color = s[::-1] return '#' + color, opacity
<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_svg_style(node): """ Given a DOM node, grab its top-level Style nodes, convert every one into a SVG style dictionary, put them in a master dictionary of the form #style ID -> SVG style dictionary, and return the result. The possible keys and values of each SVG style dictionary, the style options, are - ``iconUrl``: URL of icon - ``stroke``: stroke color; RGB hex string - ``stroke-opacity``: stroke opacity - ``stroke-width``: stroke width in pixels - ``fill``: fill color; RGB hex string - ``fill-opacity``: fill opacity """
d = {} for item in get(node, 'Style'): style_id = '#' + attr(item, 'id') # Create style properties props = {} for x in get(item, 'PolyStyle'): color = val(get1(x, 'color')) if color: rgb, opacity = build_rgb_and_opacity(color) props['fill'] = rgb props['fill-opacity'] = opacity # Set default border style props['stroke'] = rgb props['stroke-opacity'] = opacity props['stroke-width'] = 1 fill = valf(get1(x, 'fill')) if fill == 0: props['fill-opacity'] = fill elif fill == 1 and 'fill-opacity' not in props: props['fill-opacity'] = fill outline = valf(get1(x, 'outline')) if outline == 0: props['stroke-opacity'] = outline elif outline == 1 and 'stroke-opacity' not in props: props['stroke-opacity'] = outline for x in get(item, 'LineStyle'): color = val(get1(x, 'color')) if color: rgb, opacity = build_rgb_and_opacity(color) props['stroke'] = rgb props['stroke-opacity'] = opacity width = valf(get1(x, 'width')) if width is not None: props['stroke-width'] = width for x in get(item, 'IconStyle'): icon = get1(x, 'Icon') if not icon: continue # Clear previous style properties props = {} props['iconUrl'] = val(get1(icon, 'href')) d[style_id] = props return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_available(self, locator): """ Synchronization to deal with elements that are present, and are visible :raises: ElementVisiblityTimeout """
for i in range(timeout_seconds): try: if self.is_element_available(locator): break except: pass time.sleep(1) else: raise ElementVisiblityTimeout("%s availability timed out" % locator) 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 wait_for_visible(self, locator): """ Synchronization to deal with elements that are present, but are disabled until some action triggers their visibility. :raises: ElementVisiblityTimeout """
for i in range(timeout_seconds): try: if self.driver.is_visible(locator): break except: pass time.sleep(1) else: raise ElementVisiblityTimeout("%s visibility timed out" % locator) 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 wait_for_text(self, locator, text): """ Synchronization on some text being displayed in a particular element. :raises: ElementVisiblityTimeout """
for i in range(timeout_seconds): try: e = self.driver.find_element_by_locator(locator) if e.text == text: break except: pass time.sleep(1) else: raise ElementTextTimeout("%s value timed out" % locator) 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 wait_for_element_not_present(self, locator): """ Synchronization helper to wait until some element is removed from the page :raises: ElementVisiblityTimeout """
for i in range(timeout_seconds): if self.driver.is_element_present(locator): time.sleep(1) else: break else: raise ElementVisiblityTimeout("%s presence timed out" % locator) 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 validate(tool_class, model_class): """ Does basic ObjectTool option validation. """
if not hasattr(tool_class, 'name'): raise ImproperlyConfigured("No 'name' attribute found for tool %s." % ( tool_class.__name__ )) if not hasattr(tool_class, 'label'): raise ImproperlyConfigured("No 'label' attribute found for tool %s." % ( tool_class.__name__ )) if not hasattr(tool_class, 'view'): raise NotImplementedError("No 'view' method found for tool %s." % ( tool_class.__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 construct_form(self, request): """ Constructs form from POST method using self.form_class. """
if not hasattr(self, 'form_class'): return None if request.method == 'POST': form = self.form_class(self.model, request.POST, request.FILES) else: form = self.form_class(self.model) return form
<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_permission(self, user): """ Returns True if the given request has permission to use the tool. Can be overriden by the user in subclasses. """
return user.has_perm( self.model._meta.app_label + '.' + self.get_permission() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def media(self, form): """ Collects admin and form media. """
js = ['admin/js/core.js', 'admin/js/admin/RelatedObjectLookups.js', 'admin/js/jquery.min.js', 'admin/js/jquery.init.js'] media = forms.Media( js=['%s%s' % (settings.STATIC_URL, u) for u in js], ) if form: for name, field in form.fields.items(): media = media + field.widget.media return media
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _urls(self): """ URL patterns for tool linked to _view method. """
info = ( self.model._meta.app_label, self.model._meta.model_name, self.name, ) urlpatterns = [ url(r'^%s/$' % self.name, self._view, name='%s_%s_%s' % info) ] return urlpatterns
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_context(self, request): """ Builds context with various required variables. """
opts = self.model._meta app_label = opts.app_label object_name = opts.object_name.lower() form = self.construct_form(request) media = self.media(form) context = { 'user': request.user, 'title': '%s %s' % (self.label, opts.verbose_name_plural.lower()), 'tool': self, 'opts': opts, 'app_label': app_label, 'media': media, 'form': form, 'changelist_url': reverse('admin:%s_%s_changelist' % ( app_label, object_name )) } # Pass along fieldset if sepcififed. if hasattr(form, 'fieldsets'): admin_form = helpers.AdminForm(form, form.fieldsets, {}) context['adminform'] = admin_form return context
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _view(self, request, extra_context=None): """ View wrapper taking care of houskeeping for painless form rendering. """
if not self.has_permission(request.user): raise PermissionDenied return self.view(request, self.construct_context(request))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def randomRow(self): """ Gets a random row from the provider :returns: List """
l = [] for row in self.data: l.append(row) return random.choice(l)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_equal(self, first, second, msg=""): """ Soft assert for equality :params want: the value to compare against :params second: the value to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_equal(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_not_equal(self, first, second, msg=""): """ Soft assert for inequality :params want: the value to compare against :params second: the value to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_not_equal(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_true(self, expr, msg=None): """ Soft assert for whether the condition is true :params expr: the statement to evaluate :params msg: (Optional) msg explaining the difference """
try: self.assert_true(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_false(self, expr, msg=None): """ Soft assert for whether the condition is false :params expr: the statement to evaluate :params msg: (Optional) msg explaining the difference """
try: self.assert_false(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_is(self, first, second, msg=None): """ Soft assert for whether the parameters evaluate to the same object :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_is(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_is_not(self, first, second, msg=None): """ Soft assert for whether the parameters do not evaluate to the same object :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_is_not(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_is_none(self, expr, msg=None): """ Soft assert for whether the expr is None :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_is_none(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_is_not_none(self, expr, msg=None): """ Soft assert for whether the expr is not None :params want: the object to compare against :params second: the object to compare with :params msg: (Optional) msg explaining the difference """
try: self.assert_is_not_none(expr, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_in(self, first, second, msg=""): """ Soft assert for whether the first is in second :params first: the value to check :params second: the container to check in :params msg: (Optional) msg explaining the difference """
try: self.assert_in(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_not_in(self, first, second, msg=""): """ Soft assert for whether the first is not in second :params first: the value to check :params second: the container to check in :params msg: (Optional) msg explaining the difference """
try: self.assert_not_in(first, second, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_is_instance(self, obj, cls, msg=""): """ Soft assert for whether the is an instance of cls :params obj: the object instance :params cls: the class to compare against :params msg: (Optional) msg explaining the difference """
try: self.assert_is_instance(obj, cls, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)
<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_is_not_instance(self, obj, cls, msg=""): """ Soft assert for whether the is not an instance of cls :params obj: the object instance :params cls: the class to compare against :params msg: (Optional) msg explaining the difference """
try: self.assert_is_not_instance(obj, cls, msg) except AssertionError, e: if msg: m = "%s:\n%s" % (msg, str(e)) else: m = str(e) self.verification_erorrs.append(m)