예제 #1
0
 def test_get_init_file_no_param_passed(self):
     """Test the method that gets called when script is run directly when
     no params are passed"""
     error = 'A single init file name parameter is required by ' \
             'Modules.py when invoked directly'
     with mock.patch.object(sys, 'argv', ['Modules']):
         with self.assertRaisesRegexp(RuntimeError, error):
             Modules.get_init_file()
예제 #2
0
 def get_all_modules_paths(self):
     """Get common modules and modules from packs if available"""
     exploits = Modules.get_modules_names_dict(EXPLOITS_PATH)
     if not os.path.exists(PACKS_PATH):
         os.makedirs(PACKS_PATH)
     files = os.listdir(PACKS_PATH)
     for f in files:
         path_to_pack = os.path.join(PACKS_PATH, f)
         if os.path.isdir(path_to_pack):
             pack_dirs = [fname.lower() for fname in os.listdir(path_to_pack)]
             if "exploits" in pack_dirs:
                 full_path_to_pack_exploits = os.path.join(path_to_pack, "exploits")
                 exploits.update(Modules.get_modules_names_dict(full_path_to_pack_exploits))
     return exploits
예제 #3
0
 def get_all_modules_paths(self):
     """Get common modules and modules from packs if available"""
     exploits = Modules.get_modules_names_dict(EXPLOITS_PATH)
     if not os.path.exists(PACKS_PATH):
         os.makedirs(PACKS_PATH)
     files = os.listdir(PACKS_PATH)
     for f in files:
         path_to_pack = os.path.join(PACKS_PATH, f)
         if os.path.isdir(path_to_pack):
             pack_dirs = [
                 fname.lower() for fname in os.listdir(path_to_pack)
             ]
             if "exploits" in pack_dirs:
                 full_path_to_pack_exploits = os.path.join(
                     path_to_pack, "exploits")
                 exploits.update(
                     Modules.get_modules_names_dict(
                         full_path_to_pack_exploits))
     return exploits
예제 #4
0
 def test_get_init_file_no_file_found(self):
     """Test the function that gets called when script is run directly
     when no init file is returned"""
     modules_home = {'MODULESHOME': '/dummy/path/1'}
     which_side_effects = ['/path/to/modulecmd', None, None]
     find_side_effects = [None, None]
     with mock.patch.object(sys, 'argv', ['Modules', 'python']):
         with mock.patch.dict(os.environ, modules_home), \
                 mock.patch('Modules.which',
                            side_effect=which_side_effects), \
                 mock.patch('Modules.find_first_binary',
                            return_value=None), \
                 mock.patch('Modules.find_file_in_list',
                            side_effect=find_side_effects), \
                 mock.patch('__builtin__.execfile') as exec_file:
             error = 'Unable to determine init file for python in ' \
                     'Modules.py'
             with self.assertRaisesRegexp(RuntimeError, error):
                 Modules.get_init_file()
     exec_file.assert_not_called()
예제 #5
0
    def test_get_init_file(self):
        """Test the method that gets called when script is run directly"""

        modules_home = {'MODULESHOME': '/dummy/path/1'}
        which_side_effects = ['/path/to/modulecmd', None, None]
        find_side_effects = [None, '/fake/path/modules/init/python.py']
        with mock.patch('sys.stdout', new_callable=StringIO) as output:
            with mock.patch.object(sys, 'argv', ['Modules', 'python']):
                with mock.patch.dict(os.environ, modules_home), \
                        mock.patch('Modules.which',
                                   side_effect=which_side_effects), \
                        mock.patch('Modules.find_first_binary',
                                   return_value='/fake/path/modulecmd'), \
                        mock.patch('Modules.find_file_in_list',
                                   side_effect=find_side_effects), \
                        mock.patch('__builtin__.execfile') as exec_file:
                    Modules.get_init_file()
            stdout = output.getvalue()
        self.assertEqual('/fake/path/modules/init/python.py\n', stdout)
        exec_file.assert_not_called()
예제 #6
0
    def test_get_init_file(self):
        """Test the method that gets called when script is run directly"""

        modules_home = {'MODULESHOME': '/dummy/path/1'}
        which_side_effects = ['/path/to/modulecmd', None, None]
        find_side_effects = [None, '/fake/path/modules/init/python.py']
        with mock.patch('sys.stdout', new_callable=StringIO) as output:
            with mock.patch.object(sys, 'argv', ['Modules', 'python']):
                with mock.patch.dict(os.environ, modules_home), \
                        mock.patch('Modules.which',
                                   side_effect=which_side_effects), \
                        mock.patch('Modules.find_first_binary',
                                   return_value='/fake/path/modulecmd'), \
                        mock.patch('Modules.find_file_in_list',
                                   side_effect=find_side_effects), \
                        mock.patch('__builtin__.execfile') as exec_file:
                    Modules.get_init_file()
            stdout = output.getvalue()
        self.assertEqual('/fake/path/modules/init/python.py\n', stdout)
        exec_file.assert_not_called()
예제 #7
0
 def test_get_init_file_no_file_found(self):
     """Test the function that gets called when script is run directly
     when no init file is returned"""
     modules_home = {'MODULESHOME': '/dummy/path/1'}
     which_side_effects = ['/path/to/modulecmd', None, None]
     find_side_effects = [None, None]
     with mock.patch.object(sys, 'argv', ['Modules', 'python']):
         with mock.patch.dict(os.environ, modules_home), \
                 mock.patch('Modules.which',
                            side_effect=which_side_effects), \
                 mock.patch('Modules.find_first_binary',
                            return_value=None), \
                 mock.patch('Modules.find_file_in_list',
                            side_effect=find_side_effects), \
                 mock.patch('__builtin__.execfile') as exec_file:
             error = 'Unable to determine init file for python in ' \
                     'Modules.py'
             with self.assertRaisesRegexp(RuntimeError, error):
                 Modules.get_init_file()
     exec_file.assert_not_called()
예제 #8
0
def controller(postvars):
    module = Modules.Module(postvars)
    arquivo = open('./params.txt', 'r')
    line_file = arquivo.readlines()
    for line in line_file:
        if (line == "delete_data\n"):
            module.delete_data()
        elif (line == "media_measure\n"):
            print 'oi'
            #media_measure = module.media_measure(measure)
        else:
            pass
예제 #9
0
    def __init__(self, nChannels, nStack, nModules, numReductions, nJoints):
        super(StackedHourGlass, self).__init__()
        self.nChannels = nChannels
        self.nStack = nStack
        self.nModules = nModules
        self.numReductions = numReductions
        self.nJoints = nJoints

        self.start = M.BnReluConv(3, 64, kernelSize = 7, stride = 2, padding = 3)

        self.res1 = M.Residual(64, 128)
        self.mp = nn.MaxPool2d(2, 2)
        self.res2 = M.Residual(128, 128)
        self.res3 = M.Residual(128, self.nChannels)

        _hourglass, _Residual, _lin1, _chantojoints, _lin2, _jointstochan = [],[],[],[],[],[]

        for _ in range(self.nStack):
            _hourglass.append(Hourglass(self.nChannels, self.numReductions, self.nModules))
            _ResidualModules = []
            for _ in range(self.nModules):
                _ResidualModules.append(M.Residual(self.nChannels, self.nChannels))
            _ResidualModules = nn.Sequential(*_ResidualModules)
            _Residual.append(_ResidualModules)
            _lin1.append(M.BnReluConv(self.nChannels, self.nChannels))
            _chantojoints.append(nn.Conv2d(self.nChannels, self.nJoints,1))
            _lin2.append(nn.Conv2d(self.nChannels, self.nChannels,1))
            _jointstochan.append(nn.Conv2d(self.nJoints,self.nChannels,1))

        self.hourglass = nn.ModuleList(_hourglass)
        self.Residual = nn.ModuleList(_Residual)
        self.lin1 = nn.ModuleList(_lin1)
        self.chantojoints = nn.ModuleList(_chantojoints)
        self.lin2 = nn.ModuleList(_lin2)
        self.jointstochan = nn.ModuleList(_jointstochan)
예제 #10
0
 def setUp(self):
     modules_home = {'MODULESHOME': '/dummy/path/1'}
     which_side_effects = ['/path/to/modulecmd', None, None]
     find_side_effects = [None, '/fake/path/modules/init/python.py']
     with mock.patch.dict(os.environ, modules_home), \
             mock.patch('Modules.which',
                        side_effect=which_side_effects), \
             mock.patch('Modules.find_first_binary',
                        return_value='/fake/path/modulecmd'), \
             mock.patch('Modules.find_file_in_list',
                        side_effect=find_side_effects), \
             mock.patch('__builtin__.execfile'):
         self.module_obj = Modules.Module()
예제 #11
0
    def __init__(self, name, budget, type, market, time):
        self.name = name
        self.type = type
        self.market = market
        self.time = time
        # Init modules so we can pass a reference
        self.modules = ModulesList(self.time)
        # Add the basic objects
        self.modules.spawn(Modules.Archive(self.name, self.modules, self.time),
                           special="archive")
        self.modules.spawn(Modules.Office(budget, self.market, self.name,
                                          self.modules, self.time),
                           special="office")
        self.modules.spawn(Modules.HumanResources(self.name, self.modules,
                                                  self.time),
                           special="hr")
        self.modules.spawn(Modules.Logistics(self.name, self.modules,
                                             self.time),
                           special="logistics")
        self.modules.spawn(Modules.Depot(self.name, self.modules, self.time),
                           special="depot")

        self.log("Factory founded")
예제 #12
0
    def __init__(self, Class, MaxHull, Speed, Evasion, ComPoints, Cost):
        self.Class = Class
        self.BaseShield = 0
        self.BaseArmor = 0
        self.FinalHull = self.BaseHull = MaxHull
        self.FinalSpeed = self.BaseSpeed = Speed
        self.FinalEvasion = self.BaseEvasion = Evasion
        self.FinalCost = self.BaseCost = Cost

        self.FinalArmor = self.FinalShield = self.Power = 0
        self.BaseShield = 0
        self.FinalSpeed = self.BaseSpeed = Speed
        self.FinalEvasion = self.BaseEvasion = Evasion
        self.BonusTracking = 0
        self.FinalArmor = self.FinalSheild = self.Power = 0

        self.Reactor = Modules.Slot("CR", self)
        self.Sensors = Modules.Slot("CS", self)
        self.Hiperdrive = Modules.Slot("CH", self)
        self.Thrusters = Modules.Slot("CT", self)
        self.AI = Modules.Slot("CAI", self)
        self.Aura = None
        self.Name = ""
        self.Modules = []
예제 #13
0
def capfun():
    global money
    global name
    if md.resource_check(100, 200, 100) == True:
        insert_coins()
        money = 7.5
        name = "CAPPUCCINO"
        pro = tk.Button(bottom_frame,
                        text="Proceed",
                        width=10,
                        font=("Arial Bold", 15),
                        bd=5,
                        command=clicker,
                        bg="black",
                        fg="white").grid(column=3, row=6)
예제 #14
0
 def test_module_setup_lmod(self):
     """Test ability to instantiate the class if on a system using lmod"""
     modules_env = {'MODULESHOME': '/dummy/path/1', 'LMOD_CMD': 'lmodcmd'}
     which_side_effects = ['/path/to/lmodcmd', None, None]
     find_side_effects = [None, '/fake/path/modules/init/python.py']
     with mock.patch.dict(os.environ, modules_env), \
             mock.patch('Modules.which',
                        side_effect=which_side_effects), \
             mock.patch('Modules.find_first_binary',
                        return_value='/fake/path/lmodcmd'), \
             mock.patch('Modules.find_file_in_list',
                        side_effect=find_side_effects), \
             mock.patch('__builtin__.execfile') as mock_exec:
         result = Modules.Module()
     mock_exec.assert_not_called()
     self.assertEqual('lmodcmd', result.command)
     self.assertEqual('lmodcmd', result.command_name)
     self.assertEqual(None, result.init_file)
예제 #15
0
 def test_module_setup(self):
     """Test ability to instantiate the class"""
     modules_home = {'MODULESHOME': '/dummy/path/1'}
     which_side_effects = ['/path/to/modulecmd', None, None]
     find_side_effects = [None, '/fake/path/modules/init/python.py']
     with mock.patch.dict(os.environ, modules_home), \
             mock.patch('Modules.which',
                        side_effect=which_side_effects), \
             mock.patch('Modules.find_first_binary',
                        return_value='/fake/path/modulecmd'), \
             mock.patch('Modules.find_file_in_list',
                        side_effect=find_side_effects), \
             mock.patch('__builtin__.execfile') as mock_exec:
         result = Modules.Module()
     mock_exec.assert_called_once_with(find_side_effects[-1])
     self.assertEqual('/fake/path/modulecmd', result.command)
     self.assertEqual('modulecmd', result.command_name)
     self.assertEqual('/fake/path/modules/init/python.py', result.init_file)
예제 #16
0
    def __init__(self, FSettings):
        QWidget.__init__(self)
        self.FSettings = FSettings
        self.Ftemplates = GUIs.frm_PhishingManager()
        self.layout = QVBoxLayout()
        self.FormLayout = QFormLayout()
        self.GridForm = QGridLayout()
        self.Status = QStatusBar()
        self.StatusLabel = QLabel(self)
        self.Status.addWidget(QLabel('Status::'))
        self.Status.addWidget(self.StatusLabel)
        self.GroupBox = QGroupBox()
        self.GroupBox.setTitle('::Server-HTTP::')
        self.GroupBox.setLayout(self.FormLayout)
        self.btntemplates = QPushButton('Phishing M.')
        self.btnStopServer = QPushButton('Stop Server')
        self.btnRefresh = QPushButton('ReFresh')
        self.txt_IP = QLineEdit(self)
        self.ComboIface = QComboBox(self)
        self.txt_IP.setVisible(False)
        self.StatusServer(False)
        #icons
        self.btntemplates.setIcon(QIcon('Icons/page.png'))
        self.btnStopServer.setIcon(QIcon('Icons/close.png'))
        self.btnRefresh.setIcon(QIcon('Icons/refresh.png'))

        #conects
        self.refrash_interface()
        self.btntemplates.clicked.connect(self.show_template_dialog)
        self.btnStopServer.clicked.connect(self.StopLocalServer)
        self.btnRefresh.clicked.connect(self.refrash_interface)
        self.connect(self.ComboIface, SIGNAL('currentIndexChanged(QString)'),
                     self.discoveryIface)

        #layout
        self.GridForm.addWidget(self.ComboIface, 0, 1)
        self.GridForm.addWidget(self.btnRefresh, 0, 2)
        self.GridForm.addWidget(self.btntemplates, 1, 1)
        self.GridForm.addWidget(self.btnStopServer, 1, 2)
        self.FormLayout.addRow(self.GridForm)
        self.FormLayout.addWidget(self.Status)
        self.layout.addWidget(self.GroupBox)
        self.setLayout(self.layout)
예제 #17
0
    def __init__(self,FSettings):
        QWidget.__init__(self)
        self.FSettings  = FSettings
        self.Ftemplates = GUIs.frm_PhishingManager()
        self.layout     = QVBoxLayout()
        self.FormLayout = QFormLayout()
        self.GridForm   = QGridLayout()
        self.Status     = QStatusBar()
        self.StatusLabel= QLabel(self)
        self.Status.addWidget(QLabel('Status::'))
        self.Status.addWidget(self.StatusLabel)
        self.GroupBox           = QGroupBox()
        self.GroupBox.setTitle('::Server-HTTP::')
        self.GroupBox.setLayout(self.FormLayout)
        self.btntemplates       = QPushButton('Phishing M.')
        self.btnStopServer      = QPushButton('Stop Server')
        self.btnRefresh         = QPushButton('ReFresh')
        self.txt_IP             = QLineEdit(self)
        self.ComboIface         = QComboBox(self)
        self.txt_IP.setVisible(False)
        self.StatusServer(False)
        #icons
        self.btntemplates.setIcon(QIcon('Icons/page.png'))
        self.btnStopServer.setIcon(QIcon('Icons/close.png'))
        self.btnRefresh.setIcon(QIcon('Icons/refresh.png'))

        #conects
        self.refrash_interface()
        self.btntemplates.clicked.connect(self.show_template_dialog)
        self.btnStopServer.clicked.connect(self.StopLocalServer)
        self.btnRefresh.clicked.connect(self.refrash_interface)
        self.connect(self.ComboIface, SIGNAL('currentIndexChanged(QString)'), self.discoveryIface)

        #layout
        self.GridForm.addWidget(self.ComboIface,0,1)
        self.GridForm.addWidget(self.btnRefresh,0,2)
        self.GridForm.addWidget(self.btntemplates,1,1)
        self.GridForm.addWidget(self.btnStopServer,1,2)
        self.FormLayout.addRow(self.GridForm)
        self.FormLayout.addWidget(self.Status)
        self.layout.addWidget(self.GroupBox)
        self.setLayout(self.layout)
 def call(self, args):
     u"""
     call methods from parsed command
     """
     setting = False
     if args.box:
         Modules.saveDropBoxPath(args.box)
         setting |= True
     if args.dir:
         Modules.saveDestDirPath(args.dir)
         setting |= True
     if args.interval:
         try: 
             interval = int(args.interval) * 60
             Modules.backupDaemon(interval)
         except ValueError, e: 
             print "usage: %s -i [integer]" % sys.argv[0]
         setting |= True
예제 #19
0
    def load(
            self,
            origin: str,
            path: Tuple[str, str],
            percentage: float,
            thermal: float,
            box: tuple
    ) -> Modules.Image:
        """ Load one image from given path

        Load an image form the path
        Then calculate its attributes

        Args:
            origin: The origin path of image
            path: the paths of the image to load
            percentage: UO2 percentage
            thermal: Thermal conductivity
            box: The box of wanted image

        Return:
            image: An image instance
        """
        # image = Image.open(path[0])
        gray = Image.open(path[0])
        return Modules.Image(
            path=origin,
            rgb=None,  # self.pre_process(image, box),  # Not loading rgb image
            grayscale=self.pre_process(gray, box),
            percentage=float(percentage),
            thermal=from_numpy(
                # Normalize the thermal conductivity
                numpy.array(
                    (float(thermal) - self.app.config('data.bound.low')) / self.app.config('data.bound.inter'))
            ).view(1).float().cuda()
        )
예제 #20
0
                            font=("Arial Bold", 15),
                            fg="white",
                            bg="black",
                            bd=5,
                            command=capfun).grid(column=3, row=6)
    off_button = tk.Button(bottom_most,
                           text="OFF",
                           font=("Arial Bold", 20),
                           fg="white",
                           bg="black",
                           bd=5,
                           command=root.quit).grid(column=1, row=1)


on_button = tk.Button(top_frame,
                      text="ON",
                      font=("Arial Bold", 20),
                      bg="black",
                      fg="white",
                      command=order,
                      bd=5,
                      width=5).grid(column=3, row=0)

root.mainloop()
# To get the details from db
#Backend part
choice = input("Do you want the details?:Yes or No")
if choice in ["YES", "yes", "Y", "y"]:
    md.show()
else:
    print("Done")
예제 #21
0
def cotacao(ativo):
    return m.UltimoPreco(str(ativo))
예제 #22
0
from dateutil.parser import parse
import pytz
import time

# Loading .env from root directory and setting initial values
dotenv.load()
username = os.getenv("USERNAME")
password = os.getenv("PASSWORD")
baseAPI = os.getenv("BASE_API")
# Number of hours since last ticket update that will notify agent
notificationThreshold = os.getenv("NOTIFICATION_THRESHOLD")
discordWebhookId = os.getenv("DISCORD_WEBHOOK_ID")
discordWebhookToken = os.getenv("DISCORD_WEBHOOK_TOKEN")

# Initializing both Agent and Requester with username, password, and baseAPI
zendeskAgent = Modules.ZendeskAgentBot(username, password, baseAPI)
zendeskRequester = Modules.ZendeskRequesterBot(username, password, baseAPI)
# Initializing DiscordNotificationBot
discordNotification = Modules.DiscordNotificationBot(discordWebhookId,
                                                     discordWebhookToken)

while True:
    notificationDate = datetime.datetime.now() - datetime.timedelta(
        hours=int(notificationThreshold))

    # Get all open tickets, check to see if they have been updated within the notification threshold,
    # if not updated within notification threshold, send discord notification
    zendeskAgent.getOpenTickets()
    for openTicket in zendeskAgent.openTickets:
        if openTicket['updated_at']:
            updated_at = parse(openTicket['updated_at'])
예제 #23
0
#file path and name
#path = input ("Enter path: ")
#path = '/home/kishori/a/tmp_anu_dir/tmp/Geo_chap2_E1_detok_tmp'
tmp_path=os.getenv('HOME_anu_tmp')+'/tmp/'

path = tmp_path  +sys.argv[1] + '_tmp'
#path1 = path+'/*/hindi_dep_parser_original.dat'
path1 = path+'/*/hindi_parser_canonial.dat'
files = sorted(glob.glob(path1))
for parse in files:   
	res = re.split(r'/', parse)
	filename = res[-2]
	path_des = path+'/'+filename

	#create dataframe
	relation_df = Modules.create_dataframe(parse)
	dflen = len(relation_df) 
	relation_old_df = relation_df

	#step to remove all records with punctuations
	relation_df = relation_df[~relation_df.POS.str.contains("PUNCT")]
	
	#Calling function to convert PID to WID and assign correct Parent ID's
	Modules.data_PID_PIDWITH_mod(relation_df, dflen)

	#Calling function to create a dictionary
	sub_tree1 = Modules.create_dict(relation_df)

	#Calling wx_to_utf converter
	relation_df = Modules.wx_utf_converter(relation_df)
예제 #24
0
'''
Created on 08-Jan-2018

@author: kodiak
'''
import Modules
from time import sleep

ptx = Modules.ModulesforPTT('4723', "127.0.0.1")

print('''1) Install Build 
2) Continue for feature testing''')

ch = int(input("Enter Your choice : "))
if ch == 1:
    ptx.uninstall_builds()
    ptx.install_build()
if ch >= 2:
    pass
driver = ptx.appium_driver()

while driver:
    if ptx.status_check(driver, ptx.InAppStatus) == False:
        ptx.adb_launch()

    print("""=======================Menu=======================\n
1) Activation and login                                             2) XDM Operation from device
3) XDM Operation from CAT [Unavailable]                             4) Calls
5) PTX Operation                                                    6) Network Operation
7) Logout, Re-login and ADB commands                                8) Background and Foreground
9) Presence change between Avalable to DND and viceversa           10) Copy PTT files                                                 
예제 #25
0
파일: AFXMain.py 프로젝트: sadistech/afx
print "Loading modules..."
import Modules

print "Loaded Modules:"
for item in Modules.module_list:
	print "\t%s (%s)" % (item.short_name, item.long_name)

import AFX

#ok, let's just loop and take commands and stuff for now...
print "Type ? for help"
s = ""
while (s != 'q'):
	s = raw_input("> ")
	if (s == 'l'):
		Modules.print_modules()
	elif (s == '?'):
		print "Commands:"
		print "\tl: list modules"
		print "\ti: module info"
		print "\td: reload modules"
		print "\tr: run module"
		print "\t?: help"
		print "\tq: quit\n"
	elif (s == 'i'):
		s = input("Module #: ")
		Modules.print_module_info(s)
	elif (s == "d"):
		reload(Modules)
	elif (s == "r"):
		i = input("Module #: ")
예제 #26
0
# author:- Bhavana Saraswat M.Tech Banasthali University 2016-2017
import Modules
i=1
print("\t Select option by number given below:\n\t1:- To obtain vibhakti and it corresponding karak-lists.\n\t2:- To obtain sentences corresponding to vibhakti and karak.\n\t3:- To extract words of given POS or category and karak having relation with verb.\n\t4:- To extract vibhakti corresponding to given POS or category.\n\t5:- To extract verb (without pof) corresponding to given vibhakti and karak.\n\t6:- To extract modifierchunk.\n\t7:- To obtain list of sentences which contains a specific word.\n\t8:- To extract pof-verb corresponding to given vibhakti and karak.\n\t9:-  To extract chunk of given vibhakti and karak relation with chunk.\n\t10:- To extract sentences corresponding to given vibhakti and karak and verb.\n\t11:- To extract karak with respect to vibhakti and verb.\n\t12:- To generate a new query.\n\t13:- To extract sentence contain given words\n\t14:- To extract TAM information of finite verb.\n")  
ch=input("Enter your choice: ")
while i==1:
	if ch=='1':
		vibhakti=input("Enter vibhakti: ")
		Modules.vibh(vibhakti);
	elif ch=='2':
		vibhakti=input("Enter vibhakti: ")
		Modules.vibh(vibhakti);
	elif ch=='3':
		pos=input("Enter POS or Category of word: ")
		Modules.category(pos);
	elif ch=='4':
		category=input("Enter Category or POS: ")
		Modules.vibhakti(category);
	elif ch=='5':
		Vibhakti=input("Enter vibhakti: ")
		#Karak=input("Enter karak: ")
		Modules.verb(Vibhakti);
	elif ch=='6':
		Modifier=input("Enter modifier: ")
		Modules.modify(Modifier);
	elif ch=='7':
		word=input("Enter word: ")
		Modules.Word(word);
	elif ch=='8':
		vibhakti=input("Enter vibhakti: ")
		#karak=input("Enter karak: ")
예제 #27
0
 def showProbe(self):
     self.Fprobe = GUIModules.frm_PMonitor()
     self.Fprobe.setGeometry(QRect(100, 100, 400, 400))
     self.Fprobe.show()
예제 #28
0
 def show_windows_update(self):
     self.FWinUpdate = GUIModules.frm_update_attack()
     self.FWinUpdate.setGeometry(QRect(100, 100, 450, 300))
     self.FWinUpdate.show()
예제 #29
0
파일: test.py 프로젝트: vikchopde/study
#!/usr/bin/env python3

import Modules
# import Modules.one.mone
from Modules.one.mone import mone_func
import sys

print("sys.modules")
print(sys.modules)

print()
print(Modules.mod_init())

print()
# print(Modules.one.mone.i)
#print(Modules.one.mone.mone_func())
print(mone_func())


def foo():
    global my_var
    my_var = 100


if __name__ == "__main__":
    global my_var
    my_var = 200
    print(my_var)
    foo()
    print(my_var)
    print()
예제 #30
0
 def logdns2proxy(self):
     self.Fdns2proxy = GUIModules.frm_dns2proxy()
     self.Fdns2proxy.setWindowTitle('Dns2proxy Logger')
     self.Fdns2proxy.show()
예제 #31
0
 def credentials(self):
     self.Fcredentials = GUIModules.frm_get_credentials()
     self.Fcredentials.setWindowTitle('Phishing Logger')
     self.Fcredentials.show()
예제 #32
0
if __name__ == '__main__':
    check_paths()
    # Check if a module name is passed to the command line
    if len(sys.argv)>1:
        module_name_to_wrap = sys.argv[1]
        if module_name_to_wrap == 'GEOM':
            print "Generating swig files for the GEOM library"
            modules_to_wrap = Modules.SALOME_GEOM_MODULES
        elif module_name_to_wrap == 'SMESH':
            print "Generating swig files for the SMESH library"
            modules_to_wrap = Modules.SALOME_SMESH_MODULES
        else:
            modules_to_wrap = None
        # Try to find the module with the name provided
            for module in Modules.get_all_modules():
                if module[0] == module_name_to_wrap:
                    modules_to_wrap = [module]
                    break
        #print modules_to_wrap
        if modules_to_wrap == None:
            raise NameError,"Unknown module"
    else:
        if sys.platform == 'win32':
            modules_to_wrap = Modules.COMMON_MODULES + Modules.WIN_MODULES
        else:
            modules_to_wrap = Modules.COMMON_MODULES + Modules.UNIX_MODULES
        
    if MULTI_PROCESS_GENERATION:
        print "Generating pythonOCC SWIG files (MultiProcess mode)."
        generate_swig_multiprocess(modules_to_wrap)
예제 #33
0
 def test_module_list():
     """Test the module_list function"""
     with mock.patch('Modules.Module.module_list') as mock_module:
         Modules.module_list()
     mock_module.assert_called_once_with()
예제 #34
0
def clicker():
    global money
    global quarter_ent
    global dimes_ent
    global nickles_ent
    global pennies_ent
    global name
    quarter = quarter_ent.get()
    dimes = dimes_ent.get()
    nickles = nickles_ent.get()
    pennies = pennies_ent.get()
    if (quarter.isdigit() and dimes.isdigit() and nickles.isdigit()
            and pennies.isdigit()):
        a = md.calcu(quarter, dimes, nickles, pennies, money)
        if a == 1:
            val_label = tk.Label(
                bottom_frame,
                text=
                f"Payment Successful\nCollect Your change {md.val:.2f}\nHere is your {name} .Enjoy!",
                font=("Arial Bold", 10))
            val_label.grid(column=3, row=15)
        elif a == 2:
            val_label = tk.Label(bottom_frame,
                                 text="Payment successful",
                                 font=("Arial Bold", 10))
            val_label.grid(column=3, row=15)
        else:
            val_label = tk.Label(
                bottom_frame,
                text=
                f"Sorry!!! you don't have enough money \n Refunded money {md.cus_money:.2f}",
                font=("Arial Bold", 10))
            val_label.grid(column=3, row=15)
        md.save(name)
    else:
        tk.messagebox.showwarning("Wrong data", "Invalid data,Numbers Only")

    def report():
        global water
        global milk
        global coffee
        global coins
        water = tk.Label(bottom_frame,
                         text=f"Water :{md.Tot_water}ml",
                         font=("Arial Bold", 10),
                         bg="black",
                         fg="white")
        water.grid(column=4, row=1)
        milk = tk.Label(bottom_frame,
                        text=f"Milk :{md.Tot_milk}ml",
                        font=("Arial Bold", 10),
                        bg="black",
                        fg="white")
        milk.grid(column=4, row=2)
        coffee = tk.Label(bottom_frame,
                          text=f"Coffee :{md.Tot_coffee}gm",
                          font=("Arial Bold", 10),
                          bg="black",
                          fg="white")
        coffee.grid(column=4, row=3)
        coins = tk.Label(bottom_frame,
                         text=f"Money :${money:.2f}",
                         font=("Arial Bold", 10),
                         bg="black",
                         fg="white")
        coins.grid(column=4, row=4)

    report = tk.Button(bottom_most,
                       text="Report",
                       width=10,
                       font=("Arial Bold", 20),
                       bd=5,
                       command=report,
                       bg="black",
                       fg="white").grid(column=0, row=1)

    def reset():
        try:
            val_label.grid_forget()
            water.grid_forget()
            milk.grid_forget()
            coffee.grid_forget()
            coins.grid_forget()

        except NameError:
            pass

    reset = tk.Button(bottom_frame,
                      text="Reset",
                      width=10,
                      font=("Arial Bold", 15),
                      bd=5,
                      command=reset,
                      bg="black",
                      fg="white").grid(column=4, row=6)
예제 #35
0
 def form_mac(self):
     self.Fmac = GUIModules.frm_mac_generator()
     self.Fmac.setGeometry(QRect(100, 100, 300, 100))
     self.Fmac.show()
예제 #36
0
 def show_arp_posion(self):
     self.Farp_posion = GUIModules.frm_Arp_Poison()
     self.Farp_posion.setGeometry(0, 0, 450, 300)
     self.Farp_posion.show()
예제 #37
0
 def test_module():
     """Test the module function"""
     with mock.patch('Modules.Module.module') as mock_module:
         Modules.module('load', 'sierra/version')
     mock_module.assert_called_once_with('load', 'sierra/version')
예제 #38
0
 def show_dhcpDOS(self):
     self.Fstar = GUIModules.frm_dhcp_Attack()
     self.Fstar.setGeometry(QRect(100, 100, 450, 200))
     self.Fstar.show()
예제 #39
0
def process(source: str,
            destination: str,
            plugin_file: str = "",
            plugin_opt: dict = {},
            sub_list: list = [],
            sub_skip_tsv: bool = False,
            sub_skip_dir: bool = False,
            ses_skip_dir: bool = False,
            part_template: str = "",
            bidsmapfile: str = "bidsmap.yaml",
            dry_run: bool = False) -> None:
    """
    Process bidsified dataset before the bidsification.
    Can be used to produce derivatives, convertion
    anonymisation with adventage of recording identification
    by bidsmap.yaml

    Essentually it is identical to bidsification but without
    bidsification itself.

    Only subjects in source/participants.tsv are treated,
    this list can be narrowed using sub_list, sub_skip_tsv
    and sub_skip_dir options

    Parameters
    ----------
    source: str
        folder containing source dataset
    destination: str
        folder for prepeared dataset
    plugin_file: str
        path to the plugin file to use
    plugin_opt: dict
        named options passed to plugin
    sub_list: list
        list of subject to process. Subjects
        are checked after plugin and must
        start with 'sub-', as in destination
        folder
    sub_skip_tsv: bool
        if set to True, subjects found in
        destination/participants.tsv will be
        ignored
    sub_skip_dir: bool
        if set to true, subjects with already
        created directories will be ignored
        Can conflict with sub_no_dir
    ses_skip_dir: bool
        if set to True, sessions with already
        created directories will be ignored
        Can conflict with ses_no_dir
    part_template: str
        path to template json file, from whitch
        participants.tsv will be modeled. If unset
        the defeault one "source/participants.tsv"
        is used. Setting this variable may break
        workflow
    bidsmapfile: str
        The name of bidsmap file, will be searched for
        in destination/code/bidsmap directory, unless
        path is absolute
    dry_run: bool
        if set to True, no disk writing operations
        will be performed
    """

    logger.info("-------------- Processing data -------------")
    logger.info("Source directory: {}".format(source))
    logger.info("Destination directory: {}".format(destination))

    # Input checking
    # source = os.path.abspath(source)
    if not os.path.isdir(source):
        logger.critical("Source directory {} don't exists".format(source))
        raise NotADirectoryError(source)
    if not os.path.isdir(destination):
        logger.critical(
            "Destination directory {} don't exists".format(destination))
        raise NotADirectoryError(destination)

    # Input checking & defaults
    bidscodefolder = os.path.join(destination, 'code', 'bidsme')

    # Create a code/bidsme subfolder
    os.makedirs(bidscodefolder, exist_ok=True)

    # Check for dataset description file
    dataset_file = os.path.join(destination, 'dataset_description.json')
    if not os.path.isfile(dataset_file):
        logger.warning("Dataset description file 'dataset_description.json' "
                       "not found in '{}'".format(destination))

    # Check for README file
    readme_file = os.path.join(destination, 'README')
    if not os.path.isfile(readme_file):
        logger.warning("Dataset readme file 'README' "
                       "not found in '{}'".format(destination))

    # Get the bidsmap heuristics from the bidsmap YAML-file
    fname = paths.findFile(bidsmapfile, bidscodefolder, paths.local,
                           paths.config)
    if not fname:
        logger.critical('Bidsmap file {} not found.'.format(bidsmapfile))
        raise FileNotFoundError(bidsmapfile)
    else:
        bidsmapfile = fname
    logger.info("loading bidsmap {}".format(bidsmapfile))
    bidsmap = Bidsmap(bidsmapfile)

    ntotal, ntemplate, nunchecked = bidsmap.countRuns()
    logger.debug("Map contains {} runs".format(ntotal))
    if ntemplate != 0:
        logger.warning("Map contains {} template runs".format(ntemplate))
    if nunchecked != 0:
        logger.critical("Map contains {} unchecked runs".format(nunchecked))
        raise Exception("Unchecked runs present")

    ###############
    # Plugin setup
    ###############
    if plugin_file:
        plugins.ImportPlugins(plugin_file)
        plugins.InitPlugin(source=source,
                           destination=destination,
                           dry=dry_run,
                           **plugin_opt)

    ###############################
    # Checking participants list
    ###############################
    if not part_template:
        part_template = os.path.join(source, "participants.json")
    else:
        logger.warning(
            "Loading exterior participant template {}".format(part_template))
    BidsSession.loadSubjectFields(part_template)

    new_sub_file = os.path.join(source, "participants.tsv")
    df_sub = pandas.read_csv(new_sub_file, sep="\t", header=0,
                             na_values="n/a").drop_duplicates()
    df_dupl = df_sub.duplicated("participant_id")
    if df_dupl.any():
        logger.critical("Participant list contains one or several duplicated "
                        "entries: {}".format(", ".join(
                            df_sub[df_dupl]["participant_id"])))
        raise Exception("Duplicated subjects")

    dupl_file = os.path.join(source, "__duplicated.tsv")
    if os.path.isfile(dupl_file):
        logger.critical("Found unmerged file with duplicated subjects")
        raise FileExistsError(dupl_file)

    new_sub_json = os.path.join(source, "participants.json")
    if not tools.checkTsvDefinitions(df_sub, new_sub_json):
        raise Exception("Incompatible sidecar json")

    old_sub_file = os.path.join(destination, "participants.tsv")
    old_sub = None
    if os.path.isfile(old_sub_file):
        old_sub = pandas.read_csv(old_sub_file,
                                  sep="\t",
                                  header=0,
                                  na_values="n/a")
        if not old_sub.columns.equals(df_sub.columns):
            logger.warning("Source participant.tsv has different columns "
                           "from destination dataset")
        old_sub = old_sub["participant_id"]

    ##############################
    # Subjects loop
    ##############################
    n_subjects = len(df_sub["participant_id"])
    for index, sub_row in df_sub.iterrows():
        sub_no = index + 1
        sub_id = sub_row["participant_id"]
        sub_dir = os.path.join(source, sub_id)
        if not os.path.isdir(sub_dir):
            logger.error("{}: Not found in {}".format(sub_id, source))
            continue

        scan = BidsSession()
        scan.in_path = sub_dir
        scan.subject = sub_id

        #################################################
        # Cloning df_sub row values in scans sub_values
        #################################################
        for column in df_sub.columns:
            scan.sub_values[column] = sub_row[column]

        # locking subjects here forbids renaming in process
        # as it will be unclear how manage folders with data
        scan.lock_subject()
        if plugins.RunPlugin("SubjectEP", scan) < 0:
            logger.warning("Subject {} discarded by {}".format(
                scan.subject, "SubjectEP"))
            continue

        if not scan.isSubValid():
            logger.error("{}: Subject id '{}' is not valid".format(
                sub_id, scan.subject))
            continue

        if tools.skipEntity(scan.subject, sub_list,
                            old_sub if sub_skip_tsv else None,
                            destination if sub_skip_dir else ""):
            logger.info("Skipping subject '{}'".format(scan.subject))
            continue

        ses_dirs = tools.lsdirs(sub_dir, 'ses-*')
        if not ses_dirs:
            logger.error("{}: No sessions found in: {}".format(
                scan.subject, sub_dir))
            continue

        for ses_dir in ses_dirs:
            scan.in_path = ses_dir
            logger.info("{} ({}/{}): Scanning folder {}".format(
                scan.subject, sub_no, n_subjects, ses_dir))
            scan.unlock_session()
            scan.session = os.path.basename(ses_dir)
            if plugins.RunPlugin("SessionEP", scan) < 0:
                logger.warning("Session {} discarded by {}".format(
                    scan.session, "SessionEP"))
                continue

            scan.lock()

            if ses_skip_dir and tools.skipEntity(
                    scan.session, [], None,
                    os.path.join(destination, scan.subject)):
                logger.info("Skipping session '{}'".format(scan.session))
                continue

            for module in Modules.selector.types_list:
                mod_dir = os.path.join(ses_dir, module)
                if not os.path.isdir(mod_dir):
                    logger.debug("Module {} not found in {}".format(
                        module, ses_dir))
                    continue
                for run in tools.lsdirs(mod_dir):
                    scan.in_path = run
                    cls = Modules.select(run, module)
                    if cls is None:
                        logger.error(
                            "Failed to identify data in {}".format(run))
                        continue
                    recording = cls(rec_path=run)
                    if not recording or len(recording.files) == 0:
                        logger.error(
                            "unable to load data in folder {}".format(run))
                        continue
                    recording.setBidsSession(scan)
                    coin(destination, recording, bidsmap, dry_run)
            plugins.RunPlugin("SessionEndEP", scan)

        scan.in_path = sub_dir
        plugins.RunPlugin("SubjectEndEP", scan)

    ##################################
    # Merging the participants table
    ##################################
    df_processed = BidsSession.exportAsDataFrame()

    col_mismatch = False
    if not df_processed.columns.equals(df_sub.columns):
        col_mismatch = True
        logger.warning("Modified participant table do not match "
                       "original table. This is discouraged and can "
                       "break future preparation and process steps")
        for col in df_processed.columns.difference(df_sub.columns):
            df_sub[col] = None
        df_sub = df_sub[BidsSession.getSubjectColumns()]
        df_sub.drop_duplicates(inplace=True)

    df_res = pandas.concat([df_sub, df_processed],
                           join="inner",
                           keys=("original", "processed"),
                           names=("stage", "ID"))
    df_res = df_res.drop_duplicates()

    df_dupl = df_res.duplicated("participant_id", keep=False)

    if df_dupl.any():
        logger.info("Updating participants values")
        df_dupl = df_dupl.drop(["processed"])
        df_res.drop(df_dupl[df_dupl].index, inplace=True)

    df_dupl = df_res.duplicated("participant_id")
    if df_dupl.any():
        logger.error("Participant list contains one or several duplicated "
                     "entries: {}".format(", ".join(
                         df_res[df_dupl]["participant_id"])))

    ##################################
    # Saving the participants table
    ##################################
    if not dry_run:
        df_res[~df_dupl].to_csv(new_sub_file,
                                sep='\t',
                                na_rep="n/a",
                                index=False,
                                header=True)
        if df_dupl.any():
            logger.info("Saving the list to be merged manually to {}".format(
                dupl_file))
            df_res[df_dupl].to_csv(dupl_file,
                                   sep='\t',
                                   na_rep="n/a",
                                   index=False,
                                   header=True)
        json_file = tools.change_ext(new_sub_file, "json")
        if col_mismatch or not os.path.isfile(json_file):
            BidsSession.exportDefinitions(json_file)

    plugins.RunPlugin("FinaliseEP")
예제 #40
0
 def formDauth(self):
     self.Fdeauth =GUIModules.frm_deauth()
     self.Fdeauth.setGeometry(QRect(100, 100, 200, 200))
     self.Fdeauth.show()
UpTime = int(os.environ["UpTime"])
DownTime = int(os.environ["DownTime"])
Count = int(os.environ["Count"])
Build = os.environ["Build"]
NetworkOperationType = os.environ["NetworkOperationType"]

cmd = adb.AdbCommands(IP)
cmd.adb_Android_device_finder()
#print(cmd.devSerials)
cmd.adb_exec_command(key1)
cmd.adb_exec_command(key2)
for sn in range(len(cmd.devSerials.items())):
    sn = sn + 1
    cmd.adb_uninstall_builds(cmd.devSerials[sn], build=appium)

ptx = Modules.ModulesforPTT(IP)

print("======Given Details======")
print("System IP : ", IP)
print("UP time : ", UpTime)
print("DOWN time : ", DownTime)
print("Iteration count : ", Count)
print("Build is : ", Build)
print("NetworkOperationType is : ", NetworkOperationType)
print("========================\n")


def network_Simulation(UpTime, DownTime, Count):
    #print(UPtime, DOWNtime, count)

    flag = bool(ptx.Devicelist)
예제 #42
0
 def show_dns_spoof(self):
     self.Fdns = GUIModules.frm_DnsSpoof()
     self.Fdns.setGeometry(QRect(100, 100, 450, 300))
     self.Fdns.show()
예제 #43
0
import Modules

(Modules.bark(5))

print(Modules.color)
예제 #44
0
 def logsnetcreds(self):
     self.FnetCreds = GUIModules.frm_NetCredsLogger()
     self.FnetCreds.setWindowTitle('NetCreds Logger')
     self.FnetCreds.show()
예제 #45
0
 def __init__(self):  #self,Class,MaxHull,Speed,Evasion,ComPoints
     Ship.__init__(self, "Corvete", 300, 160, 60, 1, 30)
     self.Core = Modules.Slot("MCC", self)
     self.Modules.append(self.Core)
예제 #46
0
#Use a Module

import Modules
Modules.greeting("everyone")
#-----------------------------
import mymodule
a = mymodule.person["age"]
b = mymodule.person["name"]
print(a, b)
예제 #47
0
 def __init__(self):  #self,Class,MaxHull,Speed,Evasion,ComPoints
     Ship.__init__(self, "Destroyer", 800, 140, 35, 2, 60)
     self.Bow = Modules.Slot("MDB", self)
     self.Stern = Modules.Slot("MDS", self)
     self.Modules.append(self.Bow)
     self.Modules.append(self.Stern)
import Modules as m
import platform

m.greeting("balaji")
x = m.person1["age"]
print(x)

y = platform.system()
print(y)
z = dir(m)
print(z)
m = dir(platform)
print(m)
예제 #49
0
import ClockVars, USBLatency, Modules, time, msvcrt
from datetime import datetime
import numpy as np

if __name__ == "__main__":
    ser = Modules._openPort()
    sys_vars_filename = "test-sysvars"

    device_name = "YOYOYO"
    calibration = "Keyboard"
    curr_time = datetime.utcnow()

    sys_vars = []

    while 1:
        ser.write(b'V')  # sends out clock ratio mode
        time.sleep(1)
        print("attempting to start...")
        check = ser.read(1)
        if check == 'V':
            print("Mbed set to Clock Ratio Mode!")
            time.sleep(3)
            break
        else:
            print("cant start...")
            time.sleep(1)
    clkratio, tdiff, tmbed = ClockVars.clock_ratio(ser)
    sys_vars.append(clkratio)
    sys_vars.append(tdiff)
    sys_vars.append(tmbed)