text:
#Done:
#      1. done: epdg stop/failed analysis, add detailed cause
#      2. done: error table list, td with color
#      3. add html ref link,
#      4. link on the error text
#      5. error details display
#      5.1 rewrite updatereportEvent and constructreportEvent, add field
#      11. back to top
#      #       6. add catagory to display, top occurence and timestamp (Definition of Done: DoD )
#       6.1 user action,  phone, scenario
#       7. add ho, call, user action

#
#       8. add normal scenarioes details
#       8.1 timestamps, etc
#       8.2 redirect all overview log to overview.log and add a link in html, link to main.pdf
#       10. add datarouter count
#      8.1.2 imscm operation result
#        OPERATION_SWITCH_TO_VOWIFI, OPERATION_SWITCH_TO_VOLTE,...... defined in ImsConnectionMangerConstants.java
#      8.1.3 wpa_supplicant: wlan0: State: ASSOCIATED -> COMPLETED
#       8.3 datarouter error
#        D:\code\log\bug_log\vit_log\2017_3_2\wificalling_no_Voice_video_1082#0310a
#        [Adapter]VoWifiCallManager: Failed to update the data router state, please check
#         imscm Currently used IMS protocol stack: "VoLte IMS protocol stack"
#      8.1.4 cp color, green, volte failed
#     D:\code\log\bug_log\vit_log\2017_3_24\659070\Handover_to_VoLTE_Calldrop_2238\external_storage\ylog\ylog
#        8.1.5 504 timeout
#        ImsReasonInfo.java, more definition
#        D:\code\log\srvcc\wei_504
# 03-27 15:10:06.227  1134  1134 I [VoWifiService]VoWifiSerService: Notify the event: {"event_code":105,"event_name":"call_terminate","id":1,"state_code":146}
#         D:\code\log\srvcc\503\slog_20170327151140_sp9832a_2h11_4mvolt_vowif_userdebu\external_storage\ylog\ylog
#     8.1.6 ap color, servicecallback : talking, ok should be green
#       8.1.7 srvcc report
#      8.1.8 call_terminate report
#       9. radio log catagory
#       9.1 FIXME: add at cmd result , log is too verboses....
#           D:\code\iwhale2\log\cp_reject
#       self.atmsgs, add field
#     8.1.9  search pattern , add logic to handle subprocess

#     8.1.11 ImsCM code changed.
#       #temporary add some logs.
#      1. card is not enabled.
#      2. audioqos: D:\code\log\bug_log\vit_log\2017_3_24\659089\ylog

##    8.1.12  ims code ACTION_SWITCH_IMS_FEATURE,
#     , add
#     aidl: vendor/sprd/platform/frameworks/
#     case:
#          1. EVENT_WIFI_ATTACH_SUCCESSED, EVENT_WIFI_ATTACH_FAILED, ACTION_NOTIFY_VOWIFI_UNAVAILABLE
#          2. ImsService: Needn't switch to type 2 as it already registed.
#          3. OPERATION_HANDOVER_TO_VOWIFI in ImsCM is the same in tele's IMS_OPERATION_HANDOVER_TO_VOWIFI
#          4. tele's log.w, log.e
#D:\code\log\ref_log\instruments\Anritsu\call_scenarioes\merge_test\log4
#http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=663113
#http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=659089
#D:\code\log\bug_log\vit_log\2017_3_24\659089\ylog
#      8.1.3.4 new imscm : D:\code\log\ref_log\EE\poweroff_dereg
#      8.1.3.1 REGISTER display add backward option for searchsip
##     8.1.3.3 new s2b code C:\Users\Zhihua.Ye\Documents\MyJabberFiles\yingying.fan@spreadtrum.com\s2b_new\ylog\
#     8.1.10 onLoginFinished
#D:\code\log\bug_log\vit_log\2017_3_24\660071\ylog
#   8.1.3  log more
#         1. 01-01 09:18:14.321  1140  2496 I CPVoiceAgent: [cp_mediaset]: AT+SPRTPMEDIASET=3,1,1,1
#         2. DSCI D:\code\log\bug_log\vit_log\2017_4_14\660061\ylog2

##   new ho no rtp
#  8.2.0 add calling mode
#  Wifi-calling mode is "Cellular preferred"
#   8.2.a.3  CEREG add too verbose, FIXME: not to added

#   8.2.a    pcscf passing
#   8.2.a.1 ap to cp: AT+VOWIFIPCSCF
#Parameter:
#< type>: 0, FQDN
#        1, IPV4
#        2, IPV6
#<addr> string
#       AT+VOWIFIPCSCF=1,"10.15.0.26"
#   8.2.a.2 cp to ap: ImsServiceImpl: getImsPcscfAddress mImsPscfAddress = \\10.0.0.166\Logs\From_Taipei\Taipei_Logs\VoWiFiPowerTest\Indonisa\0503
#    D:\code\log\ref_log\smartfren\smart_volte_idle_ho_vowifi\android
#    full function open, error grep
#    D:\code\merge\isharkl2 do_ip failed
#    add zxsocket grep...
##   8.2.a.4 parse tw logs failed, no sip D:\code\merge\tw\672534\volte_ho_vowifi
#    8.0.111 Authentication: Failed to get the challenge response. D:\code\so\juphoonlib\develop\7lib\sos\1
#    8.2.00  imscm ho stragtegy

#   new imscm logs D:\code\merge\dtac
#   1. createPolicyTimerTask: don't create timer task during Vowifi and 2/3G or UNKNOWN network
#   add all task "Conditions are not satisfied" , warning
#    D:\code\merge\indonisia\can'tregistervowifi2\ylog\android
#   8.3 add pending warning, s2b not return
#  D:\code\log\bug_log\vit_log\2017_4_14\668339\ylog
#   handleMessageSwitchToVowifi: "MSG_SWITCH_TO_VOWIFI", mCurPendingMsgId = "MSG_RELEASE_VOWIFI_RES",

#    8.0 simplify error output.
#     eventname/timestamp in html is not correct
#   8.2.01  D:\code\log\ref_log\instruments\sprient\newversion2\nonce_null
#   1. add error:Can not get data from the nonce as it is null
#   2. impu, impi
#   3. crash log findings
#    native crash :  D:\code\log\ref_log\instruments\sprient\newversion2\nonce_null
#       04-15 16:28:38.234  6114  6114 F DEBUG   : pid: 4663, tid: 4686, name: Thread-4  >>> com.sprd.vowifi.security <<<
#    app crash:      D:\code\log\bug_log\vit_log\2017_4_14\665551\vowifiservice\log_sp9861e_1h10_vm_userdebu\external_storage\ylog
#       04-13 19:53:25.953  3814  3814 E AndroidRuntime: Process: com.spreadtrum.vowifi, PID: 3814
#      http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=678093
#    7.9.1  imscm
#    rssi = ,  loss =, audioLoss =, videoLoss =
#    D:\code\log\bug_log\vit_log\2017_5_1\677097\ylog
#TODO:
#    7.7. ScreenStateReceiver SCREEN_OFF, SCREEN_ON - not useful

#   7.7.1 at cmd:  CGDCONT

#    7.6 sip searching , should add
#    process request
#    process response
#    gui notify
#    D:\code\merge\ee\sip_error
#    7.8.x cp tuple issue
#    D:\code\merge\vdf\TCP syn no response
#    7.9.0 impu, impi
#    7.9 emergency call
#    8.1.99 save some json file

#   8.2.b optimize lemonlog in flowParser.py
#   8.2.02 onsrvccfailed http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=666546
#   8.2.002 deactive-pdn failed http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=673148

# D:\code\log\bug_log\vit_log\2017_4_14\piclab_4_17\HO_connection\ylog
#   8.2.1 ImcM Qos
#    http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=666173
#   8.2.2 call optimization
#    add call number D:\code\log\bug_log\vit_log\2017_4_14\665355
#   8.2.3 more media AT parsing., SPRTPCHANNEL
#   CPVoiceAgent: AT> AT+SPRTPCHANNEL="01018D9009AA8C9008AA010A0F200600000000000000000000000001647CDFCB000000000000000000000000"

#
#      8.1.3.2 new ike error code
#      high prio

#       1. display flag on handler
#      8.1.4 D:\code\log\ref_log\instruments\Anritsu\error_sample  error sample
#     8.1.4.1 add crash report
#     8.1.12 rssi, Qos jquery chart.

#     8.1.13 dialer
#          CallCardPresenter.java, CallButtonPresenter.java
#    add more decode about call and profile
# InCall  : CallCardPresenter - Disconnecting call: [Call_2, ACTIVE, [Capabilities: CAPABILITY_HOLD CAPABILITY_SUPPORT_HOLD CAPABILITY_MUTE CAPABILITY_SUPPORTS_VT_LOCAL_RX CAPABILITY_SUPPORTS_VT_LOCAL_TX CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL CAPABILITY_SUPPORTS_VT_REMOTE_RX CAPABILITY_SUPPORTS_VT_REMOTE_TX CAPABILITY_SUPPORTS_VT_REMOTE_BIDIRECTIONAL CAPABILITY_CAN_PAUSE_VIDEO], children:[], parent:null, conferenceable:[], videoState:Audio Only, mSessionModificationState:0, VideoSettings:(CameraDir:-1)
#    packages/apps/Dialer/InCallUI/src/com/android/incallui
#    from callcard to try the call duration
#

#     8.2.0 http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=659089
#      my comments
#       8.2.1 call session
#       event.log /main.pdf diffs
#      8.2.3 all success/failed event, only care about handover, register,call
#      handover errors:
#      volte register fail: D:\code\log\bug_log\vit_log\2017_3_24\659089\13slog_20170325222251_sp9832a_2h11_ho_VoWIFI_dropcall_2220-2222\external_storage\ylog
#      vowifi register faile: D:\code\log\bug_log\vit_log\2017_4_1\spirent_rereg\ylog
#      s2b failed: D:\code\log\bug_log\vit_log\2017_4_14\666137\ylog1\
#
#      8.2.4 owner display : too aggressive

#      8.2.300 regstatus add refresh failed

#https://SHTEMP832PC.spreadtrum.com:444/svn/Vowifi_Log_Tool/
#log tool
#一般人就用user账户下载,不需要密码
#你用admin:admin上传
#renlong.he 2296206

#
# 8.1.100 ipsec cmd
#
#
#       9.2 add CPVoiceAgent 's at parsing
#           D:\code\log\bug_log\vit_log\2017_3_2\con_call
#       at cmd
#       9.3 ringtone
#
#

#       10.0  g_astMtcCliCodeMap , g_astMtcCallCodeMap

#       10. add imsservice logic
#            onReceiveHandoverEvent, onImsHandoverStateChange,onImsPdnStatusChange,
#       imscm's logic  : "imsServiceEx"
#       add timing calcute
#       15. outgoing, alerting
#       16. more bugs to analyze
#       16.1 imswaitvoltereg D:\code\log\bug_log\vit_log\2017_2_14\644337\Fail_S2b_Attach_Data_OK_No_error_popup\AP\ylog
#
#       wifi call end with volte call ,volte not reg. , IMSEN=1 not send
#       try vowifi call ,ho to volte, end call ,if reg to volte
#       16.1.1 D:\code\iwhale2\log\cp_reject ho cp reject
#       16.2 imscmopfailed  D:\code\log\bug_log\vit_log\2017_2_14\644735\IDLE_1\slog_20170217133643_sp9832a_2h11_4mvoltesea_userdebug\external_storage\ylog\ylog
#       16.3 imscallend http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=645833
#       16.4 conf scenario:  http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=646232
#       16.5 camera D:\code\log\bug_log\vit_log\2017_2_14\644983\vowifi_Active Video + MT Alerting Video\1\2\external_storage\ylog\ylog
#        Set the camera to
#        16.6 sim card not support vowifi:  D:\code\so\juphoonlib\develop\6lib\lib\sim_not_support
#        setCheckWifiConnectivityState: not found plmn in mAllPlmnArrayList and not Lab's card
#
#        add report
#       17. predict:
#       17.1 wifi conn
#       17.2 callid, call state match, incoming ,talking...
#       17.3 idle ho , ho in call
#       17.3 stack state
#       17.3 module owner, doc update
#       17.8 ho success: epdg, pdn, etc
#       17.9 call term by user/network
#       18. supplementary service

#       12. process duration: s2b, reg, ho, call
#       12.1 duration
#       13 tracing log should be deleted.
#       14. chinese name path

# ppt prepare:
#   1. scenarioes: D:\code\log\bug_log\vit_log\2017_4_14\668542

from reportEvent import *

class langBuilder():
    def __init__(self, zh='', en=''):
        self.phrase = dict()
        self.phrase['lang'] = dict()
        self.phrase['lang']['zh'] = zh
        self.phrase['lang']['en'] = en

    def geten(self):
        return self.phrase['lang']['en']

    def getzh(self):
        return self.phrase['lang']['zh']

    def getenzh(self):
        #use
 to combine
        return self.phrase['lang']['en'] + "
" + self.phrase['lang']['zh']

class reportBuilder():
    def __init__(self, type, event, level, errorstr=''):
        self.report = dict()
        self.report['type'] = type
        self.report['event'] = event
        self.report['level'] = level
        self.report['errorstr'] = errorstr

    def getreport(self):
        return self.report

def map2phrase(key, phrasemap):
    if type(phrasemap) is not dict:
        return key
    if key in phrasemap:
        return phrasemap[key].geten()
    else:
        return key

#FIXME: not easily mapping , add more arg??
def mapzhphrase(key, phrasemap, pre= '',post=''):
    if type(phrasemap) is not dict:
        return key
    if key in phrasemap:
        assembleen = pre + phrasemap[key].geten()+ post
        if phrasemap[key].getzh():
            assemblezh = pre + phrasemap[key].getzh()+ post
        else:
            assemblezh = ''
        return assembleen + "
" + assemblezh
    else:
        return key

#S2B phrase
Reports2bphrase = dict()
Reports2bphrase['successed'] = dict()
Reports2bphrase['successed'] = langBuilder(zh="ePDG驻网成功", en="ePDG attach successfully")

Reports2bphrase['failed'] = dict()
Reports2bphrase['failed'] = langBuilder(zh="ePDG驻网失败", en="ePDG attach failed")

Reports2bphrase['stopped'] = dict()
Reports2bphrase['stopped'] = langBuilder(zh="ePDG驻网正常停止", en="ePDG attach stopped")

Reports2bphrase['stopped_abnormally'] = dict()
Reports2bphrase['stopped_abnormally'] = langBuilder(zh="ePDG驻网异常停止", en="ePDG attach stopped abnormally")

#Register callback
Reportregphrase = dict()
Reportregphrase['login_ok'] = dict()
Reportregphrase['login_ok'] = langBuilder(zh="VoWiFi注册成功", en="VoWiFi Registered")

Reportregphrase['login_failed'] = dict()
Reportregphrase['login_failed'] = langBuilder(zh="VoWiFi注册失败", en="VoWiFi Failed to Register")

Reportregphrase['logouted'] = dict()
Reportregphrase['logouted'] = langBuilder(zh="VoWiFi去注册", en="VoWiFi UnRegistered")

Reportregphrase['refresh_ok'] = dict()
Reportregphrase['refresh_ok'] = langBuilder(zh="VoWiFi 刷新注册成功", en="VoWiFi Re-Registered")

Reportregphrase['refresh_failed'] = dict()
Reportregphrase['refresh_failed'] = langBuilder(zh="VoWiFi 刷新注册失败", en="VoWiFi Failed to Re-Registered")

Reportregphrase['state_update'] = dict()
Reportregphrase['state_update'] = langBuilder(zh="VoWiFi注册状态更新", en="VoWiFi RegState Update")

#Handover actions
ReportHandoverphrase = dict()
ReportHandoverphrase['wificonn'] = dict()
ReportHandoverphrase['wificonn'] = langBuilder(zh="ImsCM 连上WiFi", en="ImsCM WiFi is Connected")

ReportHandoverphrase['wifidisconn'] = dict()
ReportHandoverphrase['wifidisconn'] = langBuilder(zh="ImsCM WiFi断开连接", en="ImsCM WiFi is Disconnected")

ReportHandoverphrase['airon'] = dict()
ReportHandoverphrase['airon'] = langBuilder(zh="打开飞行模式", en="open airplane mode")

ReportHandoverphrase['airoff'] = dict()
ReportHandoverphrase['airoff'] = langBuilder(zh="关闭飞行模式", en="close airplane mode")

ReportHandoverphrase['enwfc'] = dict()
ReportHandoverphrase['enwfc'] = langBuilder(zh="打开WiFi-Calling", en="Enable WiFi-Calling")

ReportHandoverphrase['disenwfc'] = dict()
ReportHandoverphrase['disenwfc'] = langBuilder(zh="关闭WiFi-Calling", en="Disable WiFi-Calling")

ReportHandoverphrase['invalidsim'] = dict()
ReportHandoverphrase['invalidsim'] = langBuilder(zh="Sim卡不在白名单,禁用VoWiFi", en="SimCard is not in VoWiFi whitelist")

ReportHandoverphrase['idlehowifi'] = dict()
ReportHandoverphrase['idlehowifi'] = langBuilder(zh="尝试Idle切换到VoWiFi", en="Trying to Idle Handover to VoWiFi")
ReportHandoverphrase['idleholte'] = dict()
ReportHandoverphrase['idleholte'] = langBuilder(zh="尝试Idle切换到VoLTE", en="Trying to Idle Handover to VoLTE")
ReportHandoverphrase['callhowifi'] = dict()
ReportHandoverphrase['callhowifi'] = langBuilder(zh="尝试电话中切到VoWiFi", en="Trying to Handover to VoWiFi in Call")
ReportHandoverphrase['callholte'] = dict()
ReportHandoverphrase['callholte'] = langBuilder(zh="尝试电话中切到VoLTE", en="Trying to Handover to VoLTE in Call")
ReportHandoverphrase['voiceqos2lte'] = dict()
ReportHandoverphrase['voiceqos2lte'] = langBuilder(zh="尝试语音通话质量差切换到Volte", en="Trying to Handover to VoLTE Due to Poor Voice Quality")
ReportHandoverphrase['videoqos2lte'] = dict()
ReportHandoverphrase['videoqos2lte'] = langBuilder(zh="尝试视频通话质量差切换到Volte", en="Trying to Handover to VoLTE Due to Poor Video Quality")

ReportHandoverphrase['incallrssiho2wifi'] = dict()
ReportHandoverphrase['incallrssiho2wifi'] = langBuilder(zh="尝试通话中WiFi信号好切换到VoWiFi", en="Trying to Handover to VoWiFi In Call Due to Strong WiFi Signal")

ReportHandoverphrase['rssiho2wifi'] = dict()
ReportHandoverphrase['rssiho2wifi'] = langBuilder(zh="尝试WiFi信号好切换到VoWiFi", en="Trying to Handover to VoWiFi From VoLTE Due to Strong WiFi Signal")

ReportHandoverphrase['autowifi'] = dict()
ReportHandoverphrase['autowifi'] = langBuilder(zh="尝试WiFi信号好驻网到VoWiFi", en="Trying to Auto Attach to VoWiFi Due to Strong WiFi Signal")

#some error between imscm and telephony
#defined in ImsConnectionManagerService.java
ReportHandoverphrase['switch vowifi'] = dict()
ReportHandoverphrase['switch vowifi'] = langBuilder(zh="Telephony Error: 切换到VoWiFi失败", en="Telephony Error: Failed to handover to VoWiFi")
ReportHandoverphrase['handover vowifi'] = dict()
ReportHandoverphrase['handover vowifi'] = langBuilder(zh="Telephony Error: 电话中切换到VoWiFi失败", en="Telephony Error: Failed to handover to VoWiFi In Call")
ReportHandoverphrase['handover volte'] = dict()
ReportHandoverphrase['handover volte'] = langBuilder(zh="Telephony Error: 电话中切换到VoLTE失败", en="Telephony Error: Failed to handover to VoLTE In Call")
ReportHandoverphrase['handover volte by timer'] = dict()
ReportHandoverphrase['handover volte by timer'] = langBuilder(zh="Telephony Error: 电话中定时器切换到VoLTE失败", en="Telephony Error: Failed to handover to VoLTE by Timer In Call")
ReportHandoverphrase['release vowifi resource'] = dict()
ReportHandoverphrase['release vowifi resource'] = langBuilder(zh="Telephony Error: 释放VoWiFi资源失败", en="Telephony Error: Failed to release vowifi resource")
ReportHandoverphrase['set vowifi unavailable'] = dict()
ReportHandoverphrase['set vowifi unavailable'] = langBuilder(zh="Telephony Error: 关闭VoWiFi失败", en="Telephony Error: Failed to set vowifi unavailable")
ReportHandoverphrase['cancel current request'] = dict()
ReportHandoverphrase['cancel current request'] = langBuilder(zh="Telephony Error: 取消当前请求失败", en="Telephony Error: Failed to cancel current request")
ReportHandoverphrase['videonortp'] = dict()
ReportHandoverphrase['videonortp'] = langBuilder(zh="没有视频数据", en="No RTP in Video")
ReportHandoverphrase['voicenortp'] = dict()
ReportHandoverphrase['voicenortp'] = langBuilder(zh="没有语音数据", en="No RTP in Voice")

ReportHandoverphrase['cmendcall'] = dict()
ReportHandoverphrase['cmendcall'] = langBuilder(zh="ImsConnectionManager挂断电话", en="ImsCM hung up call")

#OPERATION_SWITCH_TO_VOWIFI
ReportHandoverphrase['OPERATION_SWITCH_TO_VOWIFI'] = dict()
ReportHandoverphrase['OPERATION_SWITCH_TO_VOWIFI'] = langBuilder(en="Idle Handover to VoWiFi ")
#OPERATION_SWITCH_TO_VOLTE
ReportHandoverphrase['OPERATION_SWITCH_TO_VOLTE'] = dict()
ReportHandoverphrase['OPERATION_SWITCH_TO_VOLTE'] = langBuilder(en="Idle Handover to VoLTE ")
#OPERATION_HANDOVER_TO_VOWIFI
ReportHandoverphrase['OPERATION_HANDOVER_TO_VOWIFI'] = dict()
ReportHandoverphrase['OPERATION_HANDOVER_TO_VOWIFI'] = langBuilder(en="Handover to VoWiFi in Call ")

#OPERATION_HANDOVER_TO_VOLTE
ReportHandoverphrase['OPERATION_HANDOVER_TO_VOLTE'] = dict()
ReportHandoverphrase['OPERATION_HANDOVER_TO_VOLTE'] = langBuilder(en="Handover to VoLTE in Call ")

#OPERATION_SET_VOWIFI_UNAVAILABLE
ReportHandoverphrase['OPERATION_SET_VOWIFI_UNAVAILABLE'] = dict()
ReportHandoverphrase['OPERATION_SET_VOWIFI_UNAVAILABLE'] = langBuilder(en="Stop VoWiFi Stack ")

#OPERATION_CANCEL_CURRENT_REQUEST
ReportHandoverphrase['OPERATION_CANCEL_CURRENT_REQUEST'] = dict()
ReportHandoverphrase['OPERATION_CANCEL_CURRENT_REQUEST'] = langBuilder(en="ImsCM Cancel Current Request ")

#OPERATION_CP_REJECT_SWITCH_TO_VOWIFI
ReportHandoverphrase['OPERATION_CP_REJECT_SWITCH_TO_VOWIFI'] = dict()
ReportHandoverphrase['OPERATION_CP_REJECT_SWITCH_TO_VOWIFI'] = langBuilder(en="CP Reject to Idle Handover to VoWiFi ")

#OPERATION_CP_REJECT_HANDOVER_TO_VOWIFI
ReportHandoverphrase['OPERATION_CP_REJECT_HANDOVER_TO_VOWIFI'] = dict()
ReportHandoverphrase['OPERATION_CP_REJECT_HANDOVER_TO_VOWIFI'] = langBuilder(en="CP Reject to Handover to VoWiFi In Call ")

#OPERATION_RELEASE_WIFI_RESOURCE
ReportHandoverphrase['OPERATION_RELEASE_WIFI_RESOURCE'] = dict()
ReportHandoverphrase['OPERATION_RELEASE_WIFI_RESOURCE'] = langBuilder(en="Release VoWiFi Resource ")

ReportScenariophrase = dict()
ReportScenariophrase['startvoltecall'] = dict()
ReportScenariophrase['startvoltecall'] = langBuilder(zh="Telephony拨打VoLTE电话", en="Telephony Start VoLTE Call")
ReportScenariophrase['startvowificall'] = dict()
ReportScenariophrase['startvowificall'] = langBuilder(zh="Telephony拨打VoWiFi电话", en="Telephony Start VoWiFi Call")

ReportScenariophrase['apmakecall'] = dict()
ReportScenariophrase['apmakecall'] = langBuilder(zh="AP Stack拨打VoWiFi电话给", en="AP Stack Start VoWiFi Call to ")

ReportScenariophrase['callfailed'] = dict()
ReportScenariophrase['callfailed'] = langBuilder(zh="拨打VoWiFi电话失败", en="Failed to Start VoWiFi Call")

ReportScenariophrase['unregcallfail'] = dict()
ReportScenariophrase['unregcallfail'] = langBuilder(zh="未注册而拨打VoWiFi电话失败", en="Failed to Start VoWiFi Call Due to Unregistered")

ReportScenariophrase['Voice Call'] = dict()
ReportScenariophrase['Voice Call'] = langBuilder(zh="接听语音电话", en="Answer Voice Call")

ReportScenariophrase['Video Call'] = dict()
ReportScenariophrase['Video Call'] = langBuilder(zh="接听视频电话", en="Answer Video Call")

ReportScenariophrase['rejectcall'] = dict()
ReportScenariophrase['rejectcall'] = langBuilder(zh="拒接电话因为", en="Reject Call As ")

ReportScenariophrase['termcall'] = dict()
ReportScenariophrase['termcall'] = langBuilder(zh="挂断电话因为", en="Term Call As ")

ReportScenariophrase['holdcall'] = dict()
ReportScenariophrase['holdcall'] = langBuilder(zh="保持电话", en="Hold Call")

ReportScenariophrase['resumecall'] = dict()
ReportScenariophrase['resumecall'] = langBuilder(zh="恢复电话", en="Resume Call")

ReportScenariophrase['upgradecall'] = dict()
ReportScenariophrase['upgradecall'] = langBuilder(zh="升级为视频电话", en="Upgrade Video Call")

ReportScenariophrase['downgradecall'] = dict()
ReportScenariophrase['downgradecall'] = langBuilder(zh="降级为语音电话", en="Downgrade Voice Call")

ReportScenariophrase['mdyfailed'] = dict()
ReportScenariophrase['mdyfailed'] = langBuilder(zh="升级/降级失败", en="Failed to Upgrade/Downgrade Call")

ReportScenariophrase['akaok'] = dict()
ReportScenariophrase['akaok'] = langBuilder(zh="EAP-AKA校验成功", en="EAP-AKA AUTH correctly")

ReportScenariophrase['akafailed'] = dict()
ReportScenariophrase['akafailed'] = langBuilder(zh="EAP-AKA校验SYNC失败", en="EAP-AKA AUTH SYNC Failure")

ReportScenariophrase['akafailed'] = dict()
ReportScenariophrase['akafailed'] = langBuilder(zh="EAP-AKA校验SYNC失败", en="EAP-AKA AUTH SYNC Failure")

ReportScenariophrase['sendsms'] = dict()
ReportScenariophrase['sendsms'] = langBuilder(zh="发送SMS Over IP", en="Send SMS Over IP")

ReportScenariophrase['sendsmsok'] = dict()
ReportScenariophrase['sendsmsok'] = langBuilder(zh="发送SMS Over IP成功,类型:", en="Send SMS Over IP OK,type:")

ReportScenariophrase['recvsms'] = dict()
ReportScenariophrase['recvsms'] = langBuilder(zh="接收到SMS Over IP", en="Recv SMS Over IP")

ReportScenariophrase['sendsmsack'] = dict()
ReportScenariophrase['sendsmsack'] = langBuilder(zh="发送SMS ACK", en="Send SMS ACK")

ReportScenariophrase['sendsmsack'] = dict()
ReportScenariophrase['sendsmsack'] = langBuilder(zh="发送SMS ACK", en="Send SMS ACK")

ReportScenariophrase['sendsmsfailed'] = dict()
ReportScenariophrase['sendsmsfailed'] = langBuilder(zh="发送SMS失败, 类型:", en="Failed to send SMS, type:")

ReportScenariophrase['sendsmstimeout'] = dict()
ReportScenariophrase['sendsmstimeout'] = langBuilder(zh="发送SMS超时", en="Send SMS timeout")

ReportScenariophrase['pingfail'] = dict()
ReportScenariophrase['pingfail'] = langBuilder(zh="驻网ping失败", en="ping failed when ePDG attach")

ReportScenariophrase['wpaselect'] = dict()
ReportScenariophrase['wpaselect'] = langBuilder(zh="选择新的WiFi AP:", en="Select New WiFi AP:")

ReportScenariophrase['wpaconn'] = dict()
ReportScenariophrase['wpaconn'] = langBuilder(zh="WCN 连接上WiFi AP", en="WCN Connected to WiFi AP")

#drstatus
ReportScenariophrase['drstatus'] = dict()
ReportScenariophrase['drstatus'] = langBuilder(zh="更新数据路由到", en="Update data router to ")

#various servicecallback phrase
ReportScenariophrase["call_alert"] = dict()
ReportScenariophrase["call_alert"] = langBuilder(zh="收到18x: ", en="User Alert: ")

ReportScenariophrase["call_incoming"] = dict()
ReportScenariophrase["call_incoming"] = langBuilder(zh="收到来电", en="Receive incoming Call")

ReportScenariophrase["call_talking"] = dict()
ReportScenariophrase["call_talking"] = langBuilder(zh="电话接通", en="Call is established")

ReportScenariophrase["call_hold_ok"] = dict()
ReportScenariophrase["call_hold_ok"] = langBuilder(zh="电话保持成功", en="Call hold successfully")

ReportScenariophrase["call_resume_ok"] = dict()
ReportScenariophrase["call_resume_ok"] = langBuilder(zh="电话恢复成功", en="Call resume successfully")

ReportScenariophrase["call_hold_received"] = dict()
ReportScenariophrase["call_hold_received"] = langBuilder(zh="被对方保持电话", en="Call is held by peer")

ReportScenariophrase["call_resume_received"] = dict()
ReportScenariophrase["call_resume_received"] = langBuilder(zh="被对方恢复电话", en="Call is resumed by peer")

ReportScenariophrase["call_add_video_ok"] = dict()
ReportScenariophrase["call_add_video_ok"] = langBuilder(zh="添加视频成功", en="Add Video OK")

ReportScenariophrase["call_remove_video_ok"] = dict()
ReportScenariophrase["call_remove_video_ok"] = langBuilder(zh="移除视频成功", en="Remove Video OK")

ReportScenariophrase["call_remove_video_ok"] = dict()
ReportScenariophrase["call_remove_video_ok"] = langBuilder(zh="移除视频成功", en="Remove Video OK")

ReportScenariophrase["call_add_video_request"] = dict()
ReportScenariophrase["call_add_video_request"] = langBuilder(zh="收到添加视频的请求", en="Receive add video request")

ReportScenariophrase["call_add_video_cancel"] = dict()
ReportScenariophrase["call_add_video_cancel"] = langBuilder(zh="收到取消添加视频的请求", en="Receive request to cancel add video")

ReportScenariophrase["conf_connected"] = dict()
ReportScenariophrase["conf_connected"] = langBuilder(zh="会议电话建立", en="Conference Call is established")

ReportScenariophrase["conf_disconnected"] = dict()
ReportScenariophrase["conf_disconnected"] = langBuilder(zh="会议电话结束", en="Conference Call is disconnedted")

ReportScenariophrase["conf_invite_accept"] = dict()
ReportScenariophrase["conf_invite_accept"] = langBuilder(zh="对方接受会议电话", en="Peer accept Conference Call")

ReportScenariophrase["conf_kick_accept"] = dict()
ReportScenariophrase["conf_kick_accept"] = langBuilder(zh="移除会议参加者", en="Kick Peer from Conference Call")

ReportScenariophrase["conf_part_update"] = dict()
ReportScenariophrase["conf_part_update"] = langBuilder(zh="会议参加者状态更新", en="Conf Peer state updated")

ReportScenariophrase["conf_hold_ok"] = dict()
ReportScenariophrase["conf_hold_ok"] = langBuilder(zh="会议电话保持成功", en="Conference Call hold successfully")

ReportScenariophrase["conf_resume_ok"] = dict()
ReportScenariophrase["conf_resume_ok"] = langBuilder(zh="会议电话恢复成功", en="Conference Call resume successfully")

ReportScenariophrase["conf_hold_received"] = dict()
ReportScenariophrase["conf_hold_received"] = langBuilder(zh="被对方保持会议电话", en="Conference Call is held by peer")

ReportScenariophrase["conf_resume_received"] = dict()
ReportScenariophrase["conf_resume_received"] = langBuilder(zh="被对方恢复会议电话", en="Conference Call is resumed by peer")

ReportScenariophrase["call_hold_failed"] = dict()
ReportScenariophrase["call_hold_failed"] = langBuilder(zh="电话保持失败", en="Failed to hold call")

ReportScenariophrase["call_resume_failed"] = dict()
ReportScenariophrase["call_resume_failed"] = langBuilder(zh="电话恢复失败", en="Failed to resume call")

ReportScenariophrase["call_add_video_failed"] = dict()
ReportScenariophrase["call_add_video_failed"] = langBuilder(zh="添加视频失败", en="Failed to add video to call")

ReportScenariophrase["call_remove_video_failed"] = dict()
ReportScenariophrase["call_remove_video_failed"] = langBuilder(zh="移除视频失败", en="Failed to remove video from call")

ReportScenariophrase["conf_invite_failed"] = dict()
ReportScenariophrase["conf_invite_failed"] = langBuilder(zh="会议电话失败", en="Failed to start Conference call")

ReportScenariophrase["conf_kick_failed"] = dict()
ReportScenariophrase["conf_kick_failed"] = langBuilder(zh="会议电话移除参与者失败", en="Failed to kick peer from Conference call")

ReportScenariophrase["conf_hold_failed"] = dict()
ReportScenariophrase["conf_hold_failed"] = langBuilder(zh="会议电话保持失败", en="Failed to hold Conference call")

ReportScenariophrase["conf_resume_failed"] = dict()
ReportScenariophrase["conf_resume_failed"] = langBuilder(zh="会议电话恢复失败", en="Failed to resume Conference call")

ReportScenariophrase["conf_outgoing"] = dict()
ReportScenariophrase["conf_outgoing"] = langBuilder(zh="播出会议电话", en="Conf Call Outgoing")

ReportScenariophrase["call_outgoing"] = dict()
ReportScenariophrase["call_outgoing"] = langBuilder(zh="播出电话", en="Call Outgoing")

ReportScenariophrase["voicecallrtp"] = dict()
ReportScenariophrase["voicecallrtp"] = langBuilder(zh="电话收到语音", en="Voice RTP Received")
ReportScenariophrase["videocallrtp"] = dict()
ReportScenariophrase["videocallrtp"] = langBuilder(zh="电话收到视频", en="Video RTP Received")

ReportScenariophrase["voiceconfrtp"] = dict()
ReportScenariophrase["voiceconfrtp"] = langBuilder(zh="会议电话收到语音", en="Conf Voice RTP Received")
ReportScenariophrase["videoconfrtp"] = dict()
ReportScenariophrase["videoconfrtp"] = langBuilder(zh="会议电话收到视频", en="Conf Video RTP Received")

ReportScenariophrase["voicecallnortp"] = dict()
ReportScenariophrase["voicecallnortp"] = langBuilder(zh="电话没收到语音", en="No Voice RTP Received")
ReportScenariophrase["videocallnortp"] = dict()
ReportScenariophrase["videocallnortp"] = langBuilder(zh="电话没收到视频", en="No Video RTP Received")

ReportScenariophrase["voiceconfnortp"] = dict()
ReportScenariophrase["voiceconfnortp"] = langBuilder(zh="会议电话没收到语音", en="No Conf Voice RTP Received")

ReportScenariophrase["videoconfnortp"] = dict()
ReportScenariophrase["videoconfnortp"] = langBuilder(zh="会议电话没收到视频", en="No Conf Video RTP Received")

ReportScenariophrase["adddrerror"] = dict()
ReportScenariophrase["adddrerror"] = langBuilder(en="Failed to Update DataRouter")

ReportScenariophrase["call_terminate"] = dict()
ReportScenariophrase["call_terminate"] = langBuilder(zh="电话挂断因为 ", en="TermCall As ")

ReportScenariophrase["nonceerror"] = dict()
ReportScenariophrase["nonceerror"] = langBuilder(zh="服务器没回复nonce值", en="Auth Nonce is null")

ReportScenariophrase["akaerror"] = dict()
ReportScenariophrase["akaerror"] = langBuilder(zh="AKA计算失败", en="Failed to Caculate AKA response.")

ReportCpphrase = dict()
ReportCpphrase["PDN connection established"] = dict()
ReportCpphrase["PDN connection established"] = langBuilder(zh="PDN激活", en="PDN connection established")

ReportCpphrase["PDN connection request"] = dict()
ReportCpphrase["PDN connection request"] = langBuilder(zh="发起PDN请求", en="PDN connection request")

ReportCpphrase["Deactivate PDN connection"] = dict()
ReportCpphrase["Deactivate PDN connection"] = langBuilder(zh="PDN去激活", en="Deactivate PDN connection")

ReportCpphrase["VoLTE Unregistered"] = dict()
ReportCpphrase["VoLTE Unregistered"] = langBuilder(zh="VoLTE去注册", en="VoLTE Unregistered")

ReportCpphrase["VoLTE Registered"] = dict()
ReportCpphrase["VoLTE Registered"] = langBuilder(zh="VoLTE注册成功", en="VoLTE Registeredd")

ReportCpphrase["VoLTE Register fail"] = dict()
ReportCpphrase["VoLTE Register fail"] = langBuilder(zh="VoLTE注册失败", en="VoLTE Register fail")

ReportCpphrase["VoLTE De-Registering"] = dict()
ReportCpphrase["VoLTE De-Registering"] = langBuilder(zh="VoLTE正在去注册", en="VoLTE De-Registering")

ReportCpphrase["No RTP data!"] = dict()
ReportCpphrase["No RTP data!"] = langBuilder(en="No RTP data!")

ReportCpphrase["Enable VoLTE IMS"] = dict()
ReportCpphrase["Enable VoLTE IMS"] = langBuilder(en="Enable VoLTE IMS")

ReportCpphrase["PS to CS SRVCC Started"] = dict()
ReportCpphrase["PS to CS SRVCC Started"] = langBuilder(zh="SRVCC开始", en="SRVCC Started")

ReportCpphrase["PS to CS SRVCC Successfully"] = dict()
ReportCpphrase["PS to CS SRVCC Successfully"] = langBuilder(zh="SRVCC成功", en="SRVCC Successfully")

ReportCpphrase["PS to CS SRVCC Cancelled"] = dict()
ReportCpphrase["PS to CS SRVCC Cancelled"] = langBuilder(zh="SRVCC取消", en="SRVCC Cancelled")

ReportCpphrase["PS to CS SRVCC Failed"] = dict()
ReportCpphrase["PS to CS SRVCC Failed"] = langBuilder(zh="SRVCC失败", en="SRVCC Failed")

ReportTelphrase = dict()
ReportTelphrase['attachexception'] = dict()
ReportTelphrase['attachexception'] = langBuilder(zh="手动点击S2b驻网", en="Start S2b Attach without switch request")

#write a report builder

#helper function to construct report
#report definition is in eventdict in eventhandler
#add error event
def constructReport(type=ReportType.PHONEEVENT_BASE, event='', level=Msglevel.WARNING, errorstr=''):
    event = event
    level = level
    errorstr = errorstr
    builder = reportBuilder(type=type, event=event, level=level, errorstr=errorstr)
    return builder.getreport()
#FIXME: for this file, the msg should be arranged in a good way.


text:
using System;
using System.Globalization;
using Safewhere.Samples.RestApi.Domain;
using Safewhere.SCIMModel.Connections;

namespace Safewhere.Samples.RestApi.DeviceBasedConnectionSample
{
	class Program
	{
		static void Main()
		{
			Console.WriteLine("Begin POST DeviceBased connection");
			PostDeviceBasedConnection();
			Console.WriteLine("End POST DeviceBased connection Sample\n");

			Console.WriteLine("Begin PUT DeviceBased connection");
			PutDeviceBasedConnection();
			Console.WriteLine("End PUT DeviceBased connection Sample\n");

			Console.WriteLine("Begin GET DeviceBased connection");
			GetDeviceBasedConnection();
			Console.WriteLine("End GET DeviceBased connection Sample\n");

			Console.WriteLine("Begin DELETE DeviceBased connection");
			DeleteDeviceBasedConnection();
			Console.WriteLine("End DELETE DeviceBased connection Sample\n");

			Console.WriteLine("All done!");
		}

		private static void PostDeviceBasedConnection()
		{
			using (var request = new ApiWebRequest())
			{
				var connection = Helper.GetJsonObjectFromFile<Connection>("SampleData/PostDeviceBasedConnectionSample.json");

				RestApiCaller.CallAndHandleError
					(
						() =>
						{
							Console.WriteLine("-> Exercise POST DeviceBased connection");
							return request.Post(RequestObject.Connections, connection);
						},
						() =>
							request.Delete(string.Format(CultureInfo.InvariantCulture, "{0}/{1}", RequestObject.Connections,
								connection.Name))
					);
			}
		}

		private static void PutDeviceBasedConnection()
		{
			using (var request = new ApiWebRequest())
			{
				var connection = Helper.GetJsonObjectFromFile<Connection>("SampleData/PostDeviceBasedConnectionSample.json");
				var connectionUpdate = Helper.GetJsonObjectFromFile<Connection>("SampleData/PutDeviceBasedConnectionSample.json");

				RestApiCaller.CallAndHandleError
				   (
					   () =>
					   {
						   Console.WriteLine("-> Create data");
						   request.Post(RequestObject.Connections, connection);

						   Console.WriteLine("-> Exercise PUT DeviceBased connection");
						   var response = request.Put(RequestObject.Connections, connectionUpdate);
						   return response;
					   },
					   () =>
					   {
						   request.Delete(string.Format(CultureInfo.CurrentCulture, "{0}/{1}", RequestObject.Connections, connection.Name));
					   }
				   );
			}
		}

		private static void GetDeviceBasedConnection()
		{
			using (var request = new ApiWebRequest())
			{
				var connection = Helper.GetJsonObjectFromFile<Connection>("SampleData/PostDeviceBasedConnectionSample.json");

				RestApiCaller.CallAndHandleError
				   (
					   () =>
					   {
						   Console.WriteLine("-> Create data");
						   request.Post(RequestObject.Connections, connection);

						   Console.WriteLine("-> Exercise Get DeviceBased connection");
                           var response = request.Get(string.Format(CultureInfo.CurrentCulture, "{0}/{1}", RequestObject.Connections, connection.Name));
						   return response;
					   },
					   () =>
					   {
                           request.Delete(string.Format(CultureInfo.CurrentCulture, "{0}/{1}", RequestObject.Connections, connection.Name));
					   }
				   );
			}
		}

		private static void DeleteDeviceBasedConnection()
		{
			using (var request = new ApiWebRequest())
			{
				var connection = Helper.GetJsonObjectFromFile<Connection>("SampleData/PostDeviceBasedConnectionSample.json");

				RestApiCaller.CallAndHandleError
				   (
					   () =>
					   {
						   Console.WriteLine("-> Create data");
						   request.Post(RequestObject.Connections, connection);

						   Console.WriteLine("-> Exercise DELETE DeviceBased connection");
                           var response = request.Delete(string.Format(CultureInfo.CurrentCulture, "{0}/{1}", RequestObject.Connections, connection.Name));
						   return response;
					   },
					   () =>
					   {
                           request.Delete(string.Format(CultureInfo.CurrentCulture, "{0}/{1}", RequestObject.Connections, connection.Name));
					   }
				   );
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getProductionDependencies = void 0;
const path = require("path");
const cp = require("child_process");
const _ = require("underscore");
const parseSemver = require('parse-semver');
function asYarnDependency(prefix, tree) {
    let parseResult;
    try {
        parseResult = parseSemver(tree.name);
    }
    catch (err) {
        err.message += `: ${tree.name}`;
        console.warn(`Could not parse semver: ${tree.name}`);
        return null;
    }
    // not an actual dependency in disk
    if (parseResult.version !== parseResult.range) {
        return null;
    }
    const name = parseResult.name;
    const version = parseResult.version;
    const dependencyPath = path.join(prefix, name);
    const children = [];
    for (const child of (tree.children || [])) {
        const dep = asYarnDependency(path.join(prefix, name, 'node_modules'), child);
        if (dep) {
            children.push(dep);
        }
    }
    return { name, version, path: dependencyPath, children };
}
function getYarnProductionDependencies(cwd) {
    const raw = cp.execSync('yarn list --json', { cwd, encoding: 'utf8', env: { ...process.env, NODE_ENV: 'production' }, stdio: [null, null, 'inherit'] });
    const match = /^{"type":"tree".*$/m.exec(raw);
    if (!match || match.length !== 1) {
        throw new Error('Could not parse result of `yarn list --json`');
    }
    const trees = JSON.parse(match[0]).data.trees;
    return trees
        .map(tree => asYarnDependency(path.join(cwd, 'node_modules'), tree))
        .filter((dep) => !!dep);
}
function getProductionDependencies(cwd) {
    const result = [];
    const deps = getYarnProductionDependencies(cwd);
    const flatten = (dep) => { result.push({ name: dep.name, version: dep.version, path: dep.path }); dep.children.forEach(flatten); };
    deps.forEach(flatten);
    return _.uniq(result);
}
exports.getProductionDependencies = getProductionDependencies;
if (require.main === module) {
    const root = path.dirname(path.dirname(__dirname));
    console.log(JSON.stringify(getProductionDependencies(root), null, '  '));
}


text:
package org.apache.camel.component.rmi;

import java.net.URI;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;

/**
 * @version
 */
public class RmiRouteEndpointTest extends RmiRouteTest {

    protected int getPort() {
        return 37542;
    }

    @Override
    protected RouteBuilder getRouteBuilder(final CamelContext context) {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                RmiEndpoint say = new RmiEndpoint();
                say.setCamelContext(context);
                say.setUri(new URI("rmi://localhost:37542/bye"));

                from("direct:hello").to(say);

                // When exposing an RMI endpoint, the interfaces it exposes must
                // be configured.
                RmiEndpoint bye = new RmiEndpoint();
                bye.setCamelContext(context);
                bye.setRemoteInterfaces(ISay.class);
                bye.setUri(new URI("rmi://localhost:37542/bye"));

                from(bye).to("bean:bye");
            }
        };
    }
}


text:
#include "source/extensions/clusters/logical_dns/logical_dns_cluster.h"

#include <chrono>
#include <list>
#include <memory>
#include <string>
#include <vector>

#include "envoy/common/exception.h"
#include "envoy/config/cluster/v3/cluster.pb.h"
#include "envoy/config/core/v3/address.pb.h"
#include "envoy/config/endpoint/v3/endpoint.pb.h"
#include "envoy/stats/scope.h"

#include "source/common/common/dns_utils.h"
#include "source/common/common/fmt.h"
#include "source/common/config/utility.h"
#include "source/common/network/address_impl.h"
#include "source/common/network/utility.h"
#include "source/common/protobuf/protobuf.h"
#include "source/common/protobuf/utility.h"

namespace Envoy {
namespace Upstream {

namespace {
envoy::config::endpoint::v3::ClusterLoadAssignment
convertPriority(const envoy::config::endpoint::v3::ClusterLoadAssignment& load_assignment) {
  envoy::config::endpoint::v3::ClusterLoadAssignment converted;
  converted.MergeFrom(load_assignment);

  // We convert the priority set by the configuration back to zero. This helps
  // ensure that we don't blow up later on when using zone aware routing due
  // to a check that all priorities are zero.
  //
  // Since LOGICAL_DNS is limited to exactly one host declared per load_assignment
  // (checked in the ctor in this file), we can safely just rewrite the priority
  // to zero.
  for (auto& endpoint : *converted.mutable_endpoints()) {
    endpoint.set_priority(0);
  }

  return converted;
}
} // namespace

LogicalDnsCluster::LogicalDnsCluster(
    Server::Configuration::ServerFactoryContext& server_context,
    const envoy::config::cluster::v3::Cluster& cluster, Runtime::Loader& runtime,
    Network::DnsResolverSharedPtr dns_resolver,
    Server::Configuration::TransportSocketFactoryContextImpl& factory_context,
    Stats::ScopeSharedPtr&& stats_scope, bool added_via_api)
    : ClusterImplBase(server_context, cluster, runtime, factory_context, std::move(stats_scope),
                      added_via_api, factory_context.mainThreadDispatcher().timeSource()),
      dns_resolver_(dns_resolver),
      dns_refresh_rate_ms_(
          std::chrono::milliseconds(PROTOBUF_GET_MS_OR_DEFAULT(cluster, dns_refresh_rate, 5000))),
      respect_dns_ttl_(cluster.respect_dns_ttl()),
      resolve_timer_(
          factory_context.mainThreadDispatcher().createTimer([this]() -> void { startResolve(); })),
      local_info_(factory_context.localInfo()),
      load_assignment_(convertPriority(cluster.load_assignment())) {
  failure_backoff_strategy_ =
      Config::Utility::prepareDnsRefreshStrategy<envoy::config::cluster::v3::Cluster>(
          cluster, dns_refresh_rate_ms_.count(), factory_context.api().randomGenerator());

  const auto& locality_lb_endpoints = load_assignment_.endpoints();
  if (locality_lb_endpoints.size() != 1 || locality_lb_endpoints[0].lb_endpoints().size() != 1) {
    if (cluster.has_load_assignment()) {
      throw EnvoyException(
          "LOGICAL_DNS clusters must have a single locality_lb_endpoint and a single lb_endpoint");
    } else {
      throw EnvoyException("LOGICAL_DNS clusters must have a single host");
    }
  }

  const envoy::config::core::v3::SocketAddress& socket_address =
      lbEndpoint().endpoint().address().socket_address();

  if (!socket_address.resolver_name().empty()) {
    throw EnvoyException("LOGICAL_DNS clusters must NOT have a custom resolver name set");
  }
  dns_address_ = socket_address.address();
  dns_port_ = socket_address.port_value();

  if (lbEndpoint().endpoint().hostname().empty()) {
    hostname_ = dns_address_;
  } else {
    hostname_ = lbEndpoint().endpoint().hostname();
  }
  dns_lookup_family_ = getDnsLookupFamilyFromCluster(cluster);
}

void LogicalDnsCluster::startPreInit() {
  startResolve();
  if (!wait_for_warm_on_init_) {
    onPreInitComplete();
  }
}

LogicalDnsCluster::~LogicalDnsCluster() {
  if (active_dns_query_) {
    active_dns_query_->cancel(Network::ActiveDnsQuery::CancelReason::QueryAbandoned);
  }
}

void LogicalDnsCluster::startResolve() {
  ENVOY_LOG(debug, "starting async DNS resolution for {}", dns_address_);
  info_->configUpdateStats().update_attempt_.inc();

  active_dns_query_ = dns_resolver_->resolve(
      dns_address_, dns_lookup_family_,
      [this](Network::DnsResolver::ResolutionStatus status,
             std::list<Network::DnsResponse>&& response) -> void {
        active_dns_query_ = nullptr;
        ENVOY_LOG(debug, "async DNS resolution complete for {}", dns_address_);

        std::chrono::milliseconds final_refresh_rate = dns_refresh_rate_ms_;

        // If the DNS resolver successfully resolved with an empty response list, the logical DNS
        // cluster does not update. This ensures that a potentially previously resolved address does
        // not stabilize back to 0 hosts.
        if (status == Network::DnsResolver::ResolutionStatus::Success && !response.empty()) {
          info_->configUpdateStats().update_success_.inc();
          const auto addrinfo = response.front().addrInfo();
          // TODO(mattklein123): Move port handling into the DNS interface.
          ASSERT(addrinfo.address_ != nullptr);
          Network::Address::InstanceConstSharedPtr new_address =
              Network::Utility::getAddressWithPort(*(response.front().addrInfo().address_),
                                                   dns_port_);
          auto address_list = DnsUtils::generateAddressList(response, dns_port_);

          if (!logical_host_) {
            logical_host_ = std::make_shared<LogicalHost>(info_, hostname_, new_address,
                                                          address_list, localityLbEndpoint(),
                                                          lbEndpoint(), nullptr, time_source_);

            const auto& locality_lb_endpoint = localityLbEndpoint();
            PriorityStateManager priority_state_manager(*this, local_info_, nullptr);
            priority_state_manager.initializePriorityFor(locality_lb_endpoint);
            priority_state_manager.registerHostForPriority(logical_host_, locality_lb_endpoint);

            const uint32_t priority = locality_lb_endpoint.priority();
            priority_state_manager.updateClusterPrioritySet(
                priority, std::move(priority_state_manager.priorityState()[priority].first),
                absl::nullopt, absl::nullopt, absl::nullopt);
          }

          if (!current_resolved_address_ ||
              (*new_address != *current_resolved_address_ ||
               DnsUtils::listChanged(address_list, current_resolved_address_list_))) {
            current_resolved_address_ = new_address;
            current_resolved_address_list_ = address_list;

            // Make sure that we have an updated address for admin display, health
            // checking, and creating real host connections.
            logical_host_->setNewAddresses(new_address, address_list, lbEndpoint());
          }

          // reset failure backoff strategy because there was a success.
          failure_backoff_strategy_->reset();

          if (respect_dns_ttl_ && addrinfo.ttl_ != std::chrono::seconds(0)) {
            final_refresh_rate = addrinfo.ttl_;
          }
          ENVOY_LOG(debug, "DNS refresh rate reset for {}, refresh rate {} ms", dns_address_,
                    final_refresh_rate.count());
        } else {
          info_->configUpdateStats().update_failure_.inc();
          final_refresh_rate =
              std::chrono::milliseconds(failure_backoff_strategy_->nextBackOffMs());
          ENVOY_LOG(debug, "DNS refresh rate reset for {}, (failure) refresh rate {} ms",
                    dns_address_, final_refresh_rate.count());
        }

        onPreInitComplete();
        resolve_timer_->enableTimer(final_refresh_rate);
      });
}

std::pair<ClusterImplBaseSharedPtr, ThreadAwareLoadBalancerPtr>
LogicalDnsClusterFactory::createClusterImpl(
    Server::Configuration::ServerFactoryContext& server_context,
    const envoy::config::cluster::v3::Cluster& cluster, ClusterFactoryContext& context,
    Server::Configuration::TransportSocketFactoryContextImpl& socket_factory_context,
    Stats::ScopeSharedPtr&& stats_scope) {
  auto selected_dns_resolver = selectDnsResolver(cluster, context);

  return std::make_pair(std::make_shared<LogicalDnsCluster>(
                            server_context, cluster, context.runtime(), selected_dns_resolver,
                            socket_factory_context, std::move(stats_scope), context.addedViaApi()),
                        nullptr);
}

/**
 * Static registration for the strict dns cluster factory. @see RegisterFactory.
 */
REGISTER_FACTORY(LogicalDnsClusterFactory, ClusterFactory);

} // namespace Upstream
} // namespace Envoy


text:
<?php

namespace PHPixie\Tests\Template;

/**
 * @coversDefaultClass \PHPixie\Template\Resolver
 */
class ResolverTest extends \PHPixie\Test\Testcase
{
    protected $compiler;
    protected $filesystemLocator;
    protected $configData;

    protected $resolver;

    protected $overrides = array(
        'pixie' => 'fairy'
    );

    public function setUp()
    {
        $this->compiler          = $this->quickMock('\PHPixie\Template\Compiler');
        $this->filesystemLocator = $this->abstractMock('\PHPixie\Filesystem\Locators\Locator');
        $this->configData        = $this->getData();

        $this->method($this->configData, 'get', $this->overrides, array('overrides', array()), 0);

        $this->resolver = new \PHPixie\Template\Resolver(
            $this->compiler,
            $this->filesystemLocator,
            $this->configData
        );
    }

    /**
     * @covers ::__construct
     * @covers ::<protected>
     */
    public function testConstruct()
    {

    }

    /**
     * @covers ::resolve
     * @covers ::<protected>
     */
    public function testResolve()
    {
        $file = 'fairy.php';
        $compiledFile = 'trixie.php';

        $templateMap = array(
            'trixie' => 'trixie',
            'pixie'  => 'fairy'
        );

        foreach($templateMap as $template => $override) {
            $this->method($this->filesystemLocator, 'locate', $file, array($override), 0);
            $this->method($this->compiler, 'compile', $compiledFile, array($file), 0);

            $this->assertSame($compiledFile, $this->resolver->resolve($template));
            $this->assertSame($compiledFile, $this->resolver->resolve($template));
        }

        $this->method($this->filesystemLocator, 'locate', null, array('blum'), 0);
        $resolver = $this->resolver;
        $this->assertException(function() use($resolver){
            $resolver->resolve('blum');
        }, '\PHPixie\Template\Exception');
    }

    protected function getData()
    {
        return $this->quickMock('\PHPixie\Slice\Data');
    }
}


text:
data_root=$1
echo $data_root
command1="python3 ../pyAudioAnalysis/audioAnalysis.py featureVisualization -i \"${data_root}/speakerMaleFemale/both_small\""
echo $command1
eval $command1


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Tupistra lichuanensis Y.K.Yang, J.K.Wu & D.T.Peng

### Remarks
null


text:
<?php namespace October\Rain\Support\Facades;

use October\Rain\Support\Facade;

/**
 * Http Block Facade
 *
 * @package october\support
 * @author Alexey Bobkov, Samuel Georges
 */
class Block extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * Resolves to:
     * - October\Rain\Html\BlockBuilder
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'block'; }
}


text:
#nullable disable
using WizBot.Common.TypeReaders;
using WizBot.Modules.Permissions.Services;

namespace WizBot.Modules.Permissions;

public partial class Permissions
{
    [Group]
    public partial class GlobalPermissionCommands : WizBotModule
    {
        private readonly GlobalPermissionService _service;
        private readonly DbService _db;

        public GlobalPermissionCommands(GlobalPermissionService service, DbService db)
        {
            _service = service;
            _db = db;
        }

        [Cmd]
        [OwnerOnly]
        public async Task GlobalPermList()
        {
            var blockedModule = _service.BlockedModules;
            var blockedCommands = _service.BlockedCommands;
            if (!blockedModule.Any() && !blockedCommands.Any())
            {
                await ReplyErrorLocalizedAsync(strs.lgp_none);
                return;
            }

            var embed = _eb.Create().WithOkColor();

            if (blockedModule.Any())
                embed.AddField(GetText(strs.blocked_modules), string.Join("\n", _service.BlockedModules));

            if (blockedCommands.Any())
                embed.AddField(GetText(strs.blocked_commands), string.Join("\n", _service.BlockedCommands));

            await ctx.Channel.EmbedAsync(embed);
        }

        [Cmd]
        [OwnerOnly]
        public async Task GlobalModule(ModuleOrCrInfo module)
        {
            var moduleName = module.Name.ToLowerInvariant();

            var added = _service.ToggleModule(moduleName);

            if (added)
            {
                await ReplyConfirmLocalizedAsync(strs.gmod_add(Format.Bold(module.Name)));
                return;
            }

            await ReplyConfirmLocalizedAsync(strs.gmod_remove(Format.Bold(module.Name)));
        }

        [Cmd]
        [OwnerOnly]
        public async Task GlobalCommand(CommandOrExprInfo cmd)
        {
            var commandName = cmd.Name.ToLowerInvariant();
            var added = _service.ToggleCommand(commandName);

            if (added)
            {
                await ReplyConfirmLocalizedAsync(strs.gcmd_add(Format.Bold(cmd.Name)));
                return;
            }

            await ReplyConfirmLocalizedAsync(strs.gcmd_remove(Format.Bold(cmd.Name)));
        }
    }
}


text:
<?php
namespace Application\API;

use Zend\Mvc\Controller\AbstractRestfulController;
use Application\API\APITrait;

class QuitAPI extends AbstractRestfulController{

    use APITrait;

    public function getList(){$this->methodNotAllowed();}

    public function get($id){$this->methodNotAllowed();}

    public function create($data){$this->methodNotAllowed();}

    public function update($id, $data){
        $result = $this->participantModel()->delete($id);
        return $this->standardResponse($result);

    }

    public function delete($id = null){$this->methodNotAllowed();}

}


text: Github Viewer


text:
using System;
using Mina.Core.Buffer;

namespace Mina.Filter.Codec.StateMachine
{
    ///
    /// <see cref="IDecodingState"/> which consumes all bytes until a CRLF
    /// has been encountered.
    ///
    public abstract class ConsumeToCrLfDecodingState : IDecodingState
    {
        ///
        /// Carriage return character
        ///
        private static readonly Byte CR = 13;
        ///
        /// Line feed character
        ///
        private static readonly Byte LF = 10;
        private Boolean _lastIsCR;
        private IoBuffer _buffer;

        public IDecodingState Decode(IoBuffer input, IProtocolDecoderOutput output)
        {
            Int32 beginPos = input.Position;
            Int32 limit = input.Limit;
            Int32 terminatorPos = -1;

            for (Int32 i = beginPos; i < limit; i++)
            {
                Byte b = input.Get(i);
                if (b == CR)
                {
                    _lastIsCR = true;
                }
                else
                {
                    if (b == LF && _lastIsCR)
                    {
                        terminatorPos = i;
                        break;
                    }
                    _lastIsCR = false;
                }
            }

            if (terminatorPos >= 0)
            {
                IoBuffer product;

                Int32 endPos = terminatorPos - 1;

                if (beginPos < endPos)
                {
                    input.Limit = endPos;

                    if (_buffer == null)
                    {
                        product = input.Slice();
                    }
                    else
                    {
                        _buffer.Put(input);
                        product = _buffer.Flip();
                        _buffer = null;
                    }

                    input.Limit = limit;
                }
                else
                {
                    // When input contained only CR or LF rather than actual data...
                    if (_buffer == null)
                    {
                        product = IoBuffer.Allocate(0);
                    }
                    else
                    {
                        product = _buffer.Flip();
                        _buffer = null;
                    }
                }
                input.Position = terminatorPos + 1;
                return FinishDecode(product, output);
            }

            input.Position = beginPos;

            if (_buffer == null)
            {
                _buffer = IoBuffer.Allocate(input.Remaining);
                _buffer.AutoExpand = true;
            }

            _buffer.Put(input);

            if (_lastIsCR)
            {
                _buffer.Position = _buffer.Position - 1;
            }

            return this;
        }

        public IDecodingState FinishDecode(IProtocolDecoderOutput output)
        {
            IoBuffer product;
            // When input contained only CR or LF rather than actual data...
            if (_buffer == null)
            {
                product = IoBuffer.Allocate(0);
            }
            else
            {
                product = _buffer.Flip();
                _buffer = null;
            }
            return FinishDecode(product, output);
        }

        ///
        /// Invoked when this state has consumed all bytes until the session is closed.
        ///
        /// <param name="product">the read bytes including the CRLF</param>
        /// <param name="output">the current <see cref="IProtocolDecoderOutput"/> used to write decoded messages.</param>
        /// <returns>
        /// the next state if a state transition was triggered (use
        /// this for loop transitions) or null if
        /// the state machine has reached its end.
        /// </returns>
        protected abstract IDecodingState FinishDecode(IoBuffer product, IProtocolDecoderOutput output);
    }
}


text:
$.fullCalendar.lang("fr", {
	defaultButtonText: {
		month: "Mois",
		week: "Semaine",
		day: "Jour",
		list: "Mon planning"
	},
	allDayHTML: "Toute la journée" // allDayHTML is discouraged but used here as a hack to get the breaking correct
});


text:
function NavEditorConsoleDlg::onWake(%this) {
	%this.forceInsideCtrl(NavEditorGui);
}
function NavEditorConsoleDlg::init(%this) {
	%this.AlignCtrlToParent("top");
	%this.AlignCtrlToParent("right");
}
//==============================================================================
// Plugin Object Params - Used set default settings and build plugins options GUI
//==============================================================================

if (!isObject(NavEditorConsoleListener)) {
	new ScriptMsgListener(NavEditorConsoleListener);
	getNavMeshEventManager().subscribe(NavEditorConsoleListener, "NavMeshCreated");
	getNavMeshEventManager().subscribe(NavEditorConsoleListener, "NavMeshRemoved");
	getNavMeshEventManager().subscribe(NavEditorConsoleListener, "NavMeshStartUpdate");
	getNavMeshEventManager().subscribe(NavEditorConsoleListener, "NavMeshUpdate");
	getNavMeshEventManager().subscribe(NavEditorConsoleListener, "NavMeshTileUpdate");
}

function NavEditorConsoleListener::onNavMeshCreated(%this, %data) {
}

function NavEditorConsoleListener::onNavMeshRemoved(%this, %data) {
}

function NavEditorConsoleListener::onNavMeshStartUpdate(%this, %data) {
	NavEditorConsoleDlg-->Output.clearItems();
	NavEditorConsoleDlg-->Output.addItem("Build starting for NavMesh" SPC %data, "0 0.6 0");
	NavEditorConsoleDlg-->OutputScroll.scrollToBottom();
}

function NavEditorConsoleListener::onNavMeshUpdate(%this, %data) {
	%message = "";

	if(getWordCount(%data) == 2) {
		%seconds = getWord(%data, 1);
		%minutes = mFloor(%seconds / 60);
		%seconds -= %minutes * 60;
		%message = "Built NavMesh" SPC getWord(%data, 0) SPC "in" SPC %minutes @ "m" SPC mRound(%seconds) @ "s";

		if(NavEditorGui.playSoundWhenDone) {
			sfxPlayOnce(Audio2D, "tlab/navEditor/assets/done.wav");
		}
	} else {
		%message = "Loaded NavMesh" SPC %data;
	}

	NavEditorConsoleDlg-->Output.addItem(%message, "0 0.6 0");
	NavEditorConsoleDlg-->OutputScroll.scrollToBottom();
	NavEditorConsoleDlg->StatusLeft.setText("");
}

function NavEditorConsoleListener::onNavMeshTileUpdate(%this, %data) {
	%mesh = getWord(%data, 0);
	%index = getWord(%data, 1);
	%total = getWord(%data, 2);
	%tile = getWords(%data, 3, 4);
	%success = getWord(%data, 5) == "1";

	if(!%success) {
		%message = "NavMesh" SPC %mesh SPC "tile" SPC %tile SPC "build failed!";
		NavEditorConsoleDlg-->Output.addItem(%message, "1 0 0");
		NavEditorConsoleDlg-->OutputScroll.scrollToBottom();
	}

	%percent = %index / %total * 100;
	NavEditorConsoleDlg->StatusLeft.setText("Build progress:" SPC mRound(%percent) @ "%");
}


text:
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:opacity]

#define RGB(rgbValue) RGBA(rgbValue, 1.0)

#import "DKAccessoryButton.h"

@implementation DKAccessoryButton

- (id)initWithFrame:(CGRect)frame title:(NSString *)title
{
    self = [UIButton buttonWithType:UIButtonTypeCustom];

    if (self) {

        // Setting frame. One should set a frame before adding an image.
        [self setFrame:frame];

        // Rect shape of a button
        self.layer.cornerRadius = 0;

        self.backgroundColor = [UIColor whiteColor];

        // Adjusting title label, left alignment with 10 px padding
        [self setTitleColor:RGB(0x1460FA) forState:UIControlStateNormal];
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];

        [self.titleLabel setFont:[UIFont systemFontOfSize:17]];
        self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        self.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;

        // Here we add an arrow image to the button view
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow"]];
        imageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        CGRect imageViewFrame = imageView.frame;
        imageViewFrame.origin.x = self.frame.size.width - 20;
        imageViewFrame.origin.y = self.frame.size.height / 2.0 - 6;
        imageView.frame = imageViewFrame;
        [self addSubview:imageView];

        // Setting title
        [self setTitle:title forState:UIControlStateNormal];
    }
    return self;
}

@end


text:
        <?php if (empty($resultSet['items'])) { ?>

New events comings soon

        <?php
        } else {
            foreach ($resultSet['items'] as $event) {
                $attachment = $customerService->GetProfileAttachnmentsByEntityId($event['id'],"Event");
                ?>

                                <img src="<?php echo $attachment['file_path']; ?>" alt="" height="150" width="42"
                                     onclick="previewentity('events',<?php echo $event['id']; ?>);"/>
                                <?php echo  substr($event['description'], 0, 50); ?>
                                <a class="btn btn-default get" href="events=<?php echo $event['id']; ?>"><?php echo $event['name']; ?>

                <?php
            }
        }
        ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<migration name="Change zea variety">
  <item-change item="crop_sets#corn" varieties="zea_mays"/>
  <item-change item="crop_sets#corn_sorghum" varieties="zea_mays, sorghum"/>
  <item-change item="product_nature_variants#coop:class_a_corn_grain" derivative_of="zea_mays"/>
  <item-change item="product_nature_variants#corn_crop" variety="zea_mays"/>
  <item-change item="product_nature_variants#corn_grain" derivative_of="zea_mays"/>
  <item-change item="product_nature_variants#corn_grain_crop" variety="zea_mays"/>
  <item-change item="product_nature_variants#corn_seed_25" derivative_of="zea_mays"/>
  <item-change item="product_nature_variants#corn_seed_50tg" derivative_of="zea_mays"/>
  <item-change item="product_nature_variants#corn_seed_crop" variety="zea_mays"/>
  <item-change item="product_nature_variants#corn_silage" derivative_of="zea_mays"/>
  <item-change item="product_nature_variants#corn_silage_crop" variety="zea_mays"/>
</migration>


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview
 * TODO(garykac): Create interfaces for LogToServer and SignalStrategy.
 * @suppress {checkTypes|checkVars|reportUnknownTypes|visibility}
 */

(function() {

'use strict';

/** @constructor */
var MockLogToServer = function(/** QUnit.Assert */ assert) {
  /** @type {(sinon.Spy|Function)} */
  this.logSignalStrategyProgress = sinon.spy();
  this.assert_ = assert;
};

/** @type {function(...)} */
MockLogToServer.prototype.assertProgress = function() {
  this.assert_.equal(this.logSignalStrategyProgress.callCount * 2,
                     arguments.length);
  for (var i = 0; i < this.logSignalStrategyProgress.callCount; ++i) {
    this.assert_.equal(
        this.logSignalStrategyProgress.getCall(i).args[0], arguments[2 * i]);
    this.assert_.equal(this.logSignalStrategyProgress.getCall(i).args[1],
                arguments[2 * i + 1]);
  }
};

/** @type {(sinon.Spy|function(remoting.SignalStrategy.State))} */
var onStateChange = null;

/** @type {(sinon.Spy|function(Element):void)} */
var onIncomingStanzaCallback = null;

/** @type {remoting.FallbackSignalStrategy} */
var strategy = null;

/** @type {remoting.SignalStrategy} */
var primary = null;

/** @type {remoting.SignalStrategy} */
var secondary = null;

/** @type {MockLogToServer} */
var logToServer = null;

/**
 * @param {QUnit.Assert} assert
 * @param {remoting.MockSignalStrategy} baseSignalStrategy
 * @param {remoting.SignalStrategy.State} state
 * @param {boolean} expectCallback
 */
function setState(assert, baseSignalStrategy, state, expectCallback) {
  onStateChange.reset();
  baseSignalStrategy.setStateForTesting(state);

  if (expectCallback) {
    assert.equal(onStateChange.callCount, 1);
    assert.ok(onStateChange.calledWith(state));
    assert.equal(strategy.getState(), state);
  } else {
    assert.ok(!onStateChange.called);
  }
}

QUnit.module('fallback_signal_strategy', {
  beforeEach: function(/** QUnit.Assert */ assert) {
    onStateChange = sinon.spy();
    onIncomingStanzaCallback = sinon.spy();
    strategy = new remoting.FallbackSignalStrategy(
        new remoting.MockSignalStrategy('primary-jid',
                                        remoting.SignalStrategy.Type.XMPP),
        new remoting.MockSignalStrategy('secondary-jid',
                                        remoting.SignalStrategy.Type.WCS));
    strategy.setStateChangedCallback(onStateChange);
    strategy.setIncomingStanzaCallback(onIncomingStanzaCallback);
    primary = strategy.primary_;
    secondary = strategy.secondary_;
    logToServer = new MockLogToServer(assert);
  },
  afterEach: function() {
    onStateChange = null;
    onIncomingStanzaCallback = null;
    strategy = null;
    primary = null;
    secondary = null;
    logToServer = null;
  },
});

QUnit.test('primary succeeds; send & receive routed to it',
  function(assert) {
    assert.ok(!onStateChange.called);
    assert.ok(!primary.connect.called);
    strategy.connect('server', 'username', 'authToken');
    assert.ok(primary.connect.calledWith('server', 'username', 'authToken'));

    setState(assert, primary, remoting.SignalStrategy.State.NOT_CONNECTED,
             true);
    setState(assert, primary, remoting.SignalStrategy.State.CONNECTING, true);
    setState(assert, primary, remoting.SignalStrategy.State.HANDSHAKE, true);

    setState(assert, primary, remoting.SignalStrategy.State.CONNECTED, true);
    assert.equal(strategy.getJid(), 'primary-jid');

    strategy.sendConnectionSetupResults(logToServer);
    logToServer.assertProgress(
        remoting.SignalStrategy.Type.XMPP,
        remoting.FallbackSignalStrategy.Progress.SUCCEEDED);

    assert.ok(!onIncomingStanzaCallback.called);
    primary.onIncomingStanzaCallback_('test-receive-primary');
    secondary.onIncomingStanzaCallback_('test-receive-secondary');
    assert.ok(onIncomingStanzaCallback.calledOnce);
    assert.ok(onIncomingStanzaCallback.calledWith('test-receive-primary'));

    assert.ok(!primary.sendMessage.called);
    strategy.sendMessage('test-send');
    assert.ok(primary.sendMessage.calledOnce);
    assert.ok(primary.sendMessage.calledWith('test-send'));

    assert.ok(!primary.dispose.called);
    assert.ok(!secondary.dispose.called);
    setState(assert, primary, remoting.SignalStrategy.State.CLOSED, true);
    strategy.dispose();
    assert.ok(primary.dispose.calledOnce);
    assert.ok(secondary.dispose.calledOnce);
  }
);

QUnit.test('primary fails; secondary succeeds; send & receive routed to it',
  function(assert) {
    assert.ok(!onStateChange.called);
    assert.ok(!primary.connect.called);
    strategy.connect('server', 'username', 'authToken');
    assert.ok(primary.connect.calledWith('server', 'username', 'authToken'));

    setState(assert, primary, remoting.SignalStrategy.State.NOT_CONNECTED,
             true);
    setState(assert, primary, remoting.SignalStrategy.State.CONNECTING, true);

    assert.ok(!secondary.connect.called);
    setState(assert, primary, remoting.SignalStrategy.State.FAILED, false);
    assert.ok(secondary.connect.calledWith('server', 'username', 'authToken'));

    setState(assert, secondary, remoting.SignalStrategy.State.NOT_CONNECTED,
             false);
    setState(assert, secondary, remoting.SignalStrategy.State.CONNECTING,
             false);
    setState(assert, secondary, remoting.SignalStrategy.State.HANDSHAKE, true);

    setState(assert, secondary, remoting.SignalStrategy.State.CONNECTED, true);
    assert.equal(strategy.getJid(), 'secondary-jid');

    strategy.sendConnectionSetupResults(logToServer);
    logToServer.assertProgress(
        remoting.SignalStrategy.Type.XMPP,
        remoting.FallbackSignalStrategy.Progress.FAILED,
        remoting.SignalStrategy.Type.WCS,
        remoting.FallbackSignalStrategy.Progress.SUCCEEDED);

    assert.ok(!onIncomingStanzaCallback.called);
    primary.onIncomingStanzaCallback_('test-receive-primary');
    secondary.onIncomingStanzaCallback_('test-receive-secondary');
    assert.ok(onIncomingStanzaCallback.calledOnce);
    assert.ok(onIncomingStanzaCallback.calledWith('test-receive-secondary'));

    assert.ok(!secondary.sendMessage.called);
    strategy.sendMessage('test-send');
    assert.ok(!primary.sendMessage.called);
    assert.ok(secondary.sendMessage.calledOnce);
    assert.ok(secondary.sendMessage.calledWith('test-send'));
  }
);

QUnit.test('primary fails; secondary fails',
  function(assert) {
    assert.ok(!onStateChange.called);
    assert.ok(!primary.connect.called);
    strategy.connect('server', 'username', 'authToken');
    assert.ok(primary.connect.calledWith('server', 'username', 'authToken'));

    setState(assert, primary, remoting.SignalStrategy.State.NOT_CONNECTED,
             true);
    assert.ok(!secondary.connect.called);
    setState(assert, primary, remoting.SignalStrategy.State.CONNECTING, true);
    setState(assert, primary, remoting.SignalStrategy.State.FAILED, false);
    assert.ok(secondary.connect.calledWith('server', 'username', 'authToken'));
    setState(assert, secondary, remoting.SignalStrategy.State.NOT_CONNECTED,
             false);
    setState(assert, primary, remoting.SignalStrategy.State.CONNECTING, false);
    setState(assert, secondary, remoting.SignalStrategy.State.FAILED, true);
  }
);

QUnit.test('primary times out; secondary succeeds',
  function(assert) {
    assert.ok(!onStateChange.called);
    assert.ok(!primary.connect.called);
    strategy.connect('server', 'username', 'authToken');
    assert.ok(primary.connect.calledWith('server', 'username', 'authToken'));

    setState(assert, primary, remoting.SignalStrategy.State.NOT_CONNECTED,
                               true);
    setState(assert, primary, remoting.SignalStrategy.State.CONNECTING, true);
    this.clock.tick(strategy.PRIMARY_CONNECT_TIMEOUT_MS_ - 1);
    assert.ok(!secondary.connect.called);
    this.clock.tick(1);
    assert.ok(secondary.connect.calledWith('server', 'username', 'authToken'));
    setState(assert, secondary, remoting.SignalStrategy.State.NOT_CONNECTED,
             false);
    setState(assert, secondary, remoting.SignalStrategy.State.CONNECTING,
             false);
    setState(assert, secondary, remoting.SignalStrategy.State.HANDSHAKE, true);
    setState(assert, secondary, remoting.SignalStrategy.State.CONNECTED, true);
    strategy.sendConnectionSetupResults(logToServer);

    setState(assert, secondary, remoting.SignalStrategy.State.CLOSED, true);
    setState(assert, primary, remoting.SignalStrategy.State.FAILED, false);

    logToServer.assertProgress(
        remoting.SignalStrategy.Type.XMPP,
        remoting.FallbackSignalStrategy.Progress.TIMED_OUT,
        remoting.SignalStrategy.Type.WCS,
        remoting.FallbackSignalStrategy.Progress.SUCCEEDED,
        remoting.SignalStrategy.Type.XMPP,
        remoting.FallbackSignalStrategy.Progress.FAILED_LATE);
  }
);

QUnit.test('primary times out; secondary fails',
  function(assert) {
    assert.ok(!onStateChange.called);
    assert.ok(!primary.connect.called);
    strategy.connect('server', 'username', 'authToken');
    assert.ok(primary.connect.calledWith('server', 'username', 'authToken'));

    setState(assert, primary, remoting.SignalStrategy.State.NOT_CONNECTED,
                               true);
    setState(assert, primary, remoting.SignalStrategy.State.CONNECTING, true);
    this.clock.tick(strategy.PRIMARY_CONNECT_TIMEOUT_MS_ - 1);
    assert.ok(!secondary.connect.called);
    this.clock.tick(1);
    assert.ok(secondary.connect.calledWith('server', 'username', 'authToken'));
    setState(assert, secondary, remoting.SignalStrategy.State.NOT_CONNECTED,
             false);
    setState(assert, secondary, remoting.SignalStrategy.State.CONNECTING,
             false);
    setState(assert, secondary, remoting.SignalStrategy.State.FAILED, true);
  }
);

QUnit.test('primary times out; secondary succeeds; primary succeeds late',
  function(assert) {
    assert.ok(!onStateChange.called);
    assert.ok(!primary.connect.called);
    strategy.connect('server', 'username', 'authToken');
    assert.ok(primary.connect.calledWith('server', 'username', 'authToken'));

    setState(assert, primary, remoting.SignalStrategy.State.NOT_CONNECTED,
                               true);
    setState(assert, primary, remoting.SignalStrategy.State.CONNECTING, true);
    this.clock.tick(strategy.PRIMARY_CONNECT_TIMEOUT_MS_);
    assert.ok(secondary.connect.calledWith('server', 'username', 'authToken'));
    setState(assert, secondary, remoting.SignalStrategy.State.NOT_CONNECTED,
             false);
    setState(assert, secondary, remoting.SignalStrategy.State.CONNECTING,
             false);
    setState(assert, secondary, remoting.SignalStrategy.State.HANDSHAKE, true);
    setState(assert, secondary, remoting.SignalStrategy.State.CONNECTED, true);
    strategy.sendConnectionSetupResults(logToServer);

    setState(assert, primary, remoting.SignalStrategy.State.HANDSHAKE, false);
    setState(assert, primary, remoting.SignalStrategy.State.CONNECTED, false);

    logToServer.assertProgress(
        remoting.SignalStrategy.Type.XMPP,
        remoting.FallbackSignalStrategy.Progress.TIMED_OUT,
        remoting.SignalStrategy.Type.WCS,
        remoting.FallbackSignalStrategy.Progress.SUCCEEDED,
        remoting.SignalStrategy.Type.XMPP,
        remoting.FallbackSignalStrategy.Progress.SUCCEEDED_LATE);
  }
);

})();


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Constant Field Values (jackson-databind 2.1.0 API)
</TITLE>

<META NAME="date" CONTENT="2012-10-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Constant Field Values

Contents

com.fasterxml.*

com.fasterxml.*

com.fasterxml.jackson.databind.SerializerProvider

protected static final boolean
CACHE_UNKNOWN_MAPPINGS
false

com.fasterxml.jackson.databind.deser.DataFormatReaders

public static final int
DEFAULT_MAX_INPUT_LOOKAHEAD
64

com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer

protected static final String
PROP_NAME_MESSAGE
"message"

com.fasterxml.jackson.databind.jsonschema.JsonSerializableSchema

public static final String
NO_VALUE
"##irrelevant"

com.fasterxml.jackson.databind.util.StdDateFormat

protected static final String
DATE_FORMAT_STR_ISO8601
"yyyy-MM-dd\'T\'HH:mm:ss.SSSZ"

protected static final String
DATE_FORMAT_STR_ISO8601_Z
"yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'"

protected static final String
DATE_FORMAT_STR_PLAIN
"yyyy-MM-dd"

protected static final String
DATE_FORMAT_STR_RFC1123
"EEE, dd MMM yyyy HH:mm:ss zzz"

com.fasterxml.jackson.databind.util.TokenBuffer.Segment

public static final int
TOKENS_PER_SEGMENT
16

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2012 FasterXML. All Rights Reserved.


text:
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/

/*********************************************
This basic climate example logs a stream
of temperature and humidity to the console.
*********************************************/

var tessel = require('tessel');
// if you're using a si7020 replace this lib with climate-si7020
var climatelib = require('../');

var climate = climatelib.use(tessel.port['A']);

climate.on('ready', function () {
  console.log('Connected to si7005');

  // Loop forever
  setImmediate(function loop () {
    climate.readTemperature('f', function (err, temp) {
      climate.readHumidity(function (err, humid) {
        console.log('Degrees:', temp.toFixed(4) + 'F', 'Humidity:', humid.toFixed(4) + '%RH');
        setTimeout(loop, 300);
      });
    });
  });
});

climate.on('error', function(err) {
  console.log('error connecting module', err);
});


text:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from django.contrib import admin
from blog.models import Article
from blog.models import Category
from blog.models import Tag

# Register your models here.
admin.site.register(Article)
admin.site.register(Category)
admin.site.register(Tag)


text:
module.exports = function(e, request, action) {
	//case for -> a {{from.schema.name}} having only one {{to.schema.name}}
	//create the field to attach a {{to.schema.name}} on {{from.schema.name}} create

	//if the path already starts with {{name}}
	if(request.path.indexOf('/{{from.schema.name}}/create/{{name}}/') === 0) {
		//do nothing
		return;
	}

	var $ = jQuery;

	//add a field
	var body = Handlebars.compile("\{\{#block 'form/fieldset' '{{to.singular}}'\}\}"
	+ "\{\{{block 'field/autocomplete' '' '' ../options "
	+ "'placeholder=\"Please enter a {{to.referenceLabel}}\"'\}\}}\{\{/block\}\}")({
		options: {
			name : '{{to.schema.name}}',
			template: '\{\{value\}\} <strong>( ID: \{\{id\}\} )</strong>',
			engine: {
				compile: function(template) {
					return {
						render: function(context) {
							return Handlebars.compile(template)(context);
						}
					};
				}

			},
			remote : {
				url: this.getServerUrl() + '/{{to.schema.name}}?keyword=%QUERY',
				filter: function(data) {
					var results = data.results.map(function (item) {
						return {
							id: item.{{to.schema.primary}},
							value: item.{{to.reference}} };
					});

					return results;
				}
			}
		}
	});

	body = $(body).on('ready', function() {
		$('input.eve-field-autocomplete', this)
		.on('typeahead:selected', function(e, item) {
			$(this).parent().siblings('input[name="{{to.schema.name}}"]').val(item.id);
		})
		.on('typeahead:autocompleted', function(e, item) {
			$(this).parent().siblings('input[name="{{to.schema.name}}"]').val(item.id);
		})
		.parent().append('<input type="hidden" name="{{to.schema.name}}" />');
	});

	$('section.{{from.schema.name}}-form div.form-actions').before(body);
};


text:
xsrftoken provides cross-site-request-forgery tokens for golang.

It is a clone of Andrew Gerrard's [`xsrftoken`
project](https://code.google.com/p/xsrftoken), that doesn't have the
scary google code warning.

See [https://godoc.org/github.com/ConradIrwin/xsrftoken](https://godoc.org/github.com/ConradIrwin/xsrftoken)


text:
namespace rl
{
	namespace hal
	{
		DigitalOutputReader::DigitalOutputReader() :
			DigitalOutput()
		{
		}

		DigitalOutputReader::~DigitalOutputReader()
		{
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Time_Since_Birthday
{
    class TimeSinceBirthday
    {
        static void Main(string[] args)
        {
            byte years = byte.Parse(Console.ReadLine());
            int days = years * 365;
            int hours = days * 24;
            int minutes = hours * 60;
            Console.WriteLine($"{years} years = {days} days = {hours} hours = {minutes} minutes.");
        }
    }
}


text:
<?php

require_once 'PHP/Depend/Autoload.php';

/**
 * Simple factory that is used to return a ready to use PHP_Depend instance.
 *
 * @category  PHP
 * @package   PHP_PMD
 * @author    Manuel Pichler <mapi@phpmd.org>
 * @copyright 2008-2012 Manuel Pichler. All rights reserved.
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version   Release: @package_version@
 * @link      http://phpmd.org
 */
class PHP_PMD_ParserFactory
{
    /**
     * Creates a new factory instance.
     */
    public function __construct()
    {
        $autoload = new PHP_Depend_Autoload();
        $autoload->register();
    }

    /**
     * Creates the used PHP_PMD_Parser analyzer instance.
     *
     * @param PHP_PMD $phpmd The context php mess detector instance.
     *
     * @return PHP_PMD_Parser
     */
    public function create(PHP_PMD $phpmd)
    {
        include_once 'PHP/PMD/Parser.php';

        $pdepend = $this->createInstance();
        $pdepend = $this->init($pdepend, $phpmd);

        return new PHP_PMD_Parser($pdepend);
    }

    /**
     * Creates a clean php depend instance with some base settings.
     *
     * @return PHP_Depend
     */
    private function createInstance()
    {
        $factory = new PHP_Depend_Util_Configuration_Factory();
        return new PHP_Depend($factory->createDefault());
    }

    /**
     * Configures the given PHP_Depend instance based on some user settings.
     *
     * @param PHP_Depend $pdepend The context php depend instance.
     * @param PHP_PMD    $phpmd   The calling/parent php mess detector.
     *
     * @return PHP_Depend
     */
    private function init(PHP_Depend $pdepend, PHP_PMD $phpmd)
    {
        $this->initInput($pdepend, $phpmd);
        $this->initIgnores($pdepend, $phpmd);
        $this->initExtensions($pdepend, $phpmd);

        return $pdepend;
    }

    /**
     * Configures the input source.
     *
     * @param PHP_Depend $pdepend The context php depend instance.
     * @param PHP_PMD    $phpmd   The calling/parent php mess detector.
     *
     * @return void
     */
    private function initInput(PHP_Depend $pdepend, PHP_PMD $phpmd)
    {
        foreach (explode(',', $phpmd->getInput()) as $path) {
            if (is_dir(trim($path))) {
                $pdepend->addDirectory(trim($path));
            } else {
                $pdepend->addFile(trim($path));
            }
        }
    }

    /**
     * Initializes the ignored files and path's.
     *
     * @param PHP_Depend $pdepend The context php depend instance.
     * @param PHP_PMD    $phpmd   The calling/parent php mess detector.
     *
     * @return void
     */
    private function initIgnores(PHP_Depend $pdepend, PHP_PMD $phpmd)
    {
        if (count($phpmd->getIgnorePattern()) > 0) {
            $pdepend->addFileFilter(
                new PHP_Depend_Input_ExcludePathFilter($phpmd->getIgnorePattern())
            );
        }
    }

    /**
     * Initializes the accepted php source file extensions.
     *
     * @param PHP_Depend $pdepend The context php depend instance.
     * @param PHP_PMD    $phpmd   The calling/parent php mess detector.
     *
     * @return void
     */
    private function initExtensions(PHP_Depend $pdepend, PHP_PMD $phpmd)
    {
        if (count($phpmd->getFileExtensions()) > 0) {
            $pdepend->addFileFilter(
                new PHP_Depend_Input_ExtensionFilter($phpmd->getFileExtensions())
            );
        }
    }
}


text:
package game;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class DirectionTest {

    @Test
    public void testTurnRight() {
        Direction testObject = Direction.EAST;
        testObject = Direction.values()[testObject.ordinal()+1];
        assertEquals(Direction.SOUTH, testObject);
    }
}


text:
using namespace seqan;

int main() {
///HMM creation
	typedef LogProb<> TProbability;
	typedef Dna TAlphabet;
	typedef Size<TAlphabet>::Type TSize;
	typedef Graph<Hmm<TAlphabet, TProbability, Default> > THmm;
	typedef VertexDescriptor<THmm>::Type TVertexDescriptor;
	typedef EdgeDescriptor<THmm>::Type TEdgeDescriptor;

	Dna dnaA = Dna('A');
	Dna dnaC = Dna('C');
	Dna dnaG = Dna('G');
	Dna dnaT = Dna('T');

	THmm hmm;

///Begin state
	TVertexDescriptor begState = addVertex(hmm);
	assignBeginState(hmm, begState);

///Add exon state
	TVertexDescriptor exonState = addVertex(hmm);
	emissionProbability(hmm, exonState, dnaA) = 0.25;
	emissionProbability(hmm, exonState, dnaC) = 0.25;
	emissionProbability(hmm, exonState, dnaG) = 0.25;
	emissionProbability(hmm, exonState, dnaT) = 0.25;

///Add 5' splice site
	TVertexDescriptor spliceState = addVertex(hmm);
	emissionProbability(hmm, spliceState, dnaA) = 0.05;
	emissionProbability(hmm, spliceState, dnaC) = 0.0;
	emissionProbability(hmm, spliceState, dnaG) = 0.95;
	emissionProbability(hmm, spliceState, dnaT) = 0.0;

///Add intron state
	TVertexDescriptor intronState = addVertex(hmm);
	emissionProbability(hmm, intronState, dnaA) = 0.4;
	emissionProbability(hmm, intronState, dnaC) = 0.1;
	emissionProbability(hmm, intronState, dnaG) = 0.1;
	emissionProbability(hmm, intronState, dnaT) = 0.4;

///End state
	TVertexDescriptor eState = addVertex(hmm);
	assignEndState(hmm, eState);

///Transitions
	addEdge(hmm, exonState, exonState, 0.9);
	addEdge(hmm, exonState, spliceState, 0.1);
	addEdge(hmm, spliceState, intronState, 1.0);
	addEdge(hmm, begState, exonState, 1.0);
	addEdge(hmm, intronState, intronState, 0.9);
	addEdge(hmm, intronState, eState, 0.1);

///Print the whole model
	::std::cout << hmm << ::std::endl;

///Viterbi algorithm
	String<Dna> sequence = "CTTCATGTGAAAGCAGACGTAAGTCA";
	String<TVertexDescriptor> path;
	TProbability p = viterbiAlgorithm(hmm, sequence, path);
	::std::cout << "Viterbi algorithm" << ::std::endl;
	::std::cout << "Probability of best path: " << p << ::std::endl;
	::std::cout << "Sequence: " << ::std::endl;
	for(TSize i = 0; i<length(sequence); ++i) ::std::cout << sequence[i] << ',';
	::std::cout << ::std::endl;
	::std::cout << "State path: " << ::std::endl;
	for(TSize i = 0; i<length(path); ++i) {
		::std::cout << path[i];
		if (isSilent(hmm, path[i])) ::std::cout << " (Silent)";
		if (i < length(path) - 1) ::std::cout << ',';
	}
	::std::cout << ::std::endl;

///Forward algorithm
	::std::cout << "Forward algorithm" << ::std::endl;
	p = forwardAlgorithm(hmm, sequence);
	::std::cout << "Probability that the HMM generated the sequence: " << p << ::std::endl;

///Backward algorithm
	::std::cout << "Backward algorithm" << ::std::endl;
	p = backwardAlgorithm(hmm, sequence);
	::std::cout << "Probability that the HMM generated the sequence: " << p << ::std::endl;

	return 0;
}


text:
package org.apache.ibatis.io;

import static org.junit.jupiter.api.Assertions.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class ExternalResourcesTest {

  private File sourceFile;
  private File destFile;
  private File badFile;
  private File tempFile;

  /*
   * @throws java.lang.Exception
   */
  @BeforeEach
  void setUp() throws Exception {
    tempFile = File.createTempFile("migration", "properties");
    tempFile.canWrite();
    sourceFile = File.createTempFile("test1", "sql");
    destFile = File.createTempFile("test2", "sql");
  }

  @Test
  void testcopyExternalResource() {

    try {
      ExternalResources.copyExternalResource(sourceFile, destFile);
    } catch (IOException e) {
    }

  }

  @Test
  void testcopyExternalResource_fileNotFound() {

    try {
      badFile = new File("/tmp/nofile.sql");
      ExternalResources.copyExternalResource(badFile, destFile);
    } catch (IOException e) {
      assertTrue(e instanceof FileNotFoundException);
    }

  }

  @Test
  void testcopyExternalResource_emptyStringAsFile() {

    try {
      badFile = new File(" ");
      ExternalResources.copyExternalResource(badFile, destFile);
    } catch (Exception e) {
      assertTrue(e instanceof FileNotFoundException);
    }

  }

  @Test
  void testGetConfiguredTemplate() {
    String templateName = "";

    try (FileWriter fileWriter = new FileWriter(tempFile)) {
      fileWriter.append("new_command.template=templates/col_new_template_migration.sql");
      fileWriter.flush();
      templateName = ExternalResources.getConfiguredTemplate(tempFile.getAbsolutePath(), "new_command.template");
      assertEquals("templates/col_new_template_migration.sql", templateName);
    } catch (Exception e) {
      fail("Test failed with execption: " + e.getMessage());
    }
  }

  @AfterEach
  void cleanUp() {
    sourceFile.delete();
    destFile.delete();
    tempFile.delete();
  }
}


text:
"""Support for IKEA Tradfri."""
import logging

from pytradfri import Gateway, RequestError
from pytradfri.api.aiocoap_api import APIFactory
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.exceptions import ConfigEntryNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.util.json import load_json

from . import config_flow  # noqa: F401
from .const import (
    ATTR_TRADFRI_GATEWAY,
    ATTR_TRADFRI_GATEWAY_MODEL,
    ATTR_TRADFRI_MANUFACTURER,
    CONF_ALLOW_TRADFRI_GROUPS,
    CONF_GATEWAY_ID,
    CONF_HOST,
    CONF_IDENTITY,
    CONF_IMPORT_GROUPS,
    CONF_KEY,
    CONFIG_FILE,
    DEFAULT_ALLOW_TRADFRI_GROUPS,
    DOMAIN,
    KEY_API,
    KEY_GATEWAY,
    TRADFRI_DEVICE_TYPES,
)

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.Schema(
            {
                vol.Optional(CONF_HOST): cv.string,
                vol.Optional(
                    CONF_ALLOW_TRADFRI_GROUPS, default=DEFAULT_ALLOW_TRADFRI_GROUPS
                ): cv.boolean,
            }
        )
    },
    extra=vol.ALLOW_EXTRA,
)

async def async_setup(hass, config):
    """Set up the Tradfri component."""
    conf = config.get(DOMAIN)

    if conf is None:
        return True

    configured_hosts = [
        entry.data["host"] for entry in hass.config_entries.async_entries(DOMAIN)
    ]

    legacy_hosts = await hass.async_add_executor_job(
        load_json, hass.config.path(CONFIG_FILE)
    )

    for host, info in legacy_hosts.items():
        if host in configured_hosts:
            continue

        info[CONF_HOST] = host
        info[CONF_IMPORT_GROUPS] = conf[CONF_ALLOW_TRADFRI_GROUPS]

        hass.async_create_task(
            hass.config_entries.flow.async_init(
                DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=info
            )
        )

    host = conf.get(CONF_HOST)
    import_groups = conf[CONF_ALLOW_TRADFRI_GROUPS]

    if host is None or host in configured_hosts or host in legacy_hosts:
        return True

    hass.async_create_task(
        hass.config_entries.flow.async_init(
            DOMAIN,
            context={"source": config_entries.SOURCE_IMPORT},
            data={CONF_HOST: host, CONF_IMPORT_GROUPS: import_groups},
        )
    )

    return True

async def async_setup_entry(hass, entry):
    """Create a gateway."""
    # host, identity, key, allow_tradfri_groups

    factory = APIFactory(
        entry.data[CONF_HOST],
        psk_id=entry.data[CONF_IDENTITY],
        psk=entry.data[CONF_KEY],
        loop=hass.loop,
    )

    async def on_hass_stop(event):
        """Close connection when hass stops."""
        await factory.shutdown()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop)

    api = factory.request
    gateway = Gateway()

    try:
        gateway_info = await api(gateway.get_gateway_info())
    except RequestError:
        await factory.shutdown()
        raise ConfigEntryNotReady

    hass.data.setdefault(KEY_API, {})[entry.entry_id] = api
    hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway

    dev_reg = await hass.helpers.device_registry.async_get_registry()
    dev_reg.async_get_or_create(
        config_entry_id=entry.entry_id,
        connections=set(),
        identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])},
        manufacturer=ATTR_TRADFRI_MANUFACTURER,
        name=ATTR_TRADFRI_GATEWAY,
        # They just have 1 gateway model. Type is not exposed yet.
        model=ATTR_TRADFRI_GATEWAY_MODEL,
        sw_version=gateway_info.firmware_version,
    )

    for device in TRADFRI_DEVICE_TYPES:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, device)
        )

    return True


text:
Enemy::Enemy(void)
{
}

Enemy::Enemy(BITMAP *image, int cellWidth,int cellHeight, int animDelay, int animDirection,
		float locationX, float locationY, int initType, int initFacing, int initRotateDirection, int initAlive)
{
	spritesheet=image;
	width=cellWidth;height=cellHeight;
	row=0;column=0;
	animTime=0; delay=animDelay; if(delay==0) delay=1;
	animDir=animDirection;
	locX=locationX; locY=locationY;
	type=initType;
	facing=initFacing; if(type==0) if(facing==2) changeAnim(1);
	rotate_direction=initRotateDirection;
	alive=initAlive; life=3;
}
Enemy::~Enemy(void)
{
}

void Enemy::runAI(int time){
	//movement - depends on type
	switch(type){
		//Basic move forward then flip at wall behavior
		case 0:
			move(facing,1,0);
			if(collide_with_map()!=0){
				if(facing==2) facing=3;
				else facing=2;
				move(facing,1,0);
				nextRow();
			}
			break;
		//move along walls
		case 1:
			if(rotate_direction==0) //if moving clockwise
				switch(facing){
				//Each direction has a move order which will keep the enemy on whatever surface they are stuck to
				case 0: move_type1_helper(2,0,3,1); break; //if facing up -  order: L-U-R-D
				case 1: move_type1_helper(3,1,2,0); break; //if facing down - order: R-D-L-U
				case 2: move_type1_helper(1,2,0,3); break; //if facing left - order: D-L-U-R
				case 3: move_type1_helper(0,3,1,2); break; //if facing right - order: U-R-D-L
				}
			else //going counter clockwise changes the order
				switch(facing){
				case 0: move_type1_helper(3,0,2,1); break; //if facing up -  order: R-U-L-D
				case 1: move_type1_helper(2,1,3,0); break; //if facing down - order: L-D-R-U
				case 2: move_type1_helper(0,2,1,3); break; //if facing left - order: U-L-D-R
				case 3: move_type1_helper(1,3,0,2); break; //if facing right - order: D-R-U-L
				}
				changeAnim(facing+(4*rotate_direction));
				updateAnim(time);
			break; //end of type 1 movement
	}

}

//helps with moving enemies along walls
//checks to see if they can move in all four direction and if so sets their facing in that direction
int Enemy::move_type1_helper(int first, int second, int third, int fourth){
	int direction;
	int reverse_direction;
	for(int i=0;i<4;i++){
		switch(i){
			case 0: direction=first; break;
			case 1: direction=second; break;
			case 2: direction=third; break;
			case 3: direction=fourth; break;}
		switch(direction){
			case 0: reverse_direction=1; break;
			case 1: reverse_direction=0; break;
			case 2: reverse_direction=3; break;
			case 3: reverse_direction=2; break;}
		move(direction,1,0);//move the enemy in the specified direction
		if(collide_with_map()!=0) move(reverse_direction,1,0); //if they collide with the map move them back and continue with the for loop
		else{
			facing=direction;  //if they did not collide with the map, set their facing to the direction
			//if(direction==fourth) reverse(); //if this was the fourth direction then reverse the enemy's rotation dirction
			return 0; //getting here means this method is done, so return 0
		}
	}
	return 1; //getting here means it did not find a solution, so return 1
}

void Enemy::damage(int damage){
	if(type!=0){
		life-=damage;
	}
}

int Enemy::death_check(){
	if(life<=0) { alive=0; return 1;}
	return 0;
}

int Enemy::getType() { return type; }
void Enemy::setType(int t) { type=t; }
int Enemy::getFacing() { return facing; }
void Enemy::setFacing(int f) { facing=f; }
int Enemy::getRotateDirection() { return rotate_direction; }
void Enemy::setRotateDirection(int r) { rotate_direction=r; }
void Enemy::reverse(){ if(rotate_direction=0) rotate_direction=1; else rotate_direction=0; }


text:
import requests
import base64
with open('left.png', 'rb') as f:
    left = f.read()
with open('right.png', 'rb') as f:
    right = f.read()
len(left)
len(right)
r = requests.post('http://159.203.98.104:3000/send', data={'sendTo': 'dubchill', 'sendFrom': 'wchill', 'image_left': base64.b64encode(left), 'image_right': base64.b64encode(right)})
print r.text