Best Python code snippet using fMBT_python
imhub.py
Source:imhub.py
1'''23Logic for routing incoming messages to the correct IM window, and to the4notification system.56SMS messages are a special case, see window_for_sms78 on_message9 / \10fire_notifications window_for -> (resulting ImWin).message11 / \12 window_for_sms create_imwin13'''14from __future__ import with_statement1516import hooks17import wx18from wx import GetTopLevelWindows, GetTopLevelParent, WXK_CONTROL, GetKeyState, CallLater19FindFocus = wx.Window.FindFocus20import threading2122import gui.native.helpers as helpers23from util import strip_html2, odict, traceguard24from util.primitives.funcs import Delegate25from util.primitives.fmtstr import fmtstr26from util.lrucache import lru_cache27from common.notifications import fire28from common.sms import normalize_sms as smsize29from common.sms import validate_sms30from common import profile, pref31from gui.imwin.imwin_gui import ImWinPanel32from traceback import print_exc33from logging import getLogger; log = getLogger('imhub')34LOG = log.debug35from gui.uberwidgets.formattedinput import get_default_format3637strip_html2 = lru_cache(80)(strip_html2)3839def is_system_message(messageobj):40 return messageobj is not None and messageobj.buddy is None and \41 not getattr(messageobj, 'system_message_raises', False)4243def is_announcement(message):44 buddy = getattr(message, 'buddy', None)45 return buddy is not None and buddy.service == 'digsby' and buddy.name == 'digsby.org'4647def on_status(status, on_done=None):48 for imwin in ImWinPanel.all():49 if imwin.Buddy == status.buddy:50 wx.CallAfter(imwin.show_status, status, on_done)51 break5253def show_announce_window(message):54 from gui.imwin.imwin_gui import AnnounceWindow55 announce = AnnounceWindow(wx.FindWindowByName('Buddy List'))56 announce.message(message)57 wx.CallAfter(announce.Show)5859def show_announce_window_After(message):60 wx.CallAfter(show_announce_window, message)6162hooks.register('digsby.server.announcement', show_announce_window_After)6364def pre_message_hook(message):65 if is_announcement(message):66 # only show announcement windows to users with accounts (so new users67 # aren't shown an update changelog on first login)68 if profile.account_manager.all_accounts:69 show_announce_window(message)7071 # If the user is new, ignore the message.72 return False7374im_show = Delegate()7576def frame_show(frame, show, no_activate=False):77 assert isinstance(show, bool)7879 # wxMSW has a bug where frames created with wxMINIMIZE and then shown with ::Show()80 # do not have frame.m_iconize = true, and therefore don't send a wxIconizeEvent81 # for the first restore. showing the window with Iconize keeps m_iconized = true82 # and avoids the problem.83 if show and getattr(frame, '_starting_minimized', False):84 frame.Iconize(True)8586 # there's a wx bug where Iconize(True) to show a window as minimized does not set IsShown()87 # to be true. so call Show(True) manually here.88 frame.Show(True)8990 frame._starting_minimized = False91 else:92 if no_activate:93 frame.ShowNoActivate(show)94 else:95 frame.Show(show)969798def on_message(messageobj = None, convo = None, raisenow = False, meta = None, mode = 'im', firenots=True):99 '''100 Called with IM messages or conversations.101102 messageobj has "buddy" and "message" and "conversation" (at least)103 '''104 thread_check()105 from gui.imwin.imtabs import ImFrame106107 convo = messageobj.conversation if messageobj is not None else convo108 sms = messageobj.get('sms', False) if messageobj is not None else False109 sms = sms or getattr(getattr(convo, 'buddy', None), 'sms', False)110111 if pre_message_hook(messageobj) is False:112 return113114 system_message = is_system_message(messageobj)115116 if not raisenow:117 should_hide, isnew = hide_message(messageobj, meta, sms, system_message)118 if should_hide:119 if firenots:120 fire_notifications(messageobj, None, isnew, mode, hidden=True)121 return122123 win, isnew = window_for(convo, meta = meta, sms = sms,124 system_message = system_message,125 focus = True if raisenow else None,126 mode = mode)127 if win is None:128 return129130 # inform notification system131 if firenots:132 fire_notifications(messageobj, win, isnew, mode)133134 flashnow = True135 frame = GetTopLevelParent(win)136 focusedImFrame = isinstance(focused_top(), ImFrame)137138# print 'frame ', frame139# print 'frame.IsShown()', frame.IsShown()140# print 'focused_top ' , focused_top()141# print 'raisenow ', raisenow142# print 'focusedImFrame ', focusedImFrame143 global im_show144145 # Find out if the window's tab is currently being dragged146 if isnew:147 if raisenow and not focusedImFrame:148 im_show += lambda: log.info('calling frame.Show on frame at %r', frame.Rect)149 im_show += lambda: wx.CallAfter(lambda: frame_show(frame, True))150 else:151 if not frame.IsShown():152 im_show += lambda: log.info('calling frame.ShowNoActivate on frame at %r', frame.Rect)153 im_show += lambda: wx.CallAfter(lambda: frame_show(frame, True, no_activate=True))154155 if not focusedImFrame and (raisenow or (isnew and 'stealfocus' == new_action())):156 im_show += lambda: log.info('raising existing IM frame at %r', frame.Rect)157 im_show += lambda: raise_imwin(frame, win)158 else:159 if flashnow and messageobj is not None and not win.IsActive():160 bud = messageobj.buddy161 if bud is not None and bud is not messageobj.conversation.self_buddy:162 im_show += lambda: wx.CallAfter(win.Notify)163164 if not (pref('fullscreen.hide_convos', True) and helpers.FullscreenApp()): #@UndefinedVariable165 im_show.call_and_clear()166 else:167 log.info('im_hub.on_message ignoring for now because of fullscreen (delegate is %d messages long)', len(im_show))168 helpers.FullscreenAppLog()169170 # hand the message object off to the IM window171 win.message(messageobj, convo, mode, meta)172173 return win174175def focused_top():176 focused = FindFocus()177 return focused.Top if focused is not None else None178179def raise_imwin(frame, imwin):180 'Obtrusively raise an ImWin/ImFrame pair.'181182 log.info('raise_imwin: %r %r', frame, imwin)183184 if frame.IsIconized():185 frame.Iconize(False)186187 #HAX: For some reason Iconize(False) doesn't throw an IconizeEvent, fixed188 event = wx.IconizeEvent(frame.Id, False)189 frame.AddPendingEvent(event)190191 frame.ReallyRaise()192193 tab = imwin.Tab194 if tab is not None: tab.SetActive(True)195196def open(idstr):197 '''Opens an IM window (or raises an existing one) for a buddy id string.'''198199 contact = profile.blist.contact_for_idstr(idstr)200 if contact is not None:201 return begin_conversation(contact)202203def begin_conversation(contact, mode = 'im', forceproto = False):204 '''205 Invoked for actions like double clicking a buddy on the buddylist,206 i.e. starting a conversation with someone without messaging them207 yet.208 '''209 thread_check()210211 from contacts.metacontacts import MetaContact, OfflineBuddy212 if isinstance(contact, OfflineBuddy):213 log.info('cannot open an IM window for OfflineBuddy %r', contact)214 return215216 # are we asking for a metacontact?217 meta = contact if isinstance(contact, MetaContact) else None218219 # decide on a to/from220 if forceproto:221 proto = contact.protocol222 else:223 contact, proto = profile.blist.get_from(contact)224225 if proto is None:226 log.info('cannot open an IM window for %r, no compatible protocols?', contact)227 return228229 convo = proto.convo_for(contact)230231 # open the window232 if contact.sms and not profile.blist.on_buddylist(contact):233 mode = 'sms'234235 # pop any hidden_messages from this contact236 pop_any_hidden(contact)237238 return on_message(convo = convo, raisenow = True, meta = meta, mode = mode)239240def window_for(convo, meta = None, sms = False, system_message = False, focus = None, mode = 'im'):241 win, meta = find_window_for(convo, meta, sms, system_message)242243 if win is not None:244 return win, False245246 if sms and not profile.blist.on_buddylist(convo.buddy):247 # is this SMS number associated with a buddy? then open a window for248 # that buddy, not for the number249 convo = window_for_sms(convo)250251 if system_message:252 return None, None253254 win = create_imwin(convo, meta, sms, focus, mode)255 return win, True256257def find_window_for(convo, meta = None, sms = False, system_message = False):258 '''259 Finds the best IM tab for the given conversation.260261 Returns two objects, an ImWin and a boolean value indicating if the window262 is "new" or not.263264 If "system_message" is True, then a window will not be created on demand.265 '''266267 thread_check()268269 # the "meta" argument signifies to look only for the specified metacontact.270 if meta is None:271 metas = profile.metacontacts.forbuddy(convo.buddy) if not convo.ischat else []272 if metas:273 meta = list(metas)[0]274 else:275 metas = [meta]276277 return search_for_buddy(metas, convo, sms), meta278279def search_for_buddy(metas, convo, sms):280 for win in ImWinPanel.all():281 with traceguard:282 c = win.Conversation283284 # already talking to this buddy?285 if c is convo:286 LOG('direct conversation object match: win: %r, convo: %r', win, convo)287 return win288289 # is this an SMS message?290 if validate_sms(convo.buddy.name):291 for num in win.SMS:292 if validate_sms(num):293 if smsize(num) == smsize(convo.buddy.name):294 return win295296 # chat messages will go only to windows with matching conversation objects.297 if convo.ischat != win.convo.ischat:298 continue299300 # is there a window already open talking to another contact in this301 # contact's metacontact?302 winbud = win.Buddy303 if winbud is None:304 continue305306 for meta in metas:307 for contact in meta:308 if winbud == contact:309 LOG('matched %r with %r', winbud, contact)310 return win311312 # a looser match--one that might not match "From:" but only "To:"313 for contact in meta:314 if winbud.name == contact.name and winbud.protocol.name == contact.protocol.name:315 LOG('loosely matched %r with %r', winbud, contact)316 return win317318 if winbud.info_key == convo.buddy.info_key:319 return win320321def window_for_sms(convo):322 '''323 For a conversation with an SMS number, looks up contact infos for a buddy324 that matches and returns a conversation with that buddy.325 '''326 log.info('window_for_sms: %r', convo)327 thread_check()328329 buddy_sms = smsize(convo.buddy.name)330331 keys = []332333 # 'aim_dotsyntax1': {'alias': '',334 # 'sms': [u'4567891000', u'17248406085']},335 for infokey, infodict in profile.blist.info.iteritems():336 try:337 sms_numbers = infodict['sms']338 except KeyError:339 pass340 else:341 for s in list(sms_numbers):342 try:343 sms = smsize(s)344 except ValueError:345 log.critical("invalid SMS number in infodict[%r]['sms']: %r", infokey, s)346 sms_numbers.remove(s)347 else:348 if buddy_sms == sms:349 keys += [infokey]350 if not keys:351 log.info('no matching sms numbers found')352 return convo353354 conn = convo.protocol355356 for key in keys:357 if key.startswith('Metacontact #'):358 continue #TODO: metacontact-sms association359360 buddyname, proto = info_key_tuple(key)361362 #TODO: use something SERVICE_MAP in buddyliststore.py to make sure363 # digsby/jabber and aim/icq work correctly.364 if conn.protocol == proto and conn.has_buddy(buddyname):365 return conn.convo_for(conn.get_buddy(buddyname))366367 return convo368369def new_action():370 return pref('conversation_window.new_action')371372def create_imwin(convo, meta, sms, focus = None, mode = 'im'):373 '''374 Logic for where to place a new IM tab.375376 Spawns a a new ImWin object, placing it as a new tab in _some_ window377 somewhere, and returns the ImWin.378 '''379 thread_check()380381 from gui.imwin.imtabs import ImFrame382 f = None383384 hooks.notify('imwin.created')385386 focus = new_action() == 'stealfocus' if focus is None else focus387388 # if tabs are enabled, search for the oldest living ImFrame and place389 # the new message there--unless CTRL is being held down.390 ctrlDown = pref('messaging.tabs.ctrl_new_window', True) and GetKeyState(WXK_CONTROL)391392 if not ctrlDown and pref('messaging.tabs.enabled', True):393 for win in GetTopLevelWindows():394 if isinstance(win, ImFrame):395 f = win396 if f.IsActive():397 focus = False398 break399400 # if the focused control is an IM win's input box, don't steal focus.401 if isinstance(focused_top(), ImFrame):402 focus = False403404 if getattr(wx.Window.FindFocus(), 'click_raises_imwin', False) and wx.LeftDown():405 focus = True406407 # if we haven't found an ImFrame to put the tab in, create a new one408 if f is None:409 if pref('messaging.tabs.enabled', True):410 id = ''411 else:412 id = meta.idstr() if meta is not None else convo.buddy.idstr()413 f = ImFrame(startMinimized = not focus, posId = id)414415 w = ImWinPanel(f)416417 if convo is not None:418 w.set_conversation(convo, meta)419420 if focus:421 global im_show422 im_show += lambda: raise_imwin(f, w)423 im_show += lambda: w.FocusTextCtrl()424425 tab = f.AddTab(w, focus = focus)426 # NOTE: the native IM window doesn't use Page objects so we need to check427 # for it before adding to it.428 # FIXME: tab.OnActive seems to always be called by tab.SetActive, and tab.SetActive429 # also calls FocusTextCtrl on its text control, so is this needed still?430 if hasattr(tab, "OnActive"):431 tab.OnActive += w.FocusTextCtrl432433 hooks.notify('digsby.statistics.imwin.imwin_created')434435 return w436437438439def fire_notifications(msg, win, isnew, mode, hidden=False):440 '''441 Relays message information to the notifications system, for things like442 popups and sound effects.443444 msg a message object storage445 win the ImWin about to show this message446 isnew a bool indicating if the ImWin is "new"447 '''448449 if msg is None or msg.buddy is None: return []450451 convo = msg.conversation452 bud = msg.buddy453454 def stop_notify(win=win):455 if win:456 try:457 win.Unnotify()458 except wx.PyDeadObjectError:459 pass460 else:461 if not win.Top.AnyNotified and pref('conversation_window.notify_flash'):462 win.Top.StopFlashing()463 if hidden and pref('messaging.popups.close_dismisses_hidden', False):464 _remove_hidden_message(bud, msg)465466 if msg.get('content_type', 'text/html') in ('text/html', 'text/xhtml'):467 try:468 popup_message = strip_html2(msg.message).decode('xml')469 except Exception:470 print_exc()471 popup_message = msg.message472 else:473 popup_message = msg.message474475 # decide on options to pass to the popup476 fire_opts = dict(buddy = bud,477 onuserclose = stop_notify)478479 ischat = convo is not None and convo.ischat480 if ischat:481 from gui import skin482 fire_opts.update(header = _('Group Chat ({chat.chat_member_count:d})').format(chat=convo),483 msg = _('{alias:s}: {message:s}').format(alias=bud.alias, message=popup_message),484 icon = skin.get('ActionsBar.Icons.RoomList', None),485 popupid = 'chat!!!%r!!!%r' % (convo.protocol.name, convo.chat_room_name))486 else:487 fire_opts.update(msg = popup_message,488 icon = bud.buddy_icon if bud is not None else convo.icon,489 popupid = msg.buddy.idstr())490491492 # Clicking on the popup should open that buddy's message window.493 # - if there is text entered in the popup and not the IM window,494 # copy it there495 if bud is not None:496 def click_popup(text):497 if pop_any_hidden(bud):498 return499500 if convo.ischat:501 on_message(convo = convo, raisenow = True)502 else:503 begin_conversation(bud)504505 if win:506 try:507 val = win.input_area.Value508 except wx.PyDeadObjectError:509 pass510 else:511 if not val:512 win.input_area.Value = text513 wx.CallAfter(win.TextCtrl.SetInsertionPointEnd)514515 fire_opts.update(onclick = click_popup)516517 notification = _get_notification_types(bud, convo, win, hidden, isnew)518519 def send_from_popup(text, options, convo = convo, win = win, opts = fire_opts.copy()):520 if not text: return521522 CallLater(200, stop_notify)523524 # if the window's still around, use its formatting525 convo.send_message(fmtstr.singleformat(text, format=_get_format(win)))526527 if not wx.GetKeyState(wx.WXK_CONTROL):528 # returning a string appends it to the popup's content.529 return '> ' + text530531 # returning None results in the popup closing532533 fire_opts['input'] = send_from_popup534535 return fire(notification, **fire_opts)536537def _get_notification_types(bud, convo, win, hidden, isnew):538 # decide which type of message event to fire539 if bud is convo.self_buddy:540 notification = 'message.sent'541 elif hidden:542 # hidden messages get message.received.hidden, and also .initial if they are new543 notification = ['message.received.hidden']544 if isnew: notification.append('message.received.initial')545 else:546 # New messages have their own event type.547 if isnew:548 notification = 'message.received.initial'549550 # If the IM window isn't the active tab, or the "IM" button isn't the active one,551 # then fire a "background" message event.552 elif not win or not win.IsActive() or not wx.GetApp().IsActive() or win.Mode not in ('im', 'sms'):553 notification = 'message.received.background'554555 # Otherwise just use message.received.556 else:557 notification = 'message.received'558559 return notification560561def _get_format(win):562 '''563 returns the formatting dictionary for sending a message given an IM564 window that may or may not already be destroyed565 '''566567 format = None568569 if win:570 try:571 format = win.input_area.Format572 except wx.PyDeadObjectError:573 pass574 except Exception:575 print_exc()576577 if format is None:578 format = get_default_format()579580 return format581582def show_info(buddy):583 begin_conversation(buddy, mode = 'info')584585def thread_check():586 if threading.currentThread().getName() != 'MainThread':587 raise Exception('imhub methods must be called on the main GUI thread')588589590def info_key_tuple(info_key):591 i = info_key.find('_')592 if i == -1:593 assert False, repr(info_key)594 return info_key[:i], info_key[i+1:]595596#597# hidden messages598#599600hidden_windows = odict() # { contact: [message1, message2, ..] }601602def hidden_count():603 'Returns the number of hidden conversation windows.'604605 return len(hidden_windows)606607def hidden_convo_contacts():608 'Returns a list of all contacts with hidden conversations.'609610 return hidden_windows.keys()611612def hide_message(messageobj, meta, sms, system_message):613 'Hides a message.'614615 if messageobj is None:616 return False, False617618 convo = messageobj.conversation619620 # When messageobj buddy is self_buddy, we're sending a message. If there621 # is no existing IM window for the conversation, don't create one.622 if convo.self_buddy == messageobj.buddy:623 win, meta = find_window_for(convo, meta, sms, system_message)624 if not get_any_hidden(convo.buddy, pop=False):625 return win is None, False626627 if new_action() != 'hide':628 return False, False629630 win, meta = find_window_for(convo, meta, sms, system_message)631632 if win is not None:633 return False, False634635 ident = (meta or convo.buddy).info_key636637 if ident in hidden_windows:638 hidden_windows[ident].append(messageobj)639 isnew = False640 else:641 hidden_windows[ident] = [messageobj]642 isnew = True643644 _notify_hidden()645 return True, isnew646647def pop_all_hidden():648 'Display all hidden conversations.'649650 for contact in list(hidden_windows.keys()):651 pop_any_hidden(contact)652653def pop_any_hidden(contact, notify=True):654 # the quiet_log_messages is checked by MessageArea when replaying655 # log messages to see if any messages should be ignored656 from gui.imwin.messagearea import quiet_log_messages657658 all_messages = get_any_hidden(contact)659660 if not all_messages:661 return662663 with quiet_log_messages(all_messages):664 for messageobj in all_messages:665 with traceguard:666 on_message(messageobj, raisenow=True, firenots=False)667668 if notify:669 _notify_hidden()670671def get_any_hidden(contact, pop=True):672 keys = hidden_windows.keys()673 if not keys:674 return []675676 # hidden message may be stored under a metacontact info_key, so look it up here.677 contacts = set()678 if not isinstance(contact, basestring):679 contacts.update(m.info_key for m in680 profile.metacontacts.forbuddy(contact))681682 contact = getattr(contact, 'info_key', contact)683 contacts.add(contact)684685 all_messages = []686 for message_list in hidden_windows.values():687 all_messages.extend(message_list)688689 messages = []690 for c in keys:691 if c in contacts:692 if pop:693 msgs = hidden_windows.pop(c, [])694 else:695 msgs = hidden_windows.get(c, [])696697 messages.extend(msgs)698699 return messages700701def _remove_hidden_message(contact, message):702 contact = getattr(contact, 'info_key', contact)703704 try:705 messages = hidden_windows[contact]706 except KeyError:707 return False708 else:709 try:710 messages.remove(message)711 except ValueError:712 return False713 else:714 if len(messages) == 0:715 hidden_windows.pop(contact)716 _notify_hidden()717718 return True719720def _notify_hidden():721 hooks.notify('digsby.im.message_hidden', hidden_windows)
...
RaiseNowSalesforceTran.py
Source:RaiseNowSalesforceTran.py
1# -*- coding: utf-8 -*-2"""3Created on Tue Aug 2 16:05:40 202245@author: Sebastian Dudek6"""78import requests9import pandas as pd10import datetime11import numpy as np12import sys13from simple_salesforce import Salesforce14import time15161718class RaiseNow:1920 def __init__(self,data_start,data_end,limit=2000):212223 self._data_start = data_start24 self._data_end = data_end25 self._limit = limit2627 @property28 def data_start(self):29 return self._data_start3031 @property32 def data_end(self):33 return self._data_start3435 @property36 def limit(self):37 return self.limit383940 def download_transaction_list(self):41 """42 Funkcja pobiera dane z RaiseNow. Ustaw liczÄ rekordów.43 Dane sÄ
posortowane od najnowszych darowizn.44 """45#46 transaction_list = requests.get(47 """https://api.raisenow.com/epayment/api/"""+48 """************/transactions/search?sort[0][order]=ascendig""",49 params={'records_per_page': self._limit},50 auth=('************', '***************')).json()5152 transaction_list=pd.DataFrame(53 transaction_list['result']['transactions'])545556 transaction_list = transaction_list[transaction_list.last_status==57 'final_success']5859 transaction_list.created=transaction_list.created.apply(lambda x:60 datetime.datetime.fromtimestamp((int(x) )).strftime('%Y-%m-%d') )6162 transaction_list=transaction_list[(transaction_list.created >=63 self._data_start) & (transaction_list.created < self._data_end) ]6465 return transaction_list66676869 def download_transaction(self):7071 transaction_list=self.download_transaction_list()7273 transaction=[]7475 for i in transaction_list['epp_transaction_id']:7677 r=requests.get('https://api.raisenow.com/epayment/api/transaction/status',78 params={'transaction-id':i, 'merchant-config': '*********'},79 auth=('*****************', '**************'))80 transaction.append(r.json())8182 transaction=pd.DataFrame(transaction)8384 transaction.created=transaction.created.apply(lambda x:85 datetime.datetime.strptime(x[:10], '%Y-%m-%d') )8687 transaction=transaction[(transaction.created >88 self._data_start) & (transaction.created < self._data_end) ]8990 if transaction.empty:91 sys.exit()92 else:93 transaction = transaction[ transaction.test_mode == 'false' ]94 return transaction959697 def convert_columns(self):9899 df=self.download_transaction()100101 if df.empty:102 sys.exit()103 if 'stored_rnw_recurring_interval_text' not in df.columns:104105 df['stored_rnw_recurring_interval_text']='brak'106107108109110111112 df=df[[113 'stored_customer_firstname', 'stored_customer_lastname', 'stored_customer_street',114 'stored_customer_street2','stored_customer_street_number','stored_customer_city',115 'stored_customer_zip_code','stored_customer_email','stored_customer_email_permission',116 'stored_customer_birthdate','created','amount','stored_rnw_recurring_interval_text']]117118119120 df.columns= [ 'FirstName','LastName','MailingStreet','MailingStreet2',121 'MailingStreet3','MailingCity','MailingPostalCode', 'Email','Do_Not_Mail__c',122 'Birthdate','Transaction_Date__c', 'Transaction_Amount__c', 'is_recurring__c' ]123124 return df125126127128 def get_data(self):129130 df=self.convert_columns()131132133 # Walidacja danych do salesforce134135 df.is_recurring__c = df.is_recurring__c.apply(lambda x:136 False if ( str(x)=='nan' or str(x)=='brak') else True)137 df.Transaction_Amount__c=df.Transaction_Amount__c.apply(lambda x:138 float(x)/100.0)139140 df.Birthdate=df.Birthdate.apply(lambda x: np.nan if str(x).find('/') >0 else x)141142143144 df.Birthdate=df.Birthdate.apply(lambda x: np.nan if len(str(x))!=10 else x)145146 df.Transaction_Date__c=df.Transaction_Date__c.apply(147 lambda x: str(x)[:11])148149 df.MailingStreet = df[['MailingStreet','MailingStreet2','MailingStreet3']].apply(150 lambda x: ' '.join(x.dropna().values.tolist()) , axis=1 )151152 df=df.drop(['MailingStreet2', 'MailingStreet3' ], axis=1)153 df.MailingStreet=df.MailingStreet.apply(154 lambda x: str(x).replace(',', ' '))155156157158 df.insert(11, 'S__c', 'Accepted')159 df.insert(12, 'Source__c', 'PÅatnoÅÄ on-line')160 df.insert(13, 'Type__c', 'DOTACJA')161 df.insert(14, 'Description__c', 'Raisenow')162 df.insert(15, 'Filename__c', 'Raisenow'+'_'+ str(datetime.date.today()))163164 return df165166167168169170171class Import_Contact_RaiseNow:172173174175176177 def df_contakt(self):178179180 df_contakt = self.all_data()181 df_contakt = df_contakt[ ['FirstName', 'LastName', 'MailingStreet',182 'MailingCity', 'MailingPostalCode', 'Email', 'Do_Not_Mail__c',183 'Birthdate','is_recurring__c' ]]184185 df_contakt.Do_Not_Mail__c=df_contakt.Do_Not_Mail__c.apply(186 lambda x: 1 if x=='true' else 0 )187 df_contakt.Birthdate=df_contakt.Birthdate.apply(188 lambda x: np.nan if str(x).find('/') >0 else x)189 df_contakt.Birthdate=df_contakt.Birthdate.apply(190 lambda x: np.nan if len(str(x))!=10 else x)191 df_contakt.Birthdate = np.where((pd.isna(df_contakt['Birthdate']192 )==True),None ,df_contakt['Birthdate'] )193 df_contakt.Email = np.where((pd.isna(df_contakt['Email']194 )==True),None ,df_contakt['Email'] )195 return df_contakt196197 def salesforce_existing_emails(self):198 sf = Salesforce ( username = '****************' ,199 password = '***************' , security_token = '********************8' )200201 sf_email=pd.DataFrame(sf.query_all(202 "SELECT Id , Email from contact where Email like '_%' ")['records'])203204205 return sf_email206207 def existing_contacts(self):208 existing_contacts = pd.merge(self.salesforce_existing_emails(),209 self.df_contakt(), on='Email')210 existing_contacts = existing_contacts.iloc[:,1:]211 return existing_contacts212213 def new_contacts(self):214215 new_con = self.df_contakt().set_index('Email').join(216 self.existing_contacts().set_index('Email'),217 lsuffix='_caller', rsuffix='_other')218219220 new_con= new_con[ new_con.Id.isnull() ].iloc[ :, :8]221 new_con=new_con.reset_index()222223 new_con.columns = [ 'Email','FirstName', 'LastName', 'MailingStreet',224 'MailingCity','MailingPostalCode', 'Do_Not_Mail__c',225 'Birthdate','LeadSource' ]226227228 new_con.LeadSource= new_con.LeadSource.apply(229 lambda x: 'RC WEB' if str(x)=='True' else 'RaiseNow OneOff')230231 today_str=str(datetime.datetime.today())[:10]232233234 new_con.insert(9, 'AccountId', '*****')235 new_con.insert(10, 'OwnerId', '*****')236237 new_con.insert(11, 'Lead_creation_Date__c',str(today_str) )238239 new_con=new_con.drop_duplicates(subset=['Email'])240241 new_con.Lead_creation_Date__c.apply(lambda x: str(x))242 new_con.LeadSource.apply(lambda x: str(x) )243244245 return new_con246247 def import_new_contacts(self):248 sf = Salesforce ( username = '*************8' ,249 password = '***************' ,250 security_token = '************' )251252 log_import=[]253 if not self.new_contacts().empty:254 new_import=self.new_contacts().to_dict('records')255 new_import = [ new_import[x:x+7] for x in range(0, len(new_import), 7) ]256257 for i in new_import:258259 f=log_import=sf.bulk.Contact.insert(i)260261 log_import.append(f)262 time.sleep(10)263 else:264 time.sleep(10)265266 return log_import267268 def import_existing_contacts(self):269270 sf = Salesforce ( username = '********************' ,271 password = '**********************8' ,272 security_token = '***********************' )273274 existing_contacts = self.existing_contacts().iloc[:,:-1]275 existing_contacts=existing_contacts.drop_duplicates(subset=['Email'])276277278 log_import=[]279280 if not self.existing_contacts().empty:281 existing_contacts=existing_contacts.to_dict('records')282 existing_contacts = [ existing_contacts[x:x+25] for x in283 range(0, len(existing_contacts), 25) ]284285 for i in existing_contacts:286287 import_sf_e=log_import=sf.bulk.Contact.upsert(i, 'Id')288289 log_import.append(import_sf_e)290 time.sleep(10)291 else:292 time.sleep(10)293294 return log_import295296 def total_imports(self):297298 con_n=self.import_existing_contacts()299 time.sleep(20)300 con_e=self.import_new_contacts()301 total=[con_n,con_e]302 return total303304305 @staticmethod306307 def all_data():308 sf = Salesforce ( username = '********************' ,309 password = '****************' ,310 security_token = '**************************' )311 transakcje=pd.DataFrame(sf.query_all("SELECT Id, Transaction_Date__c FROM "312 "Transaction__c where Rachunek__c ='RAISENOW' and Transaction_Date__c > 2022-02-07 ")['records'])313314 start_date = transakcje['Transaction_Date__c'].max()315 data_end = str(datetime.datetime.today())[:10]316 all_data = RaiseNow(start_date,data_end).get_data()317318 return all_data319320321322323class Import_transaction_RaiseNow:324325326327328329 def df_transaction(self):330331332 df_transaction = self.all_data()333 df_transaction=df_transaction[['Email','Transaction_Date__c','Transaction_Amount__c',334 'is_recurring__c','S__c', 'Source__c', 'Type__c',335 'Description__c', 'Filename__c']]336 return df_transaction337338339 @staticmethod340 def all_data():341 sf = Salesforce ( username = '**********' ,342 password = '*************' ,343 security_token = '**************' )344 transakcje=pd.DataFrame(sf.query_all("SELECT Id, Transaction_Date__c FROM "345 "Transaction__c where Rachunek__c ='RAISENOW' and Transaction_Date__c > 2022-02-07 ")['records'])346347 start_date = transakcje['Transaction_Date__c'].max()348 data_end = str(datetime.datetime.today())[:10]349 all_data = RaiseNow(start_date,data_end).get_data()350351352 return all_data353354355 def salesforce_existing_emails(self):356 sf = Salesforce ( username = '************' ,357 password = '*************' , security_token = '***************' )358359 sf_email=pd.DataFrame(sf.query_all(360 "SELECT Id , Email from contact where Email like '_%' ")['records'])361362 return sf_email363364 def map_id_sf(self):365 map_id_sf = pd.merge(self.salesforce_existing_emails(),366 self.df_transaction(), on='Email')367 map_id_sf= map_id_sf[['Id', 'Transaction_Date__c',368 'Transaction_Amount__c', 'is_recurring__c', 'S__c', 'Source__c',369 'Type__c', 'Description__c', 'Filename__c']]370371 map_id_sf.columns= ['Contact_Payment__c', 'Transaction_Date__c',372 'Transaction_Amount__c', 'is_recurring__c', 'S__c', 'Source__c',373 'Type__c', 'Description__c', 'Filename__c']374 map_id_sf.Transaction_Date__c = map_id_sf.Transaction_Date__c.apply(lambda x: str(x)[:10] )375376377378 return map_id_sf379380381 def import_transaction(self):382 transaction = self.map_id_sf()383384 sf = Salesforce ( username = '************' ,385 password = '*************' , security_token = '***************' )386387388389 log_import=[]390 if not transaction.empty:391 transaction=transaction.to_dict('records')392 transaction = [ transaction[x:x+7] for x in range(0, len(transaction), 7) ]393394 for i in transaction:395396 f=log_import=sf.bulk.Transaction__c.insert(i)397398 log_import.append(f)399 time.sleep(15)400 else:401 time.sleep(15)402403 return log_import404405 def import_all_data(self):406407 contact_n=Import_Contact_RaiseNow().import_new_contacts()408409 time.sleep(20)410411 contact_e = Import_Contact_RaiseNow().import_existing_contacts()412413 time.sleep(20)414415 transaction = self.import_transaction()416417418419run=Import_transaction_RaiseNow().import_all_data()420421422423424425426427428
...
crashingsteps.py
Source:crashingsteps.py
...27import signal28g_importer_namespace = sys._getframe().f_back.f_globals29def crashnow():30 os.kill(os.getpid(), signal.SIGSEGV)31def raisenow():32 raise Exception("BogusException from crashingsteps.py")33def stdoutnow():34 sys.stdout.write('This is rubbish-to-stdout\n')35 sys.stdout.flush()36def stderrnow():37 sys.stderr.write('This is rubbish-to-stderr\n')38 sys.stderr.flush()39def check_bug(real_pos):40 if g_importer_namespace['BUG'].split('-')[0] == real_pos:41 eval(g_importer_namespace['BUG'].split('-')[1] + "now()")42check_bug("load")43def iTestStep():...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!