コード例 #1
0
ファイル: issues.py プロジェクト: sejalseth/brython
def matrix(s, types=None, char='|'):
    ds = ([j.strip() for j in i.split(char)] for i in s.strip().splitlines()
          if not i.strip().startswith('#'))

    if not types:
        yield from ds
    elif isinstance(types, (list, tuple)):
        for i in ds:
            yield [k(v or k()) for k, v in zip(types, i)]
    else:
        for i in ds:
            yield [types(v or types()) for v in i]
コード例 #2
0
ファイル: compatability.py プロジェクト: orblivion/PyPump
 def to_unicode(string):
     """ Convert to unicode object """
     if type(string) is bytes:
         return string.decode("utf-8")
     if types(string) is str:
         return string
     raise TypeError("Unknown type %s" % string)
コード例 #3
0
def change_password(username, old_password, new_password, admin=False):
    if admin == False:
        if pam.authenticate(username, old_password) == False:
            return 'Erro o fazer login, verifique o nome de' \
                ' usuário e/ou senha.'

    # Now login as root to change the password
    process = run_as_root('passwd {0}'.format(username))

    if types(process) == types.StringType:
        return process

    process.expect('Enter new UNIX password: '******'Retype new UNIX password: '******'passwd: password updated successfully', 'new password is too simple'
    ])
    if i == 0:
        return True
    if i == 1:
        return 'Senha muito fácil, use no mínimo 6 digitos.'
コード例 #4
0
ファイル: compatability.py プロジェクト: RouxRC/PyPump
 def to_unicode(string):
     """ Convert to unicode object """
     if type(string) is bytes:
         return string.decode("utf-8")
     if types(string) is str:
         return string
     raise TypeError("Unknown type %s" % string)
コード例 #5
0
 def md(text):
     import hashlib
     import types
     if types(text) is types.StringType:
         m=hashlib.md5()
         m.update(text)
         return m.hexdigest()
     else:
         return""
コード例 #6
0
ファイル: resources.py プロジェクト: Ximpia/ximpia
	def toUnicode(self, urlStr):
		"""Convert an url in string mode to unicode mode.
		@param urlStr: Url in string
		@return: url: Url in unicode""" 
		if types(urlStr) == types.UnicodeType:
			url = urlStr
		else:
			url = unicode(urlStr, "utf-8")
		return url
コード例 #7
0
ファイル: 03_splitter.py プロジェクト: maxmailman/GeekBrains
def split(line, types=None, delimiter=None):
    """ Разбивает​ ​ текстовую​ ​ строку​ ​ и​ ​ при​ ​ необходимости
    выполняет​ ​ преобразование​ ​ типов.  ​
    ​Например: 
    ​>>>​ ​ split('GOOG​ ​ 100​ ​ 490.50') 
    ['GOOG',​ ​ '100',​ ​ '490.50']  ​
    ​>>>​ ​ split('GOOG​ ​ 100​ ​ 490.50',[str,​ ​ int,​ ​ float]) 
    ​['GOOG',​ ​ 100,​ ​ 490.5] 
    ​>>> 
    ​По​ ​ умолчанию​ ​ разбиение​ ​ производится​ ​ по​ ​ пробельным​ ​ символам, но имеется возможность 
    указать другой символ-разделитель, в виде именованного​ ​ аргумента: 
    ​>>>​ ​ split('GOOG,100,490.50',delimiter=',') 
    ​['GOOG',​ ​ '100',​ ​ '490.50'] 
    ​>>>
    """
    fields = line.split(delimiter)
    if types:
        fields = [types(val) for types.val in zip(types, fields) ]
    return fields
コード例 #8
0
ファイル: test.py プロジェクト: smurfix/MoaT
	async def do(self,args):
		etc = await self.root._get_etcd()
		from moat.types import types,TYPEDEF_DIR,TYPEDEF
		for t in types():
			path = tuple(t.name.split('/'))
			if self.root.verbose:
				try:
					d = await etc.tree(TYPEDEF_DIR+path+(TYPEDEF,), create=False)
				except etcd.EtcdKeyNotFound:
					logger.info("Creating %s",t.name)
					d = await etc.tree(TYPEDEF_DIR+path+(TYPEDEF,), create=True)
				else:
					logger.debug("Found %s",t.name)
			else:
				d = await etc.tree(TYPEDEF_DIR+path+(TYPEDEF,))
			for k,v in t.vars.items():
				if k not in d:
					await d.set(k,v)
			await d.close()
コード例 #9
0
ファイル: test.py プロジェクト: ZigmundRat/moat
 async def do(self, args):
     etc = await self.root._get_etcd()
     log = logging.getLogger(__name__ + ".types")
     from moat.types import types, TYPEDEF_DIR, TYPEDEF
     for t in types():
         path = tuple(t.name.split('/'))
         if self.root.verbose:
             try:
                 d = await etc.tree(TYPEDEF_DIR + path + (TYPEDEF, ),
                                    create=False)
             except etcd.EtcdKeyNotFound:
                 log.info("Creating %s", t.name)
                 d = await etc.tree(TYPEDEF_DIR + path + (TYPEDEF, ),
                                    create=True)
             else:
                 log.debug("Found %s", t.name)
         else:
             d = await etc.tree(TYPEDEF_DIR + path + (TYPEDEF, ))
         for k, v in t.vars.items():
             if k not in d:
                 await d.set(k, str(v))
         await d.close()
コード例 #10
0
def _assembly_alu(opcode, instruction, cfg):
    sX = instruction[1]
    sY = instruction[2]
    KK = instruction[2]

    objhex = opcode

    if opcode == 0x2B000:
        if type(sX) != types.IntType and types(sY) != types.IntType:
            raise PSMPPException('Unknown types of parameters')
        if sY > 15:
            raise PSMPPException('Parameter out of bounds')
        objhex = objhex | (sX << 4) | sY
        return objhex

    objhex = objhex | (_parse_register_name(sX) << 8)
        
    if type(sY) == types.IntType:
        objhex = objhex | KK
    elif type(sY) == types.StringType:
        objhex = objhex | (_parse_register_name(sY) << 4)
    else:
        raise PSMPPException('Unknow type of parameters')

    #difference of bit-12:
    # +------+---------+---------+
    # |value |0        |1        |
    # +------+---------+---------+
    # |kcpsm3|immediate|register |
    # |kcpsm6|register |immediate|
    # +------+---------+---------+
    if type(sY) == types.IntType and '--kcpsm6' in cfg:
        objhex = objhex | 0x01000
    if type(sY) == types.StringType and '--kcpsm3' in cfg:
        objhex = objhex | 0x01000

    return objhex
コード例 #11
0
ファイル: __init__.py プロジェクト: jaysonsantos/SambaManager
def change_password(username, old_password, new_password, admin=False):
    if admin == False:
        if pam.authenticate(username, old_password) == False:
            return 'Erro o fazer login, verifique o nome de' \
                ' usuário e/ou senha.'

    # Now login as root to change the password
    process = run_as_root('passwd {0}'.format(username))

    if types(process) == types.StringType:
        return process
    
    process.expect('Enter new UNIX password: '******'Retype new UNIX password: '******'passwd: password updated successfully',
                         'new password is too simple'])
    if i == 0:
        return True
    if i == 1:
        return 'Senha muito fácil, use no mínimo 6 digitos.'
コード例 #12
0
"""
sqlobject.sqlbuilder
--------------------

:author: Ian Bicking <*****@*****.**>

Builds SQL expressions from normal Python expressions.

Disclaimer
----------

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.

Instructions
------------

To begin a SQL expression, you must use some sort of SQL object -- a
コード例 #13
0
ファイル: Animals.py プロジェクト: huangsongyan/pythondemo
#encoding:utf-8

class Animsla(object):
    def run(self):
        print 'run'


#使用type()

import types

print type(123)==type(456)

print types('abc')==types.StringType

# >>> import types
# >>> type('abc')==types.StringType
# True
# >>> type(u'abc')==types.UnicodeType
# True
# >>> type([])==types.ListType
# True
# >>> type(str)==types.TypeType
# True

#最后注意到有一种类型就叫TypeType,所有类型本身的类型就是TypeType,比如:
print (int)==type(str)==types.TypeType

#并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是str或者unicode:
isinstance('a', (str, unicode))
コード例 #14
0
 def SearchLyrics(self, artist, song):
     result = self.LeosLyrics(artist, song)
     print types(result)
     return result
コード例 #15
0
ファイル: class_demo.py プロジェクト: pingz1988/Python
 def func(self, str):
     if types(str) == types("abc"):
         print(str.upper())
         self.m_var1 = str
         print(self.m_var1)
コード例 #16
0
# @Software: PyCharm
# 我们来判断对象类型,使用type()函数
type(123)
# 如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量
import types


def fn():
    pass


type(fn) == types.FunctionType

type(abs) == types.BuiltinFunctionType

types(lambda x: x) == type.LambdaType

type((x for x in range(10))) == types.GeneratorType

# 对于class的继承关系来说,使用type()就很不方便。我们要判断class的类型,可以使用isinstance()函数
# 能用type()判断的基本类型也可以用isinstance()判断:
isinstance('a', str)
# 并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple:
isinstance([1, 2, 3], (list, tuple))

# 如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:


# 配合getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态
class MyObject(object):
    def __init__(self):
コード例 #17
0
 def setMapData(self, mapData):
     if mapData is not None:
         if types(mapData) is types.MappingProxyType:
             self.mapData = mapData
コード例 #18
0
def func(*args):
    print(len(args))
    for arg in args:
        for a in arg.__dict__.values():
            if types(a) == types.ModuleType:
                print(a)
コード例 #19
0
ファイル: 22.py プロジェクト: bodii/test-code
 def generic_visit(self, node):
     raise RuntimeError('No {} method'.format('visit_' + types(node).__name__))