blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
โŒ€
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
801a97f1e4a6d18b9f27441f5d5ded36164ccc55
f8ce149b8881ce53e29d25015206c63565c2387c
/utitled/inputtest.py
1417a706b4590ab5de75b22bc91fb83d239ea231
[]
no_license
George562/PythonProjects
98e607b3624bbefaef07c59c8bd2a24f92c580e6
f5f02988997182bcce5562e74a6592ef4b14ad2b
refs/heads/master
2022-08-30T15:18:01.503142
2022-07-11T15:30:51
2022-07-11T15:30:51
217,818,971
3
0
null
null
null
null
UTF-8
Python
false
false
2,402
py
import numpy as np import matplotlib.pyplot as plt import pygame as pg f = (lambda x, r: r * x * (1 - x)) def zoom(arr, x, y, k, increase=True): k = k if increase else 1 / k for i in range(len(arr)): arr[i] = (arr[i][0] - x) * k + x, (arr[i][1] - y) * k + y, *arr[i][2:] N = 100 Dk = 0.01 maxK = 400 y = [] x = [] for k in range(maxK): k *= Dk test = [0.5] for i in range(1, N): test.append(f(test[-1], k)) test = [round(i, 3) for i in test] if test[-1] == 0: y.append(0) x.append(k) else: done = False for i in set(test): if test.count(i) >= 10: y.append(i) x.append(k) done = True if not done: for i in set(test): y.append(i) x.append(k) # y = np.array(y) # x = np.array(x) # plt.plot(x, y) scw, sch = 1500, 800 sc = pg.display.set_mode((scw, sch)) s = len(y) space = [(scw * x[i] / maxK / Dk, sch * (1 - y[i])) for i in range(s)] def show(): sc.fill((0, 0, 0)) for i in range(s): pg.draw.circle(sc, (255, 255, 255), (int(space[i][0]), int(space[i][1])), 1) pg.display.update() clock = pg.time.Clock() show() done = False while not done: m_press = pg.mouse.get_pressed() if m_press[0]: zoom(space, *pg.mouse.get_pos(), 1.02) show() if m_press[2]: zoom(space, *pg.mouse.get_pos(), 1.02, False) show() if m_press[1]: relX, relY = pg.mouse.get_rel() space = list(map(lambda i: (i[0] + relX, i[1] + relY), space)) show() pg.mouse.get_rel() for event in pg.event.get(): if event.type == pg.QUIT: done = True # fig = plt.figure() # ax = plt.axes(xlim=(0, N), ylim=(0, 1)) # line, = ax.plot([], [], lw=2) # def init(): # line.set_data([], []) # return line, # # # def animate(k): # k = k * Dk # test = [0.5] * N # for i in range(1, N): # test[i] = f(test[i - 1], k) # print(k) # ax.set_ylim(min(test), max(test)) # y = np.array(test) # x = np.arange(0, N, 1) # line.set_data(x, y) # return line, # # # ani = FuncAnimation(fig, animate, frames=200, # interval=500, blit=True, init_func=init) # plt.show()
[ "noreply@github.com" ]
George562.noreply@github.com
7e16dcfb3d2fe97b7f81d1ff4856708059182426
3265336028e28becd17e4758cac7d1335b76582c
/tools/ftdf_dts/scripts/evaluation/arbiter/COEXv2_IgnoreMAC.py
c601113a0b49a9afa1a5ffa3c93087e67a7a4086
[]
no_license
andrew-ongh/fresh_SDK
9bf7af79a4c234fa2a7e5be878d32467e82f7a1e
f35806fe67ce18c15eb341a47885c7f503ecd08d
refs/heads/master
2023-07-29T18:51:39.765604
2021-06-23T08:51:47
2021-06-23T08:51:47
369,693,478
2
0
null
null
null
null
UTF-8
Python
false
false
31,392
py
## Arbiter v2 behavior (Auto PTI, MAC-PTI pair vs MAC-PTI pair). ## Arbiter interrupts/statistics tests, including overvlow feature ## ## Steps ## --------- ## - 1< Set FTDF TX PTI=1, RX PTI=2 ## - 1< Reset Arbiter ## - 1< Set Arbiter configuration 0=(BLE, 4), 1=(FTDF, 2) ## - 1< Enable FTDF Rx ## - 1< Start BLE active scanning ## - 1< Stop BLE active scanning ## - 1< Disable FTDF Rx ## - 1< Get arbiter stats and verify them: ## txpass1 == 0, rxpass1 != 0, txmask1 == 0, rxmask1 == 0, ## txpass2 == 0, rxpass2 == 0, txmask2 == 0, rxmask2 == 1 ## - 1< Reset Arbiter ## - 1< Set Arbiter configuration 0=(BLE, 4), 1=(FTDF, 2) and ignore BLE ## - 1< Enable FTDF Rx ## - 1< Start BLE active scanning ## - 1< Stop BLE active scanning ## - 1< Disable FTDF Rx ## - 1< Get arbiter stats and verify them: ## txpass1 == 0, rxpass1 == 0, txmask1 == 0, rxmask1 == 0, ## txpass2 == 0, rxpass2 == 1, txmask2 == 0, rxmask2 == 0 ## - 1< Reset Arbiter ## - 1< Set Arbiter configuration 0=(FTDF, 2), 1=(BLE, 4) ## - 1< Enable FTDF Rx ## - 1< Start BLE active scanning ## - 1< Stop BLE active scanning ## - 1< Disable FTDF Rx ## - 1< Get arbiter stats and verify them: ## txpass1 == 0, rxpass1 == 1, txmask1 == 0, rxmask1 == 0, ## txpass2 == 0, rxpass2 == 0, txmask2 == 0, rxmask2 != 0 ## - 1< Reset Arbiter ## - 1< Set Arbiter configuration 0=(FTDF, 2), 1=(BLE, 4) and ignore FTDF ## - 1< Enable FTDF Rx ## - 1< Start BLE active scanning ## - 1< Stop BLE active scanning ## - 1< Disable FTDF Rx ## - 1< Get arbiter stats and verify them: ## txpass1 == 0, rxpass1 == 0, txmask1 == 0, rxmask1 == 0, ## txpass2 == 0, rxpass2 != 0, txmask2 == 0, rxmask2 == 0 ## - 1< Reset Arbiter import sys #cli arguments import time #sleep from scriptIncludes import * DTS_BLEReset(devId1) # Expect OK res, ret = DTS_getMsg( devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_BLE_OK: logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_BLE_OK, ' confirm, instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) DTS_BLEReset(devId2) # Expect OK res, ret = DTS_getMsg( devId2, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_BLE_OK: logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_BLE_OK, ' confirm, instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) nrOfFrames = 1000 sduLength = 100 # Data frame msdu = [] for i in range( sduLength ): msdu.append( i ) keySource = [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0] msgDATA = { 'msgId': ftdf.FTDF_DATA_REQUEST, 'srcAddrMode': ftdf.FTDF_SHORT_ADDRESS, 'dstAddrMode': ftdf.FTDF_SHORT_ADDRESS, 'dstPANId': 0x0001, 'dstAddr': 0x0020, 'msduLength': len( msdu ), 'msdu': msdu, 'msduHandle': 1, 'ackTX': True, 'GTSTX': False, 'indirectTX': False, 'securityLevel': 0, 'keyIdMode': 0, 'keySource': keySource, 'keyIndex': 0, 'frameControlOptions': 0, 'headerIEList': 0, 'payloadIEList': 0, 'sendMultiPurpose': False } msgSET_PtiConfig = { 'msgId': ftdf.FTDF_SET_REQUEST, 'PIBAttribute': ftdf.FTDF_PIB_PTI_CONFIG, 'PIBAttributeValue': [2, 1, 3, 4, 5, 6, 7, 8] } msgCoex_StatsReq = { 'msgId': ftdf.DTS_MSG_ID_COEX_STATS } # Prepare test messages msgFlow = ( devId1, msgRESET, ftdf.FTDF_RESET_CONFIRM, devId2, msgRESET, ftdf.FTDF_RESET_CONFIRM, devId1, msgSET_PANId, ftdf.FTDF_SET_CONFIRM, devId2, msgSET_PANId, ftdf.FTDF_SET_CONFIRM, devId1, msgSET_Dev1_ShortAddress, ftdf.FTDF_SET_CONFIRM, devId2, msgSET_Dev2_ShortAddress, ftdf.FTDF_SET_CONFIRM, # devId1, msgSET_PtiConfig, ftdf.FTDF_SET_CONFIRM, devId1, msgSET_PtiConfig, ftdf.FTDF_SET_CONFIRM, ) msgDbgModeSetRequest = { 'msgId': ftdf.FTDF_DBG_MODE_SET_REQUEST, 'dbgMode': 0x1, } idx = 0 res = True while( idx < len( msgFlow ) ): # Send message DTS_sndMsg( msgFlow[idx], msgFlow[idx+1] ) # Get message confirm res, ret = DTS_getMsg( msgFlow[idx], responseTimeout ) # Check received expected confirm if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) break elif ret['msgId'] != msgFlow[idx+2]: logstr = ( 'SCRIPT: ERROR: Expected ', msgFlow[idx+2], ' confirm, instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) break else: if ret['msgId'] == ftdf.FTDF_SET_CONFIRM: if( ret['status'] != ftdf.FTDF_SUCCESS ): break # Check set request with get request msgGet['PIBAttribute'] = msgFlow[idx+1]['PIBAttribute'] DTS_sndMsg( msgFlow[idx], msgGet ) res2, ret2 = DTS_getMsg( msgFlow[idx], responseTimeout ) if( res2 == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) break elif ret2['msgId'] != ftdf.FTDF_GET_CONFIRM: logstr = ( 'SCRIPT: ERROR: Expected GET_CONFIRM, instead received ', ret2['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) break elif ret2['PIBAttributeValue'] != msgFlow[idx+1]['PIBAttributeValue']: logstr = ( 'SCRIPT: ERROR: Incorrect set PIBAttribute: ', msgGet['PIBAttribute'] ); raise StopScript( ''.join( map( str, logstr ) ) ) break else: if( ret['status'] != ftdf.FTDF_SUCCESS ): break idx += 3 # time.sleep(5) # =================================================================================================# # Reset arbiter DTS_ArbiterReset(devId1) DTS_ArbiterReset(devId2) # Set arbiter configuration so that BLE active scanning is above FTDF Rx DTS_ArbiterSetConfig(devId1, 0x07f0, 0, 0, ftdf.DTS_COEX_MAC_TYPE_BLE, 4, ftdf.DTS_COEX_MAC_TYPE_FTDF, 2, ftdf.DTS_COEX_MAC_TYPE_EXT, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0 ) # Turn on EXT # DTS_ArbiterSetExtStatus(devId1, 1) # Turn Rx on DTS_sndMsg(devId1, msgRxEnable_On) # Expect confirm res, ret = DTS_getMsg(devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.FTDF_RX_ENABLE_CONFIRM: logstr = ( 'SCRIPT: ERROR: Expected ', msgNameStr[ ftdf.FTDF_RX_ENABLE_CONFIRM - 1], ', instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) # Start scanning DTS_BLEScan( devId1, ftdf.DTS_BLE_GAP_SCAN_ACTIVE, 160, 80 ) # Expect OK res, ret = DTS_getMsg( devId1, responseTimeout) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_BLE_OK: logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_BLE_OK, ' confirm, instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # time.sleep(2) DTS_BLEStop( devId1 ) # Get 0 or more reports while 1: res, ret = DTS_getMsg( devId1, responseTimeout) if ( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif (ret['msgId'] != ftdf.DTS_MSG_ID_BLE_OK) and (ret['msgId'] != ftdf.DTS_MSG_ID_BLE_EVT): logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_BLE_OK, ' or ', ftdf.DTS_MSG_ID_BLE_EVT, ' , instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['msgId'] == ftdf.DTS_MSG_ID_BLE_OK: break; else: continue; # Expect Scan complete res, ret = DTS_getMsg( devId1, responseTimeout) if ( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_BLE_EVT: logstr = ( 'SCRIPT: ERROR: Expected msgId ', ftdf.DTS_MSG_ID_BLE_EVT, ' instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) elif ret['evt_code'] != ftdf.DTS_BLE_EVT_CODE_GAP_SCAN_COMPLETED: logstr = ( 'SCRIPT: ERROR: Expected evt_code ', ftdf.DTS_BLE_EVT_CODE_GAP_SCAN_COMPLETED, ' instead received ', ret['evt_code'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # Turn Rx off DTS_sndMsg(devId1, msgRxEnable_Off) # Expect confirm res, ret = DTS_getMsg(devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.FTDF_RX_ENABLE_CONFIRM: logstr = ( 'SCRIPT: ERROR: Expected ', msgNameStr[ ftdf.FTDF_RX_ENABLE_CONFIRM - 1], ', instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) DTS_CoexStatsReq(devId1) # Expect arbiter stats res, ret = DTS_getMsg( devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_COEX_STATS: logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_COEX_STATS, ' confirm, instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonOverflow'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonOverflow, instead received ', ret['txrxMonOverflow'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # BLE TxMasked should be 0 if ret['txrxMonTxMasked1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxMasked1, instead received ', ret['txrxMonTxMasked1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # BLE RxMasked should be 0 if ret['txrxMonRxMasked1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonRxMasked1, instead received ', ret['txrxMonRxMasked1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # BLE RxPassed should be non-zero if ret['txrxMonRxPassed1'] == 0: logstr = ( 'SCRIPT: ERROR: Expected non-zero txrxMonRxPassed1, instead received ', ret['txrxMonRxPassed1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # FTDF Tx Masked should be 0 if ret['txrxMonTxMasked2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxMasked2, instead received ', ret['txrxMonTxMasked2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # FTDF Tx Passed should be 0 if ret['txrxMonTxPassed2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxPassed2, instead received ', ret['txrxMonTxPassed2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # FTDF Rx Masked should be 1 if ret['txrxMonRxMasked2'] != 1: logstr = ( 'SCRIPT: ERROR: Expected 1 txrxMonRxMasked2, instead received ', ret['txrxMonRxMasked2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # FTDF Tx Passed should be 0 if ret['txrxMonRxPassed2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonRxPassed2, instead received ', ret['txrxMonRxPassed2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) DTS_ArbiterReset(devId1) # Set arbiter configuration so that BLE active scanning is above FTDF Rx but ignore BLE DTS_ArbiterSetConfig(devId1, 0x07f2, 0, 0, ftdf.DTS_COEX_MAC_TYPE_BLE, 4, ftdf.DTS_COEX_MAC_TYPE_FTDF, 2, ftdf.DTS_COEX_MAC_TYPE_EXT, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0 ) # Turn on EXT # DTS_ArbiterSetExtStatus(devId1, 1) # Turn Rx on DTS_sndMsg(devId1, msgRxEnable_On) # Expect confirm res, ret = DTS_getMsg(devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.FTDF_RX_ENABLE_CONFIRM: logstr = ( 'SCRIPT: ERROR: Expected ', msgNameStr[ ftdf.FTDF_RX_ENABLE_CONFIRM - 1], ', instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) # Start scanning DTS_BLEScan( devId1, ftdf.DTS_BLE_GAP_SCAN_ACTIVE, 160, 80 ) # Expect OK res, ret = DTS_getMsg( devId1, responseTimeout) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_BLE_OK: logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_BLE_OK, ' confirm, instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # time.sleep(2) DTS_BLEStop( devId1 ) # Get 0 or more reports while 1: res, ret = DTS_getMsg( devId1, responseTimeout) if ( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif (ret['msgId'] != ftdf.DTS_MSG_ID_BLE_OK) and (ret['msgId'] != ftdf.DTS_MSG_ID_BLE_EVT): logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_BLE_OK, ' or ', ftdf.DTS_MSG_ID_BLE_EVT, ' , instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['msgId'] == ftdf.DTS_MSG_ID_BLE_OK: break; else: continue; # Expect Scan complete res, ret = DTS_getMsg( devId1, responseTimeout) if ( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_BLE_EVT: logstr = ( 'SCRIPT: ERROR: Expected msgId ', ftdf.DTS_MSG_ID_BLE_EVT, ' instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) elif ret['evt_code'] != ftdf.DTS_BLE_EVT_CODE_GAP_SCAN_COMPLETED: logstr = ( 'SCRIPT: ERROR: Expected evt_code ', ftdf.DTS_BLE_EVT_CODE_GAP_SCAN_COMPLETED, ' instead received ', ret['evt_code'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # Turn Rx off DTS_sndMsg(devId1, msgRxEnable_Off) # Expect confirm res, ret = DTS_getMsg(devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.FTDF_RX_ENABLE_CONFIRM: logstr = ( 'SCRIPT: ERROR: Expected ', msgNameStr[ ftdf.FTDF_RX_ENABLE_CONFIRM - 1], ', instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) DTS_CoexStatsReq(devId1) # Expect arbiter stats res, ret = DTS_getMsg( devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_COEX_STATS: logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_COEX_STATS, ' confirm, instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonOverflow'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonOverflow, instead received ', ret['txrxMonOverflow'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # BLE TxMasked should be 0 if ret['txrxMonTxMasked1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxMasked1, instead received ', ret['txrxMonTxMasked1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # BLE RxMasked should be 0 if ret['txrxMonRxMasked1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonRxMasked1, instead received ', ret['txrxMonRxMasked1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # BLE TxPassed should be 0 if ret['txrxMonTxPassed1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected zero txrxMonTxPassed1, instead received ', ret['txrxMonTxPassed1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # BLE RxPassed should be zero if ret['txrxMonRxPassed1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected zero txrxMonRxPassed1, instead received ', ret['txrxMonRxPassed1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # FTDF Tx Masked should be 0 if ret['txrxMonTxMasked2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxMasked2, instead received ', ret['txrxMonTxMasked2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # BLE Tx Passed should be 0 if ret['txrxMonTxPassed2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxPassed2, instead received ', ret['txrxMonTxPassed2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # BLE Rx Masked should be 0 if ret['txrxMonRxMasked2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonRxMasked2, instead received ', ret['txrxMonRxMasked2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # BLE Tx Passed should be 1 if ret['txrxMonRxPassed2'] != 1: logstr = ( 'SCRIPT: ERROR: Expected 1 txrxMonRxPassed2, instead received ', ret['txrxMonRxPassed2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) ################################################################################## # Test ignore FTDF ################################################################################## # Reset arbiter DTS_ArbiterReset(devId1) # Set arbiter configuration so that FTDF Rx is above BLE active scanning DTS_ArbiterSetConfig(devId1, 0x07f0, 0, 0, ftdf.DTS_COEX_MAC_TYPE_FTDF, 2, ftdf.DTS_COEX_MAC_TYPE_BLE, 4, ftdf.DTS_COEX_MAC_TYPE_EXT, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0 ) # Turn on EXT # DTS_ArbiterSetExtStatus(devId1, 1) # Turn Rx on DTS_sndMsg(devId1, msgRxEnable_On) # Expect confirm res, ret = DTS_getMsg(devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.FTDF_RX_ENABLE_CONFIRM: logstr = ( 'SCRIPT: ERROR: Expected ', msgNameStr[ ftdf.FTDF_RX_ENABLE_CONFIRM - 1], ', instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) # Start scanning DTS_BLEScan( devId1, ftdf.DTS_BLE_GAP_SCAN_ACTIVE, 160, 80 ) # Expect OK res, ret = DTS_getMsg( devId1, responseTimeout) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_BLE_OK: logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_BLE_OK, ' confirm, instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # time.sleep(2) DTS_BLEStop( devId1 ) # Get 0 or more reports while 1: res, ret = DTS_getMsg( devId1, responseTimeout) if ( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif (ret['msgId'] != ftdf.DTS_MSG_ID_BLE_OK) and (ret['msgId'] != ftdf.DTS_MSG_ID_BLE_EVT): logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_BLE_OK, ' or ', ftdf.DTS_MSG_ID_BLE_EVT, ' , instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['msgId'] == ftdf.DTS_MSG_ID_BLE_OK: break; else: continue; # Expect Scan complete res, ret = DTS_getMsg( devId1, responseTimeout) if ( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_BLE_EVT: logstr = ( 'SCRIPT: ERROR: Expected msgId ', ftdf.DTS_MSG_ID_BLE_EVT, ' instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) elif ret['evt_code'] != ftdf.DTS_BLE_EVT_CODE_GAP_SCAN_COMPLETED: logstr = ( 'SCRIPT: ERROR: Expected evt_code ', ftdf.DTS_BLE_EVT_CODE_GAP_SCAN_COMPLETED, ' instead received ', ret['evt_code'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # Turn Rx off DTS_sndMsg(devId1, msgRxEnable_Off) # Expect confirm res, ret = DTS_getMsg(devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.FTDF_RX_ENABLE_CONFIRM: logstr = ( 'SCRIPT: ERROR: Expected ', msgNameStr[ ftdf.FTDF_RX_ENABLE_CONFIRM - 1], ', instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) DTS_CoexStatsReq(devId1) # Expect arbiter stats res, ret = DTS_getMsg( devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_COEX_STATS: logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_COEX_STATS, ' confirm, instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonOverflow'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonOverflow, instead received ', ret['txrxMonOverflow'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonTxMasked1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxMasked1, instead received ', ret['txrxMonTxMasked1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonRxMasked1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonRxMasked1, instead received ', ret['txrxMonRxMasked1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonTxPassed1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxPassed1, instead received ', ret['txrxMonTxPassed1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonRxPassed1'] != 1: logstr = ( 'SCRIPT: ERROR: Expected 1 txrxMonRxPassed1, instead received ', ret['txrxMonRxPassed1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonTxMasked2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxMasked2, instead received ', ret['txrxMonTxMasked2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonTxPassed2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxPassed2, instead received ', ret['txrxMonTxPassed2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonRxMasked2'] != 1: logstr = ( 'SCRIPT: ERROR: Expected 1 txrxMonRxMasked2, instead received ', ret['txrxMonRxMasked2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonRxPassed2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonRxPassed2, instead received ', ret['txrxMonRxPassed2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) DTS_ArbiterReset(devId1) # Set arbiter configuration so that FTDF Rx is above BLE active scanning but ignore FTDF DTS_ArbiterSetConfig(devId1, 0x07f4, 0, 0, ftdf.DTS_COEX_MAC_TYPE_FTDF, 2, ftdf.DTS_COEX_MAC_TYPE_BLE, 4, ftdf.DTS_COEX_MAC_TYPE_EXT, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0, ftdf.DTS_COEX_MAC_TYPE_NONE, 0 ) # Turn on EXT # DTS_ArbiterSetExtStatus(devId1, 1) # Turn Rx on DTS_sndMsg(devId1, msgRxEnable_On) # Expect confirm res, ret = DTS_getMsg(devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.FTDF_RX_ENABLE_CONFIRM: logstr = ( 'SCRIPT: ERROR: Expected ', msgNameStr[ ftdf.FTDF_RX_ENABLE_CONFIRM - 1], ', instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) # Start scanning DTS_BLEScan( devId1, ftdf.DTS_BLE_GAP_SCAN_ACTIVE, 160, 80 ) # Expect OK res, ret = DTS_getMsg( devId1, responseTimeout) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_BLE_OK: logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_BLE_OK, ' confirm, instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # time.sleep(2) DTS_BLEStop( devId1 ) # Get 0 or more reports while 1: res, ret = DTS_getMsg( devId1, responseTimeout) if ( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif (ret['msgId'] != ftdf.DTS_MSG_ID_BLE_OK) and (ret['msgId'] != ftdf.DTS_MSG_ID_BLE_EVT): logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_BLE_OK, ' or ', ftdf.DTS_MSG_ID_BLE_EVT, ' , instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['msgId'] == ftdf.DTS_MSG_ID_BLE_OK: break; else: continue; # Expect Scan complete res, ret = DTS_getMsg( devId1, responseTimeout) if ( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_BLE_EVT: logstr = ( 'SCRIPT: ERROR: Expected msgId ', ftdf.DTS_MSG_ID_BLE_EVT, ' instead received ', ret['msgId'] ) raise StopScript( ''.join( map( str, logstr ) ) ) elif ret['evt_code'] != ftdf.DTS_BLE_EVT_CODE_GAP_SCAN_COMPLETED: logstr = ( 'SCRIPT: ERROR: Expected evt_code ', ftdf.DTS_BLE_EVT_CODE_GAP_SCAN_COMPLETED, ' instead received ', ret['evt_code'] ) raise StopScript( ''.join( map( str, logstr ) ) ) # Turn Rx off DTS_sndMsg(devId1, msgRxEnable_Off) # Expect confirm res, ret = DTS_getMsg(devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.FTDF_RX_ENABLE_CONFIRM: logstr = ( 'SCRIPT: ERROR: Expected ', msgNameStr[ ftdf.FTDF_RX_ENABLE_CONFIRM - 1], ', instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) DTS_CoexStatsReq(devId1) # Expect arbiter stats res, ret = DTS_getMsg( devId1, responseTimeout ) if( res == False ): raise StopScript( 'SCRIPT: ERROR: No response received from device' ) elif ret['msgId'] != ftdf.DTS_MSG_ID_COEX_STATS: logstr = ( 'SCRIPT: ERROR: Expected ', ftdf.DTS_MSG_ID_COEX_STATS, ' confirm, instead received ', msgNameStr[ ret['msgId'] -1 ]) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonOverflow'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonOverflow, instead received ', ret['txrxMonOverflow'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonTxMasked1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxMasked1, instead received ', ret['txrxMonTxMasked1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonRxMasked1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonRxMasked1, instead received ', ret['txrxMonRxMasked1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonTxPassed1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected zero txrxMonTxPassed1, instead received ', ret['txrxMonTxPassed1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonRxPassed1'] != 0: logstr = ( 'SCRIPT: ERROR: Expected zero txrxMonRxPassed1, instead received ', ret['txrxMonRxPassed1'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonTxMasked2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxMasked2, instead received ', ret['txrxMonTxMasked2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonTxPassed2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonTxPassed2, instead received ', ret['txrxMonTxPassed2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonRxMasked2'] != 0: logstr = ( 'SCRIPT: ERROR: Expected 0 txrxMonRxMasked2, instead received ', ret['txrxMonRxMasked2'] ) raise StopScript( ''.join( map( str, logstr ) ) ) if ret['txrxMonRxPassed2'] == 0: logstr = ( 'SCRIPT: ERROR: Expected non-zero txrxMonRxPassed2, instead received ', ret['txrxMonRxPassed2'] ) raise StopScript( ''.join( map( str, logstr ) ) )
[ "andrew@happy.ai" ]
andrew@happy.ai
5e981652ed6772e58d6e8452013d622de03ed887
bccc2a5aa2b213c00fec2e9ac039af83d60837fd
/src/A_star.py
b06068dca89af04f7b4bd9dcb7867b2daa022ff6
[]
no_license
LucasGandara/proyecto_de_grado
df867b2c2d2075668298e0ff14f6ec1c643f2ab8
70b6a35ee5c23047916dc1627b633bca95cbd47f
refs/heads/master
2023-03-26T04:33:01.480190
2021-03-25T19:11:23
2021-03-25T19:11:23
246,616,184
0
0
null
null
null
null
UTF-8
Python
false
false
10,510
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ States: Open set: nodes that still needs to be evaluated closed set: all the nodes that have finished been evaluated """ import pygame from pygame import QUIT import sys from math import hypot from os import system pygame.init() WIDTH = 650 HEIGHT = 500 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("A* Algorithm") clock = pygame.time.Clock() obstacles = [] # How many columns and rows? cols = 32 rows = 32 #Width and height of each cell of grid w = (WIDTH - 10) / cols h = (HEIGHT - 10) / rows path = [] current = [] class Spot(object): def __init__(self, x, y): self.f = 0 self.g = 0 self.h = 0 self.x = x # posicion x del punto en el espacio self.y = y # Posicion y del punto en el espacio self.Neighbors = [] self.previous = None self.obstacle = False def addNeighbors(self, spots): if self.x >= 1: self.Neighbors.append(spots[self.x - 1][self.y]) if self.x < (cols - 1): self.Neighbors.append(spots[self.x + 1][self.y]) if self.y >= 1: self.Neighbors.append(spots[self.x][self.y - 1]) if self.y < (rows - 1): self.Neighbors.append(spots[self.x][self.y + 1]) if self.x > 0 and self.y > 0: self.Neighbors.append(spots[self.x - 1][self.y - 1]) if self.x < cols - 1 and self.y > 0: self.Neighbors.append(spots[self.x + 1][self.y - 1]) if self.x > 0 and self.y < rows - 1: self.Neighbors.append(spots[self.x - 1][self.y + 1]) if self.x < cols - 1 and self.y < rows - 1: self.Neighbors.append(spots[self.x + 1][self.y + 1]) def Isover(self): if pos[0] > self.x and pos[0] < self.x + self.width: if pos[1] > self.y and pos[1] < self.y + self.height: return True return False def heuristic(a, b): return hypot(a.x - b.x, a.y - b.y) def redrawGameWindow(win): #pygame.draw.rect(win, (255, 255, 255), (0, 0, WIDTH, HEIGHT)) #Dibujar la grilla for i in range(cols): for j in range(rows): pygame.draw.rect(win, (0, 0, 255), (spots[i][j].x * w, 1 + spots[i][j].y * h, w, h), 1) # Dibujams los openSet con verde for i,spot in enumerate(OpenSet): pygame.draw.rect(win, (0, 255, 0), (2 + spot.x * w, 3 + spot.y * h, w - 4, h - 4)) #We draw ClosedSet with red for i,spot in enumerate(closedSet): pygame.draw.rect(win, (255, 0, 0), (2 + spot.x * w, 3 + spot.y * h, w - 4, h - 4)) # Draw current pygame.draw.rect(win, (255, 0, 255), (2 + current.x * w, 3 + current.y * h, w - 4, h - 4)) # Draw the path in blue for spot in path: pygame.draw.rect(win, (0, 0, 255), (2 + spot.x * w, 3 + spot.y * h, w - 4, h - 4)) # Draw Obstacles for spot in obstacles: pygame.draw.rect(win, (255, 255, 102), (2 + spot.x * w, 3 + spot.y * h, w - 4, h - 4)) # Draw start and end spot! pygame.draw.rect(win, (255, 255, 255), (start.x * w, 1 + start.y * h, w, h)) pygame.draw.rect(win, (198, 252, 3), (end.x * w, 1 + end.y * h, w, h)) pygame.display.update() # Create the 2D array spots = [[Spot(i, j) for j in range(rows)] for i in range(cols)] for i in range(len(spots)): for j in range(len(spots[i])): spots[i][j].addNeighbors(spots) # Definir Obstรกculos obstalce_x = [] obstacle_y = [] obstacle_file = open('/home/lucas/catkin_ws/src/proyecto_de_grado/src/Obstacles.txt') pair_coodinates = obstacle_file.read() obstacle_list = pair_coodinates.split('\n') for pair in obstacle_list: pair2 = pair.split(',') obstalce_x.append(int(pair2[0]) - 5) obstacle_y.append(int(pair2[1])) for x, y in zip(obstalce_x, obstacle_y): spots[int(x)][int(y)].obstacle = True obstacles.append(spots[int(x)][int(y)]) OpenSet = [] closedSet = [] start = spots[28][3] end = spots[2][28] path = [] OpenSet.append(start) current = start gaming = True while gaming: clock.tick(12) #Find the path temp = current path = [] path.append(temp) #As long as the temp has a previous while temp.previous: current = temp path.append(temp.previous) temp = temp.previous for eventos in pygame.event.get(): pos = pygame.mouse.get_pos() if eventos.type == QUIT: sys.exit(0) # Find the one to evaluate next if len(OpenSet) > 0: winner = 0 for i in range(len(OpenSet)): if OpenSet[i].f < OpenSet[winner].f: winner = i if OpenSet[i].f == OpenSet[winner].f: if OpenSet[i].g > OpenSet[winner].g: winner = i current = OpenSet[winner] lastCheckedNode = current if current == end: #Find the path path = [] temp = current path.append(temp) #As long as the temp has a previous while temp.previous: current = temp path.append(temp.previous) temp = temp.previous del(path[-1]) del(path[-1]) system('cls') print('Finish!') gaming = False try: OpenSet.remove(current) except ValueError as e: pass closedSet.append(current) # Verify Neighbors of the current cell neighbors = current.Neighbors for neighbor in neighbors: if not(neighbor in closedSet) and not(neighbor.obstacle): # ceck if neighbor is available to visit temp = current.g + heuristic(neighbor, current) newpath = False if not(neighbor in OpenSet): OpenSet.append(neighbor) elif temp >= neighbor.g: continue neighbor.g = temp neighbor.h = heuristic(neighbor, end) neighbor.f = neighbor.g + neighbor.h neighbor.previous = current else: # No solution print('No Solution') gaming = False pass redrawGameWindow(screen) pygame.image.save(screen, '/home/lucas/catkin_ws/src/proyecto_de_grado/Imgs/Prueba2.png') """ Once the Path finder algoritm ends, export the path for the turtlebot to follow """ X_references = [] Y_references = [] for spot in reversed(path): X_references.append((spot.y - 3) * 0.178) Y_references.append((spot.x - 28) * 0.178) x_followed = [] y_followed = [] import rospy from geometry_msgs.msg import Twist, Point, Quaternion import tf from math import radians, copysign, sqrt, pow, pi, atan2 from tf.transformations import euler_from_quaternion import numpy as np import matplotlib.pyplot as plt class A_star(): def __init__(self): rospy.init_node('A_Star_Path_Finder', anonymous=False) rospy.on_shutdown(self.shutdown) self.cmd_vel = rospy.Publisher('cmd_vel', Twist, queue_size=5) position = Point() move_cmd = Twist() r = rospy.Rate(10) self.tf_listener = tf.TransformListener() self.odom_frame = 'odom' try: self.tf_listener.waitForTransform(self.odom_frame, 'base_footprint', rospy.Time(), rospy.Duration(1.0)) self.base_frame = 'base_footprint' except (tf.Exception, tf.ConnectivityException, tf.LookupException): try: self.tf_listener.waitForTransform(self.odom_frame, 'base_link', rospy.Time(), rospy.Duration(1.0)) self.base_frame = 'base_link' except (tf.Exception, tf.ConnectivityException, tf.LookupException): rospy.loginfo("Cannot find transform between odom and base_link or base_footprint") rospy.signal_shutdown("tf Exception") for i in range(len(X_references)): print """---------------------------------- Going To point: %s, %s """ % (X_references[i], Y_references[i]) (position, orientation) = self.get_odom() x_followed.append(position.y) y_followed.append(-1 * position.x) last_rotation = 0 linear_speed = 1 angular_speed = 1 goal_x = X_references[i] goal_y = Y_references[i] goal_distance = sqrt(pow(goal_x - position.x, 2) + pow(goal_y - position.y, 2)) distance = goal_distance while distance > 0.05: (position, orientation) = self.get_odom() x_start = position.x y_start = position.y errror_teta = atan2(goal_y - y_start, goal_x- x_start) move_cmd.angular.z = angular_speed * errror_teta-orientation distance = sqrt(pow((goal_x - x_start), 2) + pow((goal_y - y_start), 2)) move_cmd.linear.x = min(linear_speed * distance, 0.1) if move_cmd.angular.z > 0: move_cmd.angular.z = min(move_cmd.angular.z, 1.5) else: move_cmd.angular.z = max(move_cmd.angular.z, -1.5) last_rotation = orientation self.cmd_vel.publish(move_cmd) r.sleep() (position, orientation) = self.get_odom() self.cmd_vel.publish(Twist()) fig = plt.figure() plt.plot(x_followed, y_followed) plt.title('Prueba 1') fig.suptitle('desplazamiento del robot durante la ejecucion', fontsize=20) plt.xlabel('X - Coordinates', fontsize=18) plt.ylabel('Y - Coordinates', fontsize=18) ax = plt.gca() ax.set_ylim([-1.462,3.738]) ax.set_xlim([-3.56, 2.14]) plt.show() fig.savefig('/home/lucas/catkin_ws/src/proyecto_de_grado/Imgs/Prueba1.png') def get_odom(self): try: (trans, rot) = self.tf_listener.lookupTransform(self.odom_frame, self.base_frame, rospy.Time(0)) rotation = euler_from_quaternion(rot) except (tf.Exception, tf.ConnectivityException, tf.LookupException): rospy.loginfo("TF Exception") return return (Point(*trans), rotation[2]) def shutdown(self): """ When the node closes, stop the robot""" self.cmd_vel.publish(Twist()) rospy.sleep(1) A_star()
[ "lucas17-12@hotmail.com" ]
lucas17-12@hotmail.com
26df6309ed9c83975b4bbe7e1e401a854ddd84cc
7c15f211adc9e9eb9f66ccdd570c9f38dff7ea8d
/packages/autorest.python/test/multiapi/Expected/AcceptanceTests/MultiapiCredentialDefaultPolicy/multiapicredentialdefaultpolicy/v3/aio/operations/_multiapi_service_client_operations.py
1ff0b63db3af5c3f9da14b759b02858afe36e5e0
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
Azure/autorest.python
cc4bfbf91ae11535731cad37cedd6b733edf1ebd
a00d7aaa3753ef05cb5a0d38c664a90869478d44
refs/heads/main
2023-09-03T06:58:44.246200
2023-08-31T20:11:51
2023-08-31T20:11:51
100,315,955
47
40
MIT
2023-09-14T21:00:21
2017-08-14T22:58:33
Python
UTF-8
Python
false
false
8,070
py
# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._multiapi_service_client_operations import ( build_test_different_calls_request, build_test_paging_request, ) from .._vendor import MultiapiServiceClientMixinABC T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class MultiapiServiceClientOperationsMixin(MultiapiServiceClientMixinABC): def _api_version(self, op_name: str) -> str: # pylint: disable=unused-argument try: return self._config.api_version except: # pylint: disable=bare-except return "" @distributed_trace def test_paging(self, **kwargs: Any) -> AsyncIterable["_models.ModelThree"]: """Returns ModelThree with optionalProperty 'paged'. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ModelThree or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~multiapicredentialdefaultpolicy.v3.models.ModelThree] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} cls: ClsType[_models.PagingResult] = kwargs.pop("cls", None) error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: request = build_test_paging_request( template_url=self.test_paging.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: # make call to next link with the client's api-version _parsed_next_link = urllib.parse.urlparse(next_link) _next_request_params = case_insensitive_dict( { key: [urllib.parse.quote(v) for v in value] for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() } ) _next_request_params["api-version"] = self._config.api_version request = HttpRequest( "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request async def extract_data(pipeline_response): deserialized = self._deserialize("PagingResult", pipeline_response) list_of_elem = deserialized.values if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged(get_next, extract_data) test_paging.metadata = {"url": "/multiapi/paging/1"} @distributed_trace_async async def test_different_calls( # pylint: disable=inconsistent-return-statements self, greeting_in_english: str, greeting_in_chinese: Optional[str] = None, greeting_in_french: Optional[str] = None, **kwargs: Any ) -> None: """Has added parameters across the API versions. :param greeting_in_english: pass in 'hello' to pass test. Required. :type greeting_in_english: str :param greeting_in_chinese: pass in 'nihao' to pass test. Default value is None. :type greeting_in_chinese: str :param greeting_in_french: pass in 'bonjour' to pass test. Default value is None. :type greeting_in_french: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None or the result of cls(response) :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop( "api_version", _params.pop("api-version", self._api_version("test_different_calls") or "3.0.0") ) cls: ClsType[None] = kwargs.pop("cls", None) request = build_test_different_calls_request( greeting_in_english=greeting_in_english, greeting_in_chinese=greeting_in_chinese, greeting_in_french=greeting_in_french, api_version=api_version, template_url=self.test_different_calls.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=_stream, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) test_different_calls.metadata = {"url": "/multiapi/testDifferentCalls"}
[ "noreply@github.com" ]
Azure.noreply@github.com
b8f22048650e927d5e4b90c9f64aac54700d3b5b
2ad1116411d79d5bac26402ccac4f5785a0485e4
/Selenium/test_PageObj.py
f8077a63bab3956f8601fa927a404ebbb73f6b4d
[]
no_license
slavkoBV/solved-tasks-SoftGroup-course
0a879fcaeedd2b1d27b2970ea621eb2bdfab4ce4
12461d50a095764d5e237babaec466bc2d8dc672
refs/heads/master
2021-01-18T15:55:04.224872
2017-05-08T15:38:16
2017-05-08T15:38:16
86,691,843
3
0
null
null
null
null
UTF-8
Python
false
false
1,535
py
import unittest import HTMLTestRunner from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class SearchTest(unittest.TestCase): @classmethod def setUp(cls): cls.driver = webdriver.Firefox() cls.driver.maximize_window() cls.driver.get("http://meblilem.com.ua/") def test_search_by_category(self): self.search_field = self.driver.find_element_by_name('q') self.search_field.clear() self.search_field.send_keys('ัะฟะฐะปัŒะฝั–') self.search_field.submit() try: products = WebDriverWait(self.driver, 10).until( EC.presence_of_all_elements_located((By.CLASS_NAME, "item"))) self.assertEqual(20, len(products)) except Exception as err: print(err) def test_search_by_name(self): self.search_field = self.driver.find_element_by_name('q') self.search_field.clear() self.search_field.send_keys('ะกะพะฝั') self.search_field.submit() try: WebDriverWait(self.driver, 20) product = self.driver.find_element_by_xpath("//div[@class='item']/a[2]") self.assertEqual('ะกะพะฝั', product.text.split()[0]) except Exception as err: print(err) @classmethod def tearDown(cls): cls.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)
[ "slav_b@ukr.net" ]
slav_b@ukr.net
b31de755bd98034cd078c27fe607eddf4b9c3e32
219bc817fce7e410f189dbc706932789cabe1ea1
/core_website_app/utils/markdown_parser.py
21360fdd2a47eb1d368cfe88c5ab11722a10d18a
[ "LicenseRef-scancode-public-domain" ]
permissive
cdcs-repos/core_website_app
80595218804c9ddde72c51d3ff63cd35f8ede36a
ec2d914fb7fbe1c870009c4731ce61bc17fb8700
refs/heads/master
2020-04-22T17:36:07.040034
2018-11-28T17:13:15
2018-11-30T16:02:36
170,547,208
0
0
NOASSERTION
2019-02-13T17:11:31
2019-02-13T17:11:31
null
UTF-8
Python
false
false
425
py
""" Parser to convert Markdown to HTML in a safe way """ from markdown import markdown from xml_utils.commons.exceptions import HTMLError from xml_utils.html_tree.parser import safe_html def parse(text): """ Parse Markdown to convert it into HTML Args: text: Returns: """ md_text = markdown(text) try: return safe_html(md_text) except HTMLError as e: return e.message
[ "philippe.dessauw@nist.gov" ]
philippe.dessauw@nist.gov
1aebd431d7b7c02fd70de3ea1e613d6322ae5735
0a3705cf78d38986e6804b103081a194a0aa4dff
/hj/ciphers/substitution/polyalphabetic/__init__.py
85fab88641ea3f9f58547bdc87d2cfd1dcb84e34
[]
no_license
thunder8olt/hotel-juliet
d1ba3084d50d34d00e042b6df1a98bbcfae7a570
9ae6c78f83166d8217c3081385d168c76ec99227
refs/heads/master
2021-01-18T16:09:01.549000
2013-03-24T05:25:02
2013-03-24T05:25:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
194
py
#!/usr/bin/python # -*- coding: utf-8 -*- from .base import * from .vigenere import * from .beaufort import * from .gronsfeld import * from .trithemius import * from .variant_beaufort import *
[ "andrew@merenbach.com" ]
andrew@merenbach.com
5e4f7ad4bfd5b22b01571d3c84d41506b49335d4
471c92ba73844db89b9f0e9fb8c904af46464250
/src/lookups.py
fd8ab0c778277e58b1d8bd438caf2b6b2609a48b
[]
no_license
lalaithion/python_challenge
a5cd5e6dc459e65970da8999c008f30af572dd32
8f90312a91641fd9c3ba255c3867a7635e430b0a
refs/heads/master
2021-01-22T18:58:01.337892
2017-03-20T21:32:57
2017-03-20T21:32:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
728
py
#! python3 # Izaak Weiss, 2017 # standard library imports import random # third party imports import requests def geoip(ip_addr): # create a request string urlstr = 'http://ipinfo.io/' + str(ip_addr) + '/json' # make the request req = requests.get(urlstr) # check for errors if req.status_code != requests.codes.ok: return {} # return the data as a dictionary return req.json() def rdap(ip_addr): # create a request string urlstr = 'http://rdap.apnic.net/ip/' + str(ip_addr) # make the request req = requests.get(urlstr) # check for errors if req.status_code != requests.codes.ok: return {} # return the data as a dictionary return req.json()
[ "izwe5504@colorado.edu" ]
izwe5504@colorado.edu
8706e0fb35ef8c6fb12f3288236ff9fd8051bba3
153febd7b42fbc694761a028990f59ed47c20d8c
/TestCases/test_add_multiple_student.py
8c7a64edbcf9cffc26219be3929d84bd2056089b
[]
no_license
dineshkumar1392/Rest_API_Automation
8f2de70b526fffc07f494ef01c78d0910cd5429e
836cc8a00a2ec24935f848998602a2d9b086119c
refs/heads/master
2022-12-11T20:53:28.044837
2020-08-20T23:16:45
2020-08-20T23:16:45
289,128,084
0
0
null
null
null
null
UTF-8
Python
false
false
1,298
py
import requests import json import jsonpath import openpyxl def test_add_multiple_student_data(): #api code api_url = "http://www.thetestingworldapi.com/api/studentsDetails" f = open("D://api_json/py.txt", 'r') json_request = json.loads(f.read()) #print(json_request) # print(json_request['first_name']) #excel code wk = openpyxl.load_workbook("D://api_json/xl_data.xlsx") # load work book sh = wk['Sheet1'] # load sheet rows = sh.max_row # load maximum rows in sheet for i in range (2,rows+1) : first_name = sh.cell(row=i,column =1) #create variable for cell middle_name = sh.cell(row=i,column = 2) last_name = sh.cell(row=i,column = 3) d_o_b = sh.cell(row=i,column =4) # to read data from cell like first_name.value #put that value in json values json_request['first_name'] = first_name.value json_request['middle_name'] = middle_name.value json_request['last_name'] = last_name.value json_request['date_of_birth'] = d_o_b.value # send the request to api response = requests.post(api_url,json_request) print(response.text) print(response.status_code) assert response.status_code == 201
[ "dineshkumar1392@gmail.com" ]
dineshkumar1392@gmail.com
4e103c6fd37950ef70c1defe86c01087a3b89744
860a9eb9b2592575467dbe1a6a37dbf095714a4b
/DF_GAN-TF/pre_data.py
a368c7811039cb15bf0734161c4f8aa6bf169e14
[]
no_license
CosmosHua/Mesh
01cf6889a76c1c73f07c3e7e4dc4dacbed95ef81
72e5169d57fe519b9f3907c03861061ae679645e
refs/heads/master
2021-06-10T02:18:46.918937
2020-10-29T07:12:03
2020-10-29T07:12:03
160,528,499
2
0
null
null
null
null
UTF-8
Python
false
false
4,220
py
# coding:utf-8 # !/usr/bin/python3 import random, os, cv2 import tensorflow as tf """ ๅŠŸ่ƒฝ๏ผšๅฐ†ๆ–‡ไปถๅคนไธ‹็š„jpgๆ ผๅผๅ›พๅƒ่ฝฌๆขๆˆtfrecordsๆ ผๅผไฟๅญ˜ ่พ“ๅ…ฅ๏ผšX,Y,ZๅŸŸ็š„ๅ›พๅƒ่ทฏๅพ„ ่พ“ๅ‡บ๏ผšๅฏนๅบ”็š„tfrecordsๆ–‡ไปถ """ im_size = [220, 178] data_root_dir = "data/" FLAGS = tf.flags.FLAGS # the path of input and out tf.flags.DEFINE_string('X_dir', data_root_dir+'trainX/', "Mesh_Face_Dir") tf.flags.DEFINE_string('Y_dir', data_root_dir+'trainY/', "Clean_Face_Dir") tf.flags.DEFINE_string('Z_dir', data_root_dir+'trainZ/', "Mesh_Apart_Dir") tf.flags.DEFINE_string('X', data_root_dir+'x.tfrecords', "Mesh_Faces") tf.flags.DEFINE_string('Y', data_root_dir+'y.tfrecords', "Clean_Faces") tf.flags.DEFINE_string('Z', data_root_dir+'z.tfrecords', "Mesh_Nets") def get_net(mesh, clean, out): # sever mesh h,w = im_size if not os.path.exists(out): os.makedirs(out) for im in os.listdir(mesh): cn = im[:im.rfind("_")]+".jpg" cn = os.path.join(clean, cn) cc = cv2.resize(cv2.imread(cn), (w,h)) cv2.imwrite(cn, cc) mn = os.path.join(mesh, im) mm = cv2.resize(cv2.imread(mn), (w,h)) cv2.imwrite(mn, mm) net = os.path.join(out, im) cc = cc.astype(int)-mm.astype(int) cv2.imwrite(net, 255-cc) def data_reader(input_dir, shuffle=True): """ Read images from input_dir then shuffle them Args: input_dir: string, path of input dir, e.g., /path/to/dir Returns: file_paths: list of strings """ file_paths = [] for img_file in os.scandir(input_dir): # ้€’ๅฝ’้ๅކๆŒ‡ๅฎšๆ–‡ไปถ็›ฎๅฝ• if img_file.name.endswith('.jpg') and img_file.is_file(): file_paths.append(img_file.path) if shuffle: # ๆ˜ฏๅฆ้šๆœบๆ‰“ไนฑๅ›พ็‰‡้กบๅบ shuffled_index = list(range(len(file_paths))) random.seed(12345) random.shuffle(shuffled_index) file_paths = [file_paths[i] for i in shuffled_index] return file_paths def _int64_feature(value): """Wrapper for inserting int64 features into Example proto.""" if not isinstance(value, list): value = [value] return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) def _bytes_feature(value): """Wrapper for inserting bytes features into Example proto.""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _convert_to_example(file_path, image_buffer): """ Build an Example proto for an example. Args: file_path: string, path to an image file, e.g., '/path/to/example.JPG' image_buffer: string, JPEG encoding of RGB image Returns: Example proto """ file_name = file_path.split('/')[-1] file_name = file_name.encode() example = tf.train.Example( features = tf.train.Features( feature={ 'image/file_name': _bytes_feature((os.path.basename(file_name))), 'image/encoded_image': _bytes_feature((image_buffer))} ) ) return example def data_writer(input_dir, output_file): """Write data to tfrecords""" file_paths = data_reader(input_dir) images_num = len(file_paths) writer = tf.python_io.TFRecordWriter(output_file) for i in range(images_num): file_path = file_paths[i] with tf.gfile.FastGFile(file_path, 'rb') as f: # ่ฏปๅ–ๅ›พ็‰‡ image_data = f.read() example = _convert_to_example(file_path, image_data) writer.write(example.SerializeToString()) print("Processed {}/{}.".format(i+1, images_num)) writer.close() def make_data(): # X = faceNetDir, Y = faceDir, Z = outDir print("seperate net from %s:" % FLAGS.X_dir) get_net(FLAGS.X_dir, FLAGS.Y_dir, FLAGS.Z_dir) print("Convert X data to tfrecords:") data_writer(FLAGS.X_dir, FLAGS.X) print("Convert Y data to tfrecords:") data_writer(FLAGS.Y_dir, FLAGS.Y) print("Convert Z data to tfrecords:") data_writer(FLAGS.Z_dir, FLAGS.Z) if __name__ == '__main__': make_data()
[ "cosmoscosmos@163.com" ]
cosmoscosmos@163.com
35afccbe38609f84e36e17d562654bfd9edc0a40
8d298acd3f4e0f8371834fb73fa6cfa7598af591
/src/architectures/custom_layers/sem_recurrent.py
1870a1218383ac1ae993e1b47dbaa3710f87b5e9
[]
no_license
jderiu/e2e_nlg
64e400dc2c81fb76722189df009b93dd32e6e4b4
7959776a4da1eab2dccb816056c2c43854659759
refs/heads/master
2020-03-29T01:46:33.094566
2018-11-06T14:20:49
2018-11-06T14:20:49
149,405,677
2
2
null
null
null
null
UTF-8
Python
false
false
20,921
py
from keras.layers import Recurrent, concatenate from keras import backend as K from keras import activations from keras import initializers from keras import regularizers from keras import constraints from keras.engine import InputSpec from src.architectures.custom_layers.recurrent_tensorflow import sc_tf_rnn class SC_LSTM(Recurrent): def __init__(self, units, out_units, alpha=0.2, softmax_temperature=None, return_da=True, activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', out_kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', unit_forget_bias=True, kernel_regularizer=None, out_kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, out_kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0., recurrent_dropout=0., sc_dropout=0., **kwargs): super(SC_LSTM, self).__init__(**kwargs) self.units = units self.alpha = alpha self.out_units = out_units self.activation = activations.get(activation) self.recurrent_activation = activations.get(recurrent_activation) self.use_bias = use_bias self.return_da = return_da self.softmax_temperature = softmax_temperature #different behaviour while training than from inefrence time self.train_phase = True self.input_spec = [InputSpec(ndim=3), InputSpec(ndim=2)] self.kernel_initializer = initializers.get(kernel_initializer) self.out_kernel_initializer = initializers.get(out_kernel_initializer) self.recurrent_initializer = initializers.get(recurrent_initializer) self.bias_initializer = initializers.get(bias_initializer) self.unit_forget_bias = unit_forget_bias self.kernel_regularizer = regularizers.get(kernel_regularizer) self.out_kernel_regularizer = regularizers.get(out_kernel_regularizer) self.recurrent_regularizer = regularizers.get(recurrent_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.out_kernel_constraint = constraints.get(out_kernel_constraint) self.recurrent_constraint = constraints.get(recurrent_constraint) self.bias_constraint = constraints.get(bias_constraint) self.dropout = min(1., max(0., dropout)) self.recurrent_dropout = min(1., max(0., recurrent_dropout)) self.sc_dropout = min(1., max(0., sc_dropout)) def build(self, input_shape): assert isinstance(input_shape, list) or isinstance(input_shape, tuple) if isinstance(input_shape, tuple): main_input_shape = input_shape else: main_input_shape = input_shape[0] batch_size = main_input_shape[0] if self.stateful else None #takes orig_input while training and dialogue act for conditioning if self.state_spec: assert len(input_shape) == 4 else: assert len(input_shape) == 2 self.input_dim = main_input_shape[2] diact_shape = input_shape[-1] self.dialogue_act_dim = diact_shape[-1] self.input_spec[0] = InputSpec(shape=(batch_size, None, main_input_shape[2])) #h,c self.states = [None, None] if self.stateful: self.reset_states() self.kernel = self.add_weight(shape=(self.input_dim, self.units * 4), name='kernel', initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) self.recurrent_kernel = self.add_weight( shape=(self.units, self.units * 4), name='recurrent_kernel', initializer=self.recurrent_initializer, regularizer=self.recurrent_regularizer, constraint=self.recurrent_constraint) ### Semantic Conditioning Weights Weights self.kernel_d = self.add_weight( shape=(self.dialogue_act_dim, self.units), name='diag_kernel', initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint ) self.kernel_r = self.add_weight( shape=(self.input_dim, self.dialogue_act_dim), name='kernel_r', initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint ) self.recurrent_kernel_r = self.add_weight( shape=(self.units, self.dialogue_act_dim), name='recurrent_kernel_r', initializer=self.recurrent_initializer, regularizer=self.recurrent_regularizer, constraint=self.kernel_constraint ) self.out_kernel = self.add_weight(shape=(self.units, self.out_units), name='out_kernel', initializer=self.out_kernel_initializer, regularizer=self.out_kernel_regularizer, constraint=self.out_kernel_constraint) if self.use_bias: if self.unit_forget_bias: def bias_initializer(shape, *args, **kwargs): return K.concatenate([ self.bias_initializer((self.units,), *args, **kwargs), initializers.Ones()((self.units,), *args, **kwargs), self.bias_initializer((self.units * 2,), *args, **kwargs), ]) else: bias_initializer = self.bias_initializer self.bias = self.add_weight(shape=(self.units * 4,), name='bias', initializer=bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None self.kernel_i = self.kernel[:, :self.units] self.kernel_f = self.kernel[:, self.units * 1: self.units * 2] self.kernel_c = self.kernel[:, self.units * 2: self.units * 3] self.kernel_o = self.kernel[:, self.units * 3:] self.recurrent_kernel_i = self.recurrent_kernel[:, :self.units] self.recurrent_kernel_f = self.recurrent_kernel[:, self.units: self.units * 2] self.recurrent_kernel_c = self.recurrent_kernel[:, self.units * 2: self.units * 3] self.recurrent_kernel_o = self.recurrent_kernel[:, self.units * 3:] if self.use_bias: self.bias_i = self.bias[:self.units] self.bias_f = self.bias[self.units: self.units * 2] self.bias_c = self.bias[self.units * 2: self.units * 3] self.bias_o = self.bias[self.units * 3:] self.bias_r = self.add_weight( shape=(self.dialogue_act_dim, ), name='bias_r', initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint ) else: self.bias_i = None self.bias_f = None self.bias_c = None self.bias_o = None self.bias_r = None self.built = True def preprocess_input(self, inputs, training=None): return inputs def compute_output_shape(self, input_shape): if isinstance(input_shape, list): input_shape = input_shape[0] if self.return_sequences: output_shape = (input_shape[0], input_shape[1], self.out_units) else: output_shape = (input_shape[0], self.out_units) if self.return_state: state_shape = [(input_shape[0], self.units) for _ in self.states] return [output_shape] + state_shape if self.return_da: da_state_shape = (input_shape[0], self.dialogue_act_dim) da_outs_shape = (input_shape[0], input_shape[1], self.dialogue_act_dim) return [output_shape, da_state_shape, da_outs_shape] else: return output_shape def compute_mask(self, inputs, mask): if isinstance(mask, list): mask = mask[0] output_mask = mask if self.return_sequences else None if self.return_state: state_mask = [None for _ in self.states] return [output_mask] + state_mask elif self.return_da: state_mask = None return [output_mask, state_mask, state_mask] else: return output_mask def get_constants(self, inputs, training=None): constants = [] if self.implementation != 0 and 0 < self.dropout < 1: input_shape = K.int_shape(inputs) input_dim = input_shape[-1] ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1))) ones = K.tile(ones, (1, int(input_dim))) def dropped_inputs(): return K.dropout(ones, self.dropout) dp_mask = [K.in_train_phase(dropped_inputs, ones, training=training) for _ in range(5)] constants.append(dp_mask) else: constants.append([K.cast_to_floatx(1.) for _ in range(5)]) if 0 < self.recurrent_dropout < 1: ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1))) ones = K.tile(ones, (1, self.units)) def dropped_inputs(): return K.dropout(ones, self.recurrent_dropout) rec_dp_mask = [K.in_train_phase(dropped_inputs, ones, training=training) for _ in range(5)] constants.append(rec_dp_mask) else: constants.append([K.cast_to_floatx(1.) for _ in range(5)]) return constants def get_sc_constants(self, inputs, training=None): constants = [] if 0 < self.sc_dropout < 1: ones = K.ones_like(K.reshape(inputs[:, 0], (-1, 1))) ones = K.tile(ones, (1, self.dialogue_act_dim)) def dropped_inputs(): return K.dropout(ones, self.sc_dropout) rec_dp_mask = [K.in_train_phase(dropped_inputs, ones, training=training) for _ in range(5)] constants.append(rec_dp_mask) else: constants.append([K.cast_to_floatx(1.) for _ in range(5)]) return constants def get_initial_state(self, inputs): # build an all-zero tensor of shape (samples, output_dim) initial_state = K.zeros_like(inputs) # (samples, timesteps, input_dim) initial_state = K.sum(initial_state, axis=(1, 2)) # (samples,) initial_state = K.expand_dims(initial_state) # (samples, 1) initial_state = K.tile(initial_state, [1, self.units]) # (samples, output_dim) initial_state = [initial_state for _ in range(len(self.states))] return initial_state def get_initial_p(self, inputs): # build an all-zero tensor of shape (samples, output_dim) p_0 = K.zeros_like(inputs) # (samples, timesteps, input_dim) p_0 = K.sum(p_0, axis=(1, 2)) # (samples,) p_0 = K.expand_dims(p_0) # (samples, 1) p_0 = K.tile(p_0, [1, self.out_units]) # (samples, output_dim) return [p_0] def inference_phase(self): self.train_phase = False def __call__(self, inputs, initial_state=None, **kwargs): # If `initial_state` is specified, # and if it a Keras tensor, # then add it to the inputs and temporarily # modify the input spec to include the state. if initial_state is None: return super(Recurrent, self).__call__(inputs, **kwargs) if not isinstance(initial_state, (list, tuple)): initial_state = [initial_state] is_keras_tensor = hasattr(initial_state[0], '_keras_history') for tensor in initial_state: if hasattr(tensor, '_keras_history') != is_keras_tensor: raise ValueError('The initial state of an RNN layer cannot be' ' specified with a mix of Keras tensors and' ' non-Keras tensors') if is_keras_tensor: # Compute the full input spec, including state input_spec = self.input_spec state_spec = self.state_spec if not isinstance(input_spec, list): input_spec = [input_spec] if not isinstance(state_spec, list): state_spec = [state_spec] self.input_spec = input_spec + state_spec # Compute the full inputs, including state inputs = inputs + list(initial_state) # Perform the call output = super(Recurrent, self).__call__(inputs, **kwargs) # Restore original input spec self.input_spec = input_spec return output else: kwargs['initial_state'] = initial_state return super(Recurrent, self).__call__(inputs, **kwargs) def call(self, inputs, mask=None, training=None, initial_state=None): # input shape: `(samples, time (padded with zeros), input_dim)` # note that the .build() method of subclasses MUST define # self.input_spec and self.state_spec with complete input shapes. # input for training [aux_softmax, ground thruth, dialogue act vector] input_length = K.int_shape(inputs[0])[1] input_list = inputs #takes orig_input while training and dialogue act for conditioning inputs = input_list[0] initial_state = self.get_initial_state(inputs) constants = self.get_constants(inputs, training=None) dialogue_act = input_list[-1] initial_state = initial_state + [dialogue_act] sc_constants = self.get_sc_constants(dialogue_act, training=None) constants = constants + sc_constants p0 = self.get_initial_p(inputs) initial_state += p0 if isinstance(mask, list): mask = mask[0] preprocessed_input = self.preprocess_input(inputs, training=None) rnn_output = sc_tf_rnn( self.step, preprocessed_input, initial_state, semantic_conditioning=True, go_backwards=self.go_backwards, mask=mask, constants=constants) last_output, outputs, last_da, da_outputs, states = rnn_output # Properly set learning phase last_output._uses_learning_phase = True outputs._uses_learning_phase = True da_outputs._uses_learning_phase = True last_da._uses_learning_phase = True if self.return_sequences: output = outputs else: output = last_output if self.return_state: if not isinstance(states, (list, tuple)): states = [states] else: states = list(states) output = [output] + states if self.return_da: output = [output, last_da, da_outputs] return output def step(self, inputs, states): h_tm1 = states[0] c_tm1 = states[1] d_tm1 = states[2] p_tm1 = states[3] inputs = K.in_train_phase(inputs, p_tm1) dp_mask = states[4] rec_dp_mask = states[5] sc_dp_mask = states[6] z = K.dot(inputs * dp_mask[0], self.kernel) z += K.dot(h_tm1 * rec_dp_mask[0], self.recurrent_kernel) if self.use_bias: z = K.bias_add(z, self.bias) z0 = z[:, :self.units] z1 = z[:, self.units: 2 * self.units] z2 = z[:, 2 * self.units: 3 * self.units] z3 = z[:, 3 * self.units:] i = self.recurrent_activation(z0) f = self.recurrent_activation(z1) r = self.recurrent_activation(K.dot(inputs * dp_mask[0], self.kernel_r) + self.alpha * K.dot(h_tm1 * rec_dp_mask[0], self.recurrent_kernel_r)) if self.use_bias: r = K.bias_add(r, self.bias_r) d = r*d_tm1 c = f * c_tm1 + i * self.activation(z2) + self.activation(K.dot(d * sc_dp_mask[0], self.kernel_d)) o = self.recurrent_activation(z3) h = o * self.activation(c) #output distibution of target word prob: p in (batch_size, nclasses) if self.softmax_temperature is not None: p_softmax = K.softmax(K.dot(h, self.out_kernel)/self.softmax_temperature) p_ret = p_softmax else: p_softmax = K.softmax(K.dot(h, self.out_kernel)) p_ret = K.in_train_phase(p_softmax, K.one_hot(K.argmax(p_softmax, axis=1), self.out_units)) if 0.0 < self.dropout + self.recurrent_dropout + self.sc_dropout: h._uses_learning_phase = True return p_softmax, [h, c, d, p_ret] def get_config(self): config = {'units': self.units, 'activation': activations.serialize(self.activation), 'recurrent_activation': activations.serialize(self.recurrent_activation), 'use_bias': self.use_bias, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'recurrent_initializer': initializers.serialize(self.recurrent_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'unit_forget_bias': self.unit_forget_bias, 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'recurrent_regularizer': regularizers.serialize(self.recurrent_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'recurrent_constraint': constraints.serialize(self.recurrent_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint), 'dropout': self.dropout, 'recurrent_dropout': self.recurrent_dropout, 'sc_dropout': self.sc_dropout} base_config = super(SC_LSTM, self).get_config() return dict(list(base_config.items()) + list(config.items()))
[ "jan.deriu@googlemail.com" ]
jan.deriu@googlemail.com
fb622a48d0861fe86168d9454676451a05e7122c
55133f3b42a19f50ca52a0c0b78f8a4da95a3e8e
/scripts/kd_squeezenet.py
8c6671ec4ff083e446d9de660fa74c6dfe0cc434
[ "MIT" ]
permissive
phuochaihuynh/knowledge_distillation-1
e517932f5d99950cc25a520b2f4d4f94558ab241
7e8a508a656b2e10757bda9366139fd73be89b5b
refs/heads/master
2023-05-29T17:46:44.058315
2019-11-19T20:44:12
2019-11-19T20:44:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
10,666
py
# coding: utf-8 # In[1]: # get_ipython().run_line_magic('load_ext', 'autoreload') # get_ipython().run_line_magic('autoreload', '2') # In[2]: import numpy as np import sys, os import argparse # sys.path.append('utils/') import keras from keras import optimizers from keras.callbacks import ReduceLROnPlateau, EarlyStopping, Callback # use non standard flow_from_directory from utils.image_preprocessing_ver2 import ImageDataGenerator # it outputs y_batch that contains onehot targets and logits # logits came from xception from keras.models import Model from keras.layers import Lambda, concatenate, Activation from keras.losses import categorical_crossentropy as logloss from keras.metrics import categorical_accuracy, top_k_categorical_accuracy from keras import backend as K from squeezenet import SqueezeNet, preprocess_input import matplotlib.pyplot as plt # get_ipython().run_line_magic('matplotlib', 'inline') # In[3]: def str2bool(v): """ convert string representation of a boolean into a boolean representation """ if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') # In[3]: parser = argparse.ArgumentParser(description='Process input arguments') parser.add_argument('--data-folder', default='/home/wopauli/256_ObjectCategories_preproc/', type=str, dest='data_dir', help='data folder mounting point') parser.add_argument('--learning_rate', default=1e-2, help='learning rate', type=float, required=False) parser.add_argument('--weight_decay', default=1e-2, help='weight_decay', type=float, required=False) parser.add_argument('--temperature', default=5.0, help='temperature', type=float, required=False) parser.add_argument('--lambda_const', default=2e-1, help='lambda_const', type=float, required=False) parser.add_argument('--momentum', default=9e-1, help='momentum', type=float, required=False) parser.add_argument('--batch_size', dest="batch_size", default=64, help='Batch size', type=int, required=False) parser.add_argument('--remote_execution', dest="remote_execution", action='store_true', help='remote execution (AML compute)', required=False) parser.add_argument('--transfer_learning', dest="transfer_learning", default="False", help='use the benchmark model and perform transfer learning', type=str, required=False) args = parser.parse_args() data_dir = args.data_dir learning_rate = args.learning_rate weight_decay = args.weight_decay temperature = args.temperature lambda_const = args.lambda_const momentum = args.momentum batch_size = args.batch_size remote_execution = args.remote_execution transfer_learning = str2bool(args.transfer_learning) if remote_execution: print("Running on remote compute target:", remote_execution) from azureml.core import VERSION print("azureml.core.VERSION", VERSION) from azureml.core import Run # start an Azure ML run run = Run.get_context() run.log('learning_rate', learning_rate) run.log('weight_decay', weight_decay) run.log('temperature', temperature) run.log('lambda_const', lambda_const) run.log('momentum', momentum) run.log('batch_size', batch_size) run.log('transfer_learning', transfer_learning) # data_dir = '/home/wopauli/256_ObjectCategories_preproc/' # In[4]: train_logits = np.load(os.path.join(data_dir, 'train_logits.npy'))[()] val_logits = np.load(os.path.join(data_dir, 'val_logits.npy'))[()] # In[5]: # batch_size = 64 data_generator = ImageDataGenerator( data_format='channels_last', preprocessing_function=preprocess_input ) # note: i'm also passing dicts of logits train_generator = data_generator.flow_from_directory( os.path.join(data_dir, 'train_no_resizing'), train_logits, target_size=(299, 299), batch_size=batch_size ) val_generator = data_generator.flow_from_directory( os.path.join(data_dir,'val_no_resizing'), val_logits, target_size=(299, 299), batch_size=batch_size ) # # Show effect of the temperature # In[6]: def softmax(x): return np.exp(x)/np.exp(x).sum() # In[7]: # get a random batch pictures, labels_and_logits = train_generator.next() onehot_target, logits = labels_and_logits[:, :256], labels_and_logits[:, 256:] # In[8]: # logits for a random image v = logits[4] plt.figure(figsize=(10, 5)); plt.plot(np.sort(softmax(v)), label='$T=1$', linewidth=2); plt.plot(np.sort(softmax(v/2)), label='$T=2$', linewidth=2); plt.plot(np.sort(softmax(v/3)), label='$T=3$', linewidth=2); plt.plot(np.sort(softmax(v/7)), label='$T=7$', linewidth=2); plt.plot(np.sort(softmax(v/temperature)), label='$T=T$', linewidth=3); plt.legend(); plt.xlabel('classes sorted by probability, most probable ->'); plt.ylabel('probability'); plt.xlim([245, 255]); # log this plot to the aml workspace so we can see it in the azure portal if remote_execution: run.log_image('soft target dist', plot=plt) else: plt.savefig('soft_target_dist.png') plt.close() # In[9]: # # logits for a random image # v = logits[20] # plt.figure(figsize=(10, 5)); # plt.plot(np.sort(softmax(v)), label='$T=1$', linewidth=2); # plt.plot(np.sort(softmax(v/2)), label='$T=2$', linewidth=2); # plt.plot(np.sort(softmax(v/3)), label='$T=3$', linewidth=2); # plt.plot(np.sort(softmax(v/7)), label='$T=7$', linewidth=2); # plt.legend(); # plt.xlabel('classes sorted by probability, most probable ->'); # plt.ylabel('probability'); # plt.xlim([245, 255]); # # Create model # In[10]: # temperature = 5.0 # In[11]: if transfer_learning: trainable = False else: trainable = True model = SqueezeNet(weight_decay=weight_decay, image_size=299, trainable=trainable) # remove softmax model.layers.pop() # usual probabilities logits = model.layers[-1].output probabilities = Activation('softmax')(logits) # softed probabilities logits_T = Lambda(lambda x: x/temperature)(logits) probabilities_T = Activation('softmax')(logits_T) output = concatenate([probabilities, probabilities_T]) model = Model(model.input, output) # now model outputs 512 dimensional vectors # # Create custom loss # In[12]: def knowledge_distillation_loss(y_true, y_pred, lambda_const, temperature): # split in # onehot hard true targets # logits from xception y_true, logits = y_true[:, :256], y_true[:, 256:] # convert logits to soft targets y_soft = K.softmax(logits/temperature) # split in # usual output probabilities # probabilities made softer with temperature y_pred, y_pred_soft = y_pred[:, :256], y_pred[:, 256:] return K.in_train_phase(logloss(y_true, y_pred), logloss(y_soft, y_pred_soft)) # return lambda_const*logloss(y_true, y_pred) + logloss(y_soft, y_pred_soft) # return logloss(y_soft, y_pred_soft) # # For testing use usual output probabilities (without temperature) # In[13]: def accuracy(y_true, y_pred): y_true = y_true[:, :256] y_pred = y_pred[:, :256] return categorical_accuracy(y_true, y_pred) # In[14]: def top_5_accuracy(y_true, y_pred): y_true = y_true[:, :256] y_pred = y_pred[:, :256] return top_k_categorical_accuracy(y_true, y_pred) # In[15]: def categorical_crossentropy(y_true, y_pred): y_true = y_true[:, :256] y_pred = y_pred[:, :256] return logloss(y_true, y_pred) # In[16]: # logloss with only soft probabilities and targets def soft_logloss(y_true, y_pred): logits = y_true[:, 256:] y_soft = K.softmax(logits/temperature) y_pred_soft = y_pred[:, 256:] return logloss(y_soft, y_pred_soft) # # Train # In[17]: # lambda_const = 0.2 model.compile( optimizer=optimizers.SGD(lr=learning_rate, momentum=momentum, nesterov=True), # optimizer=optimizers.Adam(lr=0.005, decay=0.01), loss=lambda y_true, y_pred: knowledge_distillation_loss(y_true, y_pred, lambda_const, temperature), metrics=[accuracy, top_5_accuracy, categorical_crossentropy, soft_logloss] ) # In[18]: callbacks = [EarlyStopping(monitor='val_accuracy', patience=4, min_delta=0.01), ReduceLROnPlateau(monitor='val_accuracy', factor=0.1, patience=2, epsilon=0.007) ] # log progress to AML workspace if remote_execution: class LogRunMetrics(Callback): # callback at the end of every epoch def on_epoch_end(self, epoch, log): # log a value repeated which creates a list run.log('val_loss', log['val_loss']) run.log('loss', log['loss']) callbacks.append(LogRunMetrics()) model.fit_generator( train_generator, steps_per_epoch=50, epochs=30, verbose=1, callbacks=callbacks, validation_data=val_generator, validation_steps=80, workers=4 ) if remote_execution: run.log('final_val_loss', model.history.history['val_loss'][-1]) run.log('final_val_accuracy', model.history.history['val_accuracy'][-1]) # # Loss/epoch plots # # Loss/epoch plots # In[19]: plt.plot(model.history.history['categorical_crossentropy'], label='train'); plt.plot(model.history.history['val_categorical_crossentropy'], label='val'); plt.legend(); plt.xlabel('epoch'); plt.ylabel('crossentropy'); # log this plot to the aml workspace so we can see it in the azure portal if remote_execution: run.log_image('crossentropy', plot=plt) else: plt.savefig('crossentropy.png') plt.close() # In[20]: plt.plot(model.history.history['accuracy'], label='train'); plt.plot(model.history.history['val_accuracy'], label='val'); plt.legend(); plt.xlabel('epoch'); plt.ylabel('accuracy'); # log this plot to the aml workspace so we can see it in the azure portal if remote_execution: run.log_image('accuracy', plot=plt) else: plt.savefig('accuracy.png') plt.close() # In[21]: plt.plot(model.history.history['top_5_accuracy'], label='train'); plt.plot(model.history.history['val_top_5_accuracy'], label='val'); plt.legend(); plt.xlabel('epoch'); plt.ylabel('top5_accuracy'); # log this plot to the aml workspace so we can see it in the azure portal if remote_execution: run.log_image('top5_accuracy', plot=plt) else: plt.savefig('top5_accuracy.png') plt.close() # # Results # In[22]: val_generator_no_shuffle = data_generator.flow_from_directory( os.path.join(data_dir, 'val_no_resizing'), val_logits, target_size=(299, 299), batch_size=64, shuffle=False ) # In[23]: # val_loss, val_acc, val_top_k_categorical_accuracy if remote_execution: run.log_list('final eval', model.evaluate_generator(val_generator_no_shuffle, 80)) else: print(model.evaluate_generator(val_generator_no_shuffle, 80))
[ "wopauli@microsoft.com" ]
wopauli@microsoft.com
0e3f0922f40e71d9a44e75712553d05822c509a0
0ad92a847dc4ebd4c03a2a61da11875d0cfe61fe
/pages/migrations/0004_auto_20200410_1440.py
2836116e23914f5db636f1d1a3287e02103e3580
[]
no_license
CjS77/QuickAds
f2e88f6e2a358466fd01421b6f2bc87850b70dab
261e2444baa68f9c8b0ada048ce69a74c7b059d4
refs/heads/main
2023-01-28T23:50:25.847957
2020-11-24T05:30:55
2020-11-24T05:30:55
314,763,802
0
0
null
2020-11-23T14:48:27
2020-11-21T08:09:38
JavaScript
UTF-8
Python
false
false
361
py
# Generated by Django 2.2 on 2020-04-10 14:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pages', '0003_auto_20200410_1439'), ] operations = [ migrations.RenameField( model_name='contact', old_name='ad_name', new_name='ad_url', ), ]
[ "CjS77@users.noreply.github.com" ]
CjS77@users.noreply.github.com
c67aed4a8906403fdc438172470d06e2b232aa16
c66603d757f4cd252e814ad0de26f473924ff13a
/superset/reports/notifications/email.py
3f2296c3b76abdcbc44d3f36ccab9cfe6b406720
[ "Apache-2.0", "OFL-1.1" ]
permissive
fadyvictim/incubator-superset-internal
842719bcbf1866b92e524cfb96231aaa8355ef76
2f2217b29f1ebd1f99550fbb11dd81aebf8bb5e6
refs/heads/master
2023-04-21T16:07:42.032147
2021-05-18T08:15:05
2021-05-18T08:15:05
361,749,249
0
1
Apache-2.0
2021-04-26T13:02:43
2021-04-26T12:53:25
Python
UTF-8
Python
false
false
3,880
py
# -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import json import logging from dataclasses import dataclass from email.utils import make_msgid, parseaddr from typing import Any, Dict, Optional from flask_babel import gettext as __ from superset import app from superset.models.reports import ReportRecipientType from superset.reports.notifications.base import BaseNotification from superset.reports.notifications.exceptions import NotificationError from superset.utils.core import send_email_smtp logger = logging.getLogger(__name__) @dataclass class EmailContent: body: str data: Optional[Dict[str, Any]] = None images: Optional[Dict[str, bytes]] = None class EmailNotification(BaseNotification): # pylint: disable=too-few-public-methods """ Sends an email notification for a report recipient """ type = ReportRecipientType.EMAIL @staticmethod def _get_smtp_domain() -> str: return parseaddr(app.config["SMTP_MAIL_FROM"])[1].split("@")[1] @staticmethod def _error_template(text: str) -> str: return __( """ Error: %(text)s """, text=text, ) def _get_content(self) -> EmailContent: if self._content.text: return EmailContent(body=self._error_template(self._content.text)) # Get the domain from the 'From' address .. # and make a message id without the < > in the end image = None csv_data = None domain = self._get_smtp_domain() msgid = make_msgid(domain)[1:-1] body = __( """ <p>%(description)s</p> <b><a href="%(url)s">Explore in Superset</a></b><p></p> %(img_tag)s """, description=self._content.description or "", url=self._content.url, img_tag=f'<img src="cid:{msgid}">' if self._content.screenshot else "", ) if self._content.screenshot: image = {msgid: self._content.screenshot} if self._content.csv: csv_data = {__("%(name)s.csv", name=self._content.name): self._content.csv} return EmailContent(body=body, images=image, data=csv_data) def _get_subject(self) -> str: return __( "%(prefix)s %(title)s", prefix=app.config["EMAIL_REPORTS_SUBJECT_PREFIX"], title=self._content.name, ) def _get_to(self) -> str: return json.loads(self._recipient.recipient_config_json)["target"] def send(self) -> None: subject = self._get_subject() content = self._get_content() to = self._get_to() try: send_email_smtp( to, subject, content.body, app.config, files=[], data=content.data, images=content.images, bcc="", mime_subtype="related", dryrun=False, ) logger.info("Report sent to email") except Exception as ex: raise NotificationError(ex)
[ "noreply@github.com" ]
fadyvictim.noreply@github.com
02b4329d179bd975099a0ead724adf4505061041
e815ed7e08aeac03dd6245918c37a7d58e1956d6
/fbla_admin/migrations/0003_book_image.py
a5ffb7caa343e6582ebf59ef53bb1feafe22c360
[]
no_license
pavanagrawal123/bookshelf
dc461ac2dd59740d630925a059b89632bf260622
3d87d0a9ef8c36a6a83aaaf5f1bc04c747d28512
refs/heads/master
2020-04-16T00:07:10.188057
2019-05-10T21:36:51
2019-05-12T21:36:51
165,126,011
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
# Generated by Django 2.1.4 on 2018-12-31 19:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fbla_admin', '0002_auto_20181231_1751'), ] operations = [ migrations.AddField( model_name='book', name='image', field=models.ImageField(blank=True, upload_to='book_images'), ), ]
[ "pavanagrawal@outlook.com" ]
pavanagrawal@outlook.com
4e44847a2ce0365519a8337393f36ce975c783e4
c3a0ffcf4c209fbc86a6d0bcdc7daaec6bf169e5
/script/reverseHostname.py
eb5c1d69c7720e09a2afc1614b5bbede6684184e
[]
no_license
zhanghuanchen/YCSB_URL
1cfa485d57f5163e5aee38a5f57d5f55614febfa
46eed516f87db051e557e89aae0bcd45a3764edb
refs/heads/master
2016-09-06T18:22:45.923437
2013-11-21T02:20:18
2013-11-21T02:20:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,061
py
# Author: Wenlu Hu fn = "../urls/seq_urls_4M.dat" fin = open(fn, 'r') fout = open(fn+"_reverse.txt", 'w') for line in fin: # print line import string if line.startswith('http://'): line = line[7:] else: if line.startswith('https://'): line = line[8:] else: # discard anomaly lines print "ERROR! line: ", line continue ''' i = string.find(line, 'http://') if i > -1: line = line[i+7:] else: i = string.find(line, 'https://') if i > -1: line = line[i+8:] ''' # print '-', line hostname, sep, directory = line.partition('/') # print hostname hnparts = hostname.split('.') # print hnparts r_hostname = '' for part in hnparts: r_hostname = part + '.' + r_hostname # remove the '.' at then end r_hostname = r_hostname[:-1] # print r_hostname res = r_hostname + sep + directory print res[:-1] fout.write(res) fin.close() fout.close() print "Done!"
[ "wenlu@cmu.edu" ]
wenlu@cmu.edu
91c15739c4d38e4b6a8edf190e96728d20682cb2
1969f239b453f89272ad88c2d6d1ac0f1b42e77e
/rigid_transform.py
0d7c2752c8576ec9fce8581833cc5cf9c95d015a
[]
no_license
mservice/imaka_pinhole
b34fed2e0a51a5e9a75477b3a0a2b9cd958116e3
7a87d898a7a2719da5bfb770846b7db929668896
refs/heads/master
2021-07-11T22:46:31.746458
2021-03-26T12:32:47
2021-03-26T12:32:47
91,288,265
0
0
null
null
null
null
UTF-8
Python
false
false
928
py
from numpy import * from math import sqrt # Input: expects Nx3 matrix of points # Returns R,t # R = 3x3 rotation matrix # t = 3x1 column vector def rigid_transform_3D(A, B, center=True): assert len(A) == len(B) N = A.shape[0]; # total points if center: centroid_A = mean(A, axis=0) centroid_B = mean(B, axis=0) else: centroid_A = mean(A, axis=0) centroid_A = centroid_A - centroid_A centroid_B = mean(B, axis=0) - mean(B, axis=0) # centre the points AA = A - tile(centroid_A, (N, 1)) BB = B - tile(centroid_B, (N, 1)) # dot is matrix multiplication for array H = transpose(AA) * BB U, S, Vt = linalg.svd(H) R = Vt.T * U.T # special reflection case if linalg.det(R) < 0: print "Reflection detected" Vt[2,:] *= -1 R = Vt.T * U.T t = -R*centroid_A.T + centroid_B.T #print t return R, t
[ "mws83@case.edu" ]
mws83@case.edu
15f057905f7f0811b3155386e7b38e0b5bf86fac
1d3bb3304ef49ac7a5740433e8ad0f727b7900db
/src/ex2.py
0fed81849be548d9c969418b3a05eeb07bc69426
[]
no_license
Owiru/TestProject
be0071f798a5b7ca98a792f697eaf8d0917f223c
93b9e4f5ed4c1b140424c2895745a89ca914787b
refs/heads/master
2023-01-24T06:03:58.647883
2020-11-29T18:10:35
2020-11-29T18:10:35
317,002,380
0
0
null
null
null
null
UTF-8
Python
false
false
17
py
print("I'm ex2")
[ "meepmeow78@gmail.com" ]
meepmeow78@gmail.com
e93bbd2876eed4d86740b1cb243114498b1ce3b2
b1fbe7460427dbb891d4b1951e43e551e86b1e3b
/arcnlp/tf/layers/matching_layer.py
cb5d7972ef80bae0ebb2273e5c4c32bda114bc6c
[]
no_license
linhx13/arc-nlp
88a45601e09deb7883ddf4583f6f2f4607fb85d0
760cca0d44958fb4011eaa039263575388a858ae
refs/heads/master
2023-05-04T12:59:21.232168
2021-05-18T17:38:28
2021-05-18T17:38:28
230,442,944
1
0
null
2021-04-17T03:41:42
2019-12-27T12:48:02
Python
UTF-8
Python
false
false
5,713
py
# -*- coding: utf-8 -*- import typing import tensorflow as tf class MatchingLayer(tf.keras.layers.Layer): """ Layer that computes a matching matrix between samples in two tensors. :param normalize: Whether to L2-normalize samples along the dot product axis before taking the dot product. If set to True, then the output of the dot product is the cosine proximity between the two samples. :param matching_type: the similarity function for matching :param kwargs: Standard layer keyword arguments. Examples: >>> import matchzoo as mz >>> layer = mz.layers.MatchingLayer(matching_type='dot', ... normalize=True) >>> num_batch, left_len, right_len, num_dim = 5, 3, 2, 10 >>> layer.build([[num_batch, left_len, num_dim], ... [num_batch, right_len, num_dim]]) """ def __init__(self, normalize: bool = False, matching_type: str = 'dot', **kwargs): """:class:`MatchingLayer` constructor.""" super().__init__(**kwargs) self._normalize = normalize self._validate_matching_type(matching_type) self._matching_type = matching_type self._shape1 = None self._shape2 = None @classmethod def _validate_matching_type(cls, matching_type: str = 'dot'): valid_matching_type = ['dot', 'mul', 'plus', 'minus', 'concat'] if matching_type not in valid_matching_type: raise ValueError(f"{matching_type} is not a valid matching type, " f"{valid_matching_type} expected.") def build(self, input_shape: list): """ Build the layer. :param input_shape: the shapes of the input tensors, for MatchingLayer we need tow input tensors. """ # Used purely for shape validation. if not isinstance(input_shape, list) or len(input_shape) != 2: raise ValueError('A `MatchingLayer` layer should be called ' 'on a list of 2 inputs.') self._shape1 = input_shape[0] self._shape2 = input_shape[1] for idx in 0, 2: if self._shape1[idx] != self._shape2[idx]: raise ValueError( 'Incompatible dimensions: ' f'{self._shape1[idx]} != {self._shape2[idx]}.' f'Layer shapes: {self._shape1}, {self._shape2}.' ) def call(self, inputs: list, **kwargs) -> typing.Any: """ The computation logic of MatchingLayer. :param inputs: two input tensors. """ x1 = inputs[0] x2 = inputs[1] if self._matching_type == 'dot': if self._normalize: x1 = tf.math.l2_normalize(x1, axis=2) x2 = tf.math.l2_normalize(x2, axis=2) return tf.expand_dims(tf.einsum('abd,acd->abc', x1, x2), 3) else: if self._matching_type == 'mul': def func(x, y): return x * y elif self._matching_type == 'plus': def func(x, y): return x + y elif self._matching_type == 'minus': def func(x, y): return x - y elif self._matching_type == 'concat': def func(x, y): return tf.concat([x, y], axis=3) else: raise ValueError(f"Invalid matching type." f"{self._matching_type} received." f"Mut be in `dot`, `mul`, `plus`, " f"`minus` and `concat`.") x1_exp = tf.stack([x1] * self._shape2[1], 2) x2_exp = tf.stack([x2] * self._shape1[1], 1) return func(x1_exp, x2_exp) def compute_output_shape(self, input_shape: list) -> tuple: """ Calculate the layer output shape. :param input_shape: the shapes of the input tensors, for MatchingLayer we need tow input tensors. """ if not isinstance(input_shape, list) or len(input_shape) != 2: raise ValueError('A `MatchingLayer` layer should be called ' 'on a list of 2 inputs.') shape1 = list(input_shape[0]) shape2 = list(input_shape[1]) if len(shape1) != 3 or len(shape2) != 3: raise ValueError('A `MatchingLayer` layer should be called ' 'on 2 inputs with 3 dimensions.') if shape1[0] != shape2[0] or shape1[2] != shape2[2]: raise ValueError('A `MatchingLayer` layer should be called ' 'on 2 inputs with same 0,2 dimensions.') if self._matching_type in ['mul', 'plus', 'minus']: return shape1[0], shape1[1], shape2[1], shape1[2] elif self._matching_type == 'dot': return shape1[0], shape1[1], shape2[1], 1 elif self._matching_type == 'concat': return shape1[0], shape1[1], shape2[1], shape1[2] + shape2[2] else: raise ValueError(f"Invalid `matching_type`." f"{self._matching_type} received." f"Must be in `mul`, `plus`, `minus` " f"`dot` and `concat`.") def get_config(self) -> dict: """Get the config dict of MatchingLayer.""" config = { 'normalize': self._normalize, 'matching_type': self._matching_type, } base_config = super(MatchingLayer, self).get_config() return dict(list(base_config.items()) + list(config.items()))
[ "mylhx288@gmail.com" ]
mylhx288@gmail.com
b3b9e574c2e2c631342c3269b7914c37ccb639be
dbabe0e9e74ce0d80eda7b729672072bc314d7ef
/setup.py
bf97bbf48872ed70433a04fea7ab9f70e00eafdc
[ "MIT" ]
permissive
timonweb-forks/django-turbo-response
1ee61ca42de62930edaa71586315fcbfe1470bf5
e558b1a281cf37bb2554a68b08472d6a06c7bb9a
refs/heads/main
2023-02-27T12:02:07.367322
2021-02-05T22:49:13
2021-02-05T22:49:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,048
py
#!/usr/bin/env python # Third Party Libraries from setuptools import setup version = "0.0.33" setup( name="django-turbo-response", version=version, author="Dan Jacob", author_email="danjac2018@gmail.com", url="https://github.com/hotwire-django/django-turbo-response", description="Hotwired/Turbo response helpers for Django", long_description=open("README.md").read() + "\n\n" + open("CHANGES.md").read(), long_description_content_type="text/markdown", license="MIT", python_requires=">=3.7", requires=["django (>=3.0)"], packages=["turbo_response"], package_dir={"": "src"}, classifiers=[ "Development Status :: 5 - Production/Stable", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Topic :: Software Development :: Libraries :: Python Modules", ], )
[ "danjac2018@gmail.com" ]
danjac2018@gmail.com
d4ce1c54619632296876bfedd38db505e3a56eb0
7f5cae328b8e00ddcee02c1e1badba1bb61e8d76
/library_management_System/library_management_System/urls.py
453b0ab1db8806f4e84af9e5523c1980c68659e1
[]
no_license
Developer-Aayush/TA-2020-Library-System
ac34cc4224e5a0dc13a01d6f2ed1aa77d6349718
a4100863015ddbbd5f5f7fa50210f5030e44b4cf
refs/heads/master
2023-02-24T23:13:39.244559
2021-01-27T18:12:44
2021-01-27T18:12:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
982
py
from django.contrib import admin from django.urls import path from library.views import * from library import views urlpatterns = [ path("admin/", admin.site.urls), path("", views.login_view, name="login_view"), path("home", views.home, name="home"), path("add_book", views.addbooks, name="addBook"), path("update/<str:pk>/", views.update, name="up"), path("delete/<str:pk>/", views.delete, name="delete"), path("logout", views.logout_view, name="logoutView"), path("api", views.apiOverview, name="api-overview"), path("bookList", views.bookList, name="booklist"), path("bookDetail/<str:pk>", views.bookDetail, name="bookdetail"), path("bookCreate", views.bookCreate, name="bookcreate"), path("bookUpdate/<str:pk>", views.bookUpdate, name="bookupdate"), path("bookDelete/<str:pk>/", views.bookDelete, name="bookdelete"), path("upload_csv", views.csvImport, name="csv"), path("tLogin", CustomAuthTokenLogin.as_view()), ]
[ "aayush.pandey30@gmail.com" ]
aayush.pandey30@gmail.com
c42bdc155218776afedbbc06e0627a69df51c8cc
0610c0c6f02e2a498e9383c416f69e46274ba0b1
/contrib/bitrpc/bitrpc.py
39afd5410ea080f824ba0d0993a7ab66aae07717
[]
no_license
mantra2017/mantracoin
91a320f106f7833f69ba9bb63dd50739910cad77
00aee67cce4c2ebd1822f51532b6f612c41bca97
refs/heads/master
2021-01-22T21:27:58.349209
2017-03-18T21:36:54
2017-03-18T21:36:54
85,433,538
0
0
null
null
null
null
UTF-8
Python
false
false
7,842
py
from jsonrpc import ServiceProxy import sys import string # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:9332") else: access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:9332") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a MantraCoin address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n" elif cmd == "getaccountaddress": try: acct = raw_input("Enter an account name: ") print access.getaccountaddress(acct) except: print "\n---An error occurred---\n" elif cmd == "getaddressesbyaccount": try: acct = raw_input("Enter an account name: ") print access.getaddressesbyaccount(acct) except: print "\n---An error occurred---\n" elif cmd == "getbalance": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getbalance(acct, mc) except: print access.getbalance() except: print "\n---An error occurred---\n" elif cmd == "getblockbycount": try: height = raw_input("Height: ") print access.getblockbycount(height) except: print "\n---An error occurred---\n" elif cmd == "getblockcount": try: print access.getblockcount() except: print "\n---An error occurred---\n" elif cmd == "getblocknumber": try: print access.getblocknumber() except: print "\n---An error occurred---\n" elif cmd == "getconnectioncount": try: print access.getconnectioncount() except: print "\n---An error occurred---\n" elif cmd == "getdifficulty": try: print access.getdifficulty() except: print "\n---An error occurred---\n" elif cmd == "getgenerate": try: print access.getgenerate() except: print "\n---An error occurred---\n" elif cmd == "gethashespersec": try: print access.gethashespersec() except: print "\n---An error occurred---\n" elif cmd == "getinfo": try: print access.getinfo() except: print "\n---An error occurred---\n" elif cmd == "getnewaddress": try: acct = raw_input("Enter an account name: ") try: print access.getnewaddress(acct) except: print access.getnewaddress() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaccount": try: acct = raw_input("Enter an account (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaccount(acct, mc) except: print access.getreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "getreceivedbyaddress": try: addr = raw_input("Enter a MantraCoin address (optional): ") mc = raw_input("Minimum confirmations (optional): ") try: print access.getreceivedbyaddress(addr, mc) except: print access.getreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "gettransaction": try: txid = raw_input("Enter a transaction ID: ") print access.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: data = raw_input("Data (optional): ") try: print access.gettransaction(data) except: print access.gettransaction() except: print "\n---An error occurred---\n" elif cmd == "help": try: cmd = raw_input("Command (optional): ") try: print access.help(cmd) except: print access.help() except: print "\n---An error occurred---\n" elif cmd == "listaccounts": try: mc = raw_input("Minimum confirmations (optional): ") try: print access.listaccounts(mc) except: print access.listaccounts() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaccount": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaccount(mc, incemp) except: print access.listreceivedbyaccount() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaddress": try: mc = raw_input("Minimum confirmations (optional): ") incemp = raw_input("Include empty? (true/false, optional): ") try: print access.listreceivedbyaddress(mc, incemp) except: print access.listreceivedbyaddress() except: print "\n---An error occurred---\n" elif cmd == "listtransactions": try: acct = raw_input("Account (optional): ") count = raw_input("Number of transactions (optional): ") frm = raw_input("Skip (optional):") try: print access.listtransactions(acct, count, frm) except: print access.listtransactions() except: print "\n---An error occurred---\n" elif cmd == "move": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.move(frm, to, amt, mc, comment) except: print access.move(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendfrom": try: frm = raw_input("From: ") to = raw_input("To: ") amt = raw_input("Amount:") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendfrom(frm, to, amt, mc, comment, commentto) except: print access.sendfrom(frm, to, amt) except: print "\n---An error occurred---\n" elif cmd == "sendmany": try: frm = raw_input("From: ") to = raw_input("To (in format address1:amount1,address2:amount2,...): ") mc = raw_input("Minimum confirmations (optional): ") comment = raw_input("Comment (optional): ") try: print access.sendmany(frm,to,mc,comment) except: print access.sendmany(frm,to) except: print "\n---An error occurred---\n" elif cmd == "sendtoaddress": try: to = raw_input("To (in format address1:amount1,address2:amount2,...): ") amt = raw_input("Amount:") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendtoaddress(to,amt,comment,commentto) except: print access.sendtoaddress(to,amt) except: print "\n---An error occurred---\n" elif cmd == "setaccount": try: addr = raw_input("Address: ") acct = raw_input("Account:") print access.setaccount(addr,acct) except: print "\n---An error occurred---\n" elif cmd == "setgenerate": try: gen= raw_input("Generate? (true/false): ") cpus = raw_input("Max processors/cores (-1 for unlimited, optional):") try: print access.setgenerate(gen, cpus) except: print access.setgenerate(gen) except: print "\n---An error occurred---\n" elif cmd == "settxfee": try: amt = raw_input("Amount:") print access.settxfee(amt) except: print "\n---An error occurred---\n" elif cmd == "stop": try: print access.stop() except: print "\n---An error occurred---\n" elif cmd == "validateaddress": try: addr = raw_input("Address: ") print access.validateaddress(addr) except: print "\n---An error occurred---\n" elif cmd == "walletpassphrase": try: pwd = raw_input("Enter wallet passphrase: ") access.walletpassphrase(pwd, 60) print "\n---Wallet unlocked---\n" except: print "\n---An error occurred---\n" elif cmd == "walletpassphrasechange": try: pwd = raw_input("Enter old wallet passphrase: ") pwd2 = raw_input("Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2) print print "\n---Passphrase changed---\n" except: print print "\n---An error occurred---\n" print else: print "Command not found or not supported"
[ "mavrocoin@scryptmail.com" ]
mavrocoin@scryptmail.com
4af5b0231bef5d0476b48571f5e3926b41f4e01c
e6d6b029fc3f6ea81b7fc877fb475862eef8b013
/Sonar_Classification-NN/test.py
9b6ccdd960dfff89bf3d0522caee9f46e9b0be13
[]
no_license
NguyenDucHuy14287/AI-ML-semenar---Le-Thanh-Sach
96d4c6d01612da678764e3b7140c4ad379ff5f23
5b4fd295cd72ba09cd4a5e14b1289bf9bd49c2e8
refs/heads/master
2022-01-31T09:24:08.138423
2019-07-27T03:23:50
2019-07-27T03:23:50
197,871,859
0
0
null
null
null
null
UTF-8
Python
false
false
991
py
import numpy as np from pandas import read_csv from keras.models import Sequential from keras.layers import Dense from keras.optimizers import SGD import csv def read_data(url): dataframe = read_csv(url) dataset = dataframe.values # split into input (X) and output (Y) variables X = dataset[:,0:60].astype(float) Y = dataset[:,60] return X, Y # baseline def create_model(): model = Sequential() # YOUR CODE HERE model.add(Dense(units=60, input_dim=60, activation='relu')) model.add(Dense(units=30, activation='relu')) model.add(Dense(units=1, activation='sigmoid')) return model # load dataset url_train = 'train_dataset.csv' url_test = 'test_dataset.csv' X_train, Y_train = read_data(url_train) X_test, Y_test = read_data(url_test) model = create_model() model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, Y_train, epochs=1000) score, acc = model.evaluate(X_test, Y_test) print("Test accuracy:" + str(acc))
[ "nguyenduchuy14287@gmail.com" ]
nguyenduchuy14287@gmail.com
a930f39e5ff8fa74a6266ea91bccfe65d29d4ad6
f1b802f823c396d1f0718483435da1ec17ea8fe7
/local_packages/web_utility/web_utility_tests.py
30702c448d9900d8c650cb09521f7d832ac17c68
[]
no_license
OaklandPeters/local_packages
d9528eae34d55b121e4e437c9bff8fa4f1b7c8f9
7a552c3f4b194c9f6aeaa6112ac23ac6f6682a53
refs/heads/master
2016-09-10T18:38:36.852647
2014-10-31T14:53:40
2014-10-31T14:53:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,117
py
""" @todo: setter/getter/deleter/validator tests for WebRequest.parameter @todo: setter/getter/deleter/validator tests for WebRequest.cookies """ import unittest import json # import web_utility as wu import local_packages.rich_misc as rich_misc #import rich_misc as rich_misc class MockRequestTests(unittest.TestCase): """ @TODO setup tests for MockRequest() constructor: (1) url with parameters inline (2) url + parameters as keyword (3) returns via echo (4) returns via .html (5) pass via JSON (6) pass via HTML (7) What happens when I attempt a pass with variable not encoded as JSON? """ def setUp(self): self.base = 'https://gdid-test.uis.georgetown.edu/fake/server/python/' self.script = 'simulated.py' def call_script(self, parameters=None, cookies=None, index=None): """Pass parameters in with url, rather than as seperate keyword""" if index == None: index = index_basic if parameters == None: parameters = {} if cookies == None: cookies = {} url = self.base + self.script #[] Call index for this script request = wu.MockRequest( url, parameters = parameters, cookies = cookies, echo = False ) index(request) return request #Output now in req.html def test_basic(self): """Simplest test, index_basic, parameters and cookies, pass via JSON.""" request = self.call_script( parameters={'user_code':'foo'}, cookies={'user_name':'Mr. Bar'} ) result = rich_misc.read_json_string(request.html) #Check return/html property of requestuest self.assert_(isinstance(request.html, basestring)) #Check url parameters self.assertEquals(result['code'], 'foo... processed') #Check cookies self.assertEquals(result['name'], 'Mr. Bar... processed') #array-like URL parameters are not working - for now # def test_array_params(self): # """Test index_for_lists, which passes arrays/lists through # parameters and cookies; pass via JSON.""" # request = self.call_script( # parameters={'user_codes[]':'[foo,bar,baz]'}, # cookies={'user_names[]':'[MrFoo,MrsBar,MsBaz]'}, # index=index_for_lists # ) # result = rich_misc.read_json_string(request.html) # # print(result) # class ParameterTests(unittest.TestCase): # pass # class CookiesTests(unittest.TestCase): # pass #============================================================================== # Simulated AJAX response index() #============================================================================== def index_basic(request): """Simulates basic AJAX response.""" #Get from url parameter user_code = wu.get_url_parameter(request, 'user_code') #Get from cookie user_name = wu.get_cookie(request, 'user_name') #Do some processing processed = {} processed['code'] = user_code + '... processed' processed['name'] = user_name + '... processed' result = json.dumps({ 'code':processed['code'], 'name':processed['name'] }) request.write(result) return result def index_for_lists(request): """As index(), but expects to operate on lists.""" #Get from url parameter user_codes = wu.get_url_parameter(request, 'user_codes[]') #Get from cookie user_names = wu.get_cookie(request, 'user_names[]') #cookies = wu.get_cookies_dict(request) #user_names = cookies['user_names'] #Do some processing processed = {} processed['codes'] = [ code + '... processed' for code in user_codes ] processed['names'] = [ name + '... processed' for name in user_names ] result = json.dumps({ 'codes':processed['codes'], 'names':processed['names'] }) request.write(result) return result if __name__ == "__main__": unittest.main()
[ "oakland.peters@gmail.com" ]
oakland.peters@gmail.com
00b907ca82bc72c87925dbbf145cc82716347270
c7d950b54e01afd3803a4eee3bfac748ab3929b6
/Python/PythonII/Belt_Exam_Django/belt2/apps/examapp/urls.py
c1389cd392141cdd3df5c4d8aa95a6b9d2172c20
[]
no_license
akc232/Coding_Dojo_Repo
8d14f4cf9236e75d2fabbd90454604218a432fe9
b3c16eb3dc32ce344358a4f7fb3a1f509372327d
refs/heads/master
2021-03-30T21:04:38.382797
2018-04-12T02:57:46
2018-04-12T02:57:46
124,961,894
0
0
null
null
null
null
UTF-8
Python
false
false
722
py
from django.conf.urls import url urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^create$', views.create, name='create'), url(r'^add/(?P<id>\d+)$', views.add, name='add'), url(r'^destroy_quote/(?P<id>\d+)$', views.remove_quote, name='remove_quote'), url(r'^user/(?P<id>\d+)$', views.show, name='user'), url(r'^destroy/(?P<id>\d+)$', views.destroy, name='destroy'), ] # (?P<id>\d+)$ # index: Display all products # show: Display a particular product # new: Display a form to create a new product # edit: Display a form to update a product # create: Process information to create a new product # update: Process information from the edit form and update the particular product # destroy: Remove a product
[ "achang232@comcast.net" ]
achang232@comcast.net
f560e977ba4e38b370ddbf6279c7a6a0b1e47bd8
b581675ebe3633ea7d6e63ac7898335dc4dcd28c
/chef/HEADBOB.py
1f5534983bc93fd8cec861452fa5dc67c1ce1ecf
[]
no_license
udit043/little_bit_competitive
c219c1d77a48c87ac4b8384c5c09fdacbd1fe8c2
b54279e75c54337bd4d89f9a44489bf8ad00635b
refs/heads/master
2021-07-12T18:43:29.056528
2021-05-29T12:17:30
2021-05-29T12:17:30
86,187,789
0
0
null
null
null
null
UTF-8
Python
false
false
299
py
t = input() while(t > 0): t -= 1 n = input() n=0;y=0;ind=0 s = raw_input() for i in range(0,len(s)): if( s[i] == 'N' ): n += 1 elif( s[i] == 'Y' ): y += 1 elif( s[i] == 'I' ): ind += 1 if(ind != 0): print 'INDIAN' elif(y != 0): print 'NOT INDIAN' else: print 'NOT SURE'
[ "udit043.ur@gmail.com" ]
udit043.ur@gmail.com
b629068b2e680c54c869399bdbbb7e0cdc78d7b9
503e03d50d45eb80e24adfc79801265cd2260e61
/test.py
64c210c66dd51185b6c2d90b54dac293adbfc325
[]
no_license
sushilpokhrel/MatematicalEquationPlotter
fba0a971dbc4640fae44de32770c3bb845e92b79
4b35ea13cf84d524127f4c176f15bde340e29d57
refs/heads/master
2021-01-01T18:20:28.999368
2017-07-25T15:42:02
2017-07-25T15:42:02
98,311,499
1
0
null
null
null
null
UTF-8
Python
false
false
3,136
py
import cv2 import numpy as np # from matplotlib import pyplot as plt # image = cv2.imread("test2.jpg",0) # image = cv2.resize(image, (480, 640)) # create a CLAHE object (Arguments are optional). # clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(5,5)) # image = clahe.apply(image) # cv2.imshow('Test',image) # cv2.waitKey() import os import glob files = glob.glob('CroppedImages/*') for f in files: os.remove(f) img_final = cv2.imread("equation5.jpg") size = (15,15) img_final = cv2.resize(img_final, (480, 640)) cv2.imshow('Final Image',img_final) # cv2.waitKey() img2gray = cv2.cvtColor(img_final, cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 40, 100, cv2.THRESH_BINARY) image_final = cv2.bitwise_and(img2gray, img2gray, mask=mask) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3)) image_final2 = image_final cv2.imshow('Image that is cropped from',image_final2) cv2.waitKey() image_final = cv2.erode(image_final, kernel, iterations=3) cv2.imshow('Image that is cropped from',image_final) cv2.waitKey() size2 = (15,15) image_final2 = cv2.GaussianBlur(image_final2,size2,1) image_final2 = cv2.adaptiveThreshold(image_final2,255,cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,75,10) image_final2 = cv2.bitwise_not(image_final2) # kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3)) # image_final2 = cv2.dilate(image_final2, kernel, iterations=1) cv2.imshow('Image that is cropped from',image_final2) cv2.waitKey() image = cv2.GaussianBlur(image_final,size,0) image = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY,75,10) image = cv2.bitwise_not(image) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3)) image = cv2.dilate(image, kernel, iterations=2) cv2.imshow('Image after Preprocessing',image) cv2.waitKey() # image = cv2.erode(image, kernel, iterations=2) # image = cv2.dilate(image, kernel, iterations=1) # cv2.imshow("eroded",image) # cv2.waitKey() _, contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS) index = 0 our_contours = [] for contour in contours: [x, y, w, h] = cv2.boundingRect(contour) our_contours.append([x, y, w, h]) our_contours.sort() rec_file = [] for contour in our_contours: # get rectangle bounding contour [x, y, w, h] = contour # Don't plot small false positives that aren't text if w < 25 and h < 25: continue print h,y # draw rectangle around contour on original image cv2.rectangle(image,(x, y), (x + w, y + h), (255, 0, 255), 2) cropped = image_final2[y:y + h, x: x + w] # BLACK = [0, 0, 0] # if w > h: # h1 = w/2 # cropped = cv2.copyMakeBorder(cropped,h1,h1,0,0,cv2.BORDER_REPLICATE) # if h > w: # w1 = h/2 # cropped = cv2.copyMakeBorder(cropped,0,0,w1,w1,cv2.BORDER_REPLICATE) cropped = cv2.resize(cropped, (28,28), interpolation=cv2.INTER_LINEAR) s = 'CroppedImages/crop_' + str(index) + '.png' cv2.imwrite(s, cropped) cv2.imshow("Image",cropped) # cv2.imshow(s,cropped) index = index + 1 cv2.imshow("Contoured Image",image) cv2.waitKey()
[ "sushil.pokhrel@deerwalk.edu.np" ]
sushil.pokhrel@deerwalk.edu.np
9aa757a8672150944dcfb2529414c3b895ae0c9e
b42f316ebe3a756ef52b3fd0cec9def2abe1701e
/code/extract_lsat_samples/random_tundra_samples/extract_lsat_arctic_biome_eeur_srs1.py
0e1fc0764ce094ed85ee5c95f87c16deff39e518
[]
no_license
logan-berner/arctic_greening
bd33b6c6f5861c982a5f688eb8e5c61230b2812c
eaf856517d19375f720b4eb5c2db7af55148eca0
refs/heads/master
2023-04-03T08:44:41.057952
2021-04-06T21:29:38
2021-04-06T21:29:38
288,807,815
5
2
null
null
null
null
UTF-8
Python
false
false
6,963
py
import ee import sys import datetime import pandas as pd import traceback ee.Initialize() # small function for adding 'site' property to randomly created points def addID(pt): return pt.set('site', pt.id()) # SPECIFY SEVERAL VARIABLES BUFFER_DIST = 0 # set it to 0 if buffer is not needed, else it will make script timed-out CRS = 'EPSG:4326' SCALE = 30 NULL_VALUE = 0 MASK_VALUE = 0 # used for ADDON image startJulian = 91 # early April endJulian = 150 # late May # startJulian = 150 # late may # endJulian = 250 # early sept # values to copy from fusion table/feature collection feat_properties = ['site', 'CID', 'ORIG_FID'] KEYS = ee.List(feat_properties) # properties to retrieve from scene scene_properties = ['CLOUD_COVER', 'GEOMETRIC_RMSE_MODEL', 'LANDSAT_ID', 'SOLAR_ZENITH_ANGLE'] PROPERTY_LIST = ee.List(scene_properties) # Bands to retrieve bands = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'pixel_qa', 'radsat_qa'] BAND_LIST = ee.List(bands) # addon asset and bands ADDON = ee.Image('JRC/GSW1_0/GlobalSurfaceWater').float().unmask(MASK_VALUE) ADDON_BANDLIST = ee.List(['max_extent']) OUTFILE = 'C:/tmp/lsat_tundra_samples_eeur.csv' # Landsat Surface Reflectance collections ls5_1 = ee.ImageCollection("LANDSAT/LT05/C01/T1_SR") ls5_2 = ee.ImageCollection("LANDSAT/LT05/C01/T2_SR") ls7_1 = ee.ImageCollection("LANDSAT/LE07/C01/T1_SR") ls7_2 = ee.ImageCollection("LANDSAT/LE07/C01/T2_SR") ls8_1 = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR") ls8_2 = ee.ImageCollection("LANDSAT/LC08/C01/T2_SR") # define region of interest sites = ee.FeatureCollection('users/loganberner/arctic_oroarctic_eeur_srs_1_buf50m') sites = sites.map(addID) boundary = sites.geometry().bounds() # ------------------------------------------------------------------------------------ # BE CAREFUL MODIFYING THE STUFF BELOW # ------------------------------------------------------------------------------------ # function to concatenate two GEE lists def add_lists(list1, list2): first = ee.List(list1).add(list2.get(0)) n = list2.size() def _combine(this, prev): return ee.List(prev).add(this) return ee.List(list2).slice(1, n).iterate(_combine, first) ALL_BANDS = add_lists(BAND_LIST, ADDON_BANDLIST) # merge all collections in one LS_COLL = ee.ImageCollection(ls5_1 .merge(ls7_1 .merge(ls8_1 .merge(ls5_2 .merge(ls7_2 .merge(ls8_2)))))) \ .filter(ee.Filter.calendarRange(startJulian,endJulian, "day_of_year")) \ .filterBounds(boundary) \ .map(lambda image: image.addBands(ADDON, ADDON_BANDLIST)) \ .select(ALL_BANDS) \ .map(lambda image: image.float()) # print and flush function def cprint(text): sys.stdout.write(str(text) + '\n') sys.stdout.flush() # print exception with traceback without breaking the code def eprint(excep): print(excep) print('---------------------------------------------------------------------') print('Error Traceback:') print(traceback.format_exc()) print('---------------------------------------------------------------------') # function to extract properties from collection as list of dictionaries def get_coll_dict(image_collection): n_images = ee.ImageCollection(image_collection).size() coll_list = ee.ImageCollection(image_collection).toList(n_images) # extract properties in PROPERTY_LIST from one image def get_prop(image): image_dict = ee.Image(image).toDictionary() val_list = PROPERTY_LIST.map(lambda prop: image_dict.get(prop)).add(ee.Image(image).id()) return ee.Dictionary.fromLists(PROPERTY_LIST.add('id'), val_list) return coll_list.map(get_prop) # function to extract a feature from a non-null collection def get_region(feature): coll = LS_COLL.filterBounds(ee.Feature(feature).geometry()) ncoll = coll.size().getInfo() # feature to be extracted feat = ee.Algorithms.If(ee.Number(BUFFER_DIST).gt(0), ee.Feature(feature).buffer(BUFFER_DIST).bounds(), ee.Feature(feature)) feat_dict = feat.getInfo() feat_props = feat_dict['properties'] pt_list = list() if ncoll > 0: # list of properties of each image in the collection as dictionary coll_dicts = get_coll_dict(coll).getInfo() # extract pixel values from the collection # the output is a list or lists with the first row as column names temp_list = coll.getRegion(ee.Feature(feat).geometry(), SCALE).getInfo() n = len(temp_list) elem_names = temp_list[0] id_column = elem_names.index('id') for j in range(1, n): pt_dict = dict() for k in range(0, len(elem_names)): pt_dict[elem_names[k]] = temp_list[j][k] id = temp_list[j][id_column] scene_prop_list = list(coll_dict for coll_dict in coll_dicts if coll_dict['id'] == id) scene_prop = scene_prop_list[0] for prop in scene_properties: pt_dict[prop] = scene_prop[prop] for prop in feat_properties: pt_dict[prop] = feat_props[prop] pt_list.append(pt_dict) else: pt_dict = dict() pt_dict['id'] = NULL_VALUE pt_dict['time'] = NULL_VALUE for prop in feat_properties: pt_dict[prop] = feat_props[prop] for prop in scene_properties: pt_dict[prop] = NULL_VALUE for band in bands: pt_dict[band] = NULL_VALUE pt_list.append(pt_dict) return pt_list time0 = datetime.datetime.now() # convert sites collection to list n_sites = sites.size().getInfo() sites_list = sites.toList(n_sites) # iterate thru site list # for i in range(0, n_sites): for i in range(0, n_sites): time1 = datetime.datetime.now() site = sites_list.get(i) try: temp_dicts = get_region(site) # if any error occurs, print it and break the loop except Exception as e: eprint(e) break # convert to pandas data frame df = pd.DataFrame(temp_dicts) # all extracted values to file if i == 0: with open(OUTFILE, 'w') as f: df.to_csv(f, index=False, header=True) else: with open(OUTFILE, 'a') as f: df.to_csv(f, index=False, header=False) time2 = datetime.datetime.now() cprint('Time taken for sample {s}: {t} seconds'.format(s=str(i + 1), t=str(round((time2 - time1).total_seconds(), 1)))) time0_ = datetime.datetime.now() cprint('Total Time taken: {t} seconds'.format(t=str(round((time0_ - time0).total_seconds(), 1))))
[ "logan.berner@nau.edu" ]
logan.berner@nau.edu
344936961744263b75898af38578c5c1e8565953
77b3d1f51e0c471d6d5d1eb7142eaf18c421969f
/calc-math-6-sem/lab-8/plot.py
09db538be4e64bb72500d4254969204eb1ac8b42
[]
no_license
kostr2010/calc-math
d2084ee5aff6a42d84568e750c9cb1bd6b9ba69a
234aa16db00810989c98380b88135f04bcc1ff95
refs/heads/master
2023-04-21T06:35:53.705512
2021-05-07T20:08:25
2021-05-07T20:08:25
345,630,931
0
0
null
null
null
null
UTF-8
Python
false
false
884
py
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import pandas import sys points = pandas.read_csv("res_explicit.csv") fig1 = plt.figure(figsize=(16, 16)) ax1 = fig1.add_subplot(111, projection='3d') x = points['x'].values y = points['y'].values z = points['z'].values ax1.scatter(x, y, z, c='b', s=1) plt.savefig("res_explicit.png", dpi=500) points = pandas.read_csv("res_implicit.csv") fig2 = plt.figure(figsize=(16, 16)) ax2 = fig2.add_subplot(111) x1 = points['y1_11'].values y1 = points['y2_11'].values ax2.scatter(x1, y1, c='b', s=1) x2 = points['y1_12'].values y2 = points['y2_12'].values ax2.scatter(x2, y2, c='r', s=1) # plt.plot(x2, y2) # x3 = points['y1_21'].values # y3 = points['y2_21'].values # plt.plot(x3, y3) # x4 = points['y1_22'].values # y4 = points['y2_22'].values # plt.plot(x4, y4) plt.savefig("res_implicit.png", dpi=500)
[ "kostr010@gmail.com" ]
kostr010@gmail.com
475a16520cbeabe0ef68feffeed8aadaffeb0ca1
6a2abde61354a7f30d81edbfb0672744be8b76b8
/amqp/client/sub.py
6bf383758334b4c547a964ac907d8c2e1ebdc1c3
[ "MIT" ]
permissive
phragment/broker
7969eba685f19d580da320140e3190f98d605e53
e17ff7d663ce54de6e88c1233c21f92d9548efb8
refs/heads/master
2021-09-06T09:41:01.754154
2018-02-05T03:08:27
2018-02-05T03:08:27
113,892,085
0
0
null
null
null
null
UTF-8
Python
false
false
369
py
#!/usr/bin/env python3 import time from libs import amqp def msg(topic, payload): print(topic, payload) client = amqp.Client("ha-sub1") client.add_broker("127.0.0.1", 5673) client.add_broker("127.0.0.1", 5672) client.connect() client.subscribe(msg, "foo") try: while True: time.sleep(10) except KeyboardInterrupt: pass client.disconnect()
[ "t.krug@elektronenpumpe.de" ]
t.krug@elektronenpumpe.de
b43d9ff8a79954fe2e1802f1e470902414e25509
d19645f7d645095da4eccfd2cd2716230e98c227
/ss/gerenciador.py
ca6a1cf3c68c22e25151184a828ba8aa81e7f7c4
[]
no_license
viniciusluzsouza/pji2
54da267fe41cc23435d00b8b428d49a0a769eb0e
3f96176c0bb9017de779312d8d110def5e4eceea
refs/heads/master
2020-03-27T14:14:16.555135
2018-12-11T19:07:37
2018-12-11T19:07:37
146,651,743
0
0
null
null
null
null
UTF-8
Python
false
false
10,269
py
from threading import Thread from shared_ss import * from mensagens_robo import * from mensagens_auditor import * from interface_usuario import * import json class Gerenciador(Thread): """docstring for Gerenciador""" def __init__(self): self.jogo_em_andamento = 0 self.modo_jogo = None self.intf_usuario = InterfaceUsuario() self._ler_cadastro() super(Gerenciador, self).__init__() def _check_novo_jogo(self, msg): resp = {'ack': 0} if 'modo_jogo' not in msg: resp['erro'] = MsgAuditorErro.ParametroNaoInformado resp['param'] = 'modo_jogo' return resp if 'x' not in msg: resp['erro'] = MsgAuditorErro.ParametroNaoInformado resp['param'] = 'x' return resp if 'y' not in msg: resp['erro'] = MsgAuditorErro.ParametroNaoInformado resp['param'] = 'y' return resp if msg['modo_jogo'] == ModoDeJogo.AUTOMATICO \ and 'cacas' not in msg: resp['erro'] = MsgAuditorErro.ParametroNaoInformado resp['param'] = 'cacas' resp['ack'] = 1 return resp def sa_novo_jogo(self, msg): global shared_obj # Primeiro, verifica se os parametros estao corretos. # Caso nao estejam, nem envia solicitacao ao SR, envia erro ao SA check = self._check_novo_jogo(msg) if not check['ack']: shared_obj.set(SharedObj.TransmitirSALock, check) shared_obj.set_event(SharedObj.TransmitirSAEvent) return # Tudo ok, envia mensagem ao SR msg['_ttl'] = 10 shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.release(SharedObj.MensagemGerente) shared_obj.clear_event(SharedObj.SolicitaGerente) shared_obj.set_event(SharedObj.TransmitirSREvent) # Ao enviar um novo jogo ao SR, a mensagem "NovoJogoConfigurado" # deve ser a confirmacao que o jogo foi configurado shared_obj.wait_event(SharedObj.SolicitaGerente, timeout=10.0) shared_obj.acquire(SharedObj.MensagemGerente) if not shared_obj.is_set(SharedObj.SolicitaGerente): # Aconteceu timeout print("--> SA tentou iniciar jogo, porem SR nao responde.") return ack = shared_obj.get_directly(SharedObj.MensagemGerente) if ack['cmd'] == MsgSRtoSS.NovoJogoConfigurado: # Ok, jogo configurado !! # Aqui podemos colocar check de posicao!! self.jogo_em_andamento = 1 self.modo_jogo = msg['modo_jogo'] ui_msg = {'modo_jogo': self.modo_jogo, 'posicao_inicial': (msg['x'], msg['y'])} if 'cacas' in msg: ui_msg['cacas'] = msg['cacas'] # Avisa interface usuario shared_obj.set(SharedObj.InterfaceUsuarioFimJogo, 0) shared_obj.set(SharedObj.InterfaceUsuarioNovoJogoConfig, ui_msg) shared_obj.set_event(SharedObj.InterfaceUsuarioNovoJogoEvent) # Inicia jogo IniciaJogo shared_obj.clear_event(SharedObj.TransmitirSREvent) shared_obj.set(SharedObj.TransmitirSRLock, {'cmd': MsgSStoSR.IniciaJogo}) shared_obj.set_event(SharedObj.TransmitirSREvent) def _ler_cadastro(self): global shared_obj try: with open('cadastro.cfg') as f: cadastro = json.load(f) self.cor = cadastro['cor'] self.nome = cadastro['nome'] self.mac = cadastro['mac'] except: self.cor = 0 self.nome = "Grupo3" self.mac = "00:00:00:00:00:00" shared_obj.set(SharedObj.NomeDoRobo, self.nome) def _atualiza_cadastro(self): global shared_obj shared_obj.set(SharedObj.NomeDoRobo, self.nome) cadastro = {'cor': self.cor, 'nome': self.nome, 'mac': self.mac} with open('cadastro.cfg', 'w') as f: json.dump(cadastro, f) def cadastra_robo(self, msg): if 'cor' not in msg: return self.cor = msg['cor'] self.nome = msg['nome'] if 'nome' in msg else 'Grupo3' self.mac = msg['mac'] if 'mac' in msg else '00:00:00:00:00:00' self._atualiza_cadastro() def run(self): global shared_obj self.intf_usuario.start() while True: # Espera alguma mensagem ... shared_obj.wait_event(SharedObj.SolicitaGerente) shared_obj.acquire(SharedObj.MensagemGerente) msg = shared_obj.get_directly(SharedObj.MensagemGerente) if 'cmd' not in msg: shared_obj.clear_event(SharedObj.SolicitaGerente) continue cmd = msg['cmd'] # Solicitacoes vindas do SA if '_dir' in msg and msg['_dir'] == 'sa': if cmd == MsgSAtoSS.NovoJogo: self.sa_novo_jogo(msg) elif cmd == MsgSAtoSS.SolicitaID: # Transmite para SR shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) elif cmd == MsgSAtoSS.Pausa: # Avisa interface usuario ui_msg = {'cmd': InterfaceUsuario.SA_Pausa} shared_obj.set(SharedObj.InterfaceUsuarioMsg, ui_msg) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) # Transmite para SR shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) elif cmd == MsgSAtoSS.Continua: # Avisa interface usuario ui_msg = {'cmd': InterfaceUsuario.SA_Continua} shared_obj.set(SharedObj.InterfaceUsuarioMsg, ui_msg) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) # Transmite para SR shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) elif cmd == MsgSAtoSS.FimJogo: # Avisa interface usuario shared_obj.set(SharedObj.InterfaceUsuarioFimJogo, 1) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) # Transmite para SR shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) elif cmd == MsgSAtoSS.ValidacaoCaca: # Avisa interface usuario ui_msg = {'cmd': InterfaceUsuario.SA_ValidacaoCaca} shared_obj.set(SharedObj.InterfaceUsuarioMsg, ui_msg) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) # Transmite para SR shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) if 'cacas' in msg and not len(msg['cacas']): # Finaliza jogo import time time.sleep(0.1) msg['cmd'] = MsgSStoSR.FimJogo shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) shared_obj.set(SharedObj.InterfaceUsuarioFimJogo, 1) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) elif cmd == MsgSAtoSS.AtualizaMapa: # Avisa interface usuario ui_msg = {'cmd': InterfaceUsuario.SA_AtualizaMapa, 'cacas': msg['cacas']} shared_obj.set(SharedObj.InterfaceUsuarioMsg, ui_msg) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) # Transmite para SR shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) elif cmd == MsgSAtoSS.SolicitaHistorico: # Transmite para SR shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) elif cmd == MsgSAtoSS.CadastraRobo: self.cadastra_robo(msg) # Transmite para SR shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) elif cmd == MsgSAtoSS.SolicitaStatus: # Transmite para SR shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) else: pass # Solicitacoes vindas do SR elif '_dir' in msg and msg['_dir'] == 'sr': if cmd == MsgSRtoSS.SolicitaID_Resp: # Transmite para SA shared_obj.set(SharedObj.TransmitirSALock, msg) shared_obj.set_event(SharedObj.TransmitirSAEvent) elif cmd == MsgSRtoSS.MovendoPara: # Avisa interface usuario ui_msg = {'cmd': InterfaceUsuario.SR_MovendoPara, 'x': msg['x'], 'y': msg['y']} shared_obj.set(SharedObj.InterfaceUsuarioMsg, ui_msg) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) # Transmite para SA shared_obj.set(SharedObj.TransmitirSALock, msg) shared_obj.set_event(SharedObj.TransmitirSAEvent) elif cmd == MsgSRtoSS.PosicaoAtual: ui_msg = {'cmd': InterfaceUsuario.SR_PosicaoAtual, 'x': msg['x'], 'y': msg['y']} shared_obj.set(SharedObj.InterfaceUsuarioMsg, ui_msg) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) shared_obj.set(SharedObj.TransmitirSALock, msg) shared_obj.set_event(SharedObj.TransmitirSAEvent) elif cmd == MsgSRtoSS.ValidaCaca: ui_msg = {'cmd': InterfaceUsuario.SR_ValidaCaca} shared_obj.set(SharedObj.InterfaceUsuarioMsg, ui_msg) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) shared_obj.set(SharedObj.TransmitirSALock, msg) shared_obj.set_event(SharedObj.TransmitirSAEvent) elif cmd == MsgSRtoSS.ObstaculoEncontrado: ui_msg = {'cmd': InterfaceUsuario.SR_ObstaculoEncontrado} shared_obj.set(SharedObj.InterfaceUsuarioMsg, ui_msg) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) shared_obj.set(SharedObj.TransmitirSALock, msg) shared_obj.set_event(SharedObj.TransmitirSAEvent) elif cmd == MsgSRtoSS.SolicitaHistorico_RESP: # Transmite para SA shared_obj.set(SharedObj.TransmitirSALock, msg) shared_obj.set_event(SharedObj.TransmitirSAEvent) elif cmd == MsgSRtoSS.SolicitaStatus_RESP: # Transmite para SA shared_obj.set(SharedObj.TransmitirSALock, msg) shared_obj.set_event(SharedObj.TransmitirSAEvent) elif cmd == MsgSRtoSS.FinalizaJogo: # Avisa interface usuario shared_obj.set(SharedObj.InterfaceUsuarioFimJogo, 1) shared_obj.set_event(SharedObj.InterfaceUsuarioEvent) else: pass # Solicitacoes vindas do proprio ss elif '_dir' in msg and msg['_dir'] == 'ss': if cmd == MsgSStoSR.Mover: # Transmite para SR msg['_ttl'] = 5000 shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) elif cmd == MsgSStoSA.ValidaCaca: # Transmite para SA shared_obj.set(SharedObj.TransmitirSALock, msg) shared_obj.set_event(SharedObj.TransmitirSAEvent) elif cmd == MsgSStoSR.Pausa \ or MsgSStoSR.Continua: # Transmite para SR shared_obj.set(SharedObj.TransmitirSRLock, msg) shared_obj.set_event(SharedObj.TransmitirSREvent) # Transmite para SA shared_obj.set(SharedObj.TransmitirSALock, msg) shared_obj.set_event(SharedObj.TransmitirSAEvent) shared_obj.release(SharedObj.MensagemGerente) shared_obj.clear_event(SharedObj.SolicitaGerente)
[ "viniciusls22@gmail.com" ]
viniciusls22@gmail.com
cafa1a9e5a0be3638f0d4adc14a143ec08a51f29
0b01cb61a4ae4ae236a354cbfa23064e9057e434
/alipay/aop/api/domain/AlipayOpenMiniVersionGrayCancelModel.py
edc2052c0c624076b0ec219ead0be1b3c831ddf2
[ "Apache-2.0" ]
permissive
hipacloud/alipay-sdk-python-all
e4aec2869bf1ea6f7c6fb97ac7cc724be44ecd13
bdbffbc6d5c7a0a3dd9db69c99443f98aecf907d
refs/heads/master
2022-11-14T11:12:24.441822
2020-07-14T03:12:15
2020-07-14T03:12:15
277,970,730
0
0
Apache-2.0
2020-07-08T02:33:15
2020-07-08T02:33:14
null
UTF-8
Python
false
false
944
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayOpenMiniVersionGrayCancelModel(object): def __init__(self): self._app_version = None @property def app_version(self): return self._app_version @app_version.setter def app_version(self, value): self._app_version = value def to_alipay_dict(self): params = dict() if self.app_version: if hasattr(self.app_version, 'to_alipay_dict'): params['app_version'] = self.app_version.to_alipay_dict() else: params['app_version'] = self.app_version return params @staticmethod def from_alipay_dict(d): if not d: return None o = AlipayOpenMiniVersionGrayCancelModel() if 'app_version' in d: o.app_version = d['app_version'] return o
[ "liuqun.lq@alibaba-inc.com" ]
liuqun.lq@alibaba-inc.com
dbdbf0f8a5afece448cca22f6672741622e4a1c5
a1419bffb6d6c6c87448849f0c6dd861293a1c65
/emergente.py
8ab222988c30a51f811a3ebbff50f3ee9905943a
[]
no_license
DanielLopezCoto/emergent-computation
795db1e6d7eb5f96a30127e03d3cd646b99a4d6c
f78c6ecd5bf3162081395a2fee9538c0c2aa4c4f
refs/heads/master
2021-01-17T19:26:28.727290
2016-07-01T10:20:12
2016-07-01T10:20:12
60,960,938
0
1
null
null
null
null
UTF-8
Python
false
false
12,460
py
#!usr/bin/env python # -*- coding: utf-8 -*- """ Autor: Daniel Lopez Coto Este programa pretende reproducir los resultados de la computacion emergente usando los metodos de los automatas celulares unidimensionales. Informacion util: - r = 3 (vecindad de orden 3) - D = 1 (automatas unidimensionales) - k = 2 (dos posibles estados: 0 o 1) - 2**(2*r+1) = Numero de bits necesarios para las reglas (en este caso 128 bites) - Numero de reglas: 100 - Uso de algoritmos geneticos - Reglas de transicion totalisticas - Tamanio de los automatas (size) = 149 """ import numpy as np import random as rd import csv from matplotlib import pylab import sys import time as TIEMPO """ Definimos un decorador, que nos dara el tiempo de ejecucion de la funcion decorada """ def cronometro(funcion): def fun_a_ejecutar(*args): t1 = TIEMPO.time() resultado = funcion(*args) t2 = TIEMPO.time() T = t2 - t1 nombre = funcion.__name__ print("Tiempo de '%s': %g segundos" %(nombre,T)) return resultado return fun_a_ejecutar """ Clase automata que es la que creara las reglas, o en caso de haberas introducido nosotros, las manejara; calculara el ajuste (fitness) de dichas reglas y las ira modificando """ class Automata: def __init__(self,numeroReglas=100,initSize=149,tiempo=None,initVector=None,initReglas=None): """ Inicializamos los valores que vamos a necesitar en el programa. Los parametros de entrada que permite son: Numero; tamaรฑo del automata (numero de celdas); set inicial de condiciones iniciales y set de reglas, respectivamente. 'setReglas' es una lista que contiene las reglas (lista de listas). 'setVectores' es una lista que contiene las configuraciones iniciales de las celdas (lista de listas)""" self.size = initSize # Numero de celdas que tendra el automata. self.noReglas = numeroReglas # Numero de reglas. self.time = tiempo if self.time == None: self.time = initSize * 2 if initReglas == None: # Si no hay reglas inicialmente, las creamos. self.setReglas = tuple(self.crearReglas(self.noReglas)) else: # Si ya hemos introducido las reglas, las inicializamos. self.setReglas = tuple(initReglas) if initVector == None: # Si no hay un vector con los valores iniciales, # lo creamos. self.setVectores = condIniciales(self.size) else: # Si lo hay, lo inicializamos. self.setVectores = initVector def crearReglas(self,noReglas): Rules = list(np.zeros(noReglas)) # Lista que almacena las diferentes reglas. for i in xrange(noReglas): rule = [] # Lista que contendra a la regla i-esima. for j in xrange(128): a = rd.random() # En cada iteracion generamos un numero aleatorio entre 0 y 1 if a > 0.5: rule.append(1) else: rule.append(0) Rules[i] = rule return Rules # Devuelve una lista de reglas, donde cada elemento es # una regla de 128 elementos 0s y 1s (es decir, una lista # de 128 elementos). def cambiarEstado(self,regla,tiempo): """ Este metodo recibe como entrada un entero que corresponde a la cantidad de pasos de tiempo que se van a evaluar los estados de las celulas para cada regla.""" self.setEstados = self.setVectores[:] # Lista que contiene el conjunto de estados para la regla # introducida como parรกmetro, # para cada CI, y para cada paso de tiempo. numEsta2Iniciales = len(self.setEstados) # Almacena el numero de estados iniciales # que correspondera con el numero de CIs. M_r = [[None]*tiempo for s in xrange(numEsta2Iniciales)] # Matriz que almacena los estados para cada # paso de tiempo, y para cada CI. Las filas son las diferentes # CIs y las columnas los diferentes estados de tiempo. # M_r[i] todos los estados de tiempo de la CI i-esima. for i in xrange(numEsta2Iniciales): # Iteramos sobre las Configuraciones Iniciales. estadoActual = self.setEstados[i][:] # Escogemos la CI i-esima. nuevoEstado = estadoActual[:] M_r[i][0] = estadoActual[:] for t in xrange(1,tiempo): # Iteramos sobre cada paso de tiempo. for j in xrange(-3,self.size-3): # Iteramos sobre las posiciones. """ Codificamos la configuracion de vecinos en binario, y lo convertimos en un numero. Dicho numero sera la posicion de la regla que estamos evaluando, y el valor que este almacenado en dicha posicion, sera asignado al nuevo estado de la celula j.""" binario = '0b'+str(estadoActual[j-3])+str(estadoActual[j-2])+\ str(estadoActual[j-1])+str(estadoActual[j])+\ str(estadoActual[j+1])+str(estadoActual[j+2])+str(estadoActual[j+3]) nuevoEstado[j] = regla[int(binario,2)] estadoActual = nuevoEstado[:] M_r[i][t] = [float(s) for s in estadoActual] return M_r # Devuele la matriz con todas las configuraciones de cada paso de tiempo, para # cada CI. def fitnessFun(self,confVectores): """ Este metodo recibe como entrada el set de configuraciones de las celulas en cada instante de tiempo para una regla concreta.""" fit = [] # Lista que almacena los ajustes para las diferentes CIs numElementos = self.size # Tamaรฑo del automata numCIs = len(confVectores) # Numero de CIs pasosTiempo = len(confVectores[0]) # Numero de pasos de tiempo for i in xrange(numCIs): inicial = confVectores[i][0] sumaini = float(sum(inicial))/numElementos # Nos dice si la configuracion inicial tiene mas ceros o unos final = confVectores[i][-1] # Obtenemos el ultimo paso de tiempo para la CI i-esima sumafin = float(sum(final))/numElementos # Fraccion de unos en el estado final if sumaini < 0.5 and sumafin == 0 or sumaini > 0.5 and sumafin == 1: # Si el estado inicial tiene mas 0 que unos, cambia fit por 1-fit fit.append(1) else: fit.append(0) ajuste = float(sum(fit))/len(fit) # Hace una media del valor del ajuste para las # diferentes CIs return ajuste #,id_mejor @cronometro def algoritmoGenetico(self,tiempo): """ Llama al metodo 'cambiarEstado' para crear los diferentes estados para cada intervalo de tiempo en cada CI. Llama a la 'fitnessFun' para calcular el grado de ajuste de la regla que queramos ver en ese momento. Iteramos sobre cada regla para obtener un vector con la calidad de cada una, y posteriormente poder realizar la seleccion de las mejores y eliminar las demas, de forma que podamos realizar el 'crossover' de las distintas reglas, asegurandonos obtener en cada nueva generacion reglas mejores.""" contador = [] # Lista que almacena el numero de la regla que cumple la condicion para ser # seleccionada limRegla = self.noReglas/4 newReglas = [] self.bondad = [] self.M_R = [[[None]*tiempo for s in xrange(len(self.setVectores))] \ for k in xrange(self.noReglas)] # Lista que contendra todos los estados para cada paso de tiempo para cada CI de cada regla. # El elemento M_R[r] es el conjunto de todos los pasos de tiempo para todas las CIs en la regla r-esima. #self.id_mejor_CI = [] # lista que contendrรก รญndice de la CI que mejor ajusta la regla r for r in xrange(self.noReglas): # Evaluamos la bondad de cada regla. self.M_R[r] = self.cambiarEstado(self.setReglas[r],self.time) salidaFitnessFun = self.fitnessFun(self.M_R[r]) self.bondad.append(salidaFitnessFun) #[0]) #self.bondad.append(self.fitnessFun(self.M_R[r])) #self.id_mejor_CI.append(salidaFitnessFun[1]) maxima = max(self.bondad) # Mira cual es el maximo de la bondad de las reglas contador.append(self.bondad.index(maxima)) print contador for r in xrange(self.noReglas): if self.bondad[r] < maxima and self.bondad[r] >= 0.8*maxima: contador.append(r) if len(contador) == limRegla: break while len(contador) < limRegla: for r in xrange(self.noReglas): if self.bondad[r] > 0.5*maxima and self.bondad[r] < 0.8*maxima: contador.append(r) else: continue if len(contador) == limRegla: break if len(contador) != limRegla: for r in xrange(self.noReglas): a = int(rd.random()*99) if a in contador: continue else: contador.append(a) if len(contador) == limRegla: break print contador #borrar luego for i in contador: newReglas.append(self.setReglas[i]) # Aรฑade las reglas # Escribimos las reglas actuales en un fichero ruls = open('reglas.txt','w') out = csv.writer(ruls,delimiter = '\t') out.writerows(self.setReglas) ruls.close() """Ahora hay que hacer el crossover de reglas""" for r in xrange(-1,limRegla-1): a = newReglas[r][:] b = newReglas[r+1][:] c = newReglas[r+2][:] aNew = a[:] bNew = b[:] cNew = c[:] aNew[42:84],aNew[84:] = c[42:84], b[84:] bNew[42:84],bNew[84:] = a[42:84], c[84:] cNew[42:84],cNew[84:] = b[42:84], a[84:] # Aรฑade las nuevas reglas newReglas.append(aNew) newReglas.append(bNew) newReglas.append(cNew) # Probabilidad de mutacion for r in xrange(len(newReglas)): if rd.random() <= 0.05: pos_mut = int(rd.random()*127) if newReglas[r][pos_mut] ==1: newReglas[r][pos_mut] = 0 else : newReglas[r][pos_mut] = 1 # Escribimos las nuevas reglas n_ruls = open('new_reglas.txt','w') n_out = csv.writer(n_ruls,delimiter = '\t') n_out.writerows(newReglas) n_ruls.close() def condIniciales(size=149,no_CIs=100): """ Creamos un conjunto de 100 configuraciones iniciales para cada celula. Los estados posibles son 0 o 1, repartidos de forma aleatoria siguiendo una distribucion uniforme en el intervalo (0,1)""" setCIs = [] # Lista vacia que contendra el conjunto # de las 100 configuraciones iniciales. for i in xrange(no_CIs): vectIni = [] # Lista que contendra la configuracion inicial i-esima. for j in xrange(size): if rd.random() > 0.5: vectIni.append(1) else: vectIni.append(0) setCIs.append(vectIni) C = open('setCI.txt','w') Cout = csv.writer(C,delimiter = '\t') Cout.writerows(setCIs) C.close() return setCIs class AutomImagen: def __init__(self,Objeto=None): # Objeto sera la clase automata con sus parametros iniciados. if Objeto == None: sys.exit() #self.Objeto = Objeto Objeto = Objeto self.nCI = len(Objeto.setVectores) time = Objeto.time Objeto.algoritmoGenetico(time) self.bondad = Objeto.bondad self.m_r = Objeto.M_R #self.id_CI = Objeto.id_mejor_CI self.dibujAutom() @cronometro def dibujAutom(self): maximo = max(self.bondad) print maximo for r in xrange(len(self.m_r)): if self.bondad[r] == maximo: regla = r #ID = self.id_CI[r] break for i in xrange(self.nCI): c = (regla,i) # tupla que dara el numero de la regla y de la CI para guardar la imagen. matrizEstados = self.m_r[r][i] pylab.matshow(matrizEstados,cmap='binary') pylab.title("Celdas") pylab.ylabel("Tiempo") pylab.savefig("Regla%i_CI%i.eps" %c) pylab.close() # Aqui salvamos el automata seleccionado f = open('automata_R%i_CI%i.txt' %c,'w') fout = csv.writer(f,delimiter = '\t') fout.writerows(matrizEstados) f.close() """Esta parte del codigo sirve para que el programa se ejecute solo si el modulo es llamado como programa y no al importarlo.""" if __name__ == '__main__': print "ยฟTienes reglas que importar? ([y]/n):" respuesta = raw_input() if respuesta != 'n': #print "Escribe el nombre del archivo con la extension." #archivo = raw_input() archivo = 'new_reglas.txt' reglasImportadas = open(archivo,'r') setreglas = reglasImportadas.readlines() nreglas = len(setreglas) listaReglas = [] for l in xrange(nreglas): regla = setreglas[l].split() for i in xrange(len(regla)): regla[i]=int(regla[i]) listaReglas.append(regla) automata = Automata(initReglas = listaReglas) # print "ยฟTienes CIs que importar? (y/[n])" # resp = raw_input() # if resp == 'y': # ini_file = 'setCI.txt' # fCI = open(ini_file,'r') # filas = fCI.readlines() # nfilas = len(filas) # CIs = [] # for l in xrange(nfilas): # fila = filas[l].split() # for i in xrange(len(fila)): # fila[i]=int(fila[i]) # CIs.append(fila) # automata = Automata(initReglas = listaReglas, initVector = CIs) # else: # automata = Automata(initReglas = listaReglas) else: automata = Automata() AutomImagen(automata)
[ "noreply@github.com" ]
DanielLopezCoto.noreply@github.com
c2d6a7bd889b6927c42c816fbbb74da9e4cd7ca0
a84e1ed67ef2592cf22f7d19cdddaf16700d6a8e
/translator/applications/TranslatorApp.py
6daaf82a7be712cf06489b4b679b1962a8f88864
[]
no_license
danse-inelastic/inelastic-svn
dda998d7b9f1249149821d1bd3c23c71859971cc
807f16aa9510d45a45360d8f59f34f75bb74414f
refs/heads/master
2016-08-11T13:40:16.607694
2016-02-25T17:58:35
2016-02-25T17:58:35
52,544,337
1
2
null
null
null
null
UTF-8
Python
false
false
1,302
py
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Brandon Keith # California Institute of Technology # (C) 2005 All Rights Reserved All Rights Reserved # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from pyre.applications.Script import Script from translator.Trajectory import Trajectory class TranslatorApp(Script): '''Driver for file conversion''' class Inventory(Script.Inventory): import pyre.inventory as inv translator = inv.facility('translator', default=Trajectory()) #translator = inv.facility('translator', default='trajectory') translator.meta['tip'] = 'translate a file from one format to another' translator.meta['known_plugins'] = ['trajectory'] def __init__(self): Script.__init__(self, 'TranslatorApp') self.i=self.inventory def main(self, *args, **kwds): # first compute the scattering function using nmoldyn engine self.i.translator.translate() if __name__=='__main__': app=TranslatorApp() app.run() # version __id__ = "$Id$" # Generated automatically by PythonMill on Tue Jun 5 15:04:48 2007 # End of file
[ "jbrkeith@gmail.com" ]
jbrkeith@gmail.com
7a81c1603adc758fedca274bd7a3896ef2fee5ca
e53c91c5266c7fa9cb59c4527bf2aa98fd8d61ed
/word_level_train.py
789a2aeab0648d529a8c6ef90306fee2aec6b879
[]
no_license
Siddharth11235/CS419_Project
4d8eb73f1225999dddf6aa5becc1ee52ca61c07a
60b262260d9482be8808af79b7f74b0714979a5e
refs/heads/master
2021-04-03T06:44:13.775464
2018-05-07T05:16:37
2018-05-07T05:16:37
124,904,460
0
0
null
null
null
null
UTF-8
Python
false
false
4,615
py
from __future__ import division from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import model_from_json import numpy as np import random def sample(a, temperature=1.0): # helper function to sample an index from a probability array a = np.log(a) / temperature a = np.exp(a) / np.sum(np.exp(a)) if sum(a) > 1.0: # occasionally getting 1.00000X, so handling for that a *= .999 return np.argmax(np.random.multinomial(1, a, 1)) def train(): """trains the LSTM model on text corpora""" path = "datasets/WW_Dataset.txt" try: text = open(path).read().lower() except UnicodeDecodeError: import codecs text = codecs.open(path, encoding='utf-8').read().lower() print ('corpus length:', len(text)) chars = set(text) words = set(text.split()) print ("total number of unique words", len(words)) print ("total number of unique chars", len(chars)) word_indices = dict((c, i) for i, c in enumerate(words)) indices_word = dict((i, c) for i, c in enumerate(words)) maxlen = 10 step = 6 print ("maxlen:", maxlen,"step:", step) sentences = [] next_words = [] next_words = [] list_words = [] sentences2 = [] list_words = text.lower().split() for i in range(0, len(list_words) - maxlen, step): sentences2 = ' '.join(list_words[i: i + maxlen]) sentences.append(sentences2) next_words.append((list_words[i + maxlen])) print ('length of sentence list:', len(sentences)) print ("length of next_word list", len(next_words)) print ('Vectorization...') X = np.zeros((len(sentences), maxlen, len(words)), dtype=np.bool) y = np.zeros((len(sentences), len(words)), dtype=np.bool) for i, sentence in enumerate(sentences): for t, word in enumerate(sentence.split()): X[i, t, word_indices[word]] = 1 y[i, word_indices[next_words[i]]] = 1 #build the model: 2 stacked LSTM print ('Building model...') model = Sequential() model.add(LSTM(128, input_shape=(maxlen, len(words)))) model.add(Dense(len(words))) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') try: model.load_weights("Word_level_weights/word_level.h5") except Exception as e: print (e) pass # train the model, output generated text after each iteration for iteration in range(1, 3): print ('-' * 50) print ('Iteration', iteration) model.fit(X, y, batch_size=128, nb_epoch=10) json_string = model.to_json() with open('Word_level_weights/word_level_mod.h5', 'w') as f: f.write(json_string) model.save_weights('Word_level_weights/word_level.h5', overwrite=True) def generate_from_word_level_rnn(maxlen=10, diversity=1.0, min_sent_len=7, max_sent_len=25): with open("datasets/WW_Dataset.txt", "r") as f: text = f.read().lower().split()[:4940] words = set(text) start_index = random.randint(0, len(text) - maxlen - 1) word_indices = dict((c, i) for i, c in enumerate(words)) indices_word = dict((i, c) for i, c in enumerate(words)) response = "" model = model_from_json(open('Word_level_weights/word_level_mod.h5').read()) model.load_weights('Word_level_weights/word_level.h5') model.compile(loss='categorical_crossentropy', optimizer='rmsprop') sentence = text[start_index: start_index + maxlen] for i in range(random.randint(min_sent_len, max_sent_len)): x = np.zeros((1, maxlen, len(words))) for t, word in enumerate(sentence): x[0, t, word_indices[word]] = 1. preds = model.predict(x, verbose=0)[0] next_index = sample(preds, diversity) next_word = indices_word[next_index] if not response: response += ' {0}'.format(next_word) else: if response.split()[-1] != next_word: response += ' {0}'.format(next_word) del sentence[0] sentence.append(next_word) print (response) return response ### to load this model elsewhere... ### # from keras.models import model_from_json # model = model_from_json(open('<path to your saved model architecture>').read()) # model.load_weights('<path to your saved weights>') # model.compile(loss='categorical_crossentropy', optimizer='rmsprop') if __name__ == "__main__": train() generate_from_word_level_rnn()
[ "siddharth11235@gmail.com" ]
siddharth11235@gmail.com
e208f4508ee13ac9d51e8a0bc13c1be4d6da14bb
9e268d7ec4cb23249886847caa54a0f82f401d2c
/141hasCycle.py
d5d6b26176bd5ca5e45f97bc13a7b58864739963
[]
no_license
whitefir/leetcode
317ff5f20913c99f9714390ff31677b214bba3aa
dc8bf0e9ed4ec500891792bcaeb329e66951f9bd
refs/heads/master
2021-07-15T08:23:04.048332
2020-08-08T08:53:57
2020-08-08T08:53:57
195,218,781
0
0
null
null
null
null
UTF-8
Python
false
false
411
py
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head:ListNode)->bool: fast, slow=head, head while fast and fast.next: fast=fast.next.next slow=slow.next if fast==slow: return True return False
[ "noreply@github.com" ]
whitefir.noreply@github.com
eddf15913264d54a3d134075c392f37c15332d97
f524b381f819400ad2cb1c618f1a71e19282bdc6
/schedules/migrations/0003_auto_20181125_0816.py
d08943ba5894c638e9d5a94e07ab16238532037c
[]
no_license
luase/classTime
c2ad7f93d1f32c0e397e5c90d8e56e41d778778d
9687cadf7675288d95f89c82c91ae94089828e32
refs/heads/master
2020-04-07T11:03:52.601992
2018-12-06T18:39:07
2018-12-06T18:39:07
158,311,144
0
1
null
2018-11-29T19:55:04
2018-11-20T01:09:56
Python
UTF-8
Python
false
false
501
py
# Generated by Django 2.1.3 on 2018-11-25 08:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('schedules', '0002_auto_20181125_0802'), ] operations = [ migrations.AlterField( model_name='professor_subject_schedule', name='professor', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='schedules.Professor'), ), ]
[ "js.alonsosanchez@ugto.mx" ]
js.alonsosanchez@ugto.mx
bc56bf37720d13da204c3c82e4a20d297e3a720a
26555a1f341678601cf3c0f453d0e44f4569457b
/task/2018_06_07/Robot.py
21a6520ec3ad42e95ab70c925ca5c5b45277b3f3
[]
no_license
void0red/code
a5fc8af97b370e407d0b03f3c34232554221d89a
23b533352a1f5710bd350340a9092cfc77a9617b
refs/heads/master
2018-09-26T05:03:37.533670
2018-08-09T13:56:37
2018-08-09T13:56:37
106,823,130
0
1
null
null
null
null
UTF-8
Python
false
false
271
py
from pwn import * p = process('./Robot') p.recvuntil('exit...') p.sendline('666') p.recvuntil('password:') payload = '327a6c4304ad5938eaf0efb6cc3e53dc' + '\0'*0x20 + './'*16 + 'flag' p.sendline(payload) p.recvuntil('Flag') p.sendline('6') p.interactive()
[ "void0red@qq.com" ]
void0red@qq.com
852d2d4cd7964e41f27c18f6a33934b46f7d6b6d
d9ab73e3255856b3485e7f6a1462cba6389d6d69
/homework2/classification.py
f1438647c062cca6d45b7884d2592e24a6349c6c
[]
no_license
MorrisChen1998/DataMining
03a837c8829f18102f1f2fda09b28192c45ee3e3
6ca09cceca87ac2c103113c6f3583b20a391b266
refs/heads/master
2023-01-24T22:48:39.832290
2020-12-10T07:04:26
2020-12-10T07:04:26
305,160,926
0
0
null
null
null
null
UTF-8
Python
false
false
993
py
# -*- coding: utf-8 -*- """ Created on Wed Nov 25 01:59:48 2020 @author: morri """ import pandas as pd from sklearn import preprocessing from sklearn import tree#DecisionTreeClassifier from sklearn.model_selection import train_test_split train_data = pd.read_csv('classfication/csv/train.csv').values test_data = pd.read_csv('classfication/csv/test.csv').values #%% data = preprocessing.scale(train_data[:,:-1]) X_train, X_test, y_train, y_test = train_test_split( data, train_data[:,-1], test_size=0.25,random_state=0) clf = tree.DecisionTreeClassifier( criterion='entropy', class_weight='balanced', random_state=0, min_samples_split=5, max_depth=15) clf = clf.fit(X_train, y_train) validation=clf.score(X_test, y_test) #%% from print_answer import printOutAnswer data = preprocessing.scale(test_data) answer = clf.predict(data) printOutAnswer("classification",answer) #%% count = [0,0,0,0] for i in range(len(train_data[:,-1])): count[train_data[:,-1][i]]+=1
[ "morris7307@gmail.com" ]
morris7307@gmail.com
133d487f10a1630c89278bf269c1831c8fc7b077
60dae997c1c460a5c058940528669865fa44bb6d
/venv/lib/python3.5/tarfile.py
c06e9e0a164e5a97387495416e202779da6ac259
[]
no_license
abhay97ps/ReversiBot
5ba5e79e23659313de5004708642fdda508c0769
efc31516006a4819276231088f5a96acb3f4a57f
refs/heads/master
2020-03-07T04:43:37.003946
2018-05-09T03:24:48
2018-05-09T03:24:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
31
py
F:/usr/lib/python3.5/tarfile.py
[ "aakashv000@gmail.com" ]
aakashv000@gmail.com
d389f798fa8ab330db0e32ce27b0bcd1973ff239
0457a6c3ad642848678f07b9f59c711a0258ddfd
/Python Lab/17-02-2021/CO4/4.py
d00210fff39a580cecc37fe4e2b26c1a91753fa5
[]
no_license
AbhishekScariyaMB/RMCA_S1_A_-Abhishek-Scariya-M-B
a8ba3430ad25cbd36d5c5dd3cd19d285e3c1abea
42917fef0e82c01fa894a428aa3ac5bab4527208
refs/heads/main
2023-06-08T00:02:34.626533
2021-06-30T09:25:00
2021-06-30T09:25:00
353,230,261
1
0
null
null
null
null
UTF-8
Python
false
false
508
py
class Time: def __init__(self,hh=0,mm=0,ss=0): self.__hour=hh self.__minute=mm self.__second=ss def __add__(self,other): second=int((self.__second + other.__second)%60) minute=int((self.__minute + other.__minute)%60 + ((self.__second + other.__second)/60)) hour=int((self.__hour + other.__hour)%24 + (self.__minute + other.__minute)/60) print('Time[hh:mm:ss] ',hour,':',minute,':',second) T1=Time(12,25,45) T2=Time(16,45,56) T1 + T2
[ "noreply@github.com" ]
AbhishekScariyaMB.noreply@github.com
a4f693190a6e11185c3a89af3fbabdedfa6b57bf
d2ea935fbbaccf120b408ae88888324fa55c5dc9
/BSP.py
82908a7d8ec287f60cd34f31c52d9075770b043e
[]
no_license
ChamodAK/Binary-Space-Partition-Tree-BSP-Tree-
0ddb72924dd709cfefd1e6c4433e4aed74b59d4f
aec2afca5ddd2fdd6eb83b6e58bdd7ab567df04a
refs/heads/master
2020-05-19T21:38:32.614375
2019-05-06T16:05:03
2019-05-06T16:05:03
185,229,288
4
1
null
null
null
null
UTF-8
Python
false
false
5,576
py
import numpy as np class Node: def __init__(self,data): self.data = data self.x1 = None self.y1 = None self.x2 = None self.y2 = None self.sameList = [] self.frontList = [] self.backList = [] self.front = None self.back = None class Tree: def __init__(self): self.root = None def insert(self,data): if(self.root == None): n = self.pointify(data) self.root = n else: self.insertNode(self.root,data) def insertNode(self,curNode,data): n = self.pointify(data) checking = self.lineChecker(curNode.x1,curNode.y1,curNode.x2,curNode.y2,n.x1,n.y1,n.x2,n.y2) if(checking=="front"): if(curNode.front==None): curNode.front = n curNode.frontList.append(n.data) else: curNode.frontList.append(n.data) self.insertNode(curNode.front,data) elif(checking=="back"): if(curNode.back==None): curNode.back = n curNode.backList.append(n.data) else: curNode.backList.append(n.data) self.insertNode(curNode.back,data) elif(checking=="same"): curNode.sameList.append(n.data) elif(checking=="intersect"): data1,data2 = self.intersection(curNode,n) self.insertNode(curNode,data1) self.insertNode(curNode,data2) def equify(self,curNode): try: m1 = (curNode.y2-curNode.y1)/(curNode.x2-curNode.x1) c1 = curNode.y1-(m1*curNode.x1) np_y1 = 1 np_x1 = -m1 np_c1 = c1 return np_y1,np_x1,np_c1 except: np_y1 = 0 np_x1 = 1 np_c1 = curNode.x1 return np_y1,np_x1,np_c1 def intersection(self,curNode,n): y1,x1,c1 = self.equify(curNode) y2,x2,c2 = self.equify(n) a = np.array([[y1,x1], [y2,x2]]) b = np.array([c1,c2]) p,q = np.linalg.solve(a, b) y = p x = q data1 = "("+str(n.x1)+", "+str(n.y1)+")"+" , "+"("+str(x)+", "+str(y)+")" data2 = "("+str(n.x2)+", "+str(n.y2)+")"+" , "+"("+str(x)+", "+str(y)+")" return data1,data2 def lineChecker(self,x1,y1,x2,y2,x0,y0,x,y): val1 = (x-x1)*(y2-y1) - (y-y1)*(x2-x1) val2 = (x0-x1)*(y2-y1) - (y0-y1)*(x2-x1) if((val1 > 0) and (val2 > 0)): return "front" elif((val1 < 0) and (val2 < 0)): return "back" elif((val1 == 0) and (val2 == 0)): return "same" elif(((val1>0) and (val2==0)) or ((val1==0) and (val2>0))): return "front" elif(((val1<0) and (val2==0)) or ((val1==0) and (val2<0))): return "back" elif(((val1<0) and (val2>0)) or ((val1>0) and (val2<0))): return "intersect" def pointify(self,data): points = data.split(" , ") point1 = points[0].strip("()") point2 = points[1].strip("()") x1,y1 = point1.split(", ") x2,y2 = point2.split(", ") n = Node(data) n.x1 = float(x1) n.y1 = float(y1) n.x2 = float(x2) n.y2 = float(y2) return n def find(self,data): return self.findNode(self.root,data) def findNode(self,curNode,data): if(curNode is None): return "Given Line is Not Found!" elif(curNode.data==data): return curNode elif(curNode.data!=data): if(data in curNode.frontList): self.findNode(curNode.front,data) elif(data in curNode.backList): self.findNode(curNode.back,data) else: return "Given Line is Not Found!" def fnbOfNode(self,data): n = self.find(data) print("________",data,"_________") try: print("Front Lines:",n.frontList) print("Back Lines:",n.backList) except: print(n) def frontMostLine(self): self.frontLine(self.root) def frontLine(self,curNode): if(curNode.front is None): print("Front Most Line:",curNode.data) elif(curNode.front is not None): self.frontLine(curNode.front) def back2front(self,n): if(n is not None): self.back2front(n.back) print(n.data) self.back2front(n.front) def print(self): self.printGraph(self.root) def printGraph(self,curNode): if(curNode.data is not None): print("_____",curNode.data,"_______") print("Front Line Set:",curNode.frontList) print("Back Line Set:",curNode.backList) print("Same Line Set:",curNode.sameList) if(curNode.front is not None): self.printGraph(curNode.front) if(curNode.back is not None): self.printGraph(curNode.back) #________________________________ INPUTS ______________________________________# def run(): print("Please Enter Your Inputs: ") numOfLines = int(input()) startLine = int(input()) dataList = [] for i in range(0,numOfLines): dataList.append(input()) startData = startLine - 2 t = Tree() t.insert(dataList[startData-1]) for i in dataList: if(i == dataList[startData-1]): continue else: t.insert(i) return t """def commands(t): print("_______________ COMMANDS __________________") print("# Print All Lines: Enter 1") print("# Print Front Most Line: Enter 2") print("# Print Lines From Back to Front: Enter 3") print("# Get The Position Of A Given Line: Enter 4") print("# End The Programme: Enter 0") print("\n") while(True): print("Please Enter Your Command: ") a = int(input()) if(a == 1): t.print() print("\n") elif(a == 2): t.frontMostLine() print("\n") elif(a == 3): t.back2front(t.root) print("\n") elif(a == 4): print("Enter The Line Cordinates: ") data = input() t.fnbOfNode(data) print("\n") elif(a == 0): break else: print("Please Enter A Valid Command") print("\n")""" t = run() #commands(t) print("_____________ ALL LINES _________________") t.print() print("\n") print("____________ LINES FROM BACK TO FRONT _______________") t.back2front(t.root) print("\n") print("_____________ FRONT MOST LINE_____________") t.frontMostLine() print("\n")
[ "noreply@github.com" ]
ChamodAK.noreply@github.com
54652a9664135ada3b18f18d640f400d0fd64b12
de7dc8dd3d18b1f806b3722bd6b4cae4ef251192
/src/app/application.py
fa442e8af1821b800aba77744ce5831c433200d7
[]
no_license
prateekladha/LettuceFramework
f36c83f629cd35b1af280a2a12b5eed213310f14
4607379915be9d92775311d8d581462c619dc216
refs/heads/master
2021-01-11T22:38:40.489524
2017-01-15T07:28:07
2017-01-15T07:28:07
79,008,379
0
0
null
null
null
null
UTF-8
Python
false
false
137
py
''' Created on Jan 11, 2017 @author: admin ''' from flask import Flask app = Flask(__name__) if __name__ == "__main__": app.run()
[ "automation@wynk.in" ]
automation@wynk.in
b3078a4c673a74f0f819389f082bc49d16b08c7c
015a9fc9bf9ed97adb0a7a6b114542e164677d27
/app.py
9fdc984ac0b534d17662a292c3d1f2043b43b98b
[]
no_license
khosenag03/Medicare-Cost-Driver
841a0fcba1701b081925f5a88b72fcb2a15d1611
6a5b396e06b9796f1380a45337acfc27f50e3b05
refs/heads/master
2020-08-27T23:06:37.637978
2019-10-25T11:11:01
2019-10-25T11:11:01
217,514,755
1
0
null
null
null
null
UTF-8
Python
false
false
1,687
py
from flask import Flask, render_template, redirect, jsonify app = Flask(__name__) @app.route("/") def home(): # Find one record of data from the mongo database # Return template and data return render_template("dashboard.html") @app.route("/barchart") def Barcharts(): # Return template and data return render_template("Barchart.html") @app.route("/code") def coding(): # Return template and data return render_template("code.html") @app.route("/video") def Videos(): # Return template and data return render_template("video.html") @app.route("/maps") def Maps(): # Return template and data return render_template("Map.html") @app.route("/drugcost") def drgcosts(): # Return template and data return render_template("Drugcost.html") @app.route("/frequent") def FP(): # Return template and data return render_template("FruentlyP.html") @app.route("/insulins") def Insulin(): # Return template and data return render_template("Insulins.html") @app.route("/tiotropium") def Tiotro(): # Return template and data return render_template("Tiotropium.html") @app.route("/esomerprazole") def Esomerpra(): # Return template and data return render_template("Esomerprazole.html") @app.route("/rouvastatin") def Rouvasta(): # Return template and data return render_template("Rouvastatin.html") @app.route("/hydroco") def Narcotics(): # Return template and data return render_template("Hydrocodone.html") @app.route("/opioids") def Opio(): # Return template and data return render_template("Opioids.html") if __name__ == '__main__': app.run(debug=True)
[ "khosenag03@yahoo.com" ]
khosenag03@yahoo.com
4c8dd9c1fd3ee6a8f8f0d287907efeb067fe5a39
b960f2941d98aea060a53df65505956553e136ba
/py_postgressql/settings.py
d18a1bf2d833f6d9349238d8991f3d0fef73b3f0
[]
no_license
krobawsky/heroku_django_album_music
910205228cde0f3e501bdb127764c8b863d600c2
02397a5bf61e233535d41a4dbc2a9263d2bca4a1
refs/heads/master
2022-04-25T18:52:57.724815
2019-07-18T05:57:26
2019-07-18T05:57:26
197,520,790
0
0
null
2022-04-22T21:54:33
2019-07-18T05:55:18
Python
UTF-8
Python
false
false
3,653
py
""" Django settings for py_postgressql project. Generated by 'django-admin startproject' using Django 2.2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '-eusb@q(n84*4xrnhfv2d(x&wv=&e=6xvw8)e_9+4a(a%yd5he' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'pure-cove-58933.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'musiclist', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'py_postgressql.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'py_postgressql.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'd7s5u6vs73dnmi', 'USER': 'atqbgyylkdjkjq', 'PASSWORD': '31a8baf1d9752593b618c72771553ad23b2236cfdf9f139763332c49c3f4c410', 'HOST': 'ec2-23-21-186-85.compute-1.amazonaws.com', 'PORT': '5432', } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/'
[ "ricardo.berrospi@tecsup.edu.pe" ]
ricardo.berrospi@tecsup.edu.pe
2ad3e41a5dc74b833f13c1cac4d7f2b1c981e17f
63bc95150f6af526199454602e5689bfadc882ba
/07/ex7-16.py
0d84562866f12227b3bf4a1b951bd89770fdab82
[]
no_license
veenary/python-src
fd61d22a58d452ccb251402fecb0b7babd5372a7
d61374bc32b8ebe3b2be366a6de259680821a4e1
refs/heads/master
2023-03-17T10:07:27.704611
2021-03-10T01:31:56
2021-03-10T01:31:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
182
py
file = open('scores.txt', 'r', encoding='utf8') lines = file.readlines() print('scores.txt ํŒŒ์ผ์˜ ๋‚ด์šฉ : ') for line in lines : print(line, end='') file.close()
[ "park.cheongu@gmail.com" ]
park.cheongu@gmail.com
04efad6f06cfc161f3c5c68bbf358954a31fc0ae
4e353bf7035eec30e5ad861e119b03c5cafc762d
/QtGui/QLabel.py
6ccbf0d08a2516d66a727ff799df64b97d5ceb8b
[]
no_license
daym/PyQt4-Stubs
fb79f54d5c9a7fdb42e5f2506d11aa1181f3b7d5
57d880c0d453641e31e1e846be4087865fe793a9
refs/heads/master
2022-02-11T16:47:31.128023
2017-10-06T15:32:21
2017-10-06T15:32:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,098
py
# encoding: utf-8 # module PyQt4.QtGui # from C:\Python27\lib\site-packages\PyQt4\QtGui.pyd # by generator 1.145 # no doc # imports import PyQt4.QtCore as __PyQt4_QtCore from QFrame import QFrame class QLabel(QFrame): """ QLabel(QWidget parent=None, Qt.WindowFlags flags=0) QLabel(QString, QWidget parent=None, Qt.WindowFlags flags=0) """ def actionEvent(self, *args, **kwargs): # real signature unknown pass def alignment(self): # real signature unknown; restored from __doc__ """ QLabel.alignment() -> Qt.Alignment """ pass def buddy(self): # real signature unknown; restored from __doc__ """ QLabel.buddy() -> QWidget """ return QWidget def changeEvent(self, QEvent): # real signature unknown; restored from __doc__ """ QLabel.changeEvent(QEvent) """ pass def childEvent(self, *args, **kwargs): # real signature unknown pass def clear(self): # real signature unknown; restored from __doc__ """ QLabel.clear() """ pass def closeEvent(self, *args, **kwargs): # real signature unknown pass def connectNotify(self, *args, **kwargs): # real signature unknown pass def contextMenuEvent(self, QContextMenuEvent): # real signature unknown; restored from __doc__ """ QLabel.contextMenuEvent(QContextMenuEvent) """ pass def create(self, *args, **kwargs): # real signature unknown pass def customEvent(self, *args, **kwargs): # real signature unknown pass def destroy(self, *args, **kwargs): # real signature unknown pass def disconnectNotify(self, *args, **kwargs): # real signature unknown pass def dragEnterEvent(self, *args, **kwargs): # real signature unknown pass def dragLeaveEvent(self, *args, **kwargs): # real signature unknown pass def dragMoveEvent(self, *args, **kwargs): # real signature unknown pass def drawFrame(self, *args, **kwargs): # real signature unknown pass def dropEvent(self, *args, **kwargs): # real signature unknown pass def enabledChange(self, *args, **kwargs): # real signature unknown pass def enterEvent(self, *args, **kwargs): # real signature unknown pass def event(self, QEvent): # real signature unknown; restored from __doc__ """ QLabel.event(QEvent) -> bool """ return False def focusInEvent(self, QFocusEvent): # real signature unknown; restored from __doc__ """ QLabel.focusInEvent(QFocusEvent) """ pass def focusNextChild(self, *args, **kwargs): # real signature unknown pass def focusNextPrevChild(self, bool): # real signature unknown; restored from __doc__ """ QLabel.focusNextPrevChild(bool) -> bool """ return False def focusOutEvent(self, QFocusEvent): # real signature unknown; restored from __doc__ """ QLabel.focusOutEvent(QFocusEvent) """ pass def focusPreviousChild(self, *args, **kwargs): # real signature unknown pass def fontChange(self, *args, **kwargs): # real signature unknown pass def hasScaledContents(self): # real signature unknown; restored from __doc__ """ QLabel.hasScaledContents() -> bool """ return False def hasSelectedText(self): # real signature unknown; restored from __doc__ """ QLabel.hasSelectedText() -> bool """ return False def heightForWidth(self, p_int): # real signature unknown; restored from __doc__ """ QLabel.heightForWidth(int) -> int """ return 0 def hideEvent(self, *args, **kwargs): # real signature unknown pass def indent(self): # real signature unknown; restored from __doc__ """ QLabel.indent() -> int """ return 0 def inputMethodEvent(self, *args, **kwargs): # real signature unknown pass def keyPressEvent(self, QKeyEvent): # real signature unknown; restored from __doc__ """ QLabel.keyPressEvent(QKeyEvent) """ pass def keyReleaseEvent(self, *args, **kwargs): # real signature unknown pass def languageChange(self, *args, **kwargs): # real signature unknown pass def leaveEvent(self, *args, **kwargs): # real signature unknown pass def linkActivated(self, *args, **kwargs): # real signature unknown """ QLabel.linkActivated[QString] [signal] """ pass def linkHovered(self, *args, **kwargs): # real signature unknown """ QLabel.linkHovered[QString] [signal] """ pass def margin(self): # real signature unknown; restored from __doc__ """ QLabel.margin() -> int """ return 0 def metric(self, *args, **kwargs): # real signature unknown pass def minimumSizeHint(self): # real signature unknown; restored from __doc__ """ QLabel.minimumSizeHint() -> QSize """ pass def mouseDoubleClickEvent(self, *args, **kwargs): # real signature unknown pass def mouseMoveEvent(self, QMouseEvent): # real signature unknown; restored from __doc__ """ QLabel.mouseMoveEvent(QMouseEvent) """ pass def mousePressEvent(self, QMouseEvent): # real signature unknown; restored from __doc__ """ QLabel.mousePressEvent(QMouseEvent) """ pass def mouseReleaseEvent(self, QMouseEvent): # real signature unknown; restored from __doc__ """ QLabel.mouseReleaseEvent(QMouseEvent) """ pass def moveEvent(self, *args, **kwargs): # real signature unknown pass def movie(self): # real signature unknown; restored from __doc__ """ QLabel.movie() -> QMovie """ return QMovie def openExternalLinks(self): # real signature unknown; restored from __doc__ """ QLabel.openExternalLinks() -> bool """ return False def paintEvent(self, QPaintEvent): # real signature unknown; restored from __doc__ """ QLabel.paintEvent(QPaintEvent) """ pass def paletteChange(self, *args, **kwargs): # real signature unknown pass def picture(self): # real signature unknown; restored from __doc__ """ QLabel.picture() -> QPicture """ return QPicture def pixmap(self): # real signature unknown; restored from __doc__ """ QLabel.pixmap() -> QPixmap """ return QPixmap def receivers(self, *args, **kwargs): # real signature unknown pass def resetInputContext(self, *args, **kwargs): # real signature unknown pass def resizeEvent(self, *args, **kwargs): # real signature unknown pass def selectedText(self): # real signature unknown; restored from __doc__ """ QLabel.selectedText() -> QString """ pass def selectionStart(self): # real signature unknown; restored from __doc__ """ QLabel.selectionStart() -> int """ return 0 def sender(self, *args, **kwargs): # real signature unknown pass def senderSignalIndex(self, *args, **kwargs): # real signature unknown pass def setAlignment(self, Qt_Alignment): # real signature unknown; restored from __doc__ """ QLabel.setAlignment(Qt.Alignment) """ pass def setBuddy(self, QWidget): # real signature unknown; restored from __doc__ """ QLabel.setBuddy(QWidget) """ pass def setIndent(self, p_int): # real signature unknown; restored from __doc__ """ QLabel.setIndent(int) """ pass def setMargin(self, p_int): # real signature unknown; restored from __doc__ """ QLabel.setMargin(int) """ pass def setMovie(self, QMovie): # real signature unknown; restored from __doc__ """ QLabel.setMovie(QMovie) """ pass def setNum(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads """ QLabel.setNum(float) QLabel.setNum(int) """ pass def setOpenExternalLinks(self, bool): # real signature unknown; restored from __doc__ """ QLabel.setOpenExternalLinks(bool) """ pass def setPicture(self, QPicture): # real signature unknown; restored from __doc__ """ QLabel.setPicture(QPicture) """ pass def setPixmap(self, QPixmap): # real signature unknown; restored from __doc__ """ QLabel.setPixmap(QPixmap) """ pass def setScaledContents(self, bool): # real signature unknown; restored from __doc__ """ QLabel.setScaledContents(bool) """ pass def setSelection(self, p_int, p_int_1): # real signature unknown; restored from __doc__ """ QLabel.setSelection(int, int) """ pass def setText(self, QString): # real signature unknown; restored from __doc__ """ QLabel.setText(QString) """ pass def setTextFormat(self, Qt_TextFormat): # real signature unknown; restored from __doc__ """ QLabel.setTextFormat(Qt.TextFormat) """ pass def setTextInteractionFlags(self, Qt_TextInteractionFlags): # real signature unknown; restored from __doc__ """ QLabel.setTextInteractionFlags(Qt.TextInteractionFlags) """ pass def setWordWrap(self, bool): # real signature unknown; restored from __doc__ """ QLabel.setWordWrap(bool) """ pass def showEvent(self, *args, **kwargs): # real signature unknown pass def sizeHint(self): # real signature unknown; restored from __doc__ """ QLabel.sizeHint() -> QSize """ pass def tabletEvent(self, *args, **kwargs): # real signature unknown pass def text(self): # real signature unknown; restored from __doc__ """ QLabel.text() -> QString """ pass def textFormat(self): # real signature unknown; restored from __doc__ """ QLabel.textFormat() -> Qt.TextFormat """ pass def textInteractionFlags(self): # real signature unknown; restored from __doc__ """ QLabel.textInteractionFlags() -> Qt.TextInteractionFlags """ pass def timerEvent(self, *args, **kwargs): # real signature unknown pass def updateMicroFocus(self, *args, **kwargs): # real signature unknown pass def wheelEvent(self, *args, **kwargs): # real signature unknown pass def windowActivationChange(self, *args, **kwargs): # real signature unknown pass def winEvent(self, *args, **kwargs): # real signature unknown pass def wordWrap(self): # real signature unknown; restored from __doc__ """ QLabel.wordWrap() -> bool """ return False def __init__(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads pass
[ "thekewlstore@gmail.com" ]
thekewlstore@gmail.com
ccd01bbc8d5a270149654c4210f71bd079638a50
d7fd2e76bfcb726ad151563caf8ca9c46e82524b
/useful_np_feature_finder.py
17037dcd262744592702ecc9bbbd0e0695a33b76
[]
no_license
AidaAmini/MathProblems
49d3ed874fdf655a1709c600a1bd4d0895bc27f4
74b92e6a14d78af893c6a47bb29a2d794a9cef74
refs/heads/master
2020-06-16T10:08:23.512127
2017-02-02T06:46:51
2017-02-02T06:46:51
75,236,285
3
0
null
null
null
null
UTF-8
Python
false
false
4,267
py
from entity_properties import entity_properties class useful_np_feature_finder: question_prop = entity_properties() appropriate_features = [] feature_file_path = '' def __init__(self, question_prop): self.question_prop = question_prop def find_demanded_features(self): input_file = open (self.feature_file_path, 'r') feature_line = input_file.readline(); parts = feature_line.split(',') def convert_binary_to_fv(self, binary_string, starting_index, total_size): while len(binary_string) < total_size: binary_string = '0' + binary_string result = '' for i in range(0, total_size): result = result + str(starting_index + i) + ':' + binary_string[i] if i < total_size-1: result = result + ' ' return result def appropriate_feature_finder_list(self, feature_list, np1): feature_list.append(self.question_prop.in_noun_phrases_in_list(self.question_prop.related_words_with_conjunction, np1)) # feature_list.append(self.question_prop.in_noun_phrases_in_list(self.question_prop.plural_used_nouns, np1)) # binary_string = self.question_prop.find_pos_label(np1) # for i in range(0, 1): # feature_list.append(int(binary_string[i])) # res_unit = self.question_prop.find_unit_type(np1) # if res_unit == '000': # feature_list.append(1) # else: # feature_list.append(0) feature_list.append(self.question_prop.in_noun_phrases_in_list(self.question_prop.place_noun_phrases, np1)) # feature_list.append(self.question_prop.check_if_np_contains_number(np1)) feature_list.append(self.question_prop.check_for_known_word(np1)) feature_list.append(self.question_prop.in_noun_phrases_in_list(self.question_prop.named_entity_nouns, np1)) # feature_list.append(self.question_prop.in_noun_phrases_in_list(self.question_prop.same_head_noun_phrases, np1)) feature_list.append(self.question_prop.has_percent(np1)) # feature_list.append(self.question_prop.check_if_np_contains_number_anywhere(np1)) if '-' in np1: feature_list.append(1) else: feature_list.append(0) if len(np1.split(' ')) > 4: feature_list.append(1) else: feature_list.append(0) return feature_list def approriate_feature_found(self, start_index, np1): result = '' # print self.question_prop.related_words_with_conjunction result = result + (str(start_index + 1) +':'+str(self.question_prop.in_noun_phrases_in_list(self.question_prop.related_words_with_conjunction, np1)) + ' ') result = result + (str(start_index + 2) +':'+str(self.question_prop.in_noun_phrases_in_list(self.question_prop.plural_used_nouns, np1)) + ' ') binary_string = self.question_prop.find_pos_label(np1) result = result + self.convert_binary_to_fv(self.question_prop.find_pos_label(np1), start_index + 3, 2) + ' ' res_unit = self.question_prop.find_unit_type(np1) if res_unit == '000': result = result + str(start_index + 5) + ':0 ' else: result = result + str(start_index + 5) + ':1 ' # result = result + str(start_index + 15) +':'+ str(self.question_prop.check_if_np_contains_number(np1)) + ' ' result = result + str(start_index + 6) +':'+str(self.question_prop.in_noun_phrases_in_list(self.question_prop.place_noun_phrases, np1)) + ' ' result = result + str(start_index + 7) + ':'+ self.question_prop.check_for_known_word(np1) + ' ' result = result + (str(start_index + 8) +':'+str(self.question_prop.in_noun_phrases_in_list(self.question_prop.named_entity_nouns, np1)) + ' ') # print self.question_prop.same_head_noun_phrases result = result + (str(start_index + 9) +':'+str(self.question_prop.in_noun_phrases_in_list(self.question_prop.same_head_noun_phrases, np1)) + ' ') result = result + str(start_index + 10) + ':'+ self.question_prop.has_percent(np1) + ' ' result = result + str(start_index + 11) +':'+ str(self.question_prop.check_if_np_contains_number_anywhere(np1)) + ' ' if '-' in np1: result = result + str(start_index + 12) + ':1 ' else: result = result + str(start_index + 12) + ':0 ' if len(np1.split(' ')) > 4: result = result + str(start_index + 13) + ':1' else: result = result + str(start_index + 13) + ':0' return result, start_index + 14 def list_features_toString(self, start_index, np1): return self.approriate_feature_found(start_index, np1)
[ "amini91@cs.washington.edu" ]
amini91@cs.washington.edu
cdeef9da2fa6eea228fbe9c905adc1575cf00a32
05014e48fef45c0105060f881f5a64f7b4c37618
/News.py
b8ad560621ad38313fbc083b9f1e8601e400d8f1
[]
no_license
houyen/TeleBot
018bdc2baaeafa7ac26bf2b4e1fbe3c29c5464ba
19a2cb412e0e8dad81da9425b44ba12c69326ca0
refs/heads/main
2023-08-06T11:36:59.586894
2021-10-04T14:50:32
2021-10-04T14:50:32
409,940,461
0
0
null
null
null
null
UTF-8
Python
false
false
1,083
py
import requests from bs4 import BeautifulSoup import json from Article import Article baseUrl = "https://vnexpress.net/" def GetNews(limit_news = 20): # Tแบกo biแบฟn limit_news ฤ‘แปƒ lแบฅy sแป‘ lฦฐแปฃng tin mร  mรฌnh cแบงn thรดi s = requests.Session() # Store sesstion lแบกi response = s.get(baseUrl) # Thแปฑc hiแป‡n Get request soup = BeautifulSoup(response.content, 'html.parser') # ฤฦฐa vร o biแบฟn soup chuแบฉn bแป‹ bรณc tรกch dแปฏ liแป‡u article = soup.select("article.item-news", limit=limit_news) # Tรกch dแปฏ liแป‡u phแบงn thแบป article ra listArticle = [] for element in article: title = element.select("h3.title-news > a") # Lแบฅy phแบงn thแบป chแปฉa title description = element.select("p.description > a") # Lแบฅy phแบงn thแบป chแปฉa description for x in range(len(title)): # serialize object nร y lแบกi thร nh json ฤ‘แปƒ lแบฅy dแปฏ liแป‡u dแป… dร ng hฦกn listArticle.append(json.dumps(Article(title[x]['title'], title[x]['href'], description[x].text).__dict__, ensure_ascii=False)) return listArticle
[ "34957287+houyen@users.noreply.github.com" ]
34957287+houyen@users.noreply.github.com
edb00308284d3b6b5dda9516e7d81a471fb2c159
c4ab9a70f0c4c6fc465d53b839b3f0abb6c90d03
/briapi_client_python/error.py
5a3c11de50b2161165314c66616ddd11131a2a1a
[]
no_license
afifnz/briapi-client-python
cf5df0c258e12479511dc24036e8329f3f8498a0
ac5533d27475fc4d8ff023344fda13eae23d2bc0
refs/heads/master
2023-02-04T05:09:05.199574
2020-12-23T10:24:38
2020-12-23T10:24:38
323,869,697
1
0
null
null
null
null
UTF-8
Python
false
false
423
py
class JSONDecodeError(Exception): pass class APIError(Exception): def __init__(self, message, api_response_dict=None, http_status_code=None, raw_http_client_data=None): self.message = message self.api_response_dict = api_response_dict self.http_status_code = int(http_status_code) self.raw_http_client_data = raw_http_client_data def __str__(self): return self.message
[ "afifnz@gmail.com" ]
afifnz@gmail.com
a581293dcad0c0e7a8a3f1cdce4dd35059f04fe4
1714f2c09d930e5916c5fec711d4f3dc3b46e878
/crystal_identification.py
7a99e6168daa6672593a3e03ddae1fb88c0462f2
[]
no_license
merrygoat/fourier-crystal-detection
4e87e56e0c0fc5202a083889e8beb67ee7258312
2cfa39892fc08df80816669bb137e3a457de9310
refs/heads/master
2020-03-18T10:04:57.992016
2018-05-24T11:56:57
2018-05-24T11:56:57
134,596,067
0
0
null
null
null
null
UTF-8
Python
false
false
11,351
py
import numpy as np import matplotlib.pyplot as plt import matplotlib from skimage.feature import peak_local_max def get_fourier_transform_of_slice(image): """ Returns the real valued Fourier transform of an image :param image: the image to apply the Fourier transform to :return: The Fourier transform of the image """ fft = np.fft.fft2(image) power_spectrum = get_2d_power_spectrum(fft) return np.fft.fftshift(power_spectrum) def get_2d_power_spectrum(image): """ Return the power specrum of a fourier tranform :param image: The real and complex fourier transform :return: The power spectrum of the Fourier transform """ return image.real ** 2 + image.imag ** 2 def crop_image(image, cut_size): """ Returns a subsection of an array representing an image :param image: The image as a numpy array :param cut_size: The fraction to cut from each side of the image :return: The cropped image as a numpy array """ cut_high = (1 - cut_size) x_min = int(image.shape[0] * cut_size) x_max = int(image.shape[0] * cut_high) y_min = int(image.shape[1] * cut_size) y_max = int(image.shape[1] * cut_high) cropped_image = image[x_min:x_max, y_min:y_max] return cropped_image def find_maxima_in_image(image, minimum_intensity_threshold, minimum_peak_separation_distance): """ Finds peaks within an image :param image: The original image :param minimum_intensity_threshold: The minimum value of a peak relative to the maximum intensity of the image :param minimum_peak_separation_distance: The minimum seperation of detected peaks :return: ndarray of coordinates corresponding to peaks in the image """ maxima = peak_local_max(image, min_distance=minimum_peak_separation_distance, threshold_rel=minimum_intensity_threshold) maxima = remove_central_peak(image, maxima) return maxima def remove_central_peak(image, maxima): """ The Fourier transform always has a peak in the middle. We are not interested in this peak so remove it from the list of maxima. :param image: ndarray of the real valued Fourier transform of an image :param maxima: ndarray of coordinates corresponding to peaks in the image :return: ndarray corresponding to coordinates of peaks in the image """ num_maxima = len(maxima) # We only care if there might be 4 or 6 crystal maxima if 3 < num_maxima < 8: central_coordinate = get_center_of_image(image.shape) revised_maxima = [peak for peak in list(maxima) if np.all(peak != central_coordinate)] return np.array(revised_maxima) else: return maxima def get_ring_intensity(image, maxima, pixel_distances, center_coordinate): """ Calculates the relative intensity of the discovered peaks and the sampled intensity at the same distance from the centre of the fourier transform. Gives us a way of checking for "liquidity" :param image: An ndarray represnting an image :param maxima: a list of tuples representing coordinates of maxima :param pixel_distances: An array giving the distance of each pixel from the center of the image :param center_coordinate: The coordinate of the center of image :return: The ratio between the intenisty of the peaks and the radial average of the intensity at the same distance from the center as the peaks """ average_peak_intensity = np.average(image[(maxima[:, 0], maxima[:, 1])]) # average distance between center and peaks, this will be our ring radius average_distance = np.average(np.linalg.norm((maxima - center_coordinate), axis=1)) mask = np.logical_and(pixel_distances > average_distance - 0.5, pixel_distances < average_distance + 0.5) ring_intensity = np.average(image[mask]) intensityratio = np.average(ring_intensity) / average_peak_intensity return intensityratio def get_center_of_image(image_shape): """ Return the coordinates representing the center of an image :param image_shape: An tuple representing the size of an image :return: A tuple representing the coordinates of the center of image """ center_coordinate = np.rint(np.array(image_shape) / 2.0) return center_coordinate def scanfourier(original_image, minimum_intensity_threshold, size_of_scan_box, ring_threshold, rastering_interval, image_crop_factor): """ The main loop. Raster over an image and determine whether the subsections are crystalline. :param original_image: The original image to process :param minimum_intensity_threshold: The minimum intensity of a peak in fourier transform :param size_of_scan_box: The size of the region which is Fourier transformed :param ring_threshold: The threshold defining the boundary between crystal and liquid regions :param rastering_interval: The interval in pixels over which to raster the Fourier transform :param image_crop_factor: A float giving the proportion of the image to cut off each side :return: """ cropped_center, minimum_peak_separation_distance, pixel_distances = setup_fourier_scan(image_crop_factor, size_of_scan_box) num_x_rasters = int((original_image.shape[0] - size_of_scan_box) / rastering_interval) num_y_rasters = int((original_image.shape[1] - size_of_scan_box) / rastering_interval) results_array = np.zeros((num_x_rasters, num_y_rasters)) for x_bin in range(num_x_rasters): for y_bin in range(num_y_rasters): ft_of_subimage = get_ft_of_subimage(image_crop_factor, original_image, rastering_interval, size_of_scan_box, x_bin, y_bin) with np.errstate(divide='ignore'): ft_of_subimage = np.log10(ft_of_subimage) maxima = find_maxima_in_image(ft_of_subimage, minimum_intensity_threshold, minimum_peak_separation_distance) crystal_type = classify_image_region(ft_of_subimage, maxima, ring_threshold, pixel_distances, cropped_center) results_array[x_bin, y_bin] = crystal_type return results_array def setup_fourier_scan(image_crop_factor, size_of_scan_box): """ Initialise some values to be used in finding and classifying maxima :param image_crop_factor: A float specifying how much to crop off each side of the fourier transformed image subsection prior to identifying peaks :param size_of_scan_box: The size of the subimage which is Fourier transformed :return: cropped_center - The coordinates of the center of the cropped box :return: minimum_peak_separation_distance - The minimum separation in pixels of identified peaks in the fourier transform :return: pixel_distances - An array giving the distance of each pixel from the center of the image """ minimum_peak_separation_distance = int(size_of_scan_box / 20.) x_min = int(size_of_scan_box * image_crop_factor) x_max = int(size_of_scan_box * (1 - image_crop_factor)) cropped_image_size = x_max - x_min cropped_center = get_center_of_image([cropped_image_size, cropped_image_size]) binsize = 1 y, x = np.indices([cropped_image_size, cropped_image_size]) pixel_distances = np.hypot(x - cropped_center[0], y - cropped_center[1]) / binsize return cropped_center, minimum_peak_separation_distance, pixel_distances def get_ft_of_subimage(image_crop_factor, original_image, rastering_interval, size_of_scan_box, x_bin, y_bin): """ Get a subsection of an image, get the Fourier transform then crop the image :param image_crop_factor: A float giving the proportion of the image to cut off each side :param original_image: An ndarray representing the original image :param rastering_interval: The interval in pixels between rastered images :param size_of_scan_box: The size of the sub-image used for the Fourier transform :param x_bin: The bin number of the current sub-image :param y_bin: The bin number of the current sub-image :return: The cropped Fourier transform of the image subection """ subimage_minima = np.array((x_bin * rastering_interval, y_bin * rastering_interval)) subimgae_maxima = subimage_minima + size_of_scan_box subimage = original_image[subimage_minima[0]:subimgae_maxima[0], subimage_minima[1]:subimgae_maxima[1]] ft_of_subimage = get_fourier_transform_of_slice(subimage) cropped_ft_of_subimage = crop_image(ft_of_subimage, image_crop_factor) return cropped_ft_of_subimage def classify_image_region(image, maxima, ring_threshold, pixel_distances, cropped_center): """ Classify the subsection of the image depending on the number of maxima there are :param image: An ndarray representing an image :param maxima: ndarray of coordinates corresponding to peaks in the image :param ring_threshold: A peak intesnity threshold above which a crystal is identified :param pixel_distances: An array giving the distance of each pixel from the center of the image :param cropped_center: The coordinate of the center of image """ number_of_maxima = maxima.shape[0] if number_of_maxima == 0: # No maxima so just a liquid return 0 else: if number_of_maxima == 6: ring_intensity = get_ring_intensity(image, maxima, pixel_distances, cropped_center) if ring_intensity < ring_threshold: # clear hexagonal crystal return 6 else: # potential boundary between hex+liquid return 1 elif number_of_maxima == 4: ring_intensity = get_ring_intensity(image, maxima, pixel_distances, cropped_center) if ring_intensity < ring_threshold: # clear cross crystal return 4 else: # potential boundary between cross+liquid return 0.5 else: # No maxima so just a liquid return 0 def plot_result(array): """ Convert the result to a 2D image representation :param array: The result of the analysis """ cmap = matplotlib.colors.ListedColormap(['darkblue', 'skyblue', 'cadetblue', 'limegreen', 'orangered']) # plot, 6 = hexagonal crystal, 4 = cross crystal 1.0 = hex+liquid ring, 0.5 = cross + liquid ring, 0.0 = liquid (neither 4 nor 6 peaks detected) bounds = [-0.4, 0.4, 0.6, 1.4, 5.9, 6.1] norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N) fig = plt.imshow(array, interpolation='nearest', cmap=cmap, norm=norm) plt.colorbar(fig, cmap=cmap, norm=norm, boundaries=bounds, ticks=[0, 0.5, 1, 4, 6]) plt.savefig("crystal_measure.png") def load_image(filename): """ Open an image as an array :param filename: The path of the image to open :return: An ndarray of the image """ image = plt.imread(filename) if len(image.shape) == 3: image = image[:, :, 0] return image def main(): filename = 'sample_image.tif' rastering_interval = 2 ring_threshold = 0.9 size_of_scan_box = 128 minimum_peak_intensity_threshold = 0.5 image_crop_factor = 0.35 image = load_image(filename) array = scanfourier(image, minimum_peak_intensity_threshold, size_of_scan_box, ring_threshold, rastering_interval, image_crop_factor) plot_result(array) if __name__ == '__main__': main()
[ "merrygoat@users.noreply.github.com" ]
merrygoat@users.noreply.github.com
e881bd578e8cbb24291806ad1ff1a0d23c3c1f5d
46e19784eb5aac4d560926b1536694cbf25d36cb
/perfis/migrations/0001_initial.py
2175ce4cfdb3504f142ae54ca1259d4f3379125e
[]
no_license
Mateusallz1/Connected_In
ffbe203e8abd48a2ae850c7885d4ede4a9d9a28c
a5622bd14c0baeeeadd5a08a3727b8b195825b0d
refs/heads/master
2023-01-02T23:22:11.751775
2020-10-31T17:17:43
2020-10-31T17:17:43
298,578,214
0
0
null
null
null
null
UTF-8
Python
false
false
677
py
# Generated by Django 3.1 on 2020-09-24 12:20 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Perfil', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=255)), ('email', models.EmailField(max_length=255)), ('telefone', models.CharField(max_length=15)), ('nome_empresa', models.CharField(max_length=255)), ], ), ]
[ "trafalgarmateus@gmail.com" ]
trafalgarmateus@gmail.com
1cd7cce1c30d6e22621fd03c616101c46452f638
1f2808f1c263828838518d47885d38d3523c4b61
/ะŸะฐะผัั‚ะบะฐ.py
de6bfb0c080fad7850cf91f01bf987b1982abe34
[]
no_license
jbigor/python
549bec723c3144fdcf0f13a181275e664c2df5cc
413d5d08498942dbf520af6261c65d4ff603f5f3
refs/heads/master
2020-05-17T23:12:55.988913
2019-08-27T16:15:00
2019-08-27T16:15:00
184,024,941
0
0
null
null
null
null
UTF-8
Python
false
false
3,440
py
import os import psutil import sys import shutil def duplicate_file(filename): if os.path.isfile(filename): newfile = filename + '.dupl' shutil.copy(filename, newfile) if os.path.exists(newfile): print("ะคะฐะนะป", newfile, "ะฑั‹ะป ัƒัะฟะตัˆะฝะพ ัะพะทะดะฐะฝ") return True else: print("ERROR") return False def del_dublicats(dirname): file_list = os.listdir(dirname) doble_count = 0 for f in file_list: fullname = os.path.join(dirname, f) if fullname.endswith('.dupl'): os.remove(fullname) if not os.path.exists(fullname): doble_count += 1 print("ั„ะฐะนะป", fullname, "ะฑั‹ะป ัƒัะฟะตัˆะฝะพ ัƒะดะฐะปะตะฝ") return doble_count def sys_info(): print("ะšะพะปะธั‡ะตัั‚ะฒะพ ะฟั€ะพั†ะตััะพั€ะพะฒ: ", psutil.cpu_count()) print("ะŸะปะฐั‚ั„ะพั€ะผะฐ:", sys.platform) print("ะšะพะดะธั€ะพะฒะบะฐ ั„ะฐะนะปะพะฒะพะน ัะธัั‚ะตะผั‹: ", sys.getdefaultencoding()) print("ะขะตะบัƒั‰ะฐั ะดะธั€ะตะบั‚ะพั€ะธั: ", os.getcwd()) print("ะขะตะบัƒั‰ะธะน ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ: ", os.getlogin()) print("ะกะฒะพะฑะพะดะฝะพะต ะผะตัั‚ะพ ะฝะฐ ะดะธัะบะต: ", psutil.disk_usage('/')) print("ะŸะพะปัŒะทะพะฒะฐั‚ะตะปะธ ะฒ ัะธัั‚ะตะผะต:", psutil.users()) return 0 input("username:") input("root@192.168.3.52's password:") print("Connection established. To escape to local shej ll, press 'Ctrl+Alt+]'") answer = '' while answer != 'no': answer = input("Are you sure you want to continue connecting (yes/no)?") if answer == 'yes': print("Welcom to Ubuntu 16.04.5 LTS") print("Bitrix virtual appliance version 7.3.3") print("Pool Configuration manager on this host") print("1. ะกะฟะธัะตะบ ั„ะฐะนะปะพะฒ ะฒั‹ะฒะตัั‚ะธ") print("2. ะ’ั‹ะฒะตัั‚ะธ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ัะธัั‚ะตะผะต") print("3. ะ’ั‹ะฒะตัั‚ะธ ัะฟะธัะตะบ ะฟั€ะพั†ะตััะพะฒ") print("4. ะ”ัƒะฑะปะธั€ะพะฒะฐะฝะธะต ั„ะฐะนะปะพะฒ ะฒ ั‚ะตะบัƒั‰ะตะน ะดะธั€ะตะบั‚ะพั€ะธ: ") print("5. ะ”ัƒะฑะปะธั€ะพะฒะฐะฝะธะต ัƒะบะฐะทะฐะฝะฝั‹ะน ั„ะฐะนะปะพะฒ") print("6. ะฃะดะฐะปะธั‚ัŒ ะดัƒะฑะปะตะบะฐั‚ั‹ ") do = int(input("Plesse number:")) if do == 1: print(os.listdir()) elif do == 2: sys_info() elif do == 3: print(psutil.pids()) elif do == 4: print("ะ”ัƒะฑะปะธั€ะพะฒะฐะฝะธะต ั„ะฐะนะปะพะฒ ะฒ ั‚ะตะบัƒัˆะตะน ะดะธั€ะตะบั‚ะพั€ะธะธ") file_list = os.listdir() i = 0 while i < len(file_list): duplicate_file(file_list[i]) i += 1 elif do == 5: print("ะ”ัƒะฑะปะธั€ะพะฒะฐะฝะธะต ั„ะฐะนะปะพะฒ ะฒ ั‚ะตะบัƒัˆะตะน ะดะธั€ะตะบั‚ะพั€ะธะธ") filename = input("ะฃะบะฐะถะธั‚ะต ะธะผั ั„ะฐะนะปะฐ:") duplicate_file(filename) elif do == 6: print("ะฃะดะฐะปะตะฝะธะต ะดัƒะฑะปะธะบะฐั‚ะพะฒ ั„ะฐะนะปะพะฒ ะฒ ั‚ะตะบัƒัˆะตะน ะดะธั€ะตะบั‚ะพั€ะธะธ") dirname = input("ะฃะบะฐะถะธั‚ะต ะธะผั ั„ะฐะนะปะฐ:") count = del_dublicats(dirname) print("-- ะฃะดะฐะปะตะฝะพ ั„ะฐะนะปะพะฒ: ", count) else: pass elif answer == 'no': print("Close sesion") else: print("Authentication failed.") input("ะšะพะฝะตั† ะฟั€ะพะณั€ะฐะผะผั‹")
[ "admin@naocompany.ru" ]
admin@naocompany.ru
2f7b6c64db101cd44494a732066aa6347f0d6cae
2189a4ee026cb9bc7122caa88cf980910d260b86
/Scripting/images.py
291f6c297ccca502ba32af8332646dfbdedebe57
[]
no_license
osajas/Python
c7e5f0583128ff365ebfda3a42183791b0e06bf1
07abe4e01569a9c6d9e692ea54c244f976e066a4
refs/heads/master
2023-02-24T12:46:51.704937
2021-01-20T17:51:22
2021-01-20T17:51:22
277,341,447
0
1
null
2021-01-20T17:51:24
2020-07-05T16:31:28
Python
UTF-8
Python
false
false
247
py
from PIL import Image, ImageFilter img = Image.open('./Pokemon/original.jpg') print(img.size) new_image = img.resize((400, 400)) new_image.save("astro.jpg") print(new_image.size) img.thumbnail((400, 400)) img.save("thumbnail.jpg") print(img.size)
[ "omafraji@gmail.com" ]
omafraji@gmail.com
ced832e964bd27c3e0e78afe6beb2d5c5104bd31
5234835e7b059acc5c69c7c731e7aa91dae7e73a
/app/__init__.py
e5b1397d8dbace91d5ef4a5c5e728cb52b50f08e
[]
no_license
devahmedshendy/citc_lab
ae2d526bd53a4f27bcb2a064506e2a98f6feea16
45198557a1fa6ba475659b513a9fd26acbe73647
refs/heads/master
2023-02-08T01:56:02.400043
2017-07-05T11:19:08
2017-07-05T11:19:08
93,545,375
0
0
null
2023-02-02T03:11:52
2017-06-06T17:29:05
HTML
UTF-8
Python
false
false
594
py
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_assets import Environment from flask_login import LoginManager from flask_principal import Principal from config import app_config app = Flask(__name__) app.secret_key = 'this_is_my_secret_key' app.config.update(app_config) db = SQLAlchemy(app) db.__init__(app) login_manager = LoginManager() login_manager.login_view = 'login' login_manager.init_app(app) assets = Environment(app) # load the extension principals = Principal(app) from app import models from app.routes import main, users, patients, analyzes
[ "dev.ahmed.shendy@gmail.com" ]
dev.ahmed.shendy@gmail.com
48a5510da114a4e37bb1873378350e127224ad3a
fd0f67fee6af2d701ef43658d6e0b49af0a7e0cf
/web_6.py
a039a7c78b90b3896e666732140988621bb44135
[]
no_license
zhaoquanmo/webauto
c4560ea3d7e5c65ef1c9b900949035ff5156da3b
cd64dec5989dbd09a97ffce77e2aed9cb11f4643
refs/heads/master
2020-05-30T14:39:08.315695
2019-06-02T09:50:15
2019-06-02T09:50:15
189,566,274
1
0
null
null
null
null
UTF-8
Python
false
false
964
py
from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys import time # ๅˆ›ๅปบไธ€ไธชๆต่งˆๅ™จ driver = webdriver.Chrome() driver.maximize_window() # ่ฎฟ้—ฎไบฌไธœ url = "https://cn.bing.com/" driver.get(url) # # ๅฎšไฝๅ…ƒ็ด  # el_list = driver.find_elements_by_id("cate_menu_item") # # ็งปๅŠจ้ผ ๆ ‡ # for i in el_list: # ActionChains(driver).move_to_element(i).perform() # time.sleep(2) # print("ๆ‰ง่กŒๆˆๅŠŸ๏ผš%s" % i) # ๅฎšไฝๅ…ƒ็ด  el = driver.find_element_by_id("sb_form_q") # ่พ“ๅ…ฅๅ†…ๅฎน el.send_keys("selenium") # ๅ…จ้€‰ el.send_keys(Keys.CONTROL, 'a') time.sleep(2) # ๅ‰ชๅˆ‡ el.send_keys(Keys.CONTROL, 'x') time.sleep(2) # ็ฒ˜่ดด el.send_keys(Keys.CONTROL, 'v') time.sleep(2) # ๆธ…้™ค el.clear() # ่พ“ๅ…ฅๅ†…ๅฎน el.send_keys("seleniumm") # backspaceไธ€ไธช el.send_keys(Keys.BACKSPACE) time.sleep(5) # ็‚นๅ‡ปๅ›ž่ฝฆ้”ฎ el.send_keys(Keys.ENTER) time.sleep(5) # ้€€ๅ‡บ driver.quit()
[ "zhaoquan_mo@163.com" ]
zhaoquan_mo@163.com
4c45aa82a362b010b070c3212cb5a17ad59e58f0
76a8ea60480331f0f61aeb61de55be9a6270e733
/downloadable-site-packages/Bio/HMM/__init__.py
063a9354cb8db8e0a2feff789d685c6dcacf6b7f
[ "MIT" ]
permissive
bhagyas/Pyto
cd2ec3f35bec703db4ac29b56d17abc4bf03e375
907024a9b3e04a2a9de54976778c0e1a56b7b83c
refs/heads/master
2022-11-19T13:05:07.392454
2020-07-21T17:33:39
2020-07-21T17:33:39
281,886,535
2
0
MIT
2020-07-23T07:48:03
2020-07-23T07:48:02
null
UTF-8
Python
false
false
352
py
# This file is part of the Biopython distribution and governed by your # choice of the "Biopython License Agreement" or the "BSD 3-Clause License". # Please see the LICENSE file that should have been included as part of this # package. """A selection of Hidden Markov Model code.""" # File needed on Python 2 to import anything else in this directory
[ "adrilabbelol@gmail.com" ]
adrilabbelol@gmail.com
23497f5a015816a2363bafb17199f6108977f973
1c694159d84e0e2b389aac74eb80f73d990e609c
/read_reddit.py
6a9c5680e5874d37fa7101a48a29fa9bc4d22a29
[]
no_license
mikodham/intellibots_spring21
fe0b0aa149d19ddc76cb94c9499e4bdbcd0da5b4
04508adf4037fdfae952711d071d8011e28f10ca
refs/heads/main
2023-06-02T11:56:19.837924
2021-06-18T09:16:05
2021-06-18T09:16:05
367,868,733
0
0
null
null
null
null
UTF-8
Python
false
false
321
py
import pandas as pd df = pd.DataFrame() path = "./Dataset/reddit_mini.csv" df = pd.read_csv(path,usecols=[1,2]) df_negatives = df[df['class'].isin(['non-suicide'])] df_negatives.reset_index(drop=True,inplace=True) df_positives = df[df['class'].isin(['suicide'])] df_positives.reset_index(drop=True,inplace=True)
[ "timothymathews@kaist.ac.kr" ]
timothymathews@kaist.ac.kr
6d2868f78ec0a7bf47a651bb9f0d3678fe86f323
cd62e55137353d2a351f2eeb2c754383ab7cf124
/MetaGPA/mapping.py
4a4c7bbbcf8bffa4661d9302a59cc4c5f7d1a17f
[ "MIT" ]
permissive
linyc74/MetaGPA
797268863b18cd707e7d330836da1b4af4fdd9bc
2311bef2483c6fb96310626711a6663636586660
refs/heads/main
2023-07-05T14:17:54.120299
2021-12-09T10:39:40
2021-12-09T10:39:40
311,524,661
3
0
null
null
null
null
UTF-8
Python
false
false
1,605
py
from .template import Processor, Settings class Mapping(Processor): fna: str control_fq1: str control_fq2: str case_fq1: str case_fq2: str index: str control_bam: str case_bam: str def __init__(self, settings: Settings): super().__init__(settings=settings) def main( self, fna: str, control_fq1: str, control_fq2: str, case_fq1: str, case_fq2: str): self.fna = fna self.control_fq1 = control_fq1 self.control_fq2 = control_fq2 self.case_fq1 = case_fq1 self.case_fq2 = case_fq2 self.index_genome() self.map_reads() return self.control_bam, self.case_bam def index_genome(self): self.index = f'{self.workdir}/bowtie2-index' cmd = f'bowtie2-build -f {self.fna} {self.index} > {self.workdir}/bowtie2-build.log' self.call(cmd) def map_reads(self): self.control_bam = f'{self.workdir}/control.bam' self.case_bam = f'{self.workdir}/case.bam' for fq1, fq2, bam in [ (self.control_fq1, self.control_fq2, self.control_bam), (self.case_fq1, self.case_fq2, self.case_bam) ]: cmd = [ f'bowtie2 --threads {self.threads} -x {self.index} -1 {fq1} -2 {fq2} --no-unal | samtools view -@ {self.threads} -bS - | samtools sort -@ {self.threads} - > {bam}', f'samtools index {bam}'] for each in cmd: self.call(each)
[ "yclin.python@gmail.com" ]
yclin.python@gmail.com
52cd064acae2495296f4fadad4ed625761f875c5
64aabf9cad30c07f954b719973b824a96e7d2b67
/APPS/system/models.py
3bdd6e82d92826893995ce1445844a963d965e17
[]
no_license
zhouf00/mysiteTest
39041771c0e46ccd17690869a49ef3e44c665e86
472c588660524b81436d1dba0ff62b6b6aea1f1a
refs/heads/master
2021-01-04T17:49:35.754614
2020-04-27T03:07:44
2020-04-27T03:07:44
240,694,270
0
0
null
null
null
null
UTF-8
Python
false
false
1,457
py
from django.db import models # Create your models here. class SystemSetup(models.Model): loginTitle = models.CharField(max_length=20, null=True, blank=True, verbose_name='็™ป้™†ๆ ‡้ข˜') mainTitle = models.CharField(max_length=20, null=True, blank=True, verbose_name='็ณป็ปŸๆ ‡้ข˜') headTitle = models.CharField(max_length=20, null=True, blank=True, verbose_name='ๆต่งˆๅ™จๆ ‡้ข˜') copyright = models.CharField(max_length=100, null=True, blank=True, verbose_name='ๅบ•้ƒจ็‰ˆๆƒไฟกๆฏ') url = models.CharField(max_length=50, null=True, blank=True, verbose_name='็ณป็ปŸURLๅœฐๅ€') def __str__(self): return self.loginTitle class Meta: verbose_name = '็ณป็ปŸ่ฎพ็ฝฎ' verbose_name_plural = verbose_name @classmethod def getSystemSetupLastData(self): return dict(system_setup=SystemSetup.objects.last()) class EmailSetup(models.Model): emailHost = models.CharField(max_length=30, verbose_name='SMTPๆœๅŠกๅ™จ') emailPort = models.IntegerField(verbose_name='SMTP็ซฏๅฃ') emailUser = models.EmailField(max_length=100, verbose_name='้‚ฎ็ฎฑๅธๅท') emailPassword = models.CharField(max_length=30, verbose_name='้‚ฎ็ฎฑๅฏ†็ ') def __str__(self): return self.emailHost class Meta: verbose_name = 'ๅ‘ไปถ้‚ฎ็ฎฑ่ฎพ็ฝฎ' verbose_name_plural = verbose_name @classmethod def getEmailSetupLastData(self): return EmailSetup.objects.last()
[ "49618748+zhouf00@users.noreply.github.com" ]
49618748+zhouf00@users.noreply.github.com
d3ed62805f4dc37293db01fad6a99b8e1c77809a
d1bed926389986c9d3439fe1704ff80fc127ab97
/sum_to_k.py
c82bb3f41e69d4d65ab08369b05354d7b9845f5c
[]
no_license
alishalopes87/hb-coding-challenges
00f35455f768aaa5e7c33e585fb52b5291d7d6bf
559e75917744f8fa4b0dc7c20777b8f5ac3b18af
refs/heads/master
2020-05-01T07:53:03.734221
2019-08-09T00:12:17
2019-08-09T00:12:17
177,362,750
0
0
null
null
null
null
UTF-8
Python
false
false
425
py
# Given a list of numbers and a number k, return whether any two numbers from the list add up to k. # For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. # Bonus: Can you do this in one pass? def sum_to_k(lst, k): for num in range(len(lst)): if k - num in lst: return True return False output = sum_to_k([10, 15, 3, 7], 17) print(output) output = sum_to_k([5,3,8,12],40) print(output)
[ "alishalopes@MacBook-Pro-5.home" ]
alishalopes@MacBook-Pro-5.home
fd5bd50b0049c3937ac7aab4ea2085ebceb23d88
20e3ee6642d20578e48756963798acfe307ac6b5
/Traning/PyQs-master/PyQs-master/python-initial-reference/ToBeShared/reference/Code/web/flask/quick/helloRest/app/__init__.py
5c01f7af088af16ce359f07c36bdfeaffce8608a
[]
no_license
sirinenisaikiran/Python
538f64276767435de3233b720f547aac0bf4d511
bdfef0d1c04c7f3b9fc91a164b5fd1789828176c
refs/heads/master
2023-01-31T00:53:01.650916
2021-06-06T10:39:20
2021-06-06T10:39:20
237,744,104
0
0
null
2023-01-26T03:38:47
2020-02-02T08:58:49
Python
UTF-8
Python
false
false
129
py
from flask import Flask app = Flask(__name__) from app import routes #should be last as routes module needs above app variable
[ "saikiran.sirneni@gmail.com" ]
saikiran.sirneni@gmail.com
a54709a42d49049c584b8a5109b1f7916baa20cf
854d3082edf5f34ef855da6f3074875b24b37283
/blaze/tests/test_blaze_kerneltree_ckernel.py
3250521ea480242a50f559b86077ca36135aa254
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
ephrein/blaze
5c067b88de112e1aa7668d3af90b524571041637
637bc54e4c13d2acb6ba50672548d869c7114f0b
refs/heads/master
2022-06-19T14:53:31.818273
2013-07-06T07:38:26
2013-07-06T07:38:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,595
py
import unittest import sys import ctypes import blaze from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.datadescriptor import (execute_expr_single, dd_as_py) from blaze.py3help import izip class TestBlazeKernelTreeCKernel(unittest.TestCase): def test_binary_kerneltree(self): # Create some simple blaze funcs, using Numba def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[('f8(f8,f8)', _add), ('c16(c16,c16)', _add)]) mul = BlazeFunc('mul', {(double,)*3: _mul, (c128,)*3: _mul}) # Array data and expression af = blaze.array([[1,2,3], [4,5,6]],dshape=double) bf = blaze.array([2,3,4],dshape=double) cf = add(af,bf) df = mul(cf,cf) ubck = df._data.kerneltree.unbound_single_ckernel # Allocate the result, and run the kernel across the arguments result = blaze.zeros(df.dshape) args = [arg.arr._data for arg in df._data.args] ck = ubck.bind(result._data, args) execute_expr_single(result._data, args, df._data.kerneltree.kernel.dshapes[-1], df._data.kerneltree.kernel.dshapes[:-1], ck) self.assertEqual(dd_as_py(result._data), [[(a+b) * (a+b) for a, b in izip(a1, b1)] for a1, b1 in izip( [[1,2,3], [4,5,6]], [[2,3,4]]*2)]) # Use blaze.eval to evaluate cf and df into concrete arrays cf2 = blaze.eval(cf) self.assertEqual(dd_as_py(cf2._data), [[(a+b) for a, b in izip(a1, b1)] for a1, b1 in izip( [[1,2,3], [4,5,6]], [[2,3,4]]*2)]) df2 = blaze.eval(df) self.assertEqual(dd_as_py(df2._data), [[(a+b) * (a+b) for a, b in izip(a1, b1)] for a1, b1 in izip( [[1,2,3], [4,5,6]], [[2,3,4]]*2)]) """ def test_binary_kerneltree_lifted(self): # Create some simple blaze funcs, using Numba def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[('f8(f8,f8)', _add), ('c16(c16,c16)', _add)]) mul = BlazeFunc('mul', {(double,)*3: _mul, (c128,)*3: _mul}) # Array data and expression af = blaze.array([[1,2,3], [4,5,6]],dshape=double) bf = blaze.array([2,3,4],dshape=double) cf = add(af,bf) df = mul(cf,cf) lifted_kernel = df._data.kerneltree.fuse().kernel.lift(1, 'C') ubck = lifted_kernel.unbound_single_ckernel # Allocate the result, and run the kernel across the arguments result = blaze.zeros(df.dshape) args = [arg.arr._data for arg in df._data.args] ck = ubck.bind(result._data, args) execute_expr_single(result._data, args, result._data.dshape.subarray(-2), [a.dshape.subarray(-2) for a in args], ck) self.assertEqual(dd_as_py(result._data), [[(a+b) * (a+b) for a, b in izip(a1, b1)] for a1, b1 in izip( [[1,2,3], [4,5,6]], [[2,3,4]]*2)]) """ if __name__ == '__main__': unittest.main(verbosity=2)
[ "mwwiebe@gmail.com" ]
mwwiebe@gmail.com
bab087b3b495cc6c828a66207ae3265df4412478
3676b1bc902c174ff7cb69f74578afc0de6c8dd8
/qandu_app/wsgi.py
6efe7cf93d090f83158ed3954efcbd6b0be510bb
[]
no_license
amluciano/qandu_app
ce91d59bb63c82408951dbb6b66b022f8d99c1cd
e149e8f06633344e064f1fb043513f8ce829c76a
refs/heads/master
2021-01-10T13:45:03.958529
2015-10-15T20:33:48
2015-10-15T20:33:48
43,083,551
0
0
null
null
null
null
UTF-8
Python
false
false
429
py
""" WSGI config for qandu_app project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from dj_static import Cling os.environ.setdefault("DJANGO_SETTINGS_MODULE", "qandu_app.settings") application = Cling(get_wsgi_application())
[ "amluciano@quinnipiac.edu" ]
amluciano@quinnipiac.edu
02ddd2a0d78248de62aed9035d8d1be97414b98c
971cb789522341f4c1a1ce3962807538695cbea6
/venv/bin/tlsdb.py
0bbf4c53c2d8c128d707558553a43ffcc1500705
[]
no_license
18200643032/flasky
453beecab6bdad579e6b4e5527ee85e2543de98e
43ca7573adc1872925863ffb1c33a5b4ffab1bd6
refs/heads/master
2020-09-30T11:11:16.056139
2019-12-16T08:48:09
2019-12-16T08:48:09
227,275,638
0
0
null
null
null
null
UTF-8
Python
false
false
3,775
py
#!/root/flasky/venv/bin/python3.7 # Authors: # Trevor Perrin # Martin von Loewis - python 3 port # # See the LICENSE file for legal information regarding use of this file. from __future__ import print_function import sys import os import socket import math if __name__ != "__main__": raise "This must be run as a command, not used as a module!" from tlslite import * from tlslite import __version__ if len(sys.argv) == 1 or (len(sys.argv)==2 and sys.argv[1].lower().endswith("help")): print("") print("Version: %s" % __version__) print("") print("RNG: %s" % prngName) print("") print("Modules:") if m2cryptoLoaded: print(" M2Crypto : Loaded") else: print(" M2Crypto : Not Loaded") if pycryptoLoaded: print(" pycrypto : Loaded") else: print(" pycrypto : Not Loaded") if gmpyLoaded: print(" GMPY : Loaded") else: print(" GMPY : Not Loaded") print("") print("Commands:") print("") print(" createsrp <db>") print("") print(" add <db> <user> <pass> [<bits>]") print(" del <db> <user>") print(" check <db> <user> [<pass>]") print(" list <db>") sys.exit() cmd = sys.argv[1].lower() class Args: def __init__(self, argv): self.argv = argv def get(self, index): if len(self.argv)<=index: raise SyntaxError("Not enough arguments") return self.argv[index] def getLast(self, index): if len(self.argv)>index+1: raise SyntaxError("Too many arguments") return self.get(index) args = Args(sys.argv) def reformatDocString(s): lines = s.splitlines() newLines = [] for line in lines: newLines.append(" " + line.strip()) return "\n".join(newLines) try: if cmd == "help": command = args.getLast(2).lower() if command == "valid": print("") else: print("Bad command: '%s'" % command) elif cmd == "createsrp": dbName = args.get(2) db = VerifierDB(dbName) db.create() elif cmd == "add": dbName = args.get(2) username = args.get(3) password = args.get(4) db = VerifierDB(dbName) db.open() if username in db: print("User already in database!") sys.exit() bits = int(args.getLast(5)) N, g, salt, verifier = VerifierDB.makeVerifier(username, password, bits) db[username] = N, g, salt, verifier elif cmd == "del": dbName = args.get(2) username = args.getLast(3) db = VerifierDB(dbName) db.open() del(db[username]) elif cmd == "check": dbName = args.get(2) username = args.get(3) if len(sys.argv)>=5: password = args.getLast(4) else: password = None db = VerifierDB(dbName) db.open() try: db[username] print("Username exists") if password: if db.check(username, password): print("Password is correct") else: print("Password is wrong") except KeyError: print("Username does not exist") sys.exit() elif cmd == "list": dbName = args.get(2) db = VerifierDB(dbName) db.open() print("Verifier Database") def numBits(n): if n==0: return 0 return int(math.floor(math.log(n, 2))+1) for username in db.keys(): N, g, s, v = db[username] print(numBits(N), username) else: print("Bad command: '%s'" % cmd) except: raise
[ "910386943@qq.com" ]
910386943@qq.com
ba7d56a4ab941cc0e6ff36bbfede4870b3205ecb
9bd1afa4afd7754a4e19ea2217fa940486a0e067
/newfile.py
ef1b0b1efb0c331d5fd32d47a5195cbec5caf0f4
[]
no_license
aschultz10/test_branching
b8169fcf8b3665d55859679ea1db260f4ef9bbe2
5995290eb0240c95976dbcc8b07184930dc26f25
refs/heads/main
2023-03-16T11:42:54.523106
2021-03-03T00:15:42
2021-03-03T00:15:42
343,942,480
0
0
null
null
null
null
UTF-8
Python
false
false
18
py
print("whats up)")
[ "alexeschultz@gmail.com" ]
alexeschultz@gmail.com
ce53d926393d120a60e823a6d9ac9ce202916904
482b44865a69bde81cf96fd1a28dae0b832153a8
/consensus/calc_total_kmers_clust_split.py
563ea3122a731c8af08ff8bb8c8e28abdf4b2896
[]
no_license
EESI/microbiome_embeddings
407c841d33e46fcbf471f16510a7ae62e808a081
c5595d61d636ce318f3eedaa2a22aa470943e1aa
refs/heads/master
2020-04-16T01:02:24.150327
2020-02-21T17:35:34
2020-02-21T17:35:34
165,159,129
9
3
null
null
null
null
UTF-8
Python
false
false
1,384
py
#!/usr/bin/env python import sys sys.path.insert(0, '/data/sw1/embeddings/code/') from sys import argv import os import zipfile from os.path import splitext, isfile import gzip import csv import six.moves.cPickle import collections from shutil import copyfile import numpy as np import pandas as pd from itertools import product from operator import itemgetter from sklearn.manifold import TSNE import random import math import time from glob import glob from gensim.models import Word2Vec from gensim.models.word2vec import LineSentence import embed_functions as emb import r2v_functions as r2v name_reads = 'kegg' path_reads = argv[1] path_model = argv[2] name_sample = path_reads.split('/')[-1].replace('.fasta','') fn_model_base = path_model.split('/')[-1] fn_model_base = '_'.join(fn_model_base.split('_')[1:-1]) fn_out = '%s_total_kmers_split.pkl' % (name_sample) model_fn = path_model.split('/')[-1] k = int(model_fn.split('_')[1]) dir_out = '/mnt/HA/groups/rosenGrp/embed_cons/out/%s/total_kmers_split/%s' % (name_reads,fn_model_base) path_out = os.path.join(dir_out,fn_out) if not os.path.exists(dir_out): os.makedirs(dir_out) print('Calculating kmer totals for %s using model %s.' % (path_reads,path_model)) total_kmers = r2v.calc_total_kmers_split(path_reads,path_model,k,verbose=True,v=10) six.moves.cPickle.dump(total_kmers,open(path_out,'wb'),protocol=4)
[ "noreply@github.com" ]
EESI.noreply@github.com
583e8e8579676621b5f264b6df4e31cbb2ad2031
98083b3d7c3aa43abe5224e5c35c65d934a0ee1d
/Polygons Collisions Testing/polygon_stub.py
db317fc191a6874200e4cd89e4316f62e05a466e
[]
no_license
WhiteLotus9678/Physics-Models-in-Games-Using-Python
d101b351c133996487eb234fae06bc26b0df3304
eb033cec176ff529e9a930ab60f3953f4168a8b4
refs/heads/master
2021-09-15T20:01:05.726415
2018-06-09T18:46:02
2018-06-09T18:46:02
119,438,553
0
0
null
null
null
null
UTF-8
Python
false
false
9,468
py
# -*- coding: utf-8 -*- """ Created on Thu Apr 12 14:26:03 2018 @author: sinkovitsd, Will Yang """ from math import sin, cos, degrees from vec2d import Vec2d import pygame class Polygon: def __init__(self, pos, vel, density, points, color, angle=0, angvel=0): self.pos = pos self.vel = vel self.color = color self.angle = angle self.angvel = angvel self.force = Vec2d(0,0) self.torque = 0 self.type = "polygon" # Set origpoints self.origpoints = [] for p in points: self.origpoints.append(p.copy()) print("origpoints =", self.origpoints) pp = self.origpoints # pp as an alternate label for this function # Tally area, moment, and center of mass self.area = 0 self.moment = 0 center = Vec2d(0,0) for i in range(len(pp)): #> area of triangle, and add to total area # A = .5 * r1 x r2 # r1 = pp[i] # r2 = pp[i=1] # a = fabs(pp[i].cross(pp[i-1])/2) a = pp[i].cross(pp[i-1])/2 self.area += a """ Parallel Axis Theorem --> I other = I center + M abs(r)^2 """ #> moment of triange about vertex # m = density * area # density * area / 6 # I_vertex = (1/6) * density * self.area * (abs(pp[i]) * abs(pp[i]) + abs(pp[i-1]) * abs(pp[i-1]) + pp[i].dot(pp[i-1])) I_vertex = (1/6) * density * a * (pp[i].mag() * pp[i].mag() + pp[i-1].mag() * pp[i-1].mag() + pp[i].dot(pp[i-1])) #> add center of mass of triange to center of mass of shape center += a*(pp[i] + pp[i-1])/3 pass center *= 1/self.area if(self.area < 0): self.area *= -1 self.mass = density*self.area print("center =", center) print("area =", self.area) print("mass =", self.mass) # Shift self.origpoints to be centered on center of mass for p in self.origpoints: p -= center self.pos += center #> Shift moment to be about center of mass (parallel axis theorem) self.moment += I_vertex - self.mass * self.pos.mag() * self.pos.mag() if(self.moment < 0): self.moment *= -1 print("moment =", self.moment) #print(pp) # Recalculate moment around the center of mass as a check moment = 0 for i in range(len(pp)): #> same as above loop to tally moment of each triangle about vertex moment += (1/6) * density * a * (pp[i].mag() * pp[i].mag() + pp[i-1].mag() * pp[i-1].mag() + pp[i].dot(pp[i-1])) # tmpmom pass if(moment < 0): moment *= -1 print("moment =", moment) # Calculate normals to each points self.orignormals = [] for i in range(len(pp)): #> calculate normal here and append to orignormals self.orignormals.append((pp[i-1] - pp[i]).perpendicular().hat()) #perpendicular_normal() pass print("orignormals =", self.orignormals) # Calculate rotated points and normals self.points = [] for p in self.origpoints: self.points.append(Vec2d(0,0)) self.normals = [] for n in self.orignormals: self.normals.append(Vec2d(0,0)) self.update_points_normals() self.mom = self.mass*self.vel self.angmom = self.moment*self.angvel #print("points =", self.points) #print("normals =", self.normals) def update_mom(self, dt): self.mom += self.force*dt self.angmom += self.torque*dt self.update_vel() self.update_angvel() def set_vel(self, vel): self.vel.copy_in(vel) self.mom.copy_in(self.vel*self.mass) def update_vel(self): self.vel.copy_in(self.mom/self.mass) def update_angvel(self): self.angvel = self.angmom/self.moment """ distance_n = distance * n_hat dustance_t = distance * t_hat delta_v_n = ((1 / self.mass) + ((distance_t * distance_t) / self.moment)) * impulse_n - ((distance_n * distance_t) / self.moment) * impulse_t FIX: delta_v_t = ((1 / self.mass) + ((distance_t * distance_t) / self.moment)) * impulse_n - ((distance_n * distance_t) / self.moment) * impulse_t """ def update_pos(self, dt): self.pos += self.vel*dt self.angle += self.angvel*dt if self.angvel*dt != 0: self.update_points_normals() def update_points_normals(self): pp = self.origpoints pn = self.orignormals c = cos(self.angle) s = sin(self.angle) #> use s and c to calculate points and normals rotated for i in range(len(pp)): x = pp[i].x y = pp[i].y self.points[i].x = x*c - y*s self.points[i].y = y*c + x*s # Calculating normals for i in range(len(pn)): x = pn[i].x y = pn[i].y self.normals[i].x = x*c - y*s self.normals[i].y = y*c + x*s "Rotating counter clockwise by angle theta" "xPrime = x*cos(theta) - y*sin(theta)" "yPrime = y*cos(theta) + x*sin(theta)" def update(self, dt): self.update_mom(dt) self.update_pos(dt) def impulse(self, imp, point=None): self.mom += imp self.update_vel() if point is not None: self.angmom += (point - self.pos).cross(imp) self.update_angvel() """ def draw(self, screen, coords): # Draw polygon for i, p in enumerate(self.points): self.scaledpoints[i].copy_in(coords.pos_to_screen(self.pos + p)) #print(self.scaledpoints) pygame.draw.polygon(screen, self.color, self.scaledpoints) for i in range(len(self.scaledpoints)): length = 50 n = coords.unitvec_to_other(self.normals[i]) p = (self.scaledpoints[i] + self.scaledpoints[i-1])/2 pygame.draw.line(screen, (0,0,0), p, p + length*n) """ def draw(self, screen, coords): # Draw polygon points = [] for p in self.points: points.append(coords.pos_to_screen(self.pos + p)) pygame.draw.polygon(screen, self.color, points, 2) if True: for i in range(len(points)): length = 50 n = coords.unitvec_to_other(self.normals[i]) p = (points[i] + points[i-1])/2 pygame.draw.line(screen, (0,0,0), p, p + length*n) #print("p: ", p) """ Self supplies the vertices. Other provides the sides (walls). For each wall, find the point that penetrates the MOST, and record the magnitude of penetration. If for one wall, no point penetrates, there is no overlap; return False. Otherwise, find which wall is LEAST penetrated, and pass back, via result.extend(), the overlap, point and normal involved; return True. """ """ collision 1. find point of maximum penetration d is the same as the wall penetration point = self.pos + point if no penetration, immediately return false 2. looking at the other sides, find that point of maximum penetration 3. Return whichever side that gives the minimum penetration """ def check_collision(self, other, result=[]): result.clear() # See polygon_collision_test.py in check_collision() overlap = 1e99 r_other = Vec2d(0,0) r_self = Vec2d(0,0) d = 0 n_hat = 0 maxd = -1e99 #maxj = 0 normal = 0 point = None if other.type == "polygon": for i in range(len(other.normals)): # Fill in r_other = other.pos + other.points[i] n_hat = other.normals[i] maxd = -1e99 pass for j in range(len(self.points)): # Fill in r_self = self.pos + self.points[j] d = (r_other - r_self).dot(n_hat) if d > maxd: maxd = d #maxj = j maxpoint = r_self print(self.color, maxd, n_hat) if maxd < overlap: if maxd < 1e-9: # catch floating point errors return False overlap = maxd normal = n_hat #point = self.pos + self.points[maxj] point = maxpoint result.extend([self, other, overlap, normal, point]) return True
[ "noreply@github.com" ]
WhiteLotus9678.noreply@github.com
5908f7dfd7c340d09892ec22e091c0fdcfa52b05
b5b28acfd43c9a9484cbffe378c7d4a1e948ec63
/coramin/domain_reduction/__init__.py
0668d94bd8ea84c6c3151c59ec031382559bb2a2
[ "BSD-3-Clause" ]
permissive
Coramin/Coramin
d5accc7de33623ac6f3d97e0d0217b4d3344aa73
1b9883ca1a8fc7b3196d6249948fbba5d506a8bb
refs/heads/main_branch
2023-07-12T16:09:34.138155
2022-11-06T21:53:14
2022-11-06T21:53:14
166,443,751
20
13
NOASSERTION
2023-09-05T16:05:53
2019-01-18T17:00:15
Python
UTF-8
Python
false
false
414
py
from .obbt import perform_obbt from .filters import filter_variables_from_solution, aggressive_filter try: from .dbt import decompose_model, perform_dbt, perform_dbt_with_integers_relaxed, TreeBlockData, TreeBlock, \ DecompositionError, TreeBlockError, collect_vars_to_tighten, collect_vars_to_tighten_by_block, DBTInfo, \ push_integers, pop_integers, OBBTMethod, FilterMethod except: pass
[ "michaelbynum@users.noreply.github.com" ]
michaelbynum@users.noreply.github.com
2c44f3dbb7f7af8995aee818d058f9f2376409b1
6b4bd776c05aac1802927873fa665bd44677769e
/vec_prod/jvp.py
551066f83f7f1e77a3cd5671bbac988dab37e7da
[]
no_license
karush17/optimization_utils
a26102159a981778caf0aadcdca19dee5a2b787c
2b49220b4a15e90a3e60a734f3a4b0a1e718379f
refs/heads/master
2023-07-13T22:20:29.578555
2021-08-18T15:43:22
2021-08-31T14:50:37
397,654,404
0
0
null
null
null
null
UTF-8
Python
false
false
171
py
import torch from utils import flat_grad def Jvp(functional, inputs, v): grad_f = flat_grad(functional, inputs, create_graph=True) return torch.matmul(grad_f, v)
[ "karushsuri@gmail.com" ]
karushsuri@gmail.com
4af393604fe2d6a11818bf866432beb496df124b
1c4394c908a579ce21914c015181aeb408318351
/hello_world/views.py
7da2d485b1333757cdfcbdf8a79736928351ab97
[]
no_license
ceciliawambui/rp-portfolio
26b21461b6bcf497f0289fa09735bb081e53524f
e87c70f969d5dab6d86ba9033f7f8f64704d525a
refs/heads/master
2020-09-27T12:15:45.870913
2019-12-07T13:00:07
2019-12-07T13:00:07
226,514,333
0
0
null
null
null
null
UTF-8
Python
false
false
145
py
from django.shortcuts import render # Create your views here. def hello_world(request): return render(request, 'hello_world.html', {})
[ "ceciliawambui026@gmail.com" ]
ceciliawambui026@gmail.com
40f8994459638d56215b03ff948798229cf9b1bf
67708071befaea93326b4dbee48a3c7c176828c2
/django/authentication/admin.py
a9d5f405978255bd14d5bde727fb6c26a18e8775
[ "MIT" ]
permissive
vikramvaibhav/django-jwt-react-boilerplate
4dbd59a0cf3f55a5058ff703f4b08997d3ff3e67
d262bd332f8696e11e55ad9d485a3f87d8624070
refs/heads/master
2023-01-04T15:24:32.377506
2020-10-31T13:09:55
2020-10-31T13:09:55
305,959,317
3
0
null
null
null
null
UTF-8
Python
false
false
1,135
py
from django.contrib import admin from authentication.models import CustomUser from django.contrib.auth.admin import UserAdmin from django.forms import TextInput, Textarea, CharField from django import forms from django.db import models class UserAdminConfig(UserAdmin): model = CustomUser search_fields = ('email', 'username', 'first_name',) list_filter = ('email', 'username', 'first_name', 'is_active', 'is_staff') ordering = ('-start_date',) list_display = ('email', 'id', 'username', 'first_name', 'is_active', 'is_staff') fieldsets = ( (None, {'fields': ('email', 'username', 'first_name',)}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ('Personal', {'fields': ('about',)}), ) formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows': 20, 'cols': 60})}, } add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'username', 'first_name', 'password1', 'password2', 'is_active', 'is_staff')} ), ) admin.site.register(CustomUser, UserAdminConfig)
[ "vikramvaibhav@outlook.com" ]
vikramvaibhav@outlook.com
4b6330afc6e5c01baf49de22d4940eb614416a2a
b568f1b58bed5319460b7a71d9b792dbf1089a5a
/data_prep/data_generator.py
26c37ebef16685078054aa9daf7f7873c1f4b346
[ "MIT" ]
permissive
Linusmt/CS231N-BRATS
47497d3eeb0e82fd4dc16025e6faf35d756192ac
15171565c786d7e5ef697ccf1541121158955bf0
refs/heads/master
2020-03-18T13:15:33.274715
2018-06-02T18:04:36
2018-06-02T18:04:36
134,772,063
0
0
null
null
null
null
UTF-8
Python
false
false
1,934
py
import numpy as np import keras class DataGenerator(keras.utils.Sequence): 'Generates data for Keras' def __init__(self, X, y, n): 'Initialization' self.batch_size = 1 self.X = X self.y = y self.n = n def __len__(self): 'Denotes the number of batches per epoch' return 400 def __getitem__(self, index): 'Generate one batch of data' # Generate indexes of the batch index = np.random.randint(0, self.n) # Get the original data X =np.expand_dims(self.X[index], 0) y = np.array([self.y[index]]) # Find list of IDs mod_random = np.random.uniform(0,1) if np.random.uniform(0,1) < 0.3: X = np.flip(X, axis=1) y = np.flip(y, axis=1) if np.random.uniform(0,1) < 0.3: X = np.flip(X, axis=2) y = np.flip(y, axis=2) if np.random.uniform(0,1) < 0.3: X = np.flip(X, axis=3) y = np.flip(y, axis=3) # Generate data # X, y = self.__data_generation(list_IDs_temp) return X, y # def on_epoch_end(self): # 'Updates indexes after each epoch' # self.indexes = np.arange(len(self.list_IDs)) # if self.shuffle == True: # np.random.shuffle(self.indexes) # def __data_generation(self, list_IDs_temp): # 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels) # # Initialization # X = np.empty((self.batch_size, *self.dim, self.n_channels)) # y = np.empty((self.batch_size), dtype=int) # # Generate data # for i, ID in enumerate(list_IDs_temp): # # Store sample # X[i,] = np.load('data/' + ID + '.npy') # # Store class # y[i] = self.labels[ID] # return X, keras.utils.to_categorical(y, num_classes=self.n_classes)
[ "lmeyerte@stanford.edu" ]
lmeyerte@stanford.edu
c77992067ffe06f1534770472462d0687ced77ee
d81b070622fdafafbefac437bd41e377b05bf163
/Trees/BST/minimum_in_bst.py
447b272e0c2ffa512b9dbf9af591073fdf03fdc3
[]
no_license
raghavnarula/Data-Structures
9e25cbd4cfa383af738b915f359b179dfacfc56a
02163c6ee3135122cd5b5db0af7267737d2c3216
refs/heads/master
2023-06-28T08:44:46.141330
2021-07-30T18:23:34
2021-07-30T18:23:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
623
py
# keep moving to the left node until we find null class Node: # Constructor to create a new node def __init__(self, key): self.data = key self.leftval = None self.rightval = None def minValue(node): current = node # loop down to find the lefmost leaf while(current.leftval is not None): current = current.leftval return current.data root = Node(10) root.leftval = Node(8) root.rightval = Node(14) root.leftval.leftval = Node(5) root.rightval.leftval = Node(13) root.rightval.rightval = Node(16) root.leftval.rightval = Node(9) print(minValue(root))
[ "aarav30302001@gmail.com" ]
aarav30302001@gmail.com
d4032cc10f41d0a995a97ae1408b2706e2a3a3e7
afa8f872daf9047a1358eef7a354841fe949ec86
/gpt/gpnode.py
3b931ad72025d0b2e76fb0363e3ab4d81e440bb3
[]
no_license
nrjones8/Genetic-Programming-Classifier
f64294f3f646640f4490b614cd360f2b29f9deee
671bd5b0c1c58fbcc789aaf820a30c0a14a10c97
refs/heads/master
2020-06-04T09:53:42.568865
2012-12-04T20:10:53
2012-12-04T20:10:53
7,006,028
0
1
null
null
null
null
UTF-8
Python
false
false
3,877
py
# Nick Jones, written for CS 361 - Intro to Evolutionary Computing with Sherri Goings from entry import Entry class GPNode(object): """""" def __init__(self, attribute, comparisonValue): """ <attribute> is the attribute this node 'cares about' i.e. what attribute to compare <comparisonValue> is either a limit (if numeric) or a category (if categorical) """ self.attribute = attribute self.comparisonValue = comparisonValue self.attributeType = type(comparisonValue).__name__ # 'str' or 'float' self.leftChild = None self.rightChild = None def setLeftChild(self, newNode): self.leftChild = newNode def setRightChild(self, newNode): self.rightChild = newNode def getLeftChild(self): return self.leftChild def getRightChild(self): return self.rightChild def evaluate(self, entry): """Determines if this tree (as represented by root node) correctly classifies <entry>""" if self.leftChild == None and self.rightChild == None: # Terminal node, so compare entry's final category with this node's final category return self.comparisonValue == entry.attributes[self.attribute] elif self.compareAttributes(entry): # Compare; go right if true, left if false return self.rightChild.evaluate(entry) else: return self.leftChild.evaluate(entry) def compareAttributes(self, entry): """ Compares this node's attribute with the entry's attribute NOTE: Node's limit is always compared to data's limit in form: data's attribute < limit """ if self.attributeType == 'str': # Must be a categorical attribute, so compare this node's category with that of the entry return self.comparisonValue == entry.attributes[self.attribute] else: # Must be a numeric attribute return self.comparisonValue > entry.attributes[self.attribute] def getHeight(self): """Returns the height of the tree descending from this node. For example, if the node has no children then returns 0.""" # Compute the height of the left subtree. if self.leftChild == None: leftHeight = -1 else: leftHeight = self.leftChild.getHeight() # Compute the height of the right subtree. if self.rightChild == None: rightHeight = -1 else: rightHeight = self.rightChild.getHeight() return 1 + max(leftHeight, rightHeight) def __str__(self): """Returns a string representation, with an empty child represented by []. Assumes that the values stored in the tree themselves respond to __str__.""" # Get the string for the left child. if self.leftChild == None: leftString = '[]' else: leftString = str(self.leftChild) # Get the string for the right child. if self.rightChild == None: rightString = '[]' else: rightString = str(self.rightChild) selfString = str(self.attribute) if self.attributeType == 'str': selfString += ' = ' + self.comparisonValue else: selfString += ' > ' + str(self.comparisonValue) return '[' + selfString + ', ' + leftString + ', ' + rightString + ']' if __name__ == "__main__": root = GPNode('height', 4) root.setLeftChild(GPNode('weight', 190)) root.setRightChild(GPNode('size', 12)) curL = root.getLeftChild() curR = root.getRightChild() curL.setRightChild(GPNode('height', 10)) curL.setLeftChild(GPNode('foot', 12)) curR.setRightChild(GPNode('hand', 9)) curR.setLeftChild(GPNode('toe', 99)) print root print 'height:', root.getHeight()
[ "nrjones8@gmail.com" ]
nrjones8@gmail.com
9c7f18b7271263dbb1abd686aa3bccbd56cde603
00b7cd3d8aeb704d153287bcc4a8e1e1a80e552d
/Python code/polarity_distribution.py
e08e09ff4d9e25adec861724cff02f40af9252e2
[]
no_license
KoenGo/EWI3615TU
7677aa66f3ff99624356725a3507304a59628330
25edb7618fca48c661e6e81763a649928b243bad
refs/heads/master
2021-09-04T05:20:57.670801
2018-01-15T16:42:18
2018-01-15T16:42:18
110,662,490
1
0
null
2018-01-13T11:18:12
2017-11-14T08:33:28
Python
UTF-8
Python
false
false
1,362
py
import re import matplotlib.pyplot as plt import numpy as np def gather_polarities(): with open('datacollector_output/whole_tweet.txt', 'r', errors='ignore') as file: lines = file.readlines() polarity_list = [] index_count = -1 for line in lines: if re.search("at: (\d{2}-\d{2}-\d{4}) (\d{2}:\d{2}:\d{2})", line): date = re.search("at: (\d{2}-\d{2}-\d{4}) (\d{2}:\d{2}:\d{2})", line).group(0)[4:] if date == '14-01-2018 05:16:40': return polarity_list polarity_list.append([date]) index_count += 1 if re.search("Polarity: ([- \d\.]+)", line): polarity_list[index_count].append(float(re.search("Polarity: ([- \d\.]+)", line).group(1))) polarity_list = gather_polarities() x = [] for list in polarity_list: x.append(list.pop(0)[11:]) del x[1::2] del polarity_list[1::2] x = x[:8] polarity_list = polarity_list[:8] print(len(x)) print(len(polarity_list)) print(x) plt.figure(figsize=(10,7)) plt.boxplot(polarity_list) plt.xticks(range(1,len(x)+1), x) plt.title('Plot showing the distribution of the polarity of tweets for search terms: \'hawaii missile\' (13/01-14/01)') plt.ylabel('Polarity') plt.xlabel('Time') plt.savefig('distribution_polarity.eps', format = 'eps', dpi = 800) plt.show()
[ "kgoedemondt@gmail.com" ]
kgoedemondt@gmail.com
1ccbd8b0a065186765f91c9f61b20cabdb033820
d2fe80fba383f3debee17d8c360b411498069d81
/oil_lang/expr_parse_test.py
d4bdc05ec50b29d6f93784bd7d3a58cce3957d16
[]
no_license
stevenworthington/oil
7c6bfb20f5dc9485da28c6285e0f909a644316b9
721e5da392a8ae02e1af4acf03cb76900946ec29
refs/heads/master
2022-11-07T16:34:54.883277
2020-06-15T17:03:02
2020-06-15T17:29:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,011
py
#!/usr/bin/env python2 """ expr_parse_test.py: Tests for expr_parse.py """ from __future__ import print_function import unittest #from _devbuild.gen.id_kind_asdl import Kind from _devbuild.gen.syntax_asdl import source from core import alloc from core import error from core import meta from core import pyutil from core import test_lib from core.util import log from frontend import reader class ExprParseTest(unittest.TestCase): def setUp(self): """Done on every test.""" self.arena = alloc.Arena() self.arena.PushSource(source.Unused('')) loader = pyutil.GetResourceLoader() oil_grammar = meta.LoadOilGrammar(loader) self.parse_ctx = test_lib.InitParseContext(arena=self.arena, oil_grammar=oil_grammar) self.parse_ctx.Init_OnePassParse(True) def _ParseOsh(self, code_str): """Parse a line of OSH, which can include Oil assignments.""" line_reader = reader.StringLineReader(code_str, self.arena) # the OSH parser hooks into the Oil parser c_parser = self.parse_ctx.MakeOshParser(line_reader) node = c_parser.ParseLogicalLine() print('') log('\t%s', code_str) node.PrettyPrint() print('') return node def _ParseOilExpression(self, code_str): """Convenient shortcut.""" node = self._ParseOsh('var x = %s\n' % code_str) def testPythonLike(self): # This works. node = self._ParseOsh('var x = y + 2 * 3;') # The lexer isn't handling single quotes yet. #node = self._ParseOsh(r"var x = 'one\ntwo\n';") # NOTE: C-escapes aren't parsed properly. node = self._ParseOsh(r'var x = "one\ntwo\n";') # These raise NotImplementedError() node = self._ParseOsh('var x = [1,2,3];') node = self._ParseOilExpression('[4+5, 6+7*8]') node = self._ParseOilExpression('[]') node = self._ParseOilExpression('[x for x in y]') #node = self._ParseOilExpression('{foo: bar}') def testShellArrays(self): node = self._ParseOsh('var x = @(a b);') node = self._ParseOsh(r"var x = @('c' $'string\n');") node = self._ParseOsh(r"var x = @($(echo command) $(echo sub));") # Can parse multiple arrays (this is a runtime error) node = self._ParseOsh(r"var x = @(a b) * @($c ${d});") # Can parse over multiple lines node = self._ParseOsh(r"""var x = @( a b c );""") # Test out the DisallowedLineReader self.assertRaises(error.Parse, self._ParseOsh, r"""var x = @($(echo command <<EOF EOF ))""") def testShellCommandSub(self): node = self._ParseOsh('var x = $(echo hi);') node = self._ParseOsh('var x = $(echo $(echo hi));') # This doesn't use the Reader, so it's allowed node = self._ParseOsh("""var x = $(echo hi) """) # Here docs use the Reader, so aren't allowed self.assertRaises(error.Parse, self._ParseOsh, """var x = $(cat <<EOF hi EOF) """) node = self._ParseOsh('var x = $(echo $((1+2)));') node = self._ParseOsh('var x = $(for i in 1 2 3; do echo $i; done);') node = self._ParseOsh('var x = @(a b)') # TODO: Recursive 'var' shouldn't be allowed! return node = self._ParseOsh('var x = $(var x = @(a b););') node = self._ParseOsh('var x = $(var x = @(a b));') def testOtherExpr(self): """Some examples copied from pgen2/pgen2-test.sh mode-test.""" node = self._ParseOsh('@[1 2 3];') CASES = [ '@[1 2 3]', #'$/ x /', # TODO: Put this back after fixing double quoted strings in expression # mode. #'$/ "." [a-z A-Z] y /', #'$[echo hi]', '$(echo hi)', # TODO: Add these back '${x}', '"quoted ${x}"', ] # array literal for c in CASES: print('--- %s' % c) node = self._ParseOilExpression(c) def testLexer(self): # NOTE: Kind.Expr for Oil doesn't have LexerPairs #pairs = ID_SPEC.LexerPairs(Kind.Arith) pairs = [] for p in pairs: #print(p) pass if __name__ == '__main__': unittest.main()
[ "andy@oilshell.org" ]
andy@oilshell.org
f4ff06a3a2bbd4343d448f9b66994ef88c8506a1
1716cba3aae75b3e9f4aca352205b7f66afeefba
/IoT_Data_Platform/filtering_and_storage/filter_ms.py
1ae3acce9e38ee4234978b7f12e3a6e451d602b7
[]
no_license
mehai/mini-projects
df22656ed6b4e420e3cc750db13fc5d691a2a7db
50184d5d7feadc4ea1d959cceb4c2d5c609b50b8
refs/heads/master
2021-04-17T22:29:16.363488
2020-08-18T13:36:08
2020-08-18T13:36:08
249,480,495
0
0
null
2020-08-18T13:36:09
2020-03-23T16:12:39
Python
UTF-8
Python
false
false
1,532
py
import json ROOM_LOW = 1 ROOM_HIGH = 6 TEMP_LOW = 0 TEMP_HIGH = 40 HUM_LOW = 0 HUM_HIGH = 100 LIGHT_LOW = 0 LIGHT_HIGH = 100 class Filter: def __init__(self, db_connector): self.db_connector = db_connector def filter(self, message: str): try: jsonObj = json.loads(message) print(jsonObj) if isinstance(jsonObj, dict): if jsonObj['room'] is None or jsonObj['room'] < ROOM_LOW or jsonObj['room'] > ROOM_HIGH: raise ValueError if not isinstance(jsonObj['values'], dict): raise json.JSONDecodeError values = jsonObj['values'] if values['temperature'] is None or \ values['temperature'] < TEMP_LOW or values['temperature'] > TEMP_HIGH: raise ValueError if values['humidity'] is None or \ values['humidity'] < HUM_LOW or values['humidity'] > HUM_HIGH: raise ValueError if values['light'] is None or \ values['light'] < LIGHT_LOW or values['light'] > LIGHT_HIGH: raise ValueError print('calling db_connector for insert') self.db_connector.insert(jsonObj) else: raise json.JSONDecodeError except json.JSONDecodeError: print(f"Not what was expected: {message}") except ValueError: print(f"Integrity errors for: {message}")
[ "noreply@github.com" ]
mehai.noreply@github.com
721b1870ca01dfb53d0621ed1c7c1b749f120c63
32faa0ce90f98f9c4eca8e4c2c79d1d71eb1454d
/babynames.py
17d901c6c79c703f82d55e515b45c622f8fb0fa9
[]
no_license
ejhari/google_python_classes
dde2eebc1a3a6c2b4525f1a4e317347ef45cde43
e3ab441e6e4971ed896a375d72c7cfc3f627e1ed
refs/heads/master
2016-09-05T09:17:43.315834
2010-09-20T09:45:58
2010-09-20T09:45:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,541
py
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import sys import re """Baby Names exercise Define the extract_names() function below and change main() to call it. For writing regex, it's nice to include a copy of the target text for inspiration. Here's what the html looks like in the baby.html files: ... <h3 align="center">Popularity in 1990</h3> .... <tr align="right"><td>1</td><td>Michael</td><td>Jessica</td> <tr align="right"><td>2</td><td>Christopher</td><td>Ashley</td> <tr align="right"><td>3</td><td>Matthew</td><td>Brittany</td> ... Suggested milestones for incremental development: -Extract the year and print it -Extract the names and rank numbers and just print them -Get the names data into a dict and print it -Build the [year, 'name rank', ... ] list and print it -Fix main() to use the extract_names list """ def extract_names(filename): """ Given a file name for baby.html, returns a list starting with the year string followed by the name-rank strings in alphabetical order. ['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...] """ # +++your code here+++ f = open(filename,'rU') text = f.read() final = re.findall('Popularity\sin\s(\d\d\d\d)',text) if not final: print "Year not found ..." sys.exit(1) aa = {} names = re.findall('<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>',text) for r,b,g in names : if b not in aa: aa[b] = r if g not in aa: aa[g] = r sorted_aa = sorted(aa.keys()) for name in sorted_aa: final.append(name + " " + aa[name]) return final def main(): # This command-line parsing code is provided. # Make a list of command line arguments, omitting the [0] element # which is the script itself. args = sys.argv[1:] if not args: print 'usage: [--summaryfile] file [file ...]' sys.exit(1) # Notice the summary flag and remove it from args if it is present. summary = False if args[0] == '--summaryfile': summary = True del args[0] # +++your code here+++ for files in args: ans=extract_names(files) text='\n'.join(ans) if summary: out=open(files + '.summary', 'w') out.write(text + '\n') out.close() else: print text # For each filename, get the names, then either print the text output # or write it to a summary file if __name__ == '__main__': main()
[ "ejhari@gmail.com" ]
ejhari@gmail.com
94ad55e904df81587c507cd55c5674d60ccd3f87
2af6a5c2d33e2046a1d25ae9dd66d349d3833940
/res/scripts/client_common/shared_utils/account_helpers/clientinvitations.py
9aabf92cd2fe6382b567b017fdf3896b763c9b92
[]
no_license
webiumsk/WOT-0.9.12-CT
e6c8b5bb106fad71b5c3056ada59fb1aebc5f2b2
2506e34bd6634ad500b6501f4ed4f04af3f43fa0
refs/heads/master
2021-01-10T01:38:38.080814
2015-11-11T00:08:04
2015-11-11T00:08:04
45,803,240
0
0
null
null
null
null
WINDOWS-1250
Python
false
false
4,208
py
# 2015.11.10 21:31:20 Stล™ednรญ Evropa (bฤ›ลพnรฝ ฤas) # Embedded file name: scripts/client_common/shared_utils/account_helpers/ClientInvitations.py import operator from functools import partial import BigWorld import AccountCommands from constants import INVITATION_STATUS from helpers.time_utils import getCurrentTimestamp from debug_utils import LOG_DEBUG, LOG_ERROR, LOG_CURRENT_EXCEPTION class ClientInvitations(object): def __init__(self, playerEvents): self.__proxy = None self.__expCbID = None self.__invitations = {} self.__playerEvents = playerEvents return def __del__(self): self._clearExpiryCallback() def getInvites(self): return self.__invitations def setProxy(self, proxy): self.__proxy = proxy def onProxyBecomePlayer(self): pass def onProxyBecomeNonPlayer(self): pass def processInvitations(self, invitations): LOG_DEBUG('ClientInvitations::processInvitations', invitations) self.__invitations.update(dict(((inv['id'], inv) for inv in invitations))) self._loadExpiryCallback() self.__playerEvents.onPrebattleInvitationsChanged(self.__invitations) def sendInvitation(self, accountsToInvite, comment = '', callback = None): if self.__playerEvents.isPlayerEntityChanging: return self.__proxy._doCmdIntArrStrArr(AccountCommands.CMD_INVITATION_SEND, accountsToInvite, [comment], callback) def acceptInvitation(self, invitationID, senderDBID, callback = None): if self.__playerEvents.isPlayerEntityChanging: return proxy = partial(self._onInvitationResponseReceived, INVITATION_STATUS.ACCEPTED, invitationID, callback) self.__proxy._doCmdInt3(AccountCommands.CMD_INVITATION_ACCEPT, invitationID, senderDBID, 0, proxy) def declineInvitation(self, invitationID, senderDBID, callback = None): if self.__playerEvents.isPlayerEntityChanging: return proxy = partial(self._onInvitationResponseReceived, INVITATION_STATUS.DECLINED, invitationID, callback) self.__proxy._doCmdInt3(AccountCommands.CMD_INVITATION_DECLINE, invitationID, senderDBID, 0, proxy) def _onInvitationResponseReceived(self, newStatus, invID, callback, requestID, code, errStr): if AccountCommands.isCodeValid(code): try: self.__invitations[invID]['status'] = newStatus self.__playerEvents.onPrebattleInvitationsChanged(self.__invitations) except KeyError: LOG_ERROR('Unknown invitation', self.__invitations, invID, callback, code, errStr) if callback is not None: callback(code, errStr) return def _cancelInvitations(self, predicate): for inv in self.__invitations.itervalues(): if predicate(inv): inv['status'] = INVITATION_STATUS.ERROR def _loadExpiryCallback(self): self._clearExpiryCallback() if len(self.__invitations): invite = min(self.__invitations.values(), key=operator.itemgetter('expiresAt')) if invite: expTime = max(invite['expiresAt'] - getCurrentTimestamp(), 0.0) self.__expCbID = BigWorld.callback(expTime, partial(self.__onInviteExpired, invite)) LOG_DEBUG('Invite expiration callback has been loaded', invite['id'], expTime) def _clearExpiryCallback(self): if self.__expCbID is not None: BigWorld.cancelCallback(self.__expCbID) self.__expCbID = None return def __onInviteExpired(self, invite): try: del self.__invitations[invite['id']] self.__playerEvents.onPrebattleInvitationsChanged(self.__invitations) except KeyError: LOG_ERROR('There is error while removing expired invite') LOG_CURRENT_EXCEPTION() self._loadExpiryCallback() # okay decompyling c:\Users\PC\wotsources\files\originals\res\scripts\client_common\shared_utils\account_helpers\clientinvitations.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2015.11.10 21:31:20 Stล™ednรญ Evropa (bฤ›ลพnรฝ ฤas)
[ "info@webium.sk" ]
info@webium.sk
b54885425e7278e641874386e1ccff87dbbe256d
e4a9b67bf2baa6394ba003ece58cf6c4f2be8dd6
/src/vm_images.py
513654c927010adc6f9a7ed05e94c8a841f74708
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mbrukman/cloud-launcher
57d6723301efc2aa795e42128435c6566a2ac0d2
3ad9e36a523a42edbf327e2fb979dfa1c1333114
refs/heads/main
2022-05-07T07:25:46.696466
2022-04-26T14:45:16
2022-04-26T14:53:23
21,208,554
21
8
Apache-2.0
2022-04-26T14:53:24
2014-06-25T15:35:51
Shell
UTF-8
Python
false
false
1,790
py
# Copyright 2014 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################################################################## # # Handles VM images (e.g., shortnames) for simplifying config specification. import json import os class InvalidImageShortName(Exception): def __init__(self, value): self.__value = value def __str__(self): return repr(self.__value) PROJECT_IMAGES = None if PROJECT_IMAGES is None: vm_images_path = os.path.join(os.path.dirname( __file__), 'cache', 'vm_images.json') with open(vm_images_path, 'r') as vm_images_fd: PROJECT_IMAGES = json.loads(vm_images_fd.read()) def ImageShortNameToUrl(image): image_url_fmt = 'https://www.googleapis.com/compute/v1/projects/%(project)s/global/images/%(image)s' for (project, data) in PROJECT_IMAGES.items(): if image in data['images']: return image_url_fmt % { 'project': project, 'image': image, } elif ('pseudo' in data) and (image in data['pseudo']): return image_url_fmt % { 'project': project, 'image': data['pseudo'][image], } raise InvalidImageShortName('Unknown short image name: %s' % image)
[ "mbrukman@google.com" ]
mbrukman@google.com
a2147e3264f5a58102dafb2da3db2fb7016d39af
84379e15e54ba79b7e63c1fceecf712b46f22977
/apps/archetype/migrations/0012_auto_20200403_1152.py
f903f354854e67b8a7c746ddecdb14ce3407ebe8
[]
no_license
CoderEnko007/HearthStoneStationBackend
a1d74c324233ebd617ad01df13bc609d1f1aa2f6
6cc92cb806f19f2a2a0596645028cfe2fa5895d6
refs/heads/master
2022-12-11T23:20:24.335737
2022-09-18T07:04:08
2022-09-18T07:04:08
144,392,864
0
0
null
2022-12-08T02:22:42
2018-08-11T14:40:48
JavaScript
UTF-8
Python
false
false
550
py
# Generated by Django 2.0.4 on 2020-04-03 11:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('archetype', '0011_auto_20200330_1537'), ] operations = [ migrations.AlterField( model_name='archetype', name='rank_range', field=models.CharField(choices=[('BRONZE_TO_GOLD', '้’้“œ-้ป„้‡‘'), ('PLATINUM_TO_LEGEND', '็™ฝ้‡‘-ไผ ่ฏด'), ('Legend', 'ไผ ่ฏด')], default='All', max_length=200, verbose_name='ๆŽ’ๅๅˆ†ๆฎต'), ), ]
[ "yf381966217@163.com" ]
yf381966217@163.com
953b4ade341146643faf6f9ff97b66df6f468ad5
b92fc1597d41608753fe0634f65b0035e95d0886
/Dec13Spyder.py
3f55b1abc9c7273360001c014064585399d28118
[]
no_license
lilja79/advent_of_code_2020
6b54860ee20825e27a7aaecb92245c1e117501ac
638229eb5f7619d3fb4e15a8433de042a302fab0
refs/heads/main
2023-02-17T22:40:18.630020
2021-01-21T21:28:01
2021-01-21T21:28:01
318,458,409
1
1
null
2020-12-11T13:09:24
2020-12-04T08:55:20
Python
UTF-8
Python
false
false
1,254
py
# -*- coding: utf-8 -*- """ Created on Tue Dec 15 10:28:30 2020 @author: slb """ #The next two lines clears the workspace from IPython import get_ipython get_ipython().magic('reset -sf') import os file_path = os.path.join(os.path.curdir, "Dec13.txt") with open(file_path) as f: notes = f.readlines() departure = int(notes[0]) busses = notes[1].split(',') #Splits string at commas while 'x' in busses: busses.remove('x') #Remove x's busses = [int(i) for i in busses] #convert strings to int waiting_time = [busses - departure%busses for busses in busses] #Calculate the waiting time for each bus when arriving at depature o'clock for i in range(len(waiting_time)): if waiting_time[i] == min(waiting_time): bus = busses[i] #Determine the ID of the bus with least waiting time result = bus * min(waiting_time) print(result) #%% busses_with_x = notes[1].split(',') busses_str = [str(i) for i in busses] index = [busses_with_x.index(i) for i in busses_str] r = 1 t = pow(10,14) while r: tester = [(t+index[i])%busses[i] for i in range(len(index))] #If all conditions are fulfilled all elements of tester is 0 if sum(tester) == 0: r = 0 break t += 1 print(t)
[ "noreply@github.com" ]
lilja79.noreply@github.com
930adf252802ba2a3034b9c10e96e03272d2fe8b
7cec7784a70b411cc9b27f7558122c80f05dd0bb
/evasion_poc/end_central_dir_header.py
dd8a7dc5335b450087b8b00a3e8e30e8a7bb1606
[]
no_license
kcknigh1/file-inspection-evasion-PoC
8f015bab745dfb194442af991a5996d3cf68877e
4e96f5b0cb844438916dd40659828335b2e48c89
refs/heads/main
2023-05-31T17:18:59.770286
2021-06-19T13:11:51
2021-06-19T13:11:51
372,665,497
0
0
null
null
null
null
UTF-8
Python
false
false
2,034
py
"""This is the implementation of the end of central directory header """ from . import utils class EndCentralDirectoryHeader: """Class that represents the end central directory header This class is built from the string representation of the end of the central directory header in hex format. It allows access to diffrent fields in string for reading and writing. """ def __init__(self, header_hex) -> None: """Stores the hex representation of the end of central directory header Args: header_hex (str): The string version of the header in hex """ self._header_hex = header_hex def get_header_hex(self): return self._header_hex def get_num_central_dir_records(self): return utils.hex_to_int(utils.get_header_field(self._header_hex, 8, 2)) def get_size_central_dir_bytes(self): return utils.hex_to_int(utils.get_header_field(self._header_hex, 12, 4)) def get_offset_start_central_dir_from_start(self): return utils.hex_to_int(utils.get_header_field(self._header_hex, 16, 4)) def shift_start_central_dir_start_offset(self, shift_by): """Shifts the start of central directory value The start central directory value is the number of bytes from the start of the file to the start of the central directory. This function is used to shift that number to account for something being prepended to the file before the the central directory. Args: shift_by (int): the number of bytes to shift the start by. Should be the size of what ever was prepended. """ new_offset = self.get_offset_start_central_dir_from_start() + shift_by # splices in the new offset. Have to multiply the indexes by 2 to # account for the byte size. self._header_hex = (f'{self._header_hex[:16*2]}' f'{utils.int_to_hex(new_offset, 4)}' f'{self._header_hex[20*2:]}')
[ "kyle-knight@hotmail.com" ]
kyle-knight@hotmail.com
afeb3b566ef53020af09d49c264f1a05d982fb63
87425e46c05ac220be5d3f131684d45365127123
/people/people.py
c5224f9c64512cd9aa671979779dd2ce3b5e8a93
[]
no_license
JohnTheUnigoat/Python_Lab_02
02a22e7db673266a7b085ca3add37109d026013e
4331c27c668998574fc29af056a9f6d6f455bfa1
refs/heads/master
2022-06-29T12:41:55.213358
2020-05-08T23:09:31
2020-05-08T23:09:31
261,896,537
0
0
null
null
null
null
UTF-8
Python
false
false
1,735
py
from abc import ABC class Person(ABC): def __init__(self, first_name, last_name, age, salary): self.first_name = first_name self.last_name = last_name self.age = age self.salary = salary @property def email(self): return f"{self.first_name.lower()}.{self.last_name.lower()}@mail.com" def __str__(self): return f"Name: {self.first_name} {self.last_name}\nAge: {self.age}\nEmail: {self.email}\nSalary: {self.salary}\n" class Employee(Person): def __init__(self, first_name, last_name, age, salary, company_name): super().__init__(first_name, last_name, age, salary) self.company_name = company_name @property def email(self): return f"{self.first_name.lower()}.{self.last_name.lower()}@companyname.com" def __str__(self): res = "Employee:\n" res += super().__str__() res += f"Company: {self.company_name}\n" return res class Worker(Person): def __init__(self, first_name, last_name, age, salary, job): super().__init__(first_name, last_name, age, salary) self.job = job def __str__(self): res = "Worker:\n" res += super().__str__() res += f"Job: {self.job}\n" return res class Engineer(Person): def __init__(self, first_name, last_name, age, salary, speciality): super().__init__(first_name, last_name, age, salary) self.speciality = speciality @property def email(self): return f"{self.first_name.lower()}_{self.last_name.lower()}@mail.com" def __str__(self): res = "Engineer:\n" res += super().__str__() res += f"Speciality: {self.speciality}\n" return res
[ "ivanhudzinskyi2000@gmail.com" ]
ivanhudzinskyi2000@gmail.com
e40eb8dc1a774d91cdd53b25616e78a095191e6a
b66ec155356c11cabe2350a583f03dd6fad7f105
/response_operations_ui/common/validators.py
f87e7e5217061e345d8bc8b4d58eb540dab77cd8
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
ONSdigital/response-operations-ui
823344b88d71ddadb36ccc1e7ca2fbd556456e92
c0e37ac87ca8ba8ae0433d0222b3d7b4ff1c2cbd
refs/heads/main
2023-08-18T08:18:44.118075
2023-08-02T10:43:41
2023-08-02T10:43:41
112,603,785
4
2
MIT
2023-09-14T10:35:46
2017-11-30T11:31:09
Python
UTF-8
Python
false
false
544
py
from datetime import datetime from wtforms import ValidationError from config import Config def valid_date_for_event(tag, form): form_datetime = datetime( int(form.year.data), int(form.month.data), int(form.day.data), int(form.hour.data), int(form.minute.data) ) tags_can_be_in_past = ("ref_period_start", "ref_period_end", "employment") if not Config.TEST_MODE: if tag not in tags_can_be_in_past and form_datetime < datetime.now(): raise ValidationError("Selected date can not be in the past")
[ "noreply@github.com" ]
ONSdigital.noreply@github.com
8f74e37fd1c229692cb57974190948d7cb4ae773
050de0c7bae5923f11655f17f07be9687e6870de
/WORKSHOP16/workshop16/settings.py
b21e8f295185d345a9adaec25c82edcbd82ed267
[]
no_license
Kuhnhee/django_practice
a18f68333a6d7f15055e14573b1f040de95f3ba7
eea38527b7cdcd8f3d7604b7cd3bf376ae11dd71
refs/heads/master
2020-07-03T23:17:42.614630
2019-11-08T07:13:20
2019-11-08T07:13:20
202,083,524
0
0
null
null
null
null
UTF-8
Python
false
false
3,113
py
""" Django settings for workshop16 project. Generated by 'django-admin startproject' using Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'i94^wmoji0+z@w&0d)h-vcowa%ltzqw77d0g!7pd^j19*ab3#3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'pages', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'workshop16.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'workshop16.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/'
[ "sheva0902@naver.com" ]
sheva0902@naver.com
bf0f4721d7b30a41f855accbbe15d808bf835f61
11e826cd207343446cd44dbb6ac9f9a6e59e624c
/Python/OOP/oop.py
68ef8e91e6408f319169b4ebe6ddf822e010153e
[]
no_license
sbishop7/DojoAssignments
1395022f9c693f757889461410d96543f8552fa2
29a378830f8de5bbbdc6d397228c2c09329c0d38
refs/heads/master
2021-01-22T23:29:33.527805
2017-07-06T15:01:11
2017-07-06T15:01:11
85,643,842
0
0
null
null
null
null
UTF-8
Python
false
false
1,418
py
# class User(object): # name = "Anna" # anna = User() # print "anna's name: ", anna.name # User.name = "Bob" # print "anna's name after change:", anna.name # bob = User() # print "bob's name:", bob. # class User(object): # def __init__(self, name, email): # self.name = name # self.email = email # self.logged = False # user1 = User("Anna Propas", "anna@anna.com") # print user1.name # print user1.logged # print user1.email # instantiate class User class User(object): # this method to run every time a new object is instantiated def __init__(self, name, email): # instance attributes from self.name = name self.email = email self.logged = True # login method changes the logged status for a single instance (the instance calling the method) def login(self): self.logged = True print self.name + " is logged in." return self # logout method changes the logged status for a single instance (the instance calling the method) def logout(self): self.logged = False print self.name + " is not logged in" return self # print name and email of the calling instance def show(self): print "My name is {}, and I am a {}. You can email me at {}".format(self.name, self.permission, self.email) return self user1 = User("Seth", "bishop@uw.edu") user1.show() # print user1
[ "seth.bishop@gmail.com" ]
seth.bishop@gmail.com
e72d9c21c36e6e2f281ed537407a9e4d18751f70
4bcc2f7859df84bf9b54c387df6f54ade6ae6d0c
/intro_python/lesson2.py
1b8021fb25ba6ccb51cf220c0f7371a9b991482d
[]
no_license
Mojoo25/fall2021mr
9c90ecdaff7fe8918a5d6cb322dc785eaede35cf
e356bbcf161912ac11eb3f8642f3ec1244adc232
refs/heads/main
2023-08-17T16:30:29.116420
2021-09-30T21:04:22
2021-09-30T21:04:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
632
py
# lesson 2 - Arithmetic Operators a = 10 b = 3 # addition operater + print ("a: %d, b: %d, a + b: %d" % (a, b, a + b)) # subtraction operator - print ("a: %d, b: %d, a - b: %d" % (a, b, a - b)) # multiplication operator * print ("a: %d, b: %d, a * b: %d" % (a, b, a * b)) # division operator / print ("a: %d, b: %d, a / b: %.2f" % (a, b, a/b)) # modulus operator print ("a: %d, b: %d, a %% b: %d" % (a, b, a % b)) # exponentiation operator ** print ("a: %d, b: %d, a ** b: %d" % (a, b, a ** b)) # floor division operator // print ("%.1f // %.1f is %.1f" % (11.0, 3.0, 11.0//3.0)) print ("%d // %d is %d" % (-9, 2, -9//2))
[ "diane.williams@ucdenver.edu" ]
diane.williams@ucdenver.edu
63fe904b1c5e73ffde557ab9051be2b39467aae7
7dbbce6c07203e9395d4353c2289977af18fc5b8
/AMIAQuestioning/graduate/models.py
56b95b23e5c62d5894fd162d0bf6a3fe51c74258
[]
no_license
levenkoevgeny/AMIAPsychologist
9c518e8ed796d9bdb78eacca964ddd0322b4ff70
c961cc9d431bf6fcc4556ad7d7b058348c869b63
refs/heads/main
2023-08-29T02:32:31.376503
2021-10-29T12:11:35
2021-10-29T12:11:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
17,553
py
from django.db import models class Rank(models.Model): rank = models.CharField(max_length=100, verbose_name="ะกะฟะตั†ะธะฐะปัŒะฝะพะต ะทะฒะฐะฝะธะต") def __str__(self): return self.rank class Meta: ordering = ('id',) verbose_name = 'ะกะฟะตั†ะธะฐะปัŒะฝะพะต ะทะฒะฐะฝะธะต' verbose_name_plural = 'ะกะฟะตั†ะธะฐะปัŒะฝั‹ะต ะทะฒะฐะฝะธั' class Position(models.Model): position = models.CharField(max_length=255, verbose_name="ะ”ะพะปะถะฝะพัั‚ัŒ") def __str__(self): return self.position class Meta: ordering = ('id',) verbose_name = 'ะ”ะพะปะถะฝะพัั‚ัŒ' verbose_name_plural = 'ะ”ะพะปะถะฝะพัั‚ะธ' class Guardian(models.Model): guardian = models.CharField(max_length=255, verbose_name="ะžะฟะตะบัƒะฝ") def __str__(self): return self.guardian class Meta: ordering = ('id',) verbose_name = 'ะžะฟะตะบัƒะฝ' verbose_name_plural = 'ะžะฟะตะบัƒะฝั‹' class SatisfiedWithTheTraining(models.Model): satisfied = models.CharField(max_length=255, verbose_name="ะฃะดะพั‚ะฒะพะปะตั€ะตะฝั‹ ะปะธ ะ’ั‹ ะบะฐะบ ะฟั€ะพัˆะปะพ ะพะฑัƒั‡ะตะฝะธะต") def __str__(self): return self.satisfied class Meta: ordering = ('id',) verbose_name = 'ะฃะดะพะฒะปะตั‚ะฒะพั€ะตะฝะธะต ะพะฑัƒั‡ะตะฝะธะตะผ' verbose_name_plural = 'ะฃะดะพะฒะปะตั‚ะฒะพั€ะตะฝะธะต ะพะฑัƒั‡ะตะฝะธะตะผ' class Expectations(models.Model): expectation = models.CharField(max_length=255, verbose_name="ะžะถะธะดะฐะฝะธะต") def __str__(self): return self.expectation class Meta: ordering = ('id',) verbose_name = 'ะžะฟั€ะฐะฒะดะฐะฝะธะต ะพะถะธะดะฐะฝะธะน' verbose_name_plural = 'ะžะฟั€ะฐะฒะดะฐะฝะธะต ะพะถะธะดะฐะฝะธะน' class CharacterChange(models.Model): change = models.CharField(max_length=255, verbose_name="ะ˜ะทะผะตะฝะตะฝะธะต") def __str__(self): return self.change class Meta: ordering = ('id',) verbose_name = 'ะ˜ะทะผะตะฝะตะฝะธะต ั…ะฐั€ะฐะบั‚ะตั€ะฐ' verbose_name_plural = 'ะ˜ะทะผะตะฝะตะฝะธะต ั…ะฐั€ะฐะบั‚ะตั€ะฐ' class AfterGraduating(models.Model): after_graduating = models.CharField(max_length=255, verbose_name="ะ”ะตะนัั‚ะฒะธั ะฟะพัะปะต ะพะบะพะฝั‡ะฐะฝะธั ะะบะฐะดะตะผะธะธ") def __str__(self): return self.after_graduating class Meta: ordering = ('id',) verbose_name = 'ะ”ะตะนัั‚ะฒะธะต ะฟะพัะปะต ะพะบะพะฝั‡ะฐะฝะธั' verbose_name_plural = 'ะ”ะตะนัั‚ะฒะธั ะฟะพัะปะต ะพะบะพะฝั‡ะฐะฝะธั' class WhatInduceToQuit(models.Model): what_induce_to_quit = models.CharField(max_length=255, verbose_name="ะงั‚ะพ ะผะพะถะตั‚ ะฟะพะฑัƒะดะธั‚ัŒ ะ’ะฐั ัƒะฒะพะปะธั‚ัŒัั?") def __str__(self): return self.what_induce_to_quit class Meta: ordering = ('id',) verbose_name = 'ะงั‚ะพ ะผะพะถะตั‚ ะฟะพะฑัƒะดะธั‚ัŒ ัƒะฒะพะปะธั‚ัŒัั' verbose_name_plural = 'ะงั‚ะพ ะผะพะถะตั‚ ะฟะพะฑัƒะดะธั‚ัŒ ัƒะฒะพะปะธั‚ัŒัั' class WhatKeeps(models.Model): what_keeps = models.CharField(max_length=255, verbose_name="ะงั‚ะพ ะ’ะฐั ัƒะดะตั€ะถะธะฒะฐะตั‚ ะธะปะธ ะผะพั‚ะธะฒะธั€ัƒะตั‚ ะฟั€ะพะดะพะปะถะฐั‚ัŒ ัะปัƒะถะฑัƒ?") def __str__(self): return self.what_keeps class Meta: ordering = ('id',) verbose_name = 'ะงั‚ะพ ัƒะดะตั€ะถะธะฒะฐะตั‚' verbose_name_plural = 'ะงั‚ะพ ัƒะดะตั€ะถะธะฒะฐะตั‚' class HowDidTeachersInfluence(models.Model): how_did_teachers_influence = models.CharField(max_length=255, verbose_name="ะšะฐะบ ะฒ ั†ะตะปะพะผ ะฟะพะฒะปะธัะปะธ ะฝะฐ ะฒะฐัˆะต ะฟั€ะพั„ะตััะธะพะฝะฐะปัŒะฝะพะต ัั‚ะฐะฝะพะฒะปะตะฝะธะต ะฟั€ะตะฟะพะดะฐะฒะฐั‚ะตะปะธ ะะบะฐะดะตะผะธะธ ะœะ’ะ”?") def __str__(self): return self.how_did_teachers_influence class Meta: ordering = ('id',) verbose_name = 'ะšะฐะบ ะฟะพะฒะปะธัะปะธ ะฟั€ะตะฟะพะดะฐะฒะฐั‚ะตะปะธ' verbose_name_plural = 'ะšะฐะบ ะฟะพะฒะปะธัะปะธ ะฟั€ะตะฟะพะดะฐะฒะฐั‚ะตะปะธ' class HowDidLeadersInfluence(models.Model): how_did_leaders_influence = models.CharField(max_length=255, verbose_name="ะšะฐะบ ะฒ ั†ะตะปะพะผ ะฟะพะฒะปะธัะปะธ ะฝะฐ ะฒะฐัˆะต ะฟั€ะพั„ะตััะธะพะฝะฐะปัŒะฝะพะต ัั‚ะฐะฝะพะฒะปะตะฝะธะต ะบัƒั€ัะพะฒั‹ะต ะพั„ะธั†ะตั€ั‹?") def __str__(self): return self.how_did_leaders_influence class Meta: ordering = ('id',) verbose_name = 'ะšะฐะบ ะฟะพะฒะปะธัะปะธ ะบัƒั€ัะพะฒั‹ะต' verbose_name_plural = 'ะšะฐะบ ะฟะพะฒะปะธัะปะธ ะบัƒั€ัะพะฒั‹ะต' class Inform(models.Model): i_inform = models.CharField(max_length=255, verbose_name="ะฏ ะธะฝั„ะพั€ะผะธั€ะพะฒะฐะฝ - ะฟะพ ะฟัะธั…ะพะปะพะณะธั‡ะตัะบะพะน ะฟะพะผะพั‰ะธ") def __str__(self): return self.i_inform class Meta: ordering = ('id',) verbose_name = 'ะ˜ะฝั„ะพั€ะผะธั€ะพะฒะฐะฝ' verbose_name_plural = 'ะ˜ะฝั„ะพั€ะผะธั€ะพะฒะฐะฝ' class GraduateForm(models.Model): rank = models.ForeignKey(Rank, on_delete=models.CASCADE, verbose_name="ะกะฟะตั†ะธะฐะปัŒะฝะพะต ะทะฒะฐะฝะธะต") group = models.CharField(max_length=100, verbose_name="ะ“ั€ัƒะฟะฟะฐ") fio = models.CharField(max_length=255, verbose_name="ะคะ˜ะž") position = models.ForeignKey(Position, on_delete=models.CASCADE, verbose_name="ะ”ะพะปะถะฝะพัั‚ัŒ") marital_status = models.IntegerField(verbose_name="ะกะตะผะตะนะฝะพะต ะฟะพะปะพะถะตะฝะธะต") married_from = models.IntegerField(verbose_name="ะ–ะตะฝะฐั‚/ะทะฐะผัƒะถะตะผ ั - ", blank=True, null=True) has_children = models.IntegerField(verbose_name="ะ˜ะผะตัŽั‚ัั ะปะธ ะดะตั‚ะธ?", default=0) children_data = models.CharField(max_length=255, verbose_name="ะŸะพะป ะธ ะณะพะด ั€ะพะถะดะตะฝะธั ั€ะตะฑะตะฝะบะฐ", blank=True, null=True) parents_data = models.IntegerField(verbose_name="ะกะฒะตะดะตะฝะธั ะพ ั€ะพะดะธั‚ะตะปัั…") divorced_from = models.IntegerField(verbose_name="ะ’ ั€ะฐะทะฒะพะดะต ั", blank=True, null=True) divorced_live = models.IntegerField(verbose_name="ะ’ ั€ะฐะทะฒะพะดะต - ะถะธะฒัƒั‚", blank=True, null=True) mother_only_father_died_in = models.IntegerField(verbose_name="ะžั‚ะตั† ัƒะผะตั€(ะฟะพะณะธะฑ) ะฒ", blank=True, null=True) mother_only_father_died_other = models.CharField(max_length=255, verbose_name="ะžั‚ะตั† ัƒะผะตั€(ะฟะพะณะธะฑ) ะธะฝะพะต", blank=True, null=True) father_only_mother_died_in = models.IntegerField(verbose_name="ะœะฐั‚ัŒ ัƒะผะตั€ะปะฐ(ะฟะพะณะธะฑะปะฐ) ะฒ", blank=True, null=True) father_only_mother_died_other = models.CharField(max_length=255, verbose_name="ะœะฐั‚ัŒ ัƒะผะตั€ะปะฐ(ะฟะพะณะธะฑะปะฐ) ะธะฝะพะต", blank=True, null=True) stepfather_stepmother_marriage_mother = models.IntegerField(verbose_name="ะŸั€ะพะถะธะฒะฐะตั‚ ั ะพั‚ั‡ะธะผะพะผ/ะผะฐั‡ะตั…ะพะน ัะพะฒะผะตัั‚ะฝะพ/ั€ะฐะทะดะตะปัŒะฝะพ", blank=True, null=True) stepfather_stepmother_marriage_father = models.IntegerField(verbose_name="ะŸั€ะพะถะธะฒะฐะตั‚ ั ะพั‚ั‡ะธะผะพะผ/ะผะฐั‡ะตั…ะพะน ัะพะฒะผะตัั‚ะฝะพ/ั€ะฐะทะดะตะปัŒะฝะพ", blank=True, null=True) mother_father_data = models.IntegerField(verbose_name="ะกะฒะตะดะตะฝะธัะผะธ ะพ ั€ะพะดะธั‚ะตะปัั… ั€ะฐัะฟะพะปะพะณะฐัŽ/ะฝะต ั€ะฐัะฟะพะปะพะณะฐัŽ", blank=True, null=True) guardians = models.ManyToManyField(Guardian, verbose_name="ะžะฟะตะบัƒะฝั‹", blank=True) guardians_other = models.CharField(max_length=255, verbose_name="ะžะฟะตะบัƒะฝั‹ (ะธะฝะพะต)", blank=True, null=True) father_stepfather = models.TextField(verbose_name="ะžั‚ะตั†, ะพั‚ั‡ะธะผ (ะดะฐะฝะฝั‹ะต)") mother_stepmother = models.TextField(verbose_name="ะœะฐั‚ัŒ, ะผะฐั‡ะตั…ะฐ (ะดะฐะฝะฝั‹ะต)") siblings = models.TextField(verbose_name="ะ‘ั€ะฐั‚ัŒั (ะดะฐะฝะฝั‹ะต)") sport_kind = models.CharField(max_length=255, verbose_name="ะ’ะธะด ัะฟะพั€ั‚ะฐ", blank=True, null=True) sport_level = models.IntegerField(verbose_name="ะกะฟะพั€ั‚ะธะฒะฝั‹ะน ัƒั€ะพะฒะตะฝัŒ", blank=True, null=True, default=1) sport_period = models.IntegerField(verbose_name="ะŸะตั€ะธะพะดะธั‡ะฝะพัั‚ัŒ ะทะฐะฝัั‚ะธะน ัะฟะพั€ั‚ะพะผ", blank=True, null=True) sport_achievements = models.TextField(verbose_name="ะกะฟะพั€ั‚ะธะฒะฝั‹ะต ะดะพัั‚ะธะถะตะฝะธั", blank=True, null=True) sport_is_only_by_program = models.BooleanField(verbose_name="ะ—ะฐะฝะธะผะฐะปัั ัะฟะพั€ั‚ะพะผ ั‚ะพะปัŒะบะพ ะฟะพ ัƒั‡ะตะฑะฝะพะตะน ะฟั€ะพะณั€ะฐะผะผะต") interest = models.TextField(verbose_name="ะ’ะฐัˆะธ ัƒะฒะปะตั‡ะตะฝะธั ะฝะฐ ะดะฐะฝะฝั‹ะน ะผะพะผะตะฝั‚") is_satisfied_with_the_training = models.ForeignKey(SatisfiedWithTheTraining, on_delete=models.CASCADE, verbose_name="ะฃะดะพะฒะปะตั‚ะฒะพั€ะตะฝั‹ ะปะธ ะ’ั‹ ั‚ะตะผ ะบะฐะบ ะฟั€ะพั…ะพะดะธะปะพ ะ’ะฐัˆะต ะพะฑัƒั‡ะตะฝะธะต", default=1) expectations = models.ForeignKey(Expectations, on_delete=models.CASCADE, verbose_name="ะžะฟั€ะฐะฒะดะฐะปะธััŒ ะพะถะธะดะฐะฝะธั", default=1) character_change = models.ForeignKey(CharacterChange, on_delete=models.CASCADE, verbose_name="ะšะฐะบ ะธะทะผะตะฝะธะปัั ั…ะฐั€ะฐะบั‚ะตั€", default=1) traits_formed = models.TextField(verbose_name="ะšะฐะบะธะต ะบะฐั‡ะตัั‚ะฒะฐ ัั„ะพั€ะผะธั€ะพะฒะฐะปะธััŒ") would_advise = models.IntegerField(verbose_name="ะŸะพัะพะฒะตั‚ะพะฒะฐะปะธ ะฑั‹ ะฟะพัั‚ัƒะฟะฐั‚ัŒ ะฒ ะะบะฐะดะตะผะธัŽ", default=1) after_graduating = models.ForeignKey(AfterGraduating, on_delete=models.CASCADE, verbose_name="ะ”ะตะนัั‚ะฒะธั ะฟะพัะปะต ะพะบะพะฝั‡ะฐะฝะธั ะะบะฐะดะตะผะธะธ", default=1) what_induce_to_quit = models.ManyToManyField(WhatInduceToQuit, verbose_name="ะงั‚ะพ ะผะพะถะตั‚ ะฟะพะฑัƒะดะธั‚ัŒ ะ’ะฐั ัƒะฒะพะปะธั‚ัŒัั?", blank=True) what_induce_to_quit_other = models.CharField(max_length=255, verbose_name="ะงั‚ะพ ะผะพะถะตั‚ ะฟะพะฑัƒะดะธั‚ัŒ ะ’ะฐั ัƒะฒะพะปะธั‚ัŒัั? (ะธะฝะพะต)", blank=True, null=True) what_keeps = models.ManyToManyField(WhatKeeps, verbose_name="ะงั‚ะพ ะ’ะฐั ัƒะดะตั€ะถะธะฒะฐะตั‚ ะธะปะธ ะผะพั‚ะธะฒะธั€ัƒะตั‚ ะฟั€ะพะดะพะปะถะฐั‚ัŒ ัะปัƒะถะฑัƒ?", blank=True) what_keeps_other = models.CharField(max_length=255, verbose_name="ะงั‚ะพ ะ’ะฐั ัƒะดะตั€ะถะธะฒะฐะตั‚ ะธะปะธ ะผะพั‚ะธะฒะธั€ัƒะตั‚ ะฟั€ะพะดะพะปะถะฐั‚ัŒ ัะปัƒะถะฑัƒ? (ะธะฝะพะต)", blank=True, null=True) how_did_teachers_influence = models.ForeignKey(HowDidTeachersInfluence, on_delete=models.CASCADE, verbose_name="ะšะฐะบ ะฒ ั†ะตะปะพะผ ะฟะพะฒะปะธัะปะธ ะฝะฐ ะฒะฐัˆะต ะฟั€ะพั„ะตััะธะพะฝะฐะปัŒะฝะพะต ัั‚ะฐะฝะพะฒะปะตะฝะธะต ะฟั€ะตะฟะพะดะฐะฒะฐั‚ะตะปะธ ะะบะฐะดะตะผะธะธ ะœะ’ะ”?", default=1) how_did_teachers_influence_explain = models.CharField(max_length=255, verbose_name="ะšะฐะบ ะฒ ั†ะตะปะพะผ ะฟะพะฒะปะธัะปะธ ะฝะฐ ะฒะฐัˆะต ะฟั€ะพั„ะตััะธะพะฝะฐะปัŒะฝะพะต ัั‚ะฐะฝะพะฒะปะตะฝะธะต ะฟั€ะตะฟะพะดะฐะฒะฐั‚ะตะปะธ ะะบะฐะดะตะผะธะธ ะœะ’ะ”? (ะฟะพััะฝะธั‚ะต ะพั‚ะฒะตั‚)") how_did_leaders_influence = models.ForeignKey(HowDidLeadersInfluence, on_delete=models.CASCADE, verbose_name="ะšะฐะบ ะฒ ั†ะตะปะพะผ ะฟะพะฒะปะธัะปะธ ะฝะฐ ะฒะฐัˆะต ะฟั€ะพั„ะตััะธะพะฝะฐะปัŒะฝะพะต ัั‚ะฐะฝะพะฒะปะตะฝะธะต ะบัƒั€ัะพะฒั‹ะต ะพั„ะธั†ะตั€ั‹?", default=1) how_did_leaders_influence_explain = models.CharField(max_length=255, verbose_name="ะšะฐะบ ะฒ ั†ะตะปะพะผ ะฟะพะฒะปะธัะปะธ ะฝะฐ ะฒะฐัˆะต ะฟั€ะพั„ะตััะธะพะฝะฐะปัŒะฝะพะต ัั‚ะฐะฝะพะฒะปะตะฝะธะต ะบัƒั€ัะพะฒั‹ะต ะพั„ะธั†ะตั€ั‹? (ะฟะพััะฝะธั‚ะต ะพั‚ะฒะตั‚)") need_conversation = models.IntegerField(verbose_name="ะะตะพะฑั…ะพะดะธะผะพัั‚ัŒ ะฑะตัะตะดั‹ ั ะฟัะธั…ะพะปะพะณะพะผ", default=1) need_conversation_theme = models.TextField(verbose_name="ะงั‚ะพ ะพะฑััƒะดะธั‚ัŒ ั ะฟัะธั…ะพะปะพะณะพะผ", blank=True, null=True) i_inform = models.ManyToManyField(Inform, verbose_name="ะฏ ะธะฝั„ะพั€ะผะธั€ะพะฒะฐะฝ", blank=True) fill_date_time = models.DateTimeField(auto_now=True, verbose_name="ะ”ะฐั‚ะฐ ะทะฐะฟะพะปะฝะตะฝะธั") def __str__(self): return self.fio + ' ' + str(self.fill_date_time) @property def get_marital_status(self): if self.marital_status == 1: status = 'ะฅะพะปะพัั‚/ะฝะต ะทะฐะผัƒะถะตะผ' elif self.marital_status == 2: status = 'ะ–ะตะฝะฐั‚/ะทะฐะผัƒะถะตะผ ั ' + str(self.married_from) elif self.marital_status == 3: status = 'ะ ะฐะทะฒะตะดะตะฝ(ะฐ)' else: status = '' return status @property def get_has_children(self): if self.has_children == 0: has_children = 'ะะตั‚' elif self.has_children == 1: has_children = 'ะ”ะฐ ' + str(self.children_data) else: has_children = '' return has_children @property def get_parents_data(self): parents_data = '' if self.parents_data == 1: parents_data = 'ะœะฐั‚ัŒ ะธ ะพั‚ะตั† ั€ะพะดะฝั‹ะต, ัะพัั‚ะพัั‚ ะฒ ะฑั€ะฐะบะต, ะฟั€ะพะถะธะฒะฐัŽั‚ ัะพะฒะผะตัั‚ะฝะพ' elif self.parents_data == 2: parents_data = 'ะœะฐั‚ัŒ ะธ ะพั‚ะตั† ั€ะพะดะฝั‹ะต, ะฝะฐั…ะพะดัั‚ัั ะฒ ั€ะฐะทะฒะพะดะต c ' + str(self.divorced_from) if self.divorced_live == 1: parents_data = parents_data + ', ะฟั€ะพะถะธะฒะฐัŽั‚ ั€ะฐะทะดะตะปัŒะฝะพ' elif self.divorced_live == 2: parents_data = parents_data + ', ะฟั€ะพะถะธะฒะฐัŽั‚ ัะพะฒะผะตัั‚ะฝะพ' elif self.parents_data == 3: parents_data = 'ะขะพะปัŒะบะพ ะผะฐั‚ัŒ, ั‚ะฐะบ ะบะฐะบ ะพั‚ะตั† ัƒะผะตั€ (ะฟะพะณะธะฑ)' if self.mother_only_father_died_in: parents_data = parents_data + ' ะฒ ' + str(self.mother_only_father_died_in) elif self.mother_only_father_died_other: parents_data = parents_data + ' ะธะฝะพะต - ' + str(self.mother_only_father_died_other) elif self.parents_data == 4: parents_data = 'ะขะพะปัŒะบะพ ะพั‚ะตั†, ะผะฐั‚ัŒ ัƒะผะตั€ะปะฐ (ะฟะพะณะธะฑะปะฐ)' if self.father_only_mother_died_in: parents_data = parents_data + ' ะฒ ' + str(self.father_only_mother_died_in) elif self.father_only_mother_died_other: parents_data = parents_data + ' ะธะฝะพะต - ' + str(self.father_only_mother_died_other) elif self.parents_data == 5: parents_data = 'ะ ะพะดะฝะฐั ะผะฐั‚ัŒ ะฟั€ะพะถะธะฒะฐะตั‚ ัะพะฒะผะตัั‚ะฝะพ ั ะพั‚ั‡ะธะผะพะผ ' if self.stepfather_stepmother_marriage_mother == 1: parents_data = parents_data + 'ะฒ ะฑั€ะฐะบะต' elif self.stepfather_stepmother_marriage_mother == 2: parents_data = parents_data + 'ะฑะตะท ั€ะตะณะธัั‚ั€ะฐั†ะธะธ ะฑั€ะฐะบะฐ' elif self.parents_data == 6: parents_data = 'ะ ะพะดะฝะพะน ะพั‚ะตั†, ะฟั€ะพะถะธะฒะฐะตั‚ ัะพะฒะผะตัั‚ะฝะพ ั ะผะฐั‡ะตั…ะพะน ' if self.stepfather_stepmother_marriage_father == 1: parents_data = parents_data + 'ะฒ ะฑั€ะฐะบะต' elif self.stepfather_stepmother_marriage_father == 2: parents_data = parents_data + 'ะฑะตะท ั€ะตะณะธัั‚ั€ะฐั†ะธะธ ะฑั€ะฐะบะฐ' elif self.parents_data == 7: mother_father_list = ['ะผะฐั‚ะตั€ะธ', 'ะพั‚ั†ะต', 'ะพะฑะพะธั…'] parents_data = 'ะกะฒะตะดะตะฝะธัะผะธ ะพ ' parents_data = parents_data + mother_father_list[self.mother_father_data] parents_data = parents_data + ' ะฝะต ั€ะฐัะฟะพะปะฐะณะฐัŽ' elif self.parents_data == 8: parents_data = 'ะžะฟะตะบัƒะฝั‹ - ' for guardian in self.guardians.all(): parents_data += guardian.guardian parents_data += ', ' if self.guardians_other: parents_data = parents_data + self.guardians_other elif self.parents_data == 9: parents_data = 'ะŸั€ะธะตะผะฝั‹ะต ั€ะพะดะธั‚ะตะปะธ' elif self.parents_data == 10: parents_data = 'ะ’ะพัะฟะธั‚ะฐะฝะฝะธะบ ะดะตั‚ัะบะพะณะพ ะดะพะผะฐ' else: parents_data = 'ะะตั‚ ะดะฐะฝะฝั‹ั…' return parents_data @property def get_sport_level(self): sport_levels = ['ะฝะฐ ะปัŽะฑะธั‚ะตะปัŒัะบะพะผ ัƒั€ะพะฒะฝะต', 'ะฟั€ะพั„ะตััะธะพะฝะฐะปัŒะฝะพ'] if self.sport_kind: sport_level = sport_levels[self.sport_level-1] else: sport_level = '' return sport_level @property def get_sport_period(self): if self.sport_kind: return str(self.sport_period) + ' ั€ะฐะท ะฒ ะฝะตะดะตะปัŽ' else: return '' @property def get_sport_achievements(self): if self.sport_kind: return self.sport_achievements else: return '' @property def get_would_advise(self): advise_list = ['ะ”ะฐ', 'ะะตั‚', 'ะะต ะทะฝะฐัŽ'] return advise_list[self.would_advise-1] @property def get_need_conversation(self): needs_list = ['ะ’ ะฑะตัะตะดะต ะฝะต ะฝัƒะถะดะฐัŽััŒ', 'ะฅะพั‚ะตะปะพััŒ ะฑั‹ ะฟะพะฑะตัะตะดะพะฒะฐั‚ัŒ (ัƒะบะฐะถะธั‚ะต, ั‡ั‚ะพ ะบะพะฝะบั€ะตั‚ะฝะพ ะ’ั‹ ั…ะพั‚ะตะปะธ ะฑั‹ ะพะฑััƒะดะธั‚ัŒ)'] return needs_list[self.need_conversation-1] class Meta: ordering = ('id',) verbose_name = 'ะะฝะบะตั‚ะฐ ะฒั‹ะฟัƒัะบะฝะธะบะฐ' verbose_name_plural = 'ะะฝะบะตั‚ั‹ ะฒั‹ะฟัƒัะบะฝะธะบะพะฒ'
[ "levenko.evgeny@yandex.by" ]
levenko.evgeny@yandex.by
6d3f92371b83d2f63808282e298a51ec9d9ea286
78237d27a2129dccb005886f416453200de7ec4e
/Week 5/edit_distance.py
996f3373479ddd94aa96a956e99c1dcc47ca5ef4
[]
no_license
ahmedsy96/Algorithmic-Toolbox
551c1135f5ce68510fbcc8b8ac46cc0c6f236b1c
39bcd5975c04ecfd05eb22653871752c8156ed0e
refs/heads/master
2021-01-08T08:52:03.926948
2020-02-26T22:10:55
2020-02-26T22:10:55
241,972,324
0
0
null
null
null
null
UTF-8
Python
false
false
663
py
# Uses python3 import numpy as np def edit_distance(s, t): #write your code here slist = list(s) tlist = list(t) s1 =len(slist)+1 t1 = len(tlist)+1 edit = np.zeros((s1,t1)) for i in range (s1): edit[i][0]=i for j in range(t1): edit[0][j] = j for i in range(0,s1-1): for j in range (0,t1-1): if slist[i] == tlist[j]: edit[i+1][j+1] = edit[i][j] else : edit[i+1][j+1]= min(edit[i][j] , edit[i][j+1] , edit[i+1][j])+1 return int(edit[s1-1][t1-1]) if __name__ == "__main__": print(edit_distance(input(), input()))
[ "noreply@github.com" ]
ahmedsy96.noreply@github.com
f04afacbaa891c582e3606517fa5771c36c35b9d
0c0645670f8b5a18d246b42820f016ba2aa02001
/ex48/skeleton/tests/lexicon_tests.py
a61798ec861327d1730539315c3286411ed0b47d
[ "MIT" ]
permissive
MayThuHtun/python-exercises
34054ce878ddb0aaeca5294be30d91145c372892
0f4e85aa9d78855bfdb5c04ff9278799c338e0e5
refs/heads/master
2020-03-19T06:54:08.781450
2018-06-26T05:16:03
2018-06-26T05:16:03
136,065,190
0
0
null
null
null
null
UTF-8
Python
false
false
1,537
py
from nose.tools import * from ex48 import lexicon def test_directions(): assert_equal(lexicon.scan("north"), [('direction', 'north')]) result = lexicon.scan("north south east") assert_equal(result, [('direction', 'north'), ('direction', 'south'), ('direction', 'east')]) def test_verbs(): assert_equal(lexicon.scan("go"), [('verb', 'go')]) result = lexicon.scan("go kill eat") assert_equal(result, [('verb', 'go'), ('verb', 'kill'), ('verb', 'eat')]) def test_stops(): assert_equal(lexicon.scan("the"), [('stop', 'the')]) result = lexicon.scan("the in of") assert_equal(result, [('stop', 'the'), ('stop', 'in'), ('stop', 'of')]) def test_nouns(): assert_equal(lexicon.scan("bear"), [('noun', 'bear')]) result = lexicon.scan("bear princess") assert_equal(result, [('noun', 'bear'), ('noun', 'princess')]) def test_numbers(): assert_equal(lexicon.scan("1234"), [('number', 1234)]) result = lexicon.scan("3 91234") assert_equal(result, [('number', 3), ('number', 91234)]) def test_errors(): assert_equal(lexicon.scan("ASDFADFASDF"), [('error', 'ASDFADFASDF')]) result = lexicon.scan("bear IAS princess") assert_equal(result, [('noun', 'bear'), ('error', 'IAS'), ('noun', 'princess')])
[ "maythutun.ucsmdy@gmail.com" ]
maythutun.ucsmdy@gmail.com
3ca676d5d439c786ab45531d6f8f4697907f3227
7ed71c5d63a6e16933e2af6c279192c87f6dc001
/lib/texaspoker.py
0c34803176f87e275f4d238aefb588b13ab817e7
[]
no_license
Infinitywxh/Texas-Poker-platform
e267336843585373003969d71a0d91b75f69186d
318b484e604ae9c6b570f04e5069f2c48fb9e4ce
refs/heads/master
2021-10-18T23:04:59.978012
2019-02-15T03:13:43
2019-02-15T03:13:43
170,783,952
0
0
null
null
null
null
UTF-8
Python
false
false
14,956
py
from time import sleep import communicate.dealer_pb2 as dealer_pb2 import communicate.dealer_pb2_grpc as rpc # 0 ้ป‘ๆกƒ 1 ็บขๆกƒ 2 ๆ–น็‰‡ 3 ่‰่Šฑ # ็‰Œ็š„id: 0-51 ''' ็‰Œ้ขlevel็ผ–ๅท ็š‡ๅฎถๅŒ่Šฑ้กบ๏ผš10 ๅŒ่Šฑ้กบ ๏ผš9 ๅ››ๆก ๏ผš8 ่‘ซ่Šฆ ๏ผš7 ๅŒ่Šฑ ๏ผš6 ้กบๅญ ๏ผš5 ไธ‰ๆก ๏ผš4 ไธคๅฏน ๏ผš3 ไธ€ๅฏน ๏ผš2 ้ซ˜็‰Œ ๏ผš1 ''' # alter the card id into color def id2color(card): return card % 4 # alter the card id into number def id2num(card): return card // 4 # poker hand of 7 card class Hand(object): def __init__(self, cards): cards = cards[:] self.level = 0 self.cnt_num = [0] * 13 self.cnt_color = [0] * 4 self.cnt_num_eachcolor = [[0 for col in range(13)] for row in range(4)] self.maxnum = -1 self.single = [] self.pair = [] self.tripple = [] for x in cards: self.cnt_num[id2num(x)] += 1 self.cnt_color[id2color(x)] += 1 self.cnt_num_eachcolor[id2color(x)][id2num(x)] += 1 for i in range(12, -1, -1): if self.cnt_num[i] == 1: self.single.append(i) elif self.cnt_num[i] == 2: self.pair.append(i) elif self.cnt_num[i] == 3: self.tripple.append(i) self.single.sort(reverse=True) self.pair.sort(reverse=True) self.tripple.sort(reverse=True) # calculate the level of the poker hand for i in range(4): if self.cnt_num_eachcolor[i][8:13].count(1) == 5: self.level = 10 return for i in range(4): for j in range(7, -1, -1): if self.cnt_num_eachcolor[i][j:j+5].count(1) == 5: self.level = 9 self.maxnum = j + 4 return for i in range(12, -1, -1): if self.cnt_num[i] == 4: self.maxnum = i self.level = 8 return tripple = self.cnt_num.count(3) if tripple > 1: self.level = 7 return elif tripple > 0: if self.cnt_num.count(2) > 0: self.level = 7 return for i in range(4): if self.cnt_color[i] >=5: if(max(self.cnt_num_eachcolor[i]) > self.maxnum): self.maxnum = max(self.cnt_num_eachcolor[i]) self.level = 6 if self.level == 6: return for i in range(8, -1, -1): flag = 1 for j in range(i, i + 5): if self.cnt_num[j] == 0: flag = 0 break if flag == 1: self.maxnum = i + 4 self.level = 5 return for i in range(12, -1, -1): if self.cnt_num[i] == 3: self.maxnum = i self.level = 4 return if self.cnt_num.count(2) > 1: self.level = 3 return for i in range(12, -1, -1): if self.cnt_num[i] == 2: self.maxnum = i self.level = 2 return if self.cnt_num.count(1) == 7: self.level = 1 return self.level = -1 def __str__(self): return 'level = %s' % self.level def cmp(x,y): # x < y return 1 if x > y: return -1 elif x == y: return 0 else: return 1 # find the bigger of two poker hand, if cards0 < cards1 then return 1, cards0 > cards1 return -1, else return 0 def judge_two(cards0, cards1): hand0 = Hand(cards0) hand1 = Hand(cards1) if hand0.level > hand1.level: return 0 elif hand0.level < hand1.level: return 1 else: if hand0.level in [5, 6, 9]: return cmp(hand0.maxnum, hand1.maxnum) elif hand0.level in [1, 2, 4]: t = cmp(hand0.maxnum, hand1.maxnum) if t == 1: return 1 elif t == -1: return -1 else: if hand0.single < hand1.single: return 1 elif hand0.single == hand1.single: return 0 else: return -1 elif hand0.level == 8: t = cmp(hand0.maxnum, hand1.maxnum) if t == 1: return 1 elif t == -1: return -1 else: pair_single0 = hand0.pair + hand0.pair + hand0.single pair_single0.sort() pair_single1 = hand1.pair + hand1.pair + hand1.single pair_single1.sort() if pair_single0 < pair_single1: return 1 elif pair_single0 == pair_single1: return 0 else: return -1 elif hand0.level == 3: if cmp(hand0.pair[0], hand1.pair[0]) != 0: return cmp(hand0.pair[0], hand1.pair[0]) elif cmp(hand0.pair[1], hand1.pair[1]) != 0: return cmp(hand0.pair[1], hand1.pair[1]) else: hand0.pair = hand0.pair[2:] hand1.pair = hand1.pair[2:] tmp0 = hand0.pair + hand0.pair + hand0.single tmp1 = hand1.pair + hand1.pair + hand1.single if tmp0 < tmp1: return 1 elif tmp0 == tmp1: return 0 else: return -1 elif hand0.level == 7: if cmp(hand0.tripple[0], hand1.tripple[0]) != 0: return cmp(hand0.tripple[0], hand1.tripple[0]) else: tmp0 = hand0.pair tmp1 = hand1.pair if len(hand0.tripple) > 1: tmp0.append(hand0.tripple[1]) if len(hand1.tripple) > 1: tmp1.append(hand1.tripple[1]) if tmp0 < tmp1: return 1 elif tmp0 == tmp1: return 0 else: return -1 else: pass # assert 0 class Player(object): def __init__(self, initMoney, state): self.active = True # if the player is active(haven't giveups) self.money = initMoney # money player has self.bet = 0 # the bet in this round self.cards = [] # private cards self.allin = 0 # if the player has all in self.totalbet = 0 # the bet in total(all round) self.state = state # state # raise the bet by amount def raisebet(self, amount): self.money -= amount self.bet += amount assert self.money > 0 # player allin def allinbet(self): self.bet += self.money self.allin = 1 self.money = 0 def getcards(self): return self.cards + self.state.sharedcards def __str__(self): return 'player: active = %s, money = %s, bet = %s, allin = %s' % (self.active, self.money, self.bet, self.allin) class State(object): def __init__(self, totalPlayer, initMoney, bigBlind, button): ''' class to hold the game ''' self.totalPlayer = totalPlayer self.bigBlind = bigBlind self.button = button self.currpos = 0 # current position self.playernum = totalPlayer # active player number self.moneypot = 0 # money in the pot self.minbet = bigBlind # minimum bet to call self.sharedcards = [] self.turnNum = 0 self.last_raised = bigBlind # the amount of bet raise last time self.player = [] for i in range(totalPlayer): self.player.append(Player(initMoney, self)) def __str__(self): return 'state: currpos = %s, playernum = %s, moneypot = %s, \n minbet = %s, last_raised = %s' \ % (self.currpos, self.playernum, self.moneypot, self.minbet, self.last_raised) def restore(self, turn, button, bigBlind): # restore the state before each round self.turnNum = turn self.currpos = button self.minbet = 0 self.last_raised = bigBlind def update(self, totalPlayer): # update the state after each round for i in range(totalPlayer): self.player[i].totalbet += self.player[i].bet self.player[i].bet = 0 # judge if the round is over def round_over(self): if self.playernum == 1: return 1 for i in range(self.totalPlayer): if self.player[i].active is True and self.player[i].allin == 0: break else: return 1 for i in range(self.totalPlayer): if self.player[i].active is True and (self.player[i].bet != self.minbet and self.player[i].allin == 0): return 0 if self.turnNum != 0 and self.minbet == 0: return 0 return 1 # calculate the next position def nextpos(self, pos): self.currpos = (pos + 1) % self.totalPlayer return self.currpos # play a round def play_round(self, round, request, response, response_so_far): checkflag = 0 while True: if self.round_over() == 1: break self.currpos = self.nextpos(self.currpos) if self.player[self.currpos].active == False: continue if self.player[self.currpos].allin == 1: continue decision = Decision() # asking the client for the decision for i in range(self.totalPlayer): response[i].append(dealer_pb2.DealerRequest(pos=self.currpos, type=2)) cnt = 0 abort = 0 # wait more than 15 sec, abort while len(request[self.currpos]) == 0: if cnt >= 15: print('*******player %s disconnected, abort*******' % self.currpos) abort = 1 break cnt += 1 sleep(1) if abort == 0: tmp = request[self.currpos].pop(0) decision.update([tmp.giveup, tmp.allin, tmp.check, tmp.callbet, tmp.raisebet, tmp.amount]) else: decision.giveup = 1 if decision.callbet == 1 and self.minbet == 0: decision.callbet = 0 decision.check = 1 if decision.giveup == 1: self.player[self.currpos].active = False self.playernum -= 1 print("## player %s giveup" % self.currpos) elif round != 0 and decision.check == 1: if checkflag == 1: self.illegalmove() continue print("## player %s check" % self.currpos) elif decision.allin == 1: t = self.player[self.currpos].money self.moneypot += self.player[self.currpos].money self.player[self.currpos].allinbet() if self.player[self.currpos].bet > self.minbet: self.last_raised = self.player[self.currpos].bet - self.minbet self.minbet = self.player[self.currpos].bet checkflag = 1 print("## player %s allin: %s" % (self.currpos, t)) elif decision.callbet == 1: delta = self.minbet - self.player[self.currpos].bet assert delta >= 0 if delta >= self.player[self.currpos].money or delta < 0: self.illegalmove() continue self.player[self.currpos].raisebet(delta) self.moneypot += delta checkflag = 1 print("## player %s callbet: %s" % (self.currpos, delta)) elif decision.raisebet == 1: assert decision.amount >= self.minbet if decision.amount - self.minbet < self.last_raised: self.illegalmove() continue self.last_raised = decision.amount - self.minbet self.minbet = decision.amount delta = decision.amount - self.player[self.currpos].bet if delta >= self.player[self.currpos].money or delta < 0: self.illegalmove() continue self.player[self.currpos].raisebet(delta) self.moneypot += delta checkflag = 1 print("## player %s raisebet: %s" % (self.currpos, delta)) else: self.illegalmove() continue for i in range(self.totalPlayer): t = dealer_pb2.DealerRequest(giveup=decision.giveup, allin=decision.allin, check=decision.check, callbet=decision.callbet, raisebet=decision.raisebet, amount=decision.amount, pos=self.currpos, type=1) response[i].append(t) response_so_far[i].append(t) print(self) print(self.player[self.currpos]) print('\n') # find a winner in the active player def findwinner(self): winpos = -1 for pos in range(self.totalPlayer): if self.player[pos].active == 0: continue if winpos == -1: winpos = pos else: t = judge_two(self.player[winpos].getcards(), self.player[pos].getcards()) if t == 1: winpos = pos return winpos def illegalmove(self): # player่ฟ›่กŒ้žๆณ•่กŒๅŠจ็š„ๅค„็† # TODO send infomation to the player: illegal decision! self.player[self.currpos].active = False self.playernum -= 1 self.currpos = self.nextpos(self.currpos) print('player %s illegal move' % self.currpos) class Decision(object): giveup = 0 # ๅผƒ็‰Œ allin = 0 # ๅ…จๆŠผ check = 0 # ่ฟ‡็‰Œ callbet = 0 # ่ทŸๆณจ raisebet = 0 # ๅŠ ๆณจ amount = 0 # ๅŠ ๆณจๅˆฐamount def clear(self): self.giveup = self.allin = self.check = self.callbet = self.raisebet = self.amount = 0 def update(self, a): self.giveup = a[0] self.allin = a[1] self.check = a[2] self.callbet = a[3] self.raisebet = a[4] self.amount = a[5] def __str__(self): return 'giveup=%s, allin=%s, check=%s, callbet=%s, raisebet=%s, amount=%s' % (self.giveup,self.allin,self.check, self.callbet, self.raisebet, self.amount)
[ "xhwang@ubiquant.com" ]
xhwang@ubiquant.com
f78b2f8f87603c09dad3cff0b8e97b47fab22561
feb36ce65afc45ef9ada5d0097378bfdc544c9be
/site_task/Lib/site-packages/funcy/funcmakers.py
f065e93305a01ee29f380fdd5bd4887408fabeba
[]
no_license
Kryvtsov15/Task-abz
6735c483f40e73049596381c7136caa9c336c167
617556aca44b7c21353e37857a38e8bb6c0bbc74
refs/heads/master
2020-04-12T04:09:41.189439
2018-12-18T13:51:41
2018-12-18T13:51:41
162,286,930
0
0
null
null
null
null
UTF-8
Python
false
false
1,579
py
import sys from functools import wraps from operator import itemgetter from collections import Mapping, Set from .cross import imap, ifilter, ifilterfalse, basestring, PY2 from .simple_funcs import identity from .strings import re_tester, re_finder, _re_type __all__ = ('make_func', 'make_pred', 'wrap_mapper', 'wrap_selector') def make_func(f, builtin=False, test=False): if callable(f): return f elif f is None: # pass None to builtin as predicate or mapping function for speed return None if builtin else \ bool if test else identity elif isinstance(f, (basestring, _re_type)): return re_tester(f) if test else re_finder(f) elif isinstance(f, (int, slice)): return itemgetter(f) elif isinstance(f, Mapping): return f.__getitem__ elif isinstance(f, Set): return f.__contains__ else: raise TypeError("Can't make a func from %s" % f.__class__.__name__) def make_pred(pred, builtin=False): return make_func(pred, builtin=builtin, test=True) def _wrap_higher_order(func, test): # NOTE: builtin housekeeping: # map(None, ...) is much faster than map(identity, ...), # also map(None, ...) works as zip() for multiple seqs builtin = PY2 and func in set([map, filter, imap, ifilter, ifilterfalse]) return wraps(func)(lambda f, *seqs: func(make_func(f, builtin=builtin, test=test), *seqs)) def wrap_mapper(func): return _wrap_higher_order(func, test=False) def wrap_selector(func): return _wrap_higher_order(func, test=True)
[ "45894407+Kryvtsov15@users.noreply.github.com" ]
45894407+Kryvtsov15@users.noreply.github.com
436524445c48e1916ee3d9172ce8df26dd436cae
d188eb3a14a7a991edbb085d485cafeb9c740588
/src/beginner_tutorials/scripts/add_two_ints_server.py
b62bc4ef9f8d755d72723a97bd79a583b42fcf68
[]
no_license
CFreeman217/catkin_ws
988d9bc5afc78354d5c832edeaaa1895dca48dd0
3251fd2012d250dc2461226378f74955e61faa46
refs/heads/master
2020-04-22T02:30:51.955979
2019-02-11T02:00:50
2019-02-11T02:00:50
170,050,475
0
0
null
null
null
null
UTF-8
Python
false
false
445
py
#!/usr/bin/env python from beginner_tutorials.srv import * import rospy def handle_add_two_ints(req): print "returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b)) return AddTwoIntsResponse(req.a + req.b) def add_two_ints_server(): rospy.init_node('add_two_ints_server') s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints) print "Ready to add two ints." rospy.spin() if __name__ == "__main__": add_two_ints_server()
[ "freeman.clayton@gmail.com" ]
freeman.clayton@gmail.com
ba2dbe927aa7dd8176d9e84e9827c5411c465d81
da27e8f223646d7ca214cfec1338327ea7d7bd99
/accounts/Python4_calcuator.py
61125ea7bb33448a0c06ff86814da0a35a791af4
[]
no_license
rishabhkatiyar1991/dummy
b1b26d2e2025763c802f29218212cd8a747d40a2
d395add2b952371f361444ee7710943eaef18e43
refs/heads/master
2022-11-14T14:33:15.759226
2020-06-26T08:30:12
2020-06-26T08:30:12
275,107,021
0
0
null
null
null
null
UTF-8
Python
false
false
574
py
# Faulty Calculator # 45* 3 = 555, 56+9=77, 56/6= 4 num1 = int(input("Enter first Number ")) num2 = input("Chose + - * / ") num3 = int(input("Enter secound Number ")) if num1 == 45 and num2 == "*" and num3 == 3: print(555) elif num1 == 56 and num2 == "+" and num3 == 9: print(77) elif num1 == 56 and num2 == "/" and num3 == 6: print(4) elif num2 == "+" : plus = num1 + num3 print(plus) elif num2 == "-": min = num1 - num3 print(min) elif num2 == "*": mul = num1 * num3 print(mul) else: div = num1 / num3 print(format(div, '2f'))
[ "rishabhkatiyar1991@gmail.com" ]
rishabhkatiyar1991@gmail.com
ecb66454aea25f654bb7601de2c3bfcd6f53319d
8088639d3bf7a95c465b2d4abebf6ca744ec6d38
/fix_data.py
fda4912fd1e6f25fe8f886f4c2b96ba67be062c2
[ "MIT" ]
permissive
QubeHeadedT/latticeqcd
1f347eca705e18293f70fd6d357fa72af3bc9f0a
547a6b4832c6b48c0e6c59ed7a6d1f156cb44d99
refs/heads/main
2023-04-16T10:32:21.667507
2021-04-26T19:28:08
2021-04-26T19:28:08
350,472,597
0
0
null
null
null
null
UTF-8
Python
false
false
638
py
import re import os from pathlib import Path def fix_file(file_name): save_file = str(Path(file_name).with_suffix('')) + '_fixed.txt' with open(file_name, 'r') as read_file: os.chdir('fixed_originals') with open(save_file, 'w') as write_file: for line in read_file: line = re.sub(r"\s+", " ", line) write_file.write(line + "\n") os.chdir('..') if __name__ == '__main__': os.chdir('veljko_data') contents = os.listdir() print(contents) for file in contents: if os.path.isfile(file) and (file != '.DS_Store'): fix_file(file)
[ "jamesleechpublic@gmail.com" ]
jamesleechpublic@gmail.com
7bc505f082a1e10b8536f15b9721bfe54d8a6b08
7826d70034d12a32b053aac15433844a2fc91bfd
/tests/intents/test_StopIntent.py
4326116d05a330591d1d0efe52ddf6b12b46a4ca
[ "MIT" ]
permissive
rowleyaj/alexa-slack
c16d54464e8bd752b92863dee85974b19baf2fc4
a7b708aad24ac95315e22f5cdb8ecdc7c249a002
refs/heads/master
2021-01-01T18:18:57.512574
2017-07-24T15:48:50
2017-07-24T15:48:50
98,297,681
0
0
null
2017-07-25T11:11:20
2017-07-25T11:11:20
null
UTF-8
Python
false
false
371
py
from tests.utils import _AlexaTestCase class TestStopIntent(_AlexaTestCase): def input(self): return self.make_intent_request('AMAZON.StopIntent') def should_end_session(self): self.assertTrue(self.output.response.shouldEndSession) def should_say_goodbye(self): self.assertEqual(self.output.response.outputSpeech.text, 'Goodbye')
[ "patrick@promptworks.com" ]
patrick@promptworks.com
b5c4de1f689bf22b058de1ec6c5bbf55e0f84500
ce7b5157acdcba21daff00eadf41575e1297adda
/project_euler/problem10.py
187b7ed089c550a2647c11160aae8e5c9b5789dd
[]
no_license
cobalt-cho/Pythonstudy
b9f1eb553f0b9a87226378d2cd2479c72dc1d065
703fb5db6b9773ad71bac9edddcc4a2a8653d307
refs/heads/master
2020-12-04T05:41:26.940881
2020-03-15T15:22:37
2020-03-15T15:22:37
231,636,912
0
0
null
null
null
null
UTF-8
Python
false
false
867
py
''' ์ด๋ฐฑ๋งŒ ์ดํ•˜ ์†Œ์ˆ˜์˜ ํ•ฉ ์ง€๊ธˆ๊นŒ์ง€ ๊ตฌํ•ด์™”๋˜ ์†Œ์ˆ˜๋กœ๋Š” ์‹œ๊ฐ„์ด ๋„ˆ๋ฌด ์˜ค๋ž˜ ๊ฑธ๋ ค ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋‹ˆ ์‹œ๊ฐ„์ด ์—„์ฒญ๋‚˜๊ฒŒ ๋น ๋ฅด๋‹ค. ''' # ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด def prime(n): # ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด๋กœ n๊ฐœ ์š”์†Œ์— True ์„ค์ • ์†Œ์ˆ˜๋ผ ์ƒ๊ฐ. primeList = [True] * n answer = [] # n์˜ ์ตœ๋Œ€ ์•ฝ์ˆ˜๊ฐ€ sqrt(n) ์ดํ•˜๋ผ์„œ sqrt(n)๊นŒ์ง€๋งŒ ๊ฒ€์‚ฌ m = int(n ** 0.5) for i in range(2, m + 1): if primeList[i] == True: # i๊ฐ€ ์†Œ์ˆ˜์ธ ๊ฒฝ์šฐ for j in range(i+i, n, i): # i์˜ ๋ฐฐ์ˆ˜๋“ค์„ False ํŒ์ • primeList[j] = False # True๊ฐ€ ์†Œ์ˆ˜์ด๋ฏ€๋กœ True index๋งŒ ๋‹ค๋ฅธ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ for i in range(2,n): if primeList[i] == True : answer.append(i) return answer print(sum(prime(2000000)))
[ "ldnono345@naver.com" ]
ldnono345@naver.com
c430a3ee10f86cc84be8503c6297991e94e65a7f
f3fd6a1c687b16726f35bf916d75adf38170dae2
/C10_dnn/logistic_regression_theano.py
b9c1f375e08c175a526528860c5e5709c16a81db
[]
no_license
KeViNOne/MLNotebook
173c67e2204139c93490c0f98ecb323b6e3edf6e
f92ae8156379855a9f0de2df2ccc007cb5b8a5e2
refs/heads/master
2021-01-10T16:44:55.372191
2016-01-06T15:59:34
2016-01-06T15:59:34
48,027,030
0
0
null
null
null
null
UTF-8
Python
false
false
3,032
py
import os import timeit import dataset import numpy as np import theano as tn import theano.tensor as T class LogisticRegression(object): """้€ป่พ‘ๆ–ฏ่ฐ›ๅ›žๅฝ’ """ def __init__(self, n_in, n_out): """Initialize the parameters of the logistic regression :type n_in: int :param n_in: number of input units, the dimension of the space in which the datapoints lie :type n_out: int :param n_out: number of output units, the dimension of the space in which the labels lie """ self.n_in = n_in self.n_out = n_out # ๆƒ้‡็Ÿฉ้˜ต self.W = tn.shared( value=np.zeros( (n_in, n_out), dtype=tn.config.floatX ), name='W', borrow=True ) # ๅ็ฝฎ็Ÿฉ้˜ต self.b = tn.shared( value=np.zeros( (n_out,), dtype=tn.config.floatX ), name='b', borrow=True ) # ๅ…จ้ƒจๆจกๅž‹ๅ‚ๆ•ฐ self.theta = [self.W, self.b] pass def compute(self, x): return T.nnet.sigmoid(T.dot(x, self.W) + self.b) def error(self, x, y): z = self.compute(x).ravel() one = y * T.log(z) two = (1 - y) * T.log(1 - z) three = one + two # three[T.isnan(three)] = 0 return -T.mean(three) class LogisticRegressionTrainer(object): def __init__(self, train_data, m, n, regression = None): self.X, self.Y = train_data self.m = m self.n_in = n self.n_out = 1 self.regression = regression if regression != None else LogisticRegression(self.n_in, self.n_out) pass def train(self, epochs = 1000, learning_rate = 0.1): regression = self.regression X = self.X Y = self.Y x = T.fmatrix('x') # data, presented as rasterized images y = T.ivector('y') # labels, presented as 1D vector of [int] labels error = regression.error(x, y) g_W = T.grad(cost=error, wrt=regression.W) g_b = T.grad(cost=error, wrt=regression.b) updates = [(regression.W, regression.W - learning_rate * g_W), (regression.b, regression.b - learning_rate * g_b)] train_model = tn.function( inputs=[], outputs=error, updates=updates, givens={ x: X, y: Y } ) print('training start:') start_time = timeit.default_timer() epoch = 0 while(epoch < epochs): avg_error = train_model() epoch += 1 print('epoch {0}, error {1}'.format(epoch, avg_error), end='\r') print('\ntraining finish (error: {0}) took {1} seconds.'.format(regression.error(X, Y).eval(), timeit.default_timer() - start_time)) pass if __name__ == '__main__': data_file = 'simple_binarylabel.pkl' learning_rate = 0.001 epochs = 10000 borrow = True data = dataset.load_data_array(data_file) m, n = data[0].shape print('data:', data[0].shape, data[1].shape, m, n) train_x = tn.shared(data[0].astype(tn.config.floatX), borrow=borrow) train_y = tn.shared(data[1].astype(np.int32), borrow=borrow) data = None regression = LogisticRegression(n_in = n, n_out = 1) trainer = LogisticRegressionTrainer((train_x,train_y), m, n, regression=regression) trainer.train(epochs=epochs, learning_rate=learning_rate) pass
[ "KeViNOne@KeViNOne-Laptop.local" ]
KeViNOne@KeViNOne-Laptop.local