Example #1
0
def finalizeDates(monDates, arr):
    array = []
    for week in range(len(arr)):
        for event in arr[week]:
            dayNum = getDay(event[2][0])
            time = convertToTime(event[2][1])
            dateOf = monDates[week] + timedelta(dayNum)
            if event[1] == "PorG":
                continue
            string_of_date = dateOf.strftime("%m/%d/%Y")
            dicti = {}
            dicti["summary"] = event[0]
            dicti["description"] = event[1]
            dicti["date"] = string_of_date
            dicti["starTime"] = time[0]
            dicti["endtime"] = time[1]
            datetime_start = string_of_date + " " + time[0]
            datetime_end = string_of_date + " " + time[1]
            dicti["datetime_start_string"] = datetime_start
            dicti["datetime_start_string"] = datetime_end

            #format = '%m/%d/%Y %H:%M:%S'
            datetime_object_start = parse(datetime_start).isoformat()
            datetime_object_end = parse(datetime_end).isoformat()
            dicti["datetime_obj_start"] = datetime_object_start
            dicti["datetime_obj_end"] = datetime_object_end

            array.append(dicti)

    return array
Example #2
0
def tossCoin():
    global tossAmount
    global randProbabilityForHeads
    
    while(tossAmount<=-10): #tossAmount is -10 if user didn't specify how many times to toss.
        userInput = raw_input("Press n + ENTER to continue. ")
        if(userInput=="n"):
            randInt = random.random()
            if(randInt<randProbabilityForHeads):
                print "H"
            else:
                print "T"
    if(tossAmount>0):
            
            array = []
            for x in xrange(tossAmount):
                randInt = random.random()
                if(randInt<randProbabilityForHeads):
                    print "H"
                    array.append("H")
                else:
                    print "T"
                    array.append("T")
            print array
            return array
Example #3
0
def GetWalletInfoCaCPanel():
    FireFoxOptions = webdriver.FirefoxOptions()
    FireFoxOptions.set_headless()
    driver = webdriver.Firefox(
        executable_path='./modules/geckodriver-v0.29.0-win64/geckodriver',
        firefox_options=FireFoxOptions)
    driver.get("https://panel.cloudatcost.com/login.php")
    UserElem = driver.find_element_by_name("username")
    UserElem.send_keys(config['credentials']['user'])
    PasswordElem = driver.find_element_by_name("password")
    PasswordElem.send_keys(config['credentials']['passwd'])
    SubmitButton = driver.find_element_by_xpath(
        '//*[@id="login-form"]/input[4]')
    SubmitButton.click()
    driver.get("https://panel.cloudatcost.com/wallet")
    WalletInfo = (
        driver.find_element_by_xpath('//*[@id="dataTable"]/tbody')).text
    driver.close()
    array = []
    linesplit = WalletInfo.splitlines()
    for line in linesplit:
        templine = line.split(" ")
        tempObj = CaCClass.WalletLine(templine[0], templine[1], templine[2],
                                      templine[4], templine[5], templine[7])
        array.append(tempObj)
    return array
def map(array, size, z):
    for i in range(size):
        temp = []
        for j in range(size):
            temp.append(int(np.round((100*(z[i][j]+1))//2)))
        array.append(temp)
    return array
Example #5
0
 def parsePose(array, bone, parent, pose, pid, counter):
     position = []
     rotation = []
     index = counter.ctr;
     counter.ctr += 1
     
     if parent is not None:
         mat = parent.matrix.inverted() @ bone.matrix
         rot = mat.to_quaternion()
         position.append(mat[0][3])
         position.append(mat[1][3])
         position.append(mat[2][3])
         rotation.append(rot.x)
         rotation.append(rot.y)
         rotation.append(rot.z)
         rotation.append(rot.w)
         
     else:
         mat = bone.matrix
         rot = mat.to_quaternion()
         position.append(mat[0][3])
         position.append(mat[1][3])
         position.append(mat[2][3])
         rotation.append(rot.x)
         rotation.append(rot.y)
         rotation.append(rot.z)
         rotation.append(rot.w)
         
     array.extend(rotation)
     array.extend(position)
     array.append(pid)
     
     for c in bone.children:
         parsePose(array, c, bone, pose, index, counter)
Example #6
0
def extract(filename):
    file = open(filename,"r")
    xml_file = file.read()
    file.close()
    xml_page = soup(xml_file,"xml")
    array = []
    needed = ['ID','Document','Revision','Submitted','Created','Issued To','Status','Due Date','REASON','Date Approved','COMMENT BY AUTHORITY','Notice of prohibition','Notice of improvement','Non conformance report (NCR)','Observation','Other','No of notices','No notice issued','Date']
    # print(xml_page)
    body = xml_page.find('authority_visit')
    for node in body.findChildren(recursive=False):
        data={}
        if (node.name == 'projectcode'):
            continue
        result = (node.find('label',recursive=False)!=None)
        if(result and (node.find('label',recursive=False)).string in needed):
            data['label']=(node.find('label',recursive=False)).string
            data['value']=(node.find('value',recursive=False)).string
            array.append(data)
        if(node.name == 'attachments_list'):
            attachments = node.find_all('filename')
            for index, a in enumerate(attachments):
                data['label']='Document File Name'
                data['value']=add_attachment_extension((a.find('value',recursive=False)).string,index)
                array.append(data)
    return array
Example #7
0
def insert(arr, temp):
    if len(arr) == 0 or arr[len(arr) - 1] <= temp:
        arr.append(temp)
        return
    val = arr.pop()
    insert(arr, temp)
    arr.append(val)
Example #8
0
def _pad_array(array, boundary):
  """Adds padding to the array so the array size aligns to a next boundary."""
  size = array.buffer_info()[1]
  pad_bytes = boundary - (size % boundary)
  if pad_bytes == boundary:
    return
  for _ in xrange(pad_bytes):
    array.append(0)
def _pad_array(array, boundary):
    """Adds padding to the array so the array size aligns to a next boundary."""
    size = array.buffer_info()[1]
    pad_bytes = boundary - (size % boundary)
    if pad_bytes == boundary:
        return
    for _ in xrange(pad_bytes):
        array.append(0)
Example #10
0
 def getInverseBindTransform(array, bone):
     mat = bone.matrix.inverted().transposed()
     for i in range(len(mat)):
         for j in range(len(mat[i])):
             array.append(mat[i][j])
     
     for c in bone.children:
         getInverseBindTransform(array, c)
Example #11
0
 def getFortunate(self, a, b, c):
     array = []
     for aa in a:
         for bb in b:
             for cc in c:
                 sum = (aa + bb + cc)
                 if str(sum).count("8") +  str(sum).count("5") == len(str(sum)) :
                     array.append(sum)
     return len(set(array))
Example #12
0
 def getFortunate(self, a, b, c):
     array = []
     for aa in a:
         for bb in b:
             for cc in c:
                 sum = (aa + bb + cc)
                 if str(sum).count("8") + str(sum).count("5") == len(
                         str(sum)):
                     array.append(sum)
     return len(set(array))
Example #13
0
    def countGood(self, superior, workType):
        c = 0
        array = []
        for i in xrange(len(superior)):
            if superior[i] == -1:
                array.append((workType[i]))
            elif workType[superior[i]] == workType[i]:
                c += 1

        return len(workType) - c
Example #14
0
    def countGood(self, superior, workType):
        c = 0
        array = []
        for i in xrange(len(superior)):
            if superior[i] == -1:
                array.append((workType[i]))
            elif workType[superior[i]] == workType[i]:
                c += 1

        return len(workType) - c
Example #15
0
 def _load_word(self, array, reg, word):
     """Load an immediate value into a register w/o using load_word(); instead
    append the instruction objects to an array.
    Used when synthesizing the prologue/epilogue."""
     array.append(ppc.addi(reg, 0, word & 0xFFFF, ignore_active=True))
     if (word & 0xFFFF) != word:
         array.append(
             ppc.addis(reg,
                       reg, ((word + 32768) >> 16) & 0xFFFF,
                       ignore_active=True))
     return
Example #16
0
def setIndex(array, index, value, padValue):
    # pads the array so indices beyond the length can be set
    # need to add one because the length of an array
    # is one more than the index of the last element
    index += 1
    arrayLength = len(array)
    if index > arrayLength:
        for _ in range(0, index - arrayLength):
            array.append(padValue)
    # revert back to real index
    array[index - 1] = value
Example #17
0
def MyFloatRange(start, stop, step):
    if (step > 0. and stop < start) or (step < 0. and start < stop):
        raise Exception
    array = []
    i = 0.
    while (1):
        cur = start + i * step
        if cur <= stop and stop > start: array.append(cur)
        elif cur >= stop and stop < start: array.append(cur)
        else: break
        i = i + 1.
    return array
Example #18
0
File: GA1.py Project: GarethG/AAI
def pop_array(rows, cols):

	matrix = []

	for row in range(rows):
		array = []
		for col in range(cols):
			array.append(random.randint(0,1))	
		matrix.append(array)
		
		
	return matrix
Example #19
0
 def loadChunks(self):
     """
     Load all chunks from the save and store them in self.chunks
     """
     chunks = []
     while True:
         curoffs = self.dp.offset
         id = self.dp.read_uint32()
         if id == 0:
             break
         name = "%c%c%c%c" % (id >> 24 & 0xFF, id >> 16 & 0xFF,
                              id >> 8 & 0xFF, id & 0xFF)
         if self.verbosity > 2: print "loading chunk: %s" % name
         m = self.dp.read_byte()
         if m == saveload_chunk_types["CH_ARRAY"]:  # array
             array = []
             index = 0
             while True:
                 leng = self.dp.read_OTTDSimpleGamma()
                 curoffs = self.dp.offset
                 end_offset = curoffs + leng - 1  # todo: unsure if this is a correct approach ( the -1)
                 if leng == 0:
                     end_offset = self.dp.offset
                     break
                 array.append(
                     (index, self.dp.data[self.dp.offset:end_offset]))
                 index += 1
                 self.dp.offset = end_offset
             thischunk = ("CH_ARRAY", array)
         elif m == saveload_chunk_types["CH_SPARSE_ARRAY"]:  # sparse array
             array = {}
             while True:
                 curoffs = self.dp.offset
                 leng = self.dp.read_OTTDSimpleGamma()
                 if leng == 0:
                     end_offset = self.dp.offset
                     break
                 index = self.dp.read_OTTDSimpleGamma()
                 array[index] = self.dp.data[self.dp.offset:(curoffs +
                                                             leng)]
                 self.dp.offset = curoffs + leng
             thischunk = ("CH_SPARSE_ARRAY", array)
         elif (m & 0xF) == saveload_chunk_types["CH_RIFF"]:  # RIFF
             leng = ((self.dp.read_byte() << 16) |
                     ((m >> 4) << 24)) + self.dp.read_uint16()
             end_offset = self.dp.offset + leng
             thischunk = ("CH_RIFF",
                          self.dp.data[self.dp.offset:end_offset])
             self.dp.offset = end_offset
         else:
             raise LoadException("unknown chunk type")
         chunks.append((name, thischunk))
     self.chunks = chunks
def image_array(folder_path):
    array = list()
    img_counter = 1
    path, dirs, files = next(os.walk(folder_path))
    file_count = len(files)
    for image_path in glob.glob(folder_path + '*.png'):
        im = cv2.imread(image_path)
        gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
        array.append(gray)
        sys.stdout.write("\r loading %i " % img_counter +
                         "of %i " % file_count)
        sys.stdout.flush()
        img_counter += 1
    return np.asarray(array, dtype=np.float32)
def MyFloatRange(start, stop, step):
    if (step > 0.0 and stop < start) or (step < 0.0 and start < stop):
        raise Exception
    array = []
    i = 0.0
    while 1:
        cur = start + i * step
        if cur <= stop and stop > start:
            array.append(cur)
        elif cur >= stop and stop < start:
            array.append(cur)
        else:
            break
        i = i + 1.0
    return array
Example #22
0
    def determineSolvers(self, attendance, problemTopics):
        array = []

        for student in attendance:
            ans = ""
            for problem in problemTopics:
                for i, p in enumerate(problem):
                    if p == "X" and student[i] != "X":
                        ans += "-"
                        break
                else:
                    ans += "X"
            array.append(ans)

        return array
Example #23
0
    def isPossible(self, values):
        array = []
        for i in xrange(len(values)):
            for j in xrange(i + 1, len(values)):
                if values[j] % values[i] == 0:
                    array.append(values[j] // values[i])
                    break

        array.append(1)
        array.sort()

        for i in xrange(len(values)):
            if array[i] < i + 1:
                return 	"Impossible"
        return 	"Possible"
Example #24
0
 def short(self, n, h='h', exp=12):
     array = []
     offset = self.input_file.tell()
     for id in range(n):
         array.append(
             struct.unpack(self.endian + h, self.input_file.read(2))[0] *
             2**-exp)
     # array.append(self.H(1)[0]*2**-exp)
     if self.debug:
         print('short', array)
     if self.log:
         if self.logfile is not None and self.logskip is not True:
             self.logfile.write('offset ' + str(offset) + '	' + str(array) +
                                '\n')
     return array
Example #25
0
    def determineSolvers(self, attendance, problemTopics):
        array = []

        for student in attendance:
            ans = ""
            for problem in problemTopics:
                for i, p in enumerate(problem):
                    if p == "X" and student[i] != "X":
                        ans += "-"
                        break
                else:
                    ans += "X"
            array.append(ans)

        return array
Example #26
0
 def loadChunks(self):
     """
     Load all chunks from the save and store them in self.chunks
     """
     chunks = []
     while True:
         curoffs = self.dp.offset
         id = self.dp.read_uint32()
         if id == 0:
             break
         name = "%c%c%c%c" % (id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF)
         if self.verbosity > 2: print "loading chunk: %s"%name
         m = self.dp.read_byte()
         if m == saveload_chunk_types["CH_ARRAY"]: # array
             array = []
             index = 0
             while True:
                 leng    = self.dp.read_OTTDSimpleGamma()
                 curoffs = self.dp.offset
                 end_offset = curoffs + leng - 1  # todo: unsure if this is a correct approach ( the -1)
                 if leng == 0:
                     end_offset = self.dp.offset
                     break
                 array.append((index, self.dp.data[self.dp.offset:end_offset]))
                 index += 1
                 self.dp.offset = end_offset
             thischunk = ("CH_ARRAY", array)
         elif m == saveload_chunk_types["CH_SPARSE_ARRAY"]: # sparse array
             array = {}
             while True:
                 curoffs = self.dp.offset
                 leng    = self.dp.read_OTTDSimpleGamma()
                 if leng == 0:
                     end_offset = self.dp.offset
                     break
                 index = self.dp.read_OTTDSimpleGamma()
                 array[index] = self.dp.data[self.dp.offset:(curoffs+leng)]
                 self.dp.offset = curoffs + leng
             thischunk = ("CH_SPARSE_ARRAY", array)
         elif (m & 0xF) == saveload_chunk_types["CH_RIFF"]: # RIFF
             leng = ((self.dp.read_byte() << 16) | ((m >> 4) << 24)) + self.dp.read_uint16()
             end_offset = self.dp.offset + leng
             thischunk = ("CH_RIFF", self.dp.data[self.dp.offset:end_offset])
             self.dp.offset = end_offset
         else:
             raise LoadException("unknown chunk type")
         chunks.append((name, thischunk))
     self.chunks = chunks
Example #27
0
    def create_distances(self):
        with open('cities.txt') as f:
            array = []
            for line in f:
                array.append([int(x) for x in line.split()])
        if len(array) < self.NUM_OF_CITIES:
            self.generate_distances()
        # put random distances into HALF of the matrix for cities
        # to generate no differing distances between any two cities
        for x in range(0, len(array[0])):
            for y in range(0, len(array[0])):
                self.distance_matrix[(x, y)] = array[x][y]

        for x in range(0, len(array[0])):
            for y in range(0, len(array[0])):
                print(" ", self.distance_matrix[(x, y)])
Example #28
0
 def half(self, n, h='h'):
     array = []
     offset = self.input_file.tell()
     for id in range(n):
         # array.append(converthalf2float(struct.unpack(self.endian+'H',self.inputFile.read(2))[0]))
         array.append(
             converthalf2float(
                 struct.unpack(self.endian + h,
                               self.input_file.read(2))[0]))
     if self.debug:
         print('half', array)
     if self.log:
         if self.logfile is not None and self.logskip is not True:
             self.logfile.write('offset ' + str(offset) + '	' + str(array) +
                                '\n')
     return array
Example #29
0
 def i12(self, n):
     array = []
     offset = self.input_file.tell()
     for id in range(n):
         if self.endian == '>':
             var = '\x00' + self.input_file.read(3)
         if self.endian == '<':
             var = self.input_file.read(3) + '\x00'
         array.append(struct.unpack(self.endian + 'i', var)[0])
     if self.debug:
         print(array)
     if self.log:
         if self.logfile is not None and self.logskip is not True:
             self.logfile.write('offset ' + str(offset) + '	' + str(array) +
                                '\n')
     return array
Example #30
0
def append(obj, val, axis = None):
    name = None
    units = None
    if isinstance(obj, SimpleData) :
        name = obj.name
        units = obj.units
        obj = obj.storage
    return new(array.append(obj, val, axis), name, units)
Example #31
0
def append(obj, val, axis=None):
    name = None
    units = None
    if isinstance(obj, SimpleData):
        name = obj.name
        units = obj.units
        obj = obj.storage
    return new(array.append(obj, val, axis), name, units)
Example #32
0
    def _load_word(self, array, reg, word):
        """Load an immediate value into a register w/o using load_word(); instead
       append the instruction objects to an array.
       Used when synthesizing the prologue/epilogue."""
        array.append(ppc.addi(reg, 0, word & 0xFFFF, ignore_active=True))

        uw = (word >> 16) & 0xFFFF
        msb = word & 0x8000

        if msb != 0:
            # lower 16-bit MSB is set, upper 16 bits are 1, adjust uw
            # If all upper 16 bits are 1, that is the value -1, so add 1 back in.
            uw = (uw + 1) & 0xFFFF

        if uw != 0:
            array.append(ppc.addis(reg, reg, uw, ignore_active=True))
        return
def SmallLargeWord(str1):
    w = ""
    words = []
    str1 += " "
    for i in range(len(str1)):
        if (str1[i] != ' '):
            w += str1[i]
        else:
            words.append(w)
            w = " "
    sm = lg = words[0]
    for j in range(len(words)):
        if (len(sm) > len(words[j])):
            sm = words[j]
        elif (len(lg) < len(words[j])):
            lg = words[j]
    return sm, lg
Example #34
0
def deserialize(obj, content):
    if content == "":
        return None
    jsonStr = ""
    if (isinstance(content, bytearray)):
        jsonStr = content.decode("utf-8")
    else:
        jsonStr = content
    dics = json.loads(jsonStr)
    if (isinstance(dics, list)):
        array = []
        for item in dics:
            netObj = copy.copy(obj)
            d = _deserializeObj(netObj, item)
            array.append(d)
        return array
    return _deserializeObj(obj, dics)
Example #35
0
    def _load_word(self, array, reg, word):
        """Load an immediate value into a register w/o using load_word(); instead
       append the instruction objects to an array.
       Used when synthesizing the prologue/epilogue."""
        array.append(ppc.addi(reg, 0, word & 0xFFFF, ignore_active=True))

        uw = (word >> 16) & 0xFFFF
        msb = word & 0x8000

        if msb != 0:
            # lower 16-bit MSB is set, upper 16 bits are 1, adjust uw
            # If all upper 16 bits are 1, that is the value -1, so add 1 back in.
            uw = (uw + 1) & 0xFFFF

        if uw != 0:
            array.append(ppc.addis(reg, reg, uw, ignore_active=True))
        return
Example #36
0
File: SVM_HMM.py Project: astewa/MF
def get_array_classify(target):
        array = []
        previous =""
        window = []
        count =0
        for line in open(target, "r"):
                label = line.strip('\n').split(' ')
                if previous=="":
                        previous = str(label[1])
                if previous == str(label[1]):
                        window.append(line)
                elif previous != str(label[1]):
                        count +=1
                        array.append(window)
                        previous = str(label[1])
                        window = []
                        window.append(line)
        return array
Example #37
0
class CleanMFT:
    def __init__(self, import_file = sys.argv(1), id = "port_number", reg_file=True, output_filename = os.getcwd() + "result.csv",
                 suspicious=False, start_date='', end_date='', start_time='', end_time='', filter_index = ''):
        if os.path.isfile(import_file):
            self.__file = import_file   # stores the FQDN of the MFT CSV file
        self.__id = id                  # this value will be used as the id at the end of the URL.
        self.__reg_file = reg_file      # accepts a txt file
        self.__suspicious = suspicious
        self.__start_date = start_date  # accepts a date to filter
        self.__end_date = end_date
        self.__start_time = start_time  # accepts a time to filter
        self.__end_time = end_time
        self.__output_file = output_filename
        self.__filter_index = filter_index

    """ This is the main method of the program. """
    def run(self):
        sdate, edate, stime, etime = self.__start_date, self.__end_date, self.__start_time, self.__end_time
        output_file = self.__output_file
        suspicious = self.__suspicious
        mft_csv = self.__file
        reg_file = self.__reg_file
        id = self.__id

        sindex, eindex = [x.strip() for x in self.__filter_index.split(',')]
        if sindex.contains(',') or eindex.contains(','):
            sindex.replace(',', '')
            eindex.replace(',', '')
        if not sindex.isdigit and eindex.isdigit:
            raise ValueError("ERROR: The index value you entered to filter the table by was improperly formatted. \n"
                             "Please try to run the program again with different values.")
        df = pd.DataFrame()
        df = df.from_csv(mft_csv, sep='|', parse_dates=[[0, 1]])
        # df = df.from_csv("MftDump_2015-10-29_01-27-48.csv", sep='|')
        # df_attack_date = df[df.index == '2013-12-03'] # Creates an extra df for the sake of reference
        df = df.reset_index(level=0, inplace=True)
            if sindex and eindex:
                df = df[sindex : eindex]
        if reg_file:
            df = self.filter_by_filename(df)
        if suspicious:
            df = self.filter_suspicious(df)
        if sdate or edate or stime or etime:
            df = self.filter_by_dates(df)
        filtered_df = df.to_csv(index=True) # To make this easier, we'll send the CSV over socket as an Array

        # create an array of lines from the DataFrame CSV
        for line in filtered_df:
            arr = array.append(line)
    
        # server address we're sending get request to.
        address = 'http://localhost/' + id
        
        port_number = get(address)
        # send the array via the socket
        send_from(arr, (address + + ":" + port_number('task')))
Example #38
0
def create_data_table(csv_filename, types, header_lines):
    
    # if pandas is available, use it!
    if have_pandas:
        skip = range(1, header_lines)
        d = pd.read_csv(csv_filename, skiprows=skip, dtype=types, sep=',', keep_default_na=False, na_values=['']).to_dict()
        d = OrderedDict(dict((k, list(d[k].values())) for k in d)) # convert to dict of lists (as used by the python snippet)
        return d
    else:
        table = create_empty_table(csv_filename, types, header_lines)
    
        csv_file = open(csv_filename, 'rb')
    
        csv_reader = csv.reader(csv_file, delimiter=',', quotechar='"')
    
        current = -header_lines
        for row in csv_reader:
            if current >= 0:
                index = 0
                for item in types:
                    array = table[item]
                    type = types[item]
                    value = row[index]
    
                    if value == "":
                        value = None
                    elif type == FloatType:
                        value = float(value)
                    elif type == IntType:
                        value = int(value)
    
                    # Instead of setting array[current]=value we append
                    # to the array since the array was initialized as an
                    # empty list in create_empty_table
                    array.append(value)
    
                    index += 1
            current += 1

    return table
def create_data_table(csv_filename, types, header_lines):
    
    # if pandas is available, use it!
    if have_pandas:
        skip = range(1, header_lines)
        d = pd.read_csv(csv_filename, skiprows=skip).to_dict()
        d = {k: d[k].values() for k in d} # convert to dict of lists (as used by the python snippet)
        return d
    else:
        table = create_empty_table(csv_filename, types, header_lines)
    
        csv_file = open(csv_filename, 'rb')
    
        csv_reader = csv.reader(csv_file, delimiter=',', quotechar='"')
    
        current = -header_lines
        for row in csv_reader:
            if current >= 0:
                index = 0
                for item in types:
                    array = table[item]
                    type = types[item]
                    value = row[index]
    
                    if value == "":
                        value = None
                    elif type == FloatType:
                        value = float(value)
                    elif type == IntType:
                        value = int(value)
    
                    # Instead of setting array[current]=value we append
                    # to the array since the array was initialized as an
                    # empty list in create_empty_table
                    array.append(value)
    
                    index += 1
            current += 1

    return table
Example #40
0
def img_to_np_array(path: str) -> np.ndarray:
    array = []
    pil_img = Image.open(path)
    width: int = pil_img.size[0]
    height: int = pil_img.size[1]
    pix = pil_img.load()
    for i in range(width):
        for j in range(height):

            try:
                r = pix[i, j][0]
                g = pix[i, j][1]
                b = pix[i, j][2]

                pixel_value: int = int((r + g + b) / 3)
            except:
                pixel_value: int = pix[i, j]

            array.append(pixel_value)

    array = np.array(array)
    return array
Example #41
0
File: SVM_HMM.py Project: astewa/MF
def get_array_plot(target):
        array = []
	array2 =[]
        previous =""
        window = []
	window2 = []
        count =0
        for line in open(target, "r"):
                label = line.strip('\n').split(' ')
                if previous=="":
                        previous = str(label[1])
                if previous == str(label[1]):
                        window.append(int(label[3].split(':')[0]))
                        window2.append(int(label[4].split(':')[1]))
                elif previous != str(label[1]):
                        count +=1
                        array.append(window)
                        array2.append(window2)
                        previous = str(label[1])
                        window = []
			window2 = []
                        window.append(int(label[3].split(':')[0]))
                        window2.append(int(label[4].split(':')[1]))
        return array,array2
Example #42
0
def is_prime():
    import array as arr
    number = request.form.get('Num')
    #  n = int(number)
    try:
        n = int(number)
    except TypeError:
        n = 0
    arr = []
    if n == 0:
        return 'Invalid'
    if n == 2:
        return 'Even-Prime'

    if n >= 3:
        for i in range(3, n):
            if n % i == 0:
                arr.append('False')

    size = len(arr)
    if size != 0:
        return 'False'
    else:
        return 'True'
Example #43
0
def long_repeat(line):
    index = 0
    active = False
    meow = ''
    array = []
    le = 0
    for x in range(0, len(line) - 1):
        if not active:
            meow += line[index]
        if line[index] == line[index + 1]:
            active = True
            meow += line[index + 1]
        else:
            active = False
            array.append(meow)
            meow = ''
        if x not in array:
            array.append(meow)
        index += 1

    if len(array) != 0:
        le = len(max(array, key=len))

    return le
Example #44
0
    def addMidiNote(self, array, time, note, velocity=127):
        if(velocity == 0):
            note = 0

        millis = (int) (time*1000)

        while millis >= 256:
            array[-1] = 255
            array.append(array[-2])
            array.append(1)
            millis -= 255

        if millis > 1:
            array[-1] = millis
        else:
            array.pop()
            array.pop()

        array.append(note)
        array.append(100)
Example #45
0
File: SVM_HMM.py Project: astewa/MF
def load_output(outfile):
	array  = []
	for line in open(outfile, 'r'):
		array.append(line.strip('\n'))
	return array
Example #46
0
r_array=[]
g_array = []
b_array = []
bl_array = []

#different colors: (in rgba -- remove last number in set to convert to rgb)
#red = (255,0,0,0) eg. in rgb -- (255,0,0)
#green = (0,255,0,0)
#blue = (0,0,255,0)
#black = (0,0,0,0)
#white = (255,255,255,0)


while h != height:
        while w != -1:
                array.append(img.getpixel((w, h))) #get rgba black or white of each pixel and write to full array
                r,g,b,a = img.getpixel((w, h)) #get rgba of each pixel
                #check if red, green, or blue is greatest in rgb values --- check if black or white also --> then append array differently for each switch case
                if r > g and r > b :
                    r_array.append(0)
                    g_array.append(255)
                    b_array.append(255)
                    bl_array.append(255)
                elif g > r and g > b :
                    g_array.append(0)
                    r_array.append(255)
                    b_array.append(255)
                    bl_array.append(255)                    
                elif b > r and b > g :
                    b_array.append(0)
                    g_array.append(255)
Example #47
0
def sort(frame_event_set, topics_file, event_dir, stem, output_dir):


    # create directory for unknowns
    utils.ensure_dir('%s/%d/' % (output_dir, UNKNOWN_ID))

    with open(topics_file, "r") as ins:
        array = []
        for line in ins:
            array.append(line)

    topics = set()
    topics_dict = {}

    # grab all the topics and key by frame number
    for raw_line in array:
        line = raw_line.split(',')
        topic_line = line[1:]
        key = int(line[0])
        topics_dict[key] = [int(t) for t in topic_line]

        # add in all unique topics
        for lst in topic_line:
            new_topic = [x for x in lst if x not in topics] # filter out previously seen values
            topics.update(new_topic)                        # add the new values to the set


    # create topic directory per each topic
    for t in topics:
        utils.ensure_dir('%s/%s/' % (output_dir, t))
        utils.ensure_dir('%s/%s/mov' % (output_dir, t))

    last_line = []
    from collections import Counter

    # sort images into topic directories
    for fes in frame_event_set:
        for node in fes:
            frame_num = int(node.get('FrameNumber'))
            print node.tag
            print node.attrib

            if topics_dict.has_key(frame_num):
                topics_list = topics_dict[frame_num]
            else:
                topics_list = None
            j = 0
            for event in node._children:
                print event.attrib
                event_num = int(event.get('ObjectID'))
                event_file = '%s-evt%04d_%06d' % (stem, event_num, frame_num)
                event_file_full = '%s/%s.pnm' % (event_dir, event_file)

                if topics_list:
                    topics = topics_list[j:j+6]
                    c = Counter(topics)
                    winner, count = c.most_common()[0]
                    j += 1
                else:
                    winner = UNKNOWN_ID

                print 'TOPIC Majority Vote %d'  % winner
                command = '/usr/local/bin/convert %s %s/%d/%s.png' % (event_file_full, output_dir, winner, event_file)
                utils.run_command(command)

    # for each event within the topic, create montage clip
    ''' for i in range(0, num_topics):
Example #48
0
#---Main---------------------------------------------------------------------------------------#
print "\033[36m[*]\033[0m wordlists v"+version

if debug == True:
    print info+"Debug mode: On"
    print "-----------------------------------------------------"
    
for file in filename[1:]:
    try:
        file_open = open(file,"r")
        print action+"Loading file: " + file
        totalFiles = totalFiles + 1
        if files != "": files = files + ", " + file
        else: files = file
        for word in file_open.readlines():
            array.append(word.strip()) # Removes EOL
            file_open.close()
    except IOError, err:
        print error+"Cant find file: " + file

try:
    while 1==1:
        print """-----------------------------------------------------\nMain Menu:\n-----------------------------------------------------
    1.) Remove duplicates form a wordlist
    2.) Remove duplicates + sort alphabetical order [0-Z]
    3.) Remove duplicates + Higher the dups, higher the list
    4.) Remove duplicates + Higher the dups, higher the list + sorts the rest alphabetical order [0-Z]\n-----------------------------------------------------
    5.) Generate Password
    6.) Generate wordlists
   *7.) Generate wordlists ('PaulDotCom' method)\n-----------------------------------------------------
   *8.) Convert wordlist rainbow/hash tables (WPA)