prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
<|fim_middle|>
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
<|fim_middle|>
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,' |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
<|fim_middle|>
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
<|fim_middle|>
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | print ('[DEBUG] string: ' + string.strip()) |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
<|fim_middle|>
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | first_seen = string.strip() |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
<|fim_middle|>
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | last_seen = string.strip() |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
<|fim_middle|>
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | signature = string.strip()
sig_count += 1 |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
<|fim_middle|>
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
<|fim_middle|>
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
<|fim_middle|>
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
<|fim_middle|>
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
<|fim_middle|>
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
<|fim_middle|>
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def POE(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
<|fim_middle|>
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) |
<|file_name|>malware_bazaar_search.py<|end_file_name|><|fim▁begin|>#python imports
import sys
import os
import time
import datetime
import subprocess
import json
import requests
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIPTION***
Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database.
***END DESCRIPTION***
'''
def <|fim_middle|>(POE):
if (POE.logging == True):
LOG = logger()
newlogentry = ''
reputation_dump = ''
reputation_output_data = ''
malwarebazaar = ''
if (POE.logging == True):
newlogentry = 'Module: malware_bazaar_search'
LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry)
if (POE.SHA256 == ''):
print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold']))
newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
return -1
global json
query_status = ''
first_seen = ''
last_seen = ''
signature = ''
sig_count = 0
output = POE.logdir + 'MalwareBazaarSearch.json'
FI = fileio()
print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold']))
malwarebazaar = "https://mb-api.abuse.ch/api/v1/" #API URL
data = { #Our header params
'query': 'get_info',
'hash': POE.SHA256,
}
response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON
if (POE.debug == True):
print (response_dump)
try:
FI.WriteLogFile(output, response_dump.content.decode("utf-8", "ignore"))
print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold']))
if ((POE.logging == True) and (POE.nolinksummary == False)):
newlogentry = 'Malware Bazaar data has been generated to file here: <a href=\"' + output + '\"> Malware Bazaar Host Output </a>'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except:
print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'Unable to write Malware Bazaar data to file'
LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry)
POE.csv_line += 'N/A,'
return -1
try:
#Open the file we just downloaded
print ('[-] Reading Malware Bazaar file: ' + output.strip())
with open(output.strip(), 'rb') as read_file:
data = json.load(read_file, cls=None)
read_file.close()
# Check what kind of results we have
query_status = data["query_status"]
print ('[*] query_status: ' + query_status)
if (query_status == 'ok'):
with open(output.strip(), 'r') as read_file:
for string in read_file:
if (POE.debug == True):
print ('[DEBUG] string: ' + string.strip())
if ('first_seen' in string):
first_seen = string.strip()
if ('last_seen' in string):
last_seen = string.strip()
if (('signature' in string) and (sig_count == 0)):
signature = string.strip()
sig_count += 1
print ('[*] Sample ' + first_seen.replace(',',''))
print ('[*] Sample ' + last_seen.replace(',',''))
print ('[*] Sample ' + signature.replace(',',''))
if (POE.logging == True):
newlogentry = 'Sample ' + first_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + last_seen.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
newlogentry = 'Sample ' + signature.replace(',','')
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'hash_not_found'):
print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Can't find anything on this one...
elif (query_status == 'no_results'):
print (colored('[-] No results available for host...', 'yellow', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'No results available for host...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
#Something weird happened...
else:
print (colored('[x] An error has occurred...', 'red', attrs=['bold']))
if (POE.logging == True):
newlogentry = 'An error has occurred...'
LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry)
except Exception as e:
print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold']))
read_file.close()
return -1
#Clean up before returning
read_file.close()
return 0
<|fim▁end|> | POE |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core<|fim▁hole|>
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()<|fim▁end|> | from roster_server import credentials
|
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
<|fim_middle|>
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None) |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
<|fim_middle|>
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance) |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
<|fim_middle|>
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | """
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
<|fim_middle|>
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None) |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
<|fim_middle|>
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | if int (uuid, 16) < 0: return False |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: <|fim_middle|>
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | return False |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
<|fim_middle|>
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | if int (uuid, 16) < 0: return False |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: <|fim_middle|>
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | return False |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
<|fim_middle|>
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ] |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
<|fim_middle|>
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | return False |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
<|fim_middle|>
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | return False |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
<|fim_middle|>
<|fim▁end|> | unittest.main() |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def <|fim_middle|>(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | setUp |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def <|fim_middle|> (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | is_valid_uuid |
<|file_name|>credentials_test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def <|fim_middle|>(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
<|fim▁end|> | testCredentials |
<|file_name|>PRESUBMIT.py<|end_file_name|><|fim▁begin|># Copyright 2017 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be<|fim▁hole|>
def CheckChangeOnCommit(input_api, output_api):
tests = input_api.canned_checks.GetUnitTestsInDirectory(
input_api, output_api, '.', files_to_check=['test_scripts.py$'])
return input_api.RunTests(tests)<|fim▁end|> | # found in the LICENSE file. |
<|file_name|>PRESUBMIT.py<|end_file_name|><|fim▁begin|># Copyright 2017 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def CheckChangeOnCommit(input_api, output_api):
<|fim_middle|>
<|fim▁end|> | tests = input_api.canned_checks.GetUnitTestsInDirectory(
input_api, output_api, '.', files_to_check=['test_scripts.py$'])
return input_api.RunTests(tests) |
<|file_name|>PRESUBMIT.py<|end_file_name|><|fim▁begin|># Copyright 2017 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def <|fim_middle|>(input_api, output_api):
tests = input_api.canned_checks.GetUnitTestsInDirectory(
input_api, output_api, '.', files_to_check=['test_scripts.py$'])
return input_api.RunTests(tests)
<|fim▁end|> | CheckChangeOnCommit |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from pyperator.utils import InputPort, OutputPort
import pyperator.components<|fim▁end|> | from pyperator.decorators import inport, outport, component, run_once
from pyperator.nodes import Component
from pyperator.DAG import Multigraph |
<|file_name|>test_sig_source_i.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
<|fim▁hole|># You should have received a copy of the GNU General Public License along with
# this program. If not, see http://www.gnu.org/licenses/.
#
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.ScaComponentTestCase):
"""Test for all component implementations in sig_source_i"""
def testScaBasicBehavior(self):
#######################################################################
# Launch the component with the default execparams
execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
self.launch(execparams)
#######################################################################
# Verify the basic state of the component
self.assertNotEqual(self.comp, None)
self.assertEqual(self.comp.ref._non_existent(), False)
self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier())
#######################################################################
# Simulate regular component startup
# Verify that initialize nor configure throw errors
self.comp.initialize()
configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False)
self.comp.configure(configureProps)
#######################################################################
# Validate that query returns all expected parameters
# Query of '[]' should return the following set of properties
expectedProps = []
expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True))
expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
props = self.comp.query([])
props = dict((x.id, any.from_any(x.value)) for x in props)
# Query may return more than expected, but not less
for expectedProp in expectedProps:
self.assertEquals(props.has_key(expectedProp.id), True)
#######################################################################
# Verify that all expected ports are available
for port in self.scd.get_componentfeatures().get_ports().get_uses():
port_obj = self.comp.getPort(str(port.get_usesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True)
for port in self.scd.get_componentfeatures().get_ports().get_provides():
port_obj = self.comp.getPort(str(port.get_providesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a(port.get_repid()), True)
#######################################################################
# Make sure start and stop can be called without throwing exceptions
self.comp.start()
self.comp.stop()
#######################################################################
# Simulate regular component shutdown
self.comp.releaseObject()
# TODO Add additional tests here
#
# See:
# ossie.utils.bulkio.bulkio_helpers,
# ossie.utils.bluefile.bluefile_helpers
# for modules that will assist with testing components with BULKIO ports
if __name__ == "__main__":
ossie.utils.testing.main("../sig_source_i.spd.xml") # By default tests all implementations<|fim▁end|> | |
<|file_name|>test_sig_source_i.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with
# this program. If not, see http://www.gnu.org/licenses/.
#
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.ScaComponentTestCase):
<|fim_middle|>
if __name__ == "__main__":
ossie.utils.testing.main("../sig_source_i.spd.xml") # By default tests all implementations
<|fim▁end|> | """Test for all component implementations in sig_source_i"""
def testScaBasicBehavior(self):
#######################################################################
# Launch the component with the default execparams
execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
self.launch(execparams)
#######################################################################
# Verify the basic state of the component
self.assertNotEqual(self.comp, None)
self.assertEqual(self.comp.ref._non_existent(), False)
self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier())
#######################################################################
# Simulate regular component startup
# Verify that initialize nor configure throw errors
self.comp.initialize()
configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False)
self.comp.configure(configureProps)
#######################################################################
# Validate that query returns all expected parameters
# Query of '[]' should return the following set of properties
expectedProps = []
expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True))
expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
props = self.comp.query([])
props = dict((x.id, any.from_any(x.value)) for x in props)
# Query may return more than expected, but not less
for expectedProp in expectedProps:
self.assertEquals(props.has_key(expectedProp.id), True)
#######################################################################
# Verify that all expected ports are available
for port in self.scd.get_componentfeatures().get_ports().get_uses():
port_obj = self.comp.getPort(str(port.get_usesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True)
for port in self.scd.get_componentfeatures().get_ports().get_provides():
port_obj = self.comp.getPort(str(port.get_providesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a(port.get_repid()), True)
#######################################################################
# Make sure start and stop can be called without throwing exceptions
self.comp.start()
self.comp.stop()
#######################################################################
# Simulate regular component shutdown
self.comp.releaseObject()
# TODO Add additional tests here
#
# See:
# ossie.utils.bulkio.bulkio_helpers,
# ossie.utils.bluefile.bluefile_helpers
# for modules that will assist with testing components with BULKIO ports |
<|file_name|>test_sig_source_i.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with
# this program. If not, see http://www.gnu.org/licenses/.
#
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.ScaComponentTestCase):
"""Test for all component implementations in sig_source_i"""
def testScaBasicBehavior(self):
#######################################################################
# Launch the component with the default execparams
<|fim_middle|>
# TODO Add additional tests here
#
# See:
# ossie.utils.bulkio.bulkio_helpers,
# ossie.utils.bluefile.bluefile_helpers
# for modules that will assist with testing components with BULKIO ports
if __name__ == "__main__":
ossie.utils.testing.main("../sig_source_i.spd.xml") # By default tests all implementations
<|fim▁end|> | execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
self.launch(execparams)
#######################################################################
# Verify the basic state of the component
self.assertNotEqual(self.comp, None)
self.assertEqual(self.comp.ref._non_existent(), False)
self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier())
#######################################################################
# Simulate regular component startup
# Verify that initialize nor configure throw errors
self.comp.initialize()
configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False)
self.comp.configure(configureProps)
#######################################################################
# Validate that query returns all expected parameters
# Query of '[]' should return the following set of properties
expectedProps = []
expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True))
expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
props = self.comp.query([])
props = dict((x.id, any.from_any(x.value)) for x in props)
# Query may return more than expected, but not less
for expectedProp in expectedProps:
self.assertEquals(props.has_key(expectedProp.id), True)
#######################################################################
# Verify that all expected ports are available
for port in self.scd.get_componentfeatures().get_ports().get_uses():
port_obj = self.comp.getPort(str(port.get_usesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True)
for port in self.scd.get_componentfeatures().get_ports().get_provides():
port_obj = self.comp.getPort(str(port.get_providesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a(port.get_repid()), True)
#######################################################################
# Make sure start and stop can be called without throwing exceptions
self.comp.start()
self.comp.stop()
#######################################################################
# Simulate regular component shutdown
self.comp.releaseObject() |
<|file_name|>test_sig_source_i.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with
# this program. If not, see http://www.gnu.org/licenses/.
#
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.ScaComponentTestCase):
"""Test for all component implementations in sig_source_i"""
def testScaBasicBehavior(self):
#######################################################################
# Launch the component with the default execparams
execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
self.launch(execparams)
#######################################################################
# Verify the basic state of the component
self.assertNotEqual(self.comp, None)
self.assertEqual(self.comp.ref._non_existent(), False)
self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier())
#######################################################################
# Simulate regular component startup
# Verify that initialize nor configure throw errors
self.comp.initialize()
configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False)
self.comp.configure(configureProps)
#######################################################################
# Validate that query returns all expected parameters
# Query of '[]' should return the following set of properties
expectedProps = []
expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True))
expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
props = self.comp.query([])
props = dict((x.id, any.from_any(x.value)) for x in props)
# Query may return more than expected, but not less
for expectedProp in expectedProps:
self.assertEquals(props.has_key(expectedProp.id), True)
#######################################################################
# Verify that all expected ports are available
for port in self.scd.get_componentfeatures().get_ports().get_uses():
port_obj = self.comp.getPort(str(port.get_usesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True)
for port in self.scd.get_componentfeatures().get_ports().get_provides():
port_obj = self.comp.getPort(str(port.get_providesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a(port.get_repid()), True)
#######################################################################
# Make sure start and stop can be called without throwing exceptions
self.comp.start()
self.comp.stop()
#######################################################################
# Simulate regular component shutdown
self.comp.releaseObject()
# TODO Add additional tests here
#
# See:
# ossie.utils.bulkio.bulkio_helpers,
# ossie.utils.bluefile.bluefile_helpers
# for modules that will assist with testing components with BULKIO ports
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | ossie.utils.testing.main("../sig_source_i.spd.xml") # By default tests all implementations |
<|file_name|>test_sig_source_i.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of GNUHAWK.
#
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with
# this program. If not, see http://www.gnu.org/licenses/.
#
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.ScaComponentTestCase):
"""Test for all component implementations in sig_source_i"""
def <|fim_middle|>(self):
#######################################################################
# Launch the component with the default execparams
execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
self.launch(execparams)
#######################################################################
# Verify the basic state of the component
self.assertNotEqual(self.comp, None)
self.assertEqual(self.comp.ref._non_existent(), False)
self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier())
#######################################################################
# Simulate regular component startup
# Verify that initialize nor configure throw errors
self.comp.initialize()
configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False)
self.comp.configure(configureProps)
#######################################################################
# Validate that query returns all expected parameters
# Query of '[]' should return the following set of properties
expectedProps = []
expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True))
expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
props = self.comp.query([])
props = dict((x.id, any.from_any(x.value)) for x in props)
# Query may return more than expected, but not less
for expectedProp in expectedProps:
self.assertEquals(props.has_key(expectedProp.id), True)
#######################################################################
# Verify that all expected ports are available
for port in self.scd.get_componentfeatures().get_ports().get_uses():
port_obj = self.comp.getPort(str(port.get_usesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True)
for port in self.scd.get_componentfeatures().get_ports().get_provides():
port_obj = self.comp.getPort(str(port.get_providesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a(port.get_repid()), True)
#######################################################################
# Make sure start and stop can be called without throwing exceptions
self.comp.start()
self.comp.stop()
#######################################################################
# Simulate regular component shutdown
self.comp.releaseObject()
# TODO Add additional tests here
#
# See:
# ossie.utils.bulkio.bulkio_helpers,
# ossie.utils.bluefile.bluefile_helpers
# for modules that will assist with testing components with BULKIO ports
if __name__ == "__main__":
ossie.utils.testing.main("../sig_source_i.spd.xml") # By default tests all implementations
<|fim▁end|> | testScaBasicBehavior |
<|file_name|>Plot.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | #Scripts to plot the data, currently only in the context of Q&A communites. |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)<|fim▁hole|> np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)<|fim▁end|> | return (-np.log(pi) - np.log(self.scale) - |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
<|fim_middle|>
<|fim▁end|> | r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale) |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
<|fim_middle|>
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args) |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
<|fim_middle|>
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | return nan |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
<|fim_middle|>
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | return nan |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
<|fim_middle|>
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u) |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
<|fim_middle|>
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | return self.sample(sample_n_shape_converter(size)) |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
<|fim_middle|>
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2)) |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
<|fim_middle|>
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5 |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
<|fim_middle|>
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | return np.tan(pi * (value - 0.5)) * self.scale + self.loc |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
<|fim_middle|>
<|fim▁end|> | return np.log(4 * pi) + np.log(self.scale) |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
<|fim_middle|>
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | u = np.random.uniform(size=size) |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
<|fim_middle|>
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size) |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
<|fim_middle|>
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | self._validate_samples(value) |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
<|fim_middle|>
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | self._validate_samples(value) |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def <|fim_middle|>(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | __init__ |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def <|fim_middle|>(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | mean |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def <|fim_middle|>(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | variance |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def <|fim_middle|>(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | sample |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def <|fim_middle|>(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | sample_n |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def <|fim_middle|>(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | log_prob |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def <|fim_middle|>(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | cdf |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def <|fim_middle|>(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def entropy(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | icdf |
<|file_name|>cauchy.py<|end_file_name|><|fim▁begin|># 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.
# coding: utf-8
# pylint: disable=wildcard-import
"""Cauchy distribution"""
__all__ = ['Cauchy']
from numbers import Number
from numpy import nan, pi
from .constraint import Real
from .distribution import Distribution
from .utils import sample_n_shape_converter
from .... import np
class Cauchy(Distribution):
r"""Create a relaxed Cauchy distribution object.
Parameters
----------
loc : Tensor or scalar, default 0
mode or median of the distribution
scale : Tensor or scalar, default 1
half width at half maximum
"""
# pylint: disable=abstract-method
has_grad = True
support = Real()
arg_constraints = {'loc': Real(), 'scale': Real()}
def __init__(self, loc=0.0, scale=1.0, validate_args=None):
self.loc = loc
self.scale = scale
super(Cauchy, self).__init__(
event_dim=0, validate_args=validate_args)
@property
def mean(self):
return nan
@property
def variance(self):
return nan
def sample(self, size=None):
# TODO: Implement sampling op in the backend.
# `np.zeros_like` does not support scalar at this moment.
if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True):
u = np.random.uniform(size=size)
else:
u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args
self.loc + self.scale), size=size)
return self.icdf(u)
def sample_n(self, size=None):
return self.sample(sample_n_shape_converter(size))
def log_prob(self, value):
if self._validate_args:
self._validate_samples(value)
return (-np.log(pi) - np.log(self.scale) -
np.log(1 + ((value - self.loc) / self.scale) ** 2))
def cdf(self, value):
if self._validate_args:
self._validate_samples(value)
return np.arctan((value - self.loc) / self.scale) / pi + 0.5
def icdf(self, value):
return np.tan(pi * (value - 0.5)) * self.scale + self.loc
def <|fim_middle|>(self):
return np.log(4 * pi) + np.log(self.scale)
<|fim▁end|> | entropy |
<|file_name|>17.py<|end_file_name|><|fim▁begin|>import struct
''' Refer to docs for all the exact formats. There are many so check them out before converting things yourself '''
''' If there's a specific offset you want to do things from, use pack_into and unack_into from the docs '''
#Integer to string
i1= 1234
print "Int to string as 8 byte little endian", repr(struct.pack("<Q",i1))
print "Int to string as 8 byte big endian", repr(struct.pack(">Q",i1))
#String to integer. Make sure size of destination matches the length of the string
s1= '1234'<|fim▁hole|>
''' Whenever you want to convert to and from binary, think of binascii '''
import binascii
h1= binascii.b2a_hex(s1)
print "String to hex", h1
uh1= binascii.a2b_hex(h1)
print "Hex to string, even a binary string", uh1<|fim▁end|> | print "String to 4 byte integer little endian", struct.unpack("<i", s1)
print "String to 4 byte integer big endian", struct.unpack(">i", s1) |
<|file_name|>229MajorityElementII.py<|end_file_name|><|fim▁begin|>class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""<|fim▁hole|>
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
cnt2 += 1
else:
if cnt1 == 0:
num1, cnt1 = num, 1
elif cnt2 == 0:
num2, cnt2 = num, 1
else:
cnt1, cnt2 = cnt1 - 1, cnt2 - 1
return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3]<|fim▁end|> | num1, cnt1 = 0, 0
num2, cnt2 = 1, 0 |
<|file_name|>229MajorityElementII.py<|end_file_name|><|fim▁begin|>class Solution:
<|fim_middle|>
<|fim▁end|> | def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num1, cnt1 = 0, 0
num2, cnt2 = 1, 0
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
cnt2 += 1
else:
if cnt1 == 0:
num1, cnt1 = num, 1
elif cnt2 == 0:
num2, cnt2 = num, 1
else:
cnt1, cnt2 = cnt1 - 1, cnt2 - 1
return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3] |
<|file_name|>229MajorityElementII.py<|end_file_name|><|fim▁begin|>class Solution:
def majorityElement(self, nums):
<|fim_middle|>
<|fim▁end|> | """
:type nums: List[int]
:rtype: List[int]
"""
num1, cnt1 = 0, 0
num2, cnt2 = 1, 0
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
cnt2 += 1
else:
if cnt1 == 0:
num1, cnt1 = num, 1
elif cnt2 == 0:
num2, cnt2 = num, 1
else:
cnt1, cnt2 = cnt1 - 1, cnt2 - 1
return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3] |
<|file_name|>229MajorityElementII.py<|end_file_name|><|fim▁begin|>class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num1, cnt1 = 0, 0
num2, cnt2 = 1, 0
for num in nums:
if num == num1:
<|fim_middle|>
elif num == num2:
cnt2 += 1
else:
if cnt1 == 0:
num1, cnt1 = num, 1
elif cnt2 == 0:
num2, cnt2 = num, 1
else:
cnt1, cnt2 = cnt1 - 1, cnt2 - 1
return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3]
<|fim▁end|> | cnt1 += 1 |
<|file_name|>229MajorityElementII.py<|end_file_name|><|fim▁begin|>class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num1, cnt1 = 0, 0
num2, cnt2 = 1, 0
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
<|fim_middle|>
else:
if cnt1 == 0:
num1, cnt1 = num, 1
elif cnt2 == 0:
num2, cnt2 = num, 1
else:
cnt1, cnt2 = cnt1 - 1, cnt2 - 1
return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3]
<|fim▁end|> | cnt2 += 1 |
<|file_name|>229MajorityElementII.py<|end_file_name|><|fim▁begin|>class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num1, cnt1 = 0, 0
num2, cnt2 = 1, 0
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
cnt2 += 1
else:
<|fim_middle|>
return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3]
<|fim▁end|> | if cnt1 == 0:
num1, cnt1 = num, 1
elif cnt2 == 0:
num2, cnt2 = num, 1
else:
cnt1, cnt2 = cnt1 - 1, cnt2 - 1 |
<|file_name|>229MajorityElementII.py<|end_file_name|><|fim▁begin|>class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num1, cnt1 = 0, 0
num2, cnt2 = 1, 0
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
cnt2 += 1
else:
if cnt1 == 0:
<|fim_middle|>
elif cnt2 == 0:
num2, cnt2 = num, 1
else:
cnt1, cnt2 = cnt1 - 1, cnt2 - 1
return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3]
<|fim▁end|> | num1, cnt1 = num, 1 |
<|file_name|>229MajorityElementII.py<|end_file_name|><|fim▁begin|>class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num1, cnt1 = 0, 0
num2, cnt2 = 1, 0
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
cnt2 += 1
else:
if cnt1 == 0:
num1, cnt1 = num, 1
elif cnt2 == 0:
<|fim_middle|>
else:
cnt1, cnt2 = cnt1 - 1, cnt2 - 1
return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3]
<|fim▁end|> | num2, cnt2 = num, 1 |
<|file_name|>229MajorityElementII.py<|end_file_name|><|fim▁begin|>class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num1, cnt1 = 0, 0
num2, cnt2 = 1, 0
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
cnt2 += 1
else:
if cnt1 == 0:
num1, cnt1 = num, 1
elif cnt2 == 0:
num2, cnt2 = num, 1
else:
<|fim_middle|>
return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3]
<|fim▁end|> | cnt1, cnt2 = cnt1 - 1, cnt2 - 1 |
<|file_name|>229MajorityElementII.py<|end_file_name|><|fim▁begin|>class Solution:
def <|fim_middle|>(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num1, cnt1 = 0, 0
num2, cnt2 = 1, 0
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
cnt2 += 1
else:
if cnt1 == 0:
num1, cnt1 = num, 1
elif cnt2 == 0:
num2, cnt2 = num, 1
else:
cnt1, cnt2 = cnt1 - 1, cnt2 - 1
return [num for num in (num1, num2) if nums.count(num) > len(nums) // 3]
<|fim▁end|> | majorityElement |
<|file_name|>pe029_distinct_powers.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|>"""
Distinct powers
Problem 29
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and
2 ≤ b ≤ 100?
"""
from __future__ import print_function
def power_combinations(a, b):
for i in range(2, a):
for j in range(2, b):
yield i ** j
if __name__ == '__main__':
print(len(set(power_combinations(101, 101)))) # 9183<|fim▁end|> | # coding=utf-8 |
<|file_name|>pe029_distinct_powers.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# coding=utf-8
"""
Distinct powers
Problem 29
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and
2 ≤ b ≤ 100?
"""
from __future__ import print_function
def power_combinations(a, b):
for i in range(2<|fim_middle|>
= '__main__':
print(len(set(power_combinations(101, 101)))) # 9183
<|fim▁end|> | , a):
for j in range(2, b):
yield i ** j
if __name__ = |
<|file_name|>pe029_distinct_powers.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# coding=utf-8
"""
Distinct powers
Problem 29
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and
2 ≤ b ≤ 100?
"""
from __future__ import print_function
def power_combinations(a, b):
for i in range(2, a):
for j in range(2, b):
yield i ** j
if __name__ == '__main__':
print(len(set(po <|fim_middle|>
<|fim▁end|> | wer_combinations(101, 101)))) # 9183
|
<|file_name|>pe029_distinct_powers.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# coding=utf-8
"""
Distinct powers
Problem 29
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and
2 ≤ b ≤ 100?
"""
from __future__ import print_function
def power_combinatio<|fim_middle|>i in range(2, a):
for j in range(2, b):
yield i ** j
if __name__ == '__main__':
print(len(set(power_combinations(101, 101)))) # 9183
<|fim▁end|> | ns(a, b):
for |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)<|fim▁hole|>def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)<|fim▁end|> | |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
<|fim_middle|>
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
<|fim_middle|>
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
<|fim_middle|>
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
<|fim_middle|>
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
<|fim_middle|>
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
<|fim_middle|>
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
<|fim_middle|>
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
<|fim_middle|>
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
<|fim_middle|>
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
<|fim_middle|>
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
<|fim_middle|>
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
<|fim_middle|>
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
<|fim_middle|>
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
<|fim_middle|>
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
<|fim_middle|>
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text'] |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
<|fim_middle|>
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
<|fim_middle|>
<|fim▁end|> | assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
<|fim_middle|>
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(wrap_var('foo'), AnsibleUnsafeText) |
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
<|fim_middle|>
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|> | assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes) |
Subsets and Splits