Python string.ascii_lowercase() Examples

The following are 30 code examples for showing how to use string.ascii_lowercase(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: pyscf   Author: pyscf   File: pyscf_helpers.py    License: Apache License 2.0 6 votes vote down vote up
def v2a_sym(a, labels, shapes, ixs):
    """
    Decompresses the antisymmetric array.
    Args:
        a (numpy.ndarray): array to decompress;
        labels (iterable): array's axes' labels;
        shapes (iterable): arrays' shapes;
        ixs (iterable): indexes of lower-triangle parts;

    Returns:
        Decompressed amplitude tensors.
    """
    result = []
    pos = 0
    for lbls, shape, ix in zip(labels, shapes, ixs):
        ampl = numpy.zeros(shape, dtype=a.dtype)
        end = pos + len(ix[0])
        ampl[ix] = a[pos:end]
        pos = end
        for l in set(lbls):
            letters = iter(string.ascii_lowercase)
            str_spec = ''.join(next(letters) if i == l else '.' for i in lbls)
            ampl = p(str_spec, ampl)
        result.append(ampl)
    return result 
Example 2
Project: thingsboard-gateway   Author: thingsboard   File: custom_serial_connector.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        super().__init__()    # Initialize parents classes
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}    # Dictionary, will save information about count received and sent messages.
        self.__config = config    # Save configuration from the configuration file.
        self.__gateway = gateway    # Save gateway object, we will use some gateway methods for adding devices and saving data from them.
        self.setName(self.__config.get("name",
                                       "Custom %s connector " % self.get_name() + ''.join(choice(ascii_lowercase) for _ in range(5))))    # get from the configuration or create name for logs.
        log.info("Starting Custom %s connector", self.get_name())    # Send message to logger
        self.daemon = True    # Set self thread as daemon
        self.stopped = True    # Service variable for check state
        self.__connected = False    # Service variable for check connection to device
        self.__devices = {}    # Dictionary with devices, will contain devices configurations, converters for devices and serial port objects
        self.__load_converters(connector_type)    # Call function to load converters and save it into devices dictionary
        self.__connect_to_devices()    # Call function for connect to devices
        log.info('Custom connector %s initialization success.', self.get_name())    # Message to logger
        log.info("Devices in configuration file found: %s ", '\n'.join(device for device in self.__devices))    # Message to logger 
Example 3
Project: thingsboard-gateway   Author: thingsboard   File: test_bytes_can_uplink_converter.py    License: Apache License 2.0 6 votes vote down vote up
def _test_string(self, encoding="ascii"):
        str_length = randint(1, 8)
        str_value = ''.join(choice(ascii_lowercase) for _ in range(str_length))

        configs = [{
            "key": "stringVar",
            "is_ts": True,
            "type": "string",
            "start": 0,
            "length": str_length,
            "encoding": encoding
        }]

        can_data = str_value.encode(encoding)
        tb_data = self.converter.convert(configs, can_data)
        self.assertEqual(tb_data["telemetry"]["stringVar"], str_value) 
Example 4
Project: thingsboard-gateway   Author: thingsboard   File: test_can_connector.py    License: Apache License 2.0 6 votes vote down vote up
def test_string_attribute_and_custom_device_type(self):
        self._create_connector("ts_and_attr.json")
        device_name = self.config["devices"][0]["name"]
        config = self.config["devices"][0]["attributes"][0]
        value_matches = re.search(self.connector.VALUE_REGEX, config["value"])

        string_value = ''.join(choice(ascii_lowercase) for _ in range(int(value_matches.group(2))))
        can_data = list(config["command"]["value"].to_bytes(config["command"]["length"],
                                                            config["command"]["byteorder"]))
        can_data.extend(string_value.encode(value_matches.group(5)))

        message_count = 5
        for _ in range(message_count):
            self.bus.send(Message(arbitration_id=config["nodeId"],
                                  is_fd=config["isFd"],
                                  data=can_data))

        sleep(1)  # Wait while connector process CAN message

        self.assertEqual(self.gateway.send_to_storage.call_count, message_count)
        self.gateway.send_to_storage.assert_called_with(self.connector.get_name(),
                                                        {"deviceName": device_name,
                                                         "deviceType": self.config["devices"][0]["type"],
                                                         "attributes": [{"serialNumber": string_value}],
                                                         "telemetry": []}) 
Example 5
Project: thingsboard-gateway   Author: thingsboard   File: custom_serial_connector.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        super().__init__()    # Initialize parents classes
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}    # Dictionary, will save information about count received and sent messages.
        self.__config = config    # Save configuration from the configuration file.
        self.__gateway = gateway    # Save gateway object, we will use some gateway methods for adding devices and saving data from them.
        self.setName(self.__config.get("name",
                                       "Custom %s connector " % self.get_name() + ''.join(choice(ascii_lowercase) for _ in range(5))))    # get from the configuration or create name for logs.
        log.info("Starting Custom %s connector", self.get_name())    # Send message to logger
        self.daemon = True    # Set self thread as daemon
        self.stopped = True    # Service variable for check state
        self.__connected = False    # Service variable for check connection to device
        self.__devices = {}    # Dictionary with devices, will contain devices configurations, converters for devices and serial port objects
        self.__load_converters(connector_type)    # Call function to load converters and save it into devices dictionary
        self.__connect_to_devices()    # Call function for connect to devices
        log.info('Custom connector %s initialization success.', self.get_name())    # Message to logger
        log.info("Devices in configuration file found: %s ", '\n'.join(device for device in self.__devices))    # Message to logger 
Example 6
Project: thingsboard-gateway   Author: thingsboard   File: rest_connector.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        super().__init__()
        self.__log = log
        self._default_converters = {
            "uplink": "JsonRESTUplinkConverter",
            "downlink": "JsonRESTDownlinkConverter"
        }
        self.__config = config
        self._connector_type = connector_type
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}
        self.__gateway = gateway
        self.__USER_DATA = {}
        self.setName(config.get("name", 'REST Connector ' + ''.join(choice(ascii_lowercase) for _ in range(5))))

        self._connected = False
        self.__stopped = False
        self.daemon = True
        self._app = Flask(self.get_name())
        self._api = Api(self._app)
        self.__rpc_requests = []
        self.__attribute_updates = []
        self.__fill_requests_from_TB()
        self.endpoints = self.load_endpoints()
        self.load_handlers() 
Example 7
Project: thingsboard-gateway   Author: thingsboard   File: modbus_connector.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}
        super().__init__()
        self.__gateway = gateway
        self._connector_type = connector_type
        self.__master = None
        self.__config = config.get("server")
        self.__byte_order = self.__config.get("byteOrder")
        self.__configure_master()
        self.__devices = {}
        self.setName(self.__config.get("name",
                                       'Modbus Default ' + ''.join(choice(ascii_lowercase) for _ in range(5))))
        self.__load_converters()
        self.__connected = False
        self.__stopped = False
        self.daemon = True 
Example 8
Project: thingsboard-gateway   Author: thingsboard   File: bacnet_connector.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        self.__connector_type = connector_type
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}
        super().__init__()
        self.__config = config
        self.setName(config.get('name', 'BACnet ' + ''.join(choice(ascii_lowercase) for _ in range(5))))
        self.__devices = []
        self.__device_indexes = {}
        self.__devices_address_name = {}
        self.__gateway = gateway
        self._application = TBBACnetApplication(self, self.__config)
        self.__bacnet_core_thread = Thread(target=run, name="BACnet core thread")
        self.__bacnet_core_thread.start()
        self.__stopped = False
        self.__config_devices = self.__config["devices"]
        self.default_converters = {"uplink_converter": TBUtility.check_and_import(self.__connector_type, "BACnetUplinkConverter"),
                                     "downlink_converter": TBUtility.check_and_import(self.__connector_type, "BACnetDownlinkConverter")}
        self.__request_functions = {"writeProperty": self._application.do_write_property,
                                    "readProperty": self._application.do_read_property}
        self.__available_object_resources = {}
        self.rpc_requests_in_progress = {}
        self.__connected = False
        self.daemon = True 
Example 9
Project: thingsboard-gateway   Author: thingsboard   File: ble_connector.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, gateway, config, connector_type):
        super().__init__()
        self.__connector_type = connector_type
        self.__default_services = list(range(0x1800, 0x183A))
        self.statistics = {'MessagesReceived': 0,
                           'MessagesSent': 0}
        self.__gateway = gateway
        self.__config = config
        self.setName(self.__config.get("name",
                                       'BLE Connector ' + ''.join(choice(ascii_lowercase) for _ in range(5))))

        self._connected = False
        self.__stopped = False
        self.__previous_scan_time = time.time() - 10000
        self.__previous_read_time = time.time() - 10000
        self.__check_interval_seconds = self.__config['checkIntervalSeconds'] if self.__config.get(
            'checkIntervalSeconds') is not None else 10
        self.__rescan_time = self.__config['rescanIntervalSeconds'] if self.__config.get(
            'rescanIntervalSeconds') is not None else 10
        self.__scanner = Scanner().withDelegate(ScanDelegate(self))
        self.__devices_around = {}
        self.__available_converters = []
        self.__notify_delegators = {}
        self.__fill_interest_devices()
        self.daemon = True 
Example 10
Project: instavpn   Author: sockeye44   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def setup_passwords():
    try:
        char_set = string.ascii_lowercase + string.ascii_uppercase + string.digits
        f = open('/etc/ppp/chap-secrets', 'w')
        pw1 = gen_random_text(12)
        pw2 = gen_random_text(12)
        f.write("username1 l2tpd {} *\n".format(pw1))
        f.write("username2 l2tpd {} *".format(pw2))
        f.close()
        f = open('/etc/ipsec.secrets', 'w')
        f.write('1.2.3.4 %any: PSK "{}"'.format(gen_random_text(16)))
        f.close()
    except:
        logger.exception("Exception creating passwords:")
        return False

    return True 
Example 11
Project: coursys   Author: sfu-fas   File: demodata_importer.py    License: GNU General Public License v3.0 6 votes vote down vote up
def create_fake_students():
    """
    Make a bunch of fake students so we can add them to classes later.
    """
    global all_students
    for lett in string.ascii_lowercase:
        for i in range(11):
            if i==10:
                userid = "0%sgrad" % (lett*3)
                fname = randname(8)
                lname = "Grad"
            else:
                userid = "0%s%i" % (lett*3, i)
                fname = randname(8)
                lname = "Student"
            p = Person(emplid=fake_emplid(), userid=userid, last_name=lname, first_name=fname, middle_name="", pref_first_name=fname[:4])
            p.save()
            all_students[userid] = p 
Example 12
Project: aegea   Author: kislyuk   File: iam.py    License: Apache License 2.0 5 votes vote down vote up
def generate_password(length=16):
    while True:
        password = [random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length)]
        password.insert(8, "-")
        if not any(c in string.ascii_uppercase for c in password):
            continue
        if not any(c in string.ascii_lowercase for c in password):
            continue
        if not any(c in string.digits for c in password):
            continue
        return ''.join(password) 
Example 13
Project: jsonrpcclient   Author: bcb   File: id_generators.py    License: MIT License 5 votes vote down vote up
def random(length: int = 8, chars: str = digits + ascii_lowercase) -> Iterator[str]:
    """
    A random string.

    Not unique, but has around 1 in a million chance of collision (with the default 8
    character length). e.g. 'fubui5e6'

    Args:
        length: Length of the random string.
        chars: The characters to randomly choose from.
    """
    while True:
        yield "".join([choice(chars) for _ in range(length)]) 
Example 14
Project: DOTA_models   Author: ringringyi   File: graphs_test.py    License: Apache License 2.0 5 votes vote down vote up
def _build_random_vocabulary(vocab_size=100):
  """Builds and returns a dict<term, id>."""
  vocab = set()
  while len(vocab) < (vocab_size - 1):
    rand_word = ''.join(
        random.choice(string.ascii_lowercase)
        for _ in range(random.randint(1, 10)))
    vocab.add(rand_word)

  vocab_ids = dict([(word, i) for i, word in enumerate(vocab)])
  vocab_ids[data.EOS_TOKEN] = vocab_size - 1
  return vocab_ids 
Example 15
Project: suffix-trees   Author: ptrus   File: gen_vectors.py    License: MIT License 5 votes vote down vote up
def random_str(n):
    return ''.join(random.choice(string.ascii_lowercase) for _ in range(n)) 
Example 16
Project: PickTrue   Author: winkidney   File: huaban.py    License: MIT License 5 votes vote down vote up
def _random_string(length):
    return ''.join(
        random.choice(string.ascii_lowercase + string.digits)
        for _ in range(length)
    ) 
Example 17
Project: controller   Author: deis   File: app.py    License: MIT License 5 votes vote down vote up
def run(self, user, command):
        def pod_name(size=5, chars=string.ascii_lowercase + string.digits):
            return ''.join(random.choice(chars) for _ in range(size))

        """Run a one-off command in an ephemeral app container."""
        release = self.release_set.filter(failed=False).latest()
        if release.build is None:
            raise DeisException('No build associated with this release to run this command')

        app_settings = self.appsettings_set.latest()
        # use slugrunner image for app if buildpack app otherwise use normal image
        image = settings.SLUGRUNNER_IMAGE if release.build.type == 'buildpack' else release.image

        data = self._gather_app_settings(release, app_settings, process_type='run', replicas=1)

        # create application config and build the pod manifest
        self.set_application_config(release)

        scale_type = 'run'
        name = self._get_job_id(scale_type) + '-' + pod_name()
        self.log("{} on {} runs '{}'".format(user.username, name, command))

        try:
            exit_code, output = self._scheduler.run(
                self.id,
                name,
                image,
                self._get_entrypoint(scale_type),
                [command],
                **data
            )

            return exit_code, output
        except Exception as e:
            err = '{} (run): {}'.format(name, e)
            raise ServiceUnavailable(err) from e 
Example 18
Project: controller   Author: deis   File: mock.py    License: MIT License 5 votes vote down vote up
def pod_name(size=5, chars=string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size)) 
Example 19
Project: certidude   Author: laurivosandi   File: tokens.py    License: MIT License 5 votes vote down vote up
def issue(self, issuer, subject, subject_mail=None):
        # Expand variables
        subject_username = subject.name
        if not subject_mail:
            subject_mail = subject.mail

        # Generate token
        token = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(32))
        token_created = datetime.utcnow()
        token_expires = token_created + config.TOKEN_LIFETIME

        self.sql_execute("token_issue.sql",
            token_created, token_expires, token,
            issuer.name if issuer else None,
            subject_username, subject_mail, "rw")

        # Token lifetime in local time, to select timezone: dpkg-reconfigure tzdata
        try:
            with open("/etc/timezone") as fh:
                token_timezone = fh.read().strip()
        except EnvironmentError:
            token_timezone = None

        router = sorted([j[0] for j in authority.list_signed(
                    common_name=config.SERVICE_ROUTERS)])[0]
        protocols = ",".join(config.SERVICE_PROTOCOLS)
        url = config.TOKEN_URL % locals()

        context = globals()
        context.update(locals())

        mailer.send("token.md", to=subject_mail, **context)
        return token 
Example 20
Project: pymoo   Author: msu-coinlab   File: usage_nsga2_custom.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, n_characters=10):
        super().__init__(n_var=1, n_obj=2, n_constr=0, elementwise_evaluation=True)
        self.n_characters = n_characters
        self.ALPHABET = [c for c in string.ascii_lowercase] 
Example 21
Project: pyspark-cassandra   Author: TargetHolding   File: tests.py    License: Apache License 2.0 5 votes vote down vote up
def test_list(self):
        lists = {'l%s' % i: list(string.ascii_lowercase[:i]) for i in range(1, 10)}
        self.collections_common_tests(lists, 'l') 
Example 22
Project: pyspark-cassandra   Author: TargetHolding   File: tests.py    License: Apache License 2.0 5 votes vote down vote up
def test_map(self):
        maps = {'m%s' % i : {k : 'x' for k in string.ascii_lowercase[:i]} for i in range(1, 10)}
        self.collections_common_tests(maps, 'm') 
Example 23
Project: pyspark-cassandra   Author: TargetHolding   File: tests.py    License: Apache License 2.0 5 votes vote down vote up
def test_set(self):
        maps = {'s%s' % i : set(string.ascii_lowercase[:i]) for i in range(1, 10)}
        self.collections_common_tests(maps, 's') 
Example 24
Project: pyspark-cassandra   Author: TargetHolding   File: tests.py    License: Apache License 2.0 5 votes vote down vote up
def test_simple_pk(self):
        table = 'join_rdd_test_simple_pk'

        self.session.execute('''
            CREATE TABLE IF NOT EXISTS ''' + table + ''' (
                key text primary key, value text
            )
        ''')
        self.session.execute('TRUNCATE %s' % table)

        rows = {
           str(c) : str(i) for i, c in
           enumerate(string.ascii_lowercase)
        }

        for k, v in rows.items():
            self.session.execute(
                'INSERT INTO ' + table + ' (key, value) values (%s, %s)', (k, v)
            )

        rdd = self.sc.parallelize(rows.items())
        self.assertEqual(dict(rdd.collect()), rows)

        tbl = rdd.joinWithCassandraTable(self.keyspace, table)
        joined = tbl.on('key').select('key', 'value').cache()
        self.assertEqual(dict(joined.keys().collect()), dict(joined.values().collect()))
        for (k, v) in joined.collect():
            self.assertEqual(k, v) 
Example 25
Project: pyspark-cassandra   Author: TargetHolding   File: tests.py    License: Apache License 2.0 5 votes vote down vote up
def test_composite_pk(self):
        table = 'join_rdd_test_composite_pk'

        self.session.execute('''
            CREATE TABLE IF NOT EXISTS ''' + table + ''' (
                pk text, cc text, value text,
                primary key (pk, cc)
            )
        ''')
        self.session.execute('TRUNCATE %s' % table)

        rows = [
           # (pk, cc, pk + '-' + cc)
           (unicode(pk), unicode(cc), unicode(pk + '-' + cc))
           for pk in string.ascii_lowercase[:3]
           for cc in (str(i) for i in range(3))
        ]

        for row in rows:
            self.session.execute(
                'INSERT INTO ' + table + ' (pk, cc, value) values (%s, %s, %s)', row
            )

        rdd = self.sc.parallelize(rows)

        joined = rdd.joinWithCassandraTable(self.keyspace, table).on('pk', 'cc')
        self.assertEqual(sorted(zip(rows, rows)), sorted(joined.map(tuple).collect()))

        joined = rdd.joinWithCassandraTable(self.keyspace, table).on('pk')
        self.assertEqual(len(rows) * sqrt(len(rows)), joined.count())


        # TODO test
        # .where()
        # .limit() 
Example 26
Project: pyscf   Author: pyscf   File: numpy_helper.py    License: Apache License 2.0 5 votes vote down vote up
def norm(x, ord=None, axis=None):
        '''numpy.linalg.norm for numpy 1.6.*
        '''
        if axis is None or ord is not None:
            return numpy.linalg.norm(x, ord)
        else:
            x = numpy.asarray(x)
            axes = string.ascii_lowercase[:x.ndim]
            target = axes.replace(axes[axis], '')
            descr = '%s,%s->%s' % (axes, axes, target)
            xx = _numpy_einsum(descr, x.conj(), x)
            return numpy.sqrt(xx.real) 
Example 27
Project: iAI   Author: aimuch   File: generator.py    License: MIT License 5 votes vote down vote up
def bottleneck_layer_set(
        prev_top,               # Previous activation name
        level,                  # Level number of this set, used for naming
        num_output,             # "num_output" param for most layers of this set
        num_bottlenecks,        # number of bottleneck sets
        shortcut_params='default',    # Conv params of the shortcut convolution 
        sublevel_naming='letters', # Naming scheme of layer sets. MSRA sometimes uses letters sometimes numbers
        make_layers=bottleneck_layers, # Function to make layers with
    ):
    """A set of bottleneck layers, with the first one having an convolution shortcut to accomodate size"""

    if shortcut_params == 'default':
        shortcut_params = (1, num_output*(4 if make_layers is bottleneck_layers else 1), 2, 0)
    shortcut_str, shortcut_activation = normalized_conv_layers(shortcut_params, '%da'%level, '1', prev_top, activation=False)
    network_str = ''
    if sublevel_naming == 'letters' and num_bottlenecks <= 26:
        sublevel_names = ascii_lowercase[:num_bottlenecks]
    else:
        sublevel_names = ['a'] + ['b' + str(i) for i in range(1, num_bottlenecks)]
    for index, sublevel in enumerate(sublevel_names):
        if index != 0:
            shortcut_activation, shortcut_str = None, ''
            layers, prev_top = make_layers(prev_top, '%d%s'%(level, sublevel), num_output, shortcut_activation, shortcut_str)
        else:
            layers, prev_top = make_layers(prev_top, '%d%s'%(level, sublevel), num_output, shortcut_activation, shortcut_str, shortcut_params[2])
        network_str += layers
    return network_str, prev_top 
Example 28
Project: Jtyoui   Author: jtyoui   File: methods.py    License: MIT License 5 votes vote down vote up
def random_lower_char(number=1):
    """随机选择小写字母

    :param number: 生成个数
    """
    ls = random.choices(string.ascii_lowercase, k=number)
    return ''.join(ls)


# 随机选择大写字母: 
Example 29
Project: qutebrowser   Author: qutebrowser   File: hints.py    License: GNU General Public License v3.0 5 votes vote down vote up
def ensure_initialized(self) -> None:
        """Generate the used words if yet uninitialized."""
        dictionary = config.val.hints.dictionary
        if not self.words or self.dictionary != dictionary:
            self.words.clear()
            self.dictionary = dictionary
            try:
                with open(dictionary, encoding="UTF-8") as wordfile:
                    alphabet = set(ascii_lowercase)
                    hints = set()
                    lines = (line.rstrip().lower() for line in wordfile)
                    for word in lines:
                        if set(word) - alphabet:
                            # contains none-alphabetic chars
                            continue
                        if len(word) > 4:
                            # we don't need words longer than 4
                            continue
                        for i in range(len(word)):
                            # remove all prefixes of this word
                            hints.discard(word[:i + 1])
                        hints.add(word)
                    self.words.update(hints)
            except IOError as e:
                error = "Word hints requires reading the file at {}: {}"
                raise HintingError(error.format(dictionary, str(e))) 
Example 30
Project: app   Author: simple-login   File: utils.py    License: MIT License 5 votes vote down vote up
def random_string(length=10):
    """Generate a random string of fixed length """
    letters = string.ascii_lowercase
    return "".join(random.choice(letters) for _ in range(length))