def test_padded_kernel(self):
        """ Implement a simple padded kernel. """
        for case in self.cases:
            # Form data to work on.
            space.initialize_space(case['shape'])
            x_np = comm.allreduce(np.random.randn(*case['shape']).astype(case['dtype']))
            x = Grid(x_np, x_overlap=1)
            s_np = comm.allreduce(np.random.randn(1).astype(case['dtype']))
            s = Const(s_np)
            z = Out(case['dtype'])

            # Make a kernel.
            code = Template("""
                            if (_in_local && _in_global) {
                                x(0,0,0) = s(0) * x(0,0,0);
                                z += a * x(0,0,0);
                            }
                            """).render()
            fun = Kernel(code, \
                        ('a', 'number', case['dtype']), \
                        ('x', 'grid', x.dtype), \
                        ('s', 'const', s.dtype, s.data.size), \
                        ('z', 'out', z.dtype), \
                        padding=(1,1,1,1))

            # Execute and check the result.
            fun(case['dtype'](2), x, s, z)
            gpu_sum = z.get()
            cpu_sum = np.sum(2.0 * s_np * x_np)
            err = abs(gpu_sum - cpu_sum) / abs(cpu_sum)
            # print case, err
            if case['dtype'] in (np.float32, np.complex64):
                self.assertTrue(err < 1e-2, (case, err))
            else:
                self.assertTrue(err < 1e-6, (case, err))
    def __init__(self, hostname: str, workgroup_name: str):
        self.logged_in: list = list()
        self.failed_login: bool = False
        self.session_key: int = 1
        self.packet: bytes = b''
        self.client_port: int = -1  # Used for Metasploit shell deception
        try:
            self.hostname: str = hostname
            self.workgroup_name: str = workgroup_name
        except (AttributeError, TypeError):
            Out.err(
                "Samba: The workgroup and host names must be strings. Shutting down."
            )
            sys.exit(1)

        self.current_dir: str = ""
        self.bind: bool = False  # If false, NetShareEnumAll is requested; if true, Bind packet was received.
        self.info: str = ""  # Used for NetShareGetInfo; if data, will give info on data; if ipc, info on ipc, etc.
        self.files: dict = dict()
        self.call_id: bytes = b''  # Used for NetShare-messages; Default--Nmap 'AAAA', Metasploit '0000'
        self.payload: bytes = b''  # Stores malicious payloads sent by Nmap/Metasploit; stored to verify later
        self.packet_to_reassemble: bytes = b''  # Stores packets that may be fragmented and sent out of order
        self.exploited: list = list(
        )  # This is used to deceive Metasploit shell and is tied to a specific client port
        self.log_interaction = LogData(
            "interaction", "info", "N/A",
            "unknown")  # Default log, used frequently
        self.log_nmap = LogData("vulnerability scan", "medium", "confirmed",
                                "nmap")  # Default log, used frequently
        self.log_metasploit = LogData(
            "exploitation", "high", "confirmed",
            "metasploit")  # Default log, used frequently
    def __init__(self,
                 stdout: bool,
                 log_location: str,
                 image_name: str,
                 host_name: str,
                 container_name: str = "corecpro_shell"):
        super().__init__(stdout, log_location, container_name)
        if log_location:
            self.log: Logger = Logger(location_shell=log_location)
        else:
            self.log: Logger = Logger()
        self.log.stdout = stdout
        self.image_name: str = image_name
        self.host_name: str = host_name
        self.container_name: str = container_name + "_" + str(time.time())

        docker_init = subprocess.run([
            'docker', 'run', '-dit', '-h', self.host_name, '--name',
            self.container_name, self.image_name, self.shell
        ],
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
        if docker_init.stderr:
            Out.err("Docker container failed to initialize.")
            Out.err("SYSTEM: " + docker_init.stderr.decode("UTF-8"))
            raise ChildProcessError()
        else:
            self.container_id: str = docker_init.stdout[0:len(docker_init.
                                                              stdout) -
                                                        1].decode("UTF-8")
            Out.norm("Docker container ID  : " + self.container_id)
            Out.norm("Docker container name: " + self.container_name)
            Out.good("Docker container successfully initialized.")
 def check_defun(self, s_exp):
     from out import Out
     myout = Out()
     if s_exp.car().atom().main_l != 't':
         raise AnyError("Funcion name should be an atom")
     if not myout.islist(s_exp.cdr().main_l) or \
             not myout.islist(s_exp.cdr().cdr().main_l):
         raise AnyError("Parameter list/body has to be a list")
Exemple #5
0
 def __init__(self):
     In.__init__(self)
     Out.__init__(self)
     self.dron = tellopy.Tello()
     self.dron.connect()
     self.dron.start_video()
     self.capturing_video = True
     threading.Thread(target=self.videoThread, args=[]).start()
     dron.subscribe(dron.EVENT_FLIGHT_DATA, self.flightDataHandler)
 def __delete(self, filename: bytes):
     smb = Smb1
     try:
         del self.files[filename]
     except KeyError:
         Out.warn(
             "Samba: Client attempted to delete a file that doesn't exist. Ignoring."
         )
     return smb.netbios_wrapper(
         smb.smb_wrapper(self.packet, True, smb.empty()))
Exemple #7
0
 def rand_num_gen(length: int = 8) -> bytes:
     """Generates a random number in bytes (default length 8 bytes); used for SMB challenge and User ID generation.
     """
     try:
         output = os.urandom(length)
     except NotImplementedError:
         Out.err("Samba: Your OS does not support crypto-safe random number generation. "
                 "Samba deception will not function. Shutting down.")
         sys.exit(1)
     return bytes(output)
Exemple #8
0
 def petri(self, *elements):
     a = elements[0]
     firings = elements[1]
     ps = [Place(m) for m in a]
     ts = dict(
         t1=Transition([Out(ps[elements[2]])], [In(ps[elements[3]])]),
         t2=Transition([Out(ps[1])], [In(ps[2]), In(ps[0])]),
     )
     firing_sequence = [choice(list(ts.keys()))
                        for _ in range(firings)]  # stochastic execution
     print(firing_sequence)
     petri_net = PetriNet(ts)
     petri_net.run(firing_sequence, ps)
Exemple #9
0
 def __init__(self):
     self.version = '3.0.0'        
     self.cgi = functions.CgiHelper(FieldStorage(keep_blank_values=True), self.version)
     self.sql = Sql(self.cgi, db='tempcat', user='******', passwd='catpass')
     self.usr = User(self.sql, self.cgi)
     self.outobj = Out(self.cgi, self.sql, self.usr, version=self.version)
     self.parseParams()
Exemple #10
0
    def test_sum(self):
        """ Make sure summing works. """
        for case in self.cases:
            space.initialize_space(case['shape'])
            x = Out(case['dtype'], op='sum')
            x_cpu_data = np.random.randn(*case['shape'][1:]).astype(case['dtype'])
            if case['dtype'] in (np.complex64, np.complex128):
                x_cpu_data = (1 + 1j) * x_cpu_data

            x.data.set(x_cpu_data)
            res_gold = comm.allreduce(np.sum(x_cpu_data.flatten()))

            x.reduce()
            err = abs(res_gold - x.get()) / abs(res_gold)

            if case['dtype'] in (np.float32, np.complex64):
                self.assertTrue(err < 1e-3)
            else:
                self.assertTrue(err < 1e-10)
Exemple #11
0
class Main:
    
    def __init__(self):
        self.version = '3.0.0'        
        self.cgi = functions.CgiHelper(FieldStorage(keep_blank_values=True), self.version)
        self.sql = Sql(self.cgi, db='tempcat', user='******', passwd='catpass')
        self.usr = User(self.sql, self.cgi)
        self.outobj = Out(self.cgi, self.sql, self.usr, version=self.version)
        self.parseParams()
        
    def ajax(self):
        return Ajax(self.cgi, self.sql, self.usr, self.outobj)
    
    def card(self):
        return Card(self.cgi, self.sql, self.usr)
    
    def stat(self):
        return Stat(self.cgi, self.sql, self.usr)

    def out(self):
        self.outobj.out()

    def parseParams(self):        
        getVal = self.cgi.getVal
        if getVal('card'):
            self.card().out(getVal('card'))
        elif getVal('stat'):
            self.stat().out(getVal('stat'))
        elif getVal('search'):
            self.ajax().search()
        elif getVal('get'):
            self.ajax().get()
        elif getVal('edit'):
            self.ajax().edit()
        elif getVal('add'):
            self.ajax().add()
        elif getVal('login'):
            self.ajax().login()
        elif getVal('register'):
            self.ajax().register()        
        else:
            self.out()
    def test_simple_example(self):
        """ Implement a simple kernel. """
        # Form data to work on.
        shape = (100,100,100)
        space.initialize_space(shape)
        x = Grid((1 + 1j) * np.ones(shape).astype(np.complex128))
        z = Out(np.float64)

        # Make a kernel.
        code = """  
                if (_in_global) { // Need to be in the space.
                    z += real(x(0,0,0)) + imag(x(0,0,0));
                } """
        fun = Kernel(code, \
                    ('x', 'grid', x.dtype), \
                    ('z', 'out', z.dtype))

        # Execute and check the result.
        fun(x, z)
        gpu_sum = z.get()
Exemple #13
0
    def test_simple_example(self):
        """ Implement a simple kernel. """
        # Form data to work on.
        shape = (100, 100, 100)
        space.initialize_space(shape)
        x = Grid((1 + 1j) * np.ones(shape).astype(np.complex128))
        z = Out(np.float64)

        # Make a kernel.
        code = """  
                if (_in_global) { // Need to be in the space.
                    z += real(x(0,0,0)) + imag(x(0,0,0));
                } """
        fun = Kernel(code, \
                    ('x', 'grid', x.dtype), \
                    ('z', 'out', z.dtype))

        # Execute and check the result.
        fun(x, z)
        gpu_sum = z.get()
Exemple #14
0
    def test_simple_kernel(self):
        """ Implement a simple kernel. """
        for case in self.cases:
            # Form data to work on.
            space.initialize_space(case['shape'])
            x_np = comm.allreduce(np.random.randn(*case['shape']).astype(case['dtype']))
            x = Grid(x_np, x_overlap=2)
            s_np = comm.allreduce(np.random.randn(case['shape'][0],1,1).astype(case['dtype']))
            s = Const(s_np)
            z = Out(case['dtype'])

            # Make a kernel.
            code = Template("""
                            if (_in_local && _in_global) {
                                z += a * s(_X) * x(0,0,0);
                                // z += a * x(0,0,0);
                            }
                            """).render()
            fun = Kernel(code, \
                        ('a', 'number', case['dtype']), \
                        ('x', 'grid', x.dtype), \
                        ('s', 'const', s.dtype), \
                        ('z', 'out', z.dtype), \
                        shape_filter='all')

            # Execute and check the result.
            # fun()
            while fun.exec_configs:
            # for k in range(40):
                fun(case['dtype'](2.0), x, s, z)
                # fun(case['dtype'](2.0), x, z)
                gpu_sum = z.get()
                cpu_sum = np.sum(2 * s_np * x_np)
                # cpu_sum = np.sum(2 * x_np)
                err = abs(gpu_sum - cpu_sum) / abs(cpu_sum)
                if case['dtype'] in (np.float32, np.complex64):
                    self.assertTrue(err < 1e-2, (case, err))
                else:
                    self.assertTrue(err < 1e-6, (case, err))
    def __init__(self,
                 stdout: bool,
                 log_location: str,
                 container_name: str = "corecpro_shell"):
        super().__init__(stdout, log_location, container_name)

        rand: bytes = ''.join(
            choice(digits + ascii_letters) for n in range(20)).encode()
        docker_run = self._raw_cmd(b'echo ' + rand)
        if docker_run[0] != b'':
            Out.err("Failed to connect to Docker container " +
                    self.container_name + ".")
            Out.err("SYSTEM: " + docker_run[0].decode('UTF-8'))
            raise ChildProcessError()
        elif docker_run[1][:-1] != rand:
            Out.err("Failed to verify connectivity, but no error is thrown.")
            Out.err("We sent the following command: echo " +
                    rand.decode('UTF-8'))
            Out.err("We expected to receive: " + rand.decode('UTF-8'))
            Out.err("Instead we got: " + docker_run[1].decode('UTF-8'))
            Out.err("Please report this error.")
            raise ChildProcessError()
        else:
            Out.good("Successfully connected to Docker container " +
                     self.container_name)
Exemple #16
0
from mfea.mfea import MFEA
from tasks.bar import Task
from out import Out
from get_data import setting
from draw import draw
import numpy as np

out = Out()


def weight(n_steps):
    return np.array(
        [1 / (n_steps + 1) + i * 1 / (n_steps + 1) for i in range(n_steps)])


def is_end(x, task):
    if x is None:
        return False
    else:
        is_complete = 0
        for i in range(task.task):
            task.tasks[i].parameter['start'] = x[i]
            if np.array_equal(task.tasks[i].parameter['start'],
                              task.tasks[i].parameter['end']):
                is_complete += 1
            # if np.linalg.norm(task.tasks[i].parameter['start']-task.tasks[i].parameter['end']) <= 10:
            #     is_complete += 1
        if is_complete == task.task:
            return True
        else:
            return False
Exemple #17
0
def petri(elements):
  print(elements)
  between = ''
  list_places = []
  in_statement = False
  checklbrac = '['
  checkrbrac = ']'
  checktime = 'time'
  checkstar = '*'
  checknarrow = '|'

  checkless = '<'
  checkmore = '>'

  listoutinbeforenarrow = []
  listoutinafternarrow = []

  for i in elements:
    if checklbrac in i:
      in_statement = True
    if in_statement:
      between += i
    if checkrbrac in i:
      in_statement = False
      break
  between = between.replace('[','').replace(']','')
  for i in between:
    list_places.append(int(i))
  print(list_places)

  between = ''
  for i in elements:
    if checktime in i:
      in_statement = True
    if in_statement:
      between += i
    if checkstar in i:
      in_statement = False
      break
  between = between.replace('time','').replace('*','').replace('=', '')
  firings = int(between)
  print(firings)

  between = ''
  for i in elements:
    if checkstar in i:
      in_statement = True
    if in_statement:
      between += i
    if checknarrow in i:
      in_statement = False
      break
  between = between.replace('*','').replace('|','')
  for i in between:
    listoutinbeforenarrow.append(i)
  print(listoutinbeforenarrow)

  listoutinafternarrow = elements[13]
  #between = between.replace('|','').replace('*','')
  # for i in between:
  #   listoutinafternarrow.append(i)
  # print(listoutinafternarrow)

  ps = [Place(m) for m in list_places]

  countless = 0
  countmore = 0

  for i in listoutinbeforenarrow:
    if checkless in i:
      countless += 1
    if checkmore in i:
      countmore += 1
  print(countless, countmore)

  listout = []
  listin = []
  for i in range(countless):
    listout = [Out(ps[i])]
  for i in range(countmore):
    listin = [In(ps[i])]

  for i in range(1):
    ts = dict(i=Transition(listout, listin + [In(ps[1])]))
    # a = elements[0]
    # firings = elements[1]
    # coeff = [num for num in elements[2:] if isinstance(num, int)]
    # print('all coeff', coeff)

    # ps = [Place(m) for m in a]
    # ts = dict(
    #      t1=Transition(
    #          [Out(ps[0])], 
    #          [In(ps[0]), In(ps[1])]
    #     )
        # t2=Transition(
        #     [Out(ps[1])],
        #     [In(ps[2]), In(ps[0])])
    #     ,)
    
    firing_sequence = [choice(list(ts.keys())) for _ in range(firings)] # stochastic execution
    print(firing_sequence)
    petri_net = PetriNet(ts)
    petri_net.run(firing_sequence, ps)