def _exec_adb_cmd(self, name, args, shell, timeout):
if shell:
# Add quotes around "adb" in case the ADB path contains spaces. This
# is pretty common on Windows (e.g. Program Files).
if self.serial:
adb_cmd = '"%s" -s "%s" %s %s' % (ADB, self.serial, name, args)
else:
adb_cmd = '"%s" %s %s' % (ADB, name, args)
else:
adb_cmd = [ADB]
if self.serial:
adb_cmd.extend(['-s', self.serial])
adb_cmd.append(name)
if args:
if isinstance(args, basestring):
adb_cmd.append(args)
else:
adb_cmd.extend(args)
return self._exec_cmd(adb_cmd, shell=shell, timeout=timeout)
python类basestring()的实例源码
def _set_text_property(self, name, value, allow_utf8=True):
atom = xlib.XInternAtom(self._x_display, asbytes(name), False)
if not atom:
raise XlibException('Undefined atom "%s"' % name)
assert isinstance(value, basestring)
property = xlib.XTextProperty()
if _have_utf8 and allow_utf8:
buf = create_string_buffer(value.encode('utf8'))
result = xlib.Xutf8TextListToTextProperty(self._x_display,
cast(pointer(buf), c_char_p), 1, xlib.XUTF8StringStyle,
byref(property))
if result < 0:
raise XlibException('Could not create UTF8 text property')
else:
buf = create_string_buffer(value.encode('ascii', 'ignore'))
result = xlib.XStringListToTextProperty(
cast(pointer(buf), c_char_p), 1, byref(property))
if result < 0:
raise XlibException('Could not create text property')
xlib.XSetTextProperty(self._x_display,
self._window, byref(property), atom)
# XXX <rj> Xlib doesn't like us freeing this
#xlib.XFree(property.value)
def add_file(font):
"""Add a font to pyglet's search path.
In order to load a font that is not installed on the system, you must
call this method to tell pyglet that it exists. You can supply
either a filename or any file-like object.
The font format is platform-dependent, but is typically a TrueType font
file containing a single font face. Note that to use a font added with this method,
you should pass the face name (not the file name) to :meth:`pyglet.font.load` or any
other place where you normally specify a font.
:Parameters:
`font` : str or file
Filename or file-like object to load fonts from.
"""
if isinstance(font, basestring):
font = open(font, 'rb')
if hasattr(font, 'read'):
font = font.read()
_font_class.add_font_data(font)
def _set_text_property(self, name, value, allow_utf8=True):
atom = xlib.XInternAtom(self._x_display, asbytes(name), False)
if not atom:
raise XlibException('Undefined atom "%s"' % name)
assert isinstance(value, basestring)
property = xlib.XTextProperty()
if _have_utf8 and allow_utf8:
buf = create_string_buffer(value.encode('utf8'))
result = xlib.Xutf8TextListToTextProperty(self._x_display,
cast(pointer(buf), c_char_p), 1, xlib.XUTF8StringStyle,
byref(property))
if result < 0:
raise XlibException('Could not create UTF8 text property')
else:
buf = create_string_buffer(value.encode('ascii', 'ignore'))
result = xlib.XStringListToTextProperty(
cast(pointer(buf), c_char_p), 1, byref(property))
if result < 0:
raise XlibException('Could not create text property')
xlib.XSetTextProperty(self._x_display,
self._window, byref(property), atom)
# XXX <rj> Xlib doesn't like us freeing this
#xlib.XFree(property.value)
def add_file(font):
"""Add a font to pyglet's search path.
In order to load a font that is not installed on the system, you must
call this method to tell pyglet that it exists. You can supply
either a filename or any file-like object.
The font format is platform-dependent, but is typically a TrueType font
file containing a single font face. Note that to use a font added with this method,
you should pass the face name (not the file name) to :meth:`pyglet.font.load` or any
other place where you normally specify a font.
:Parameters:
`font` : str or file
Filename or file-like object to load fonts from.
"""
if isinstance(font, basestring):
font = open(font, 'rb')
if hasattr(font, 'read'):
font = font.read()
_font_class.add_font_data(font)
def __add__(self, move):
if isinstance(move, (str, basestring)):
return self + Move(move)
elif move is None:
return self
elif isinstance(move, Move):
if self.face != move.face:
raise ValueError("Only same faces can be added")
if self.clockwise and move.counterclockwise:
return None
if self.double and move.double:
return None
offset = (
(self.clockwise + (self.double * 2) + (self.counterclockwise * 3)) +
(move.clockwise + (move.double * 2) + (move.counterclockwise * 3))
) % 4
if offset == 0:
return None
return Move(self.face + [None, "", "2", "'"][offset])
else:
raise ValueError("Unable to add %s and %s" %(self.raw, str(move)))
def __init__(self, size=3, init=None, check=True):
self.size = size
if init:
init = init.replace(' ', '')
if check and not isinstance(init, (str, basestring)):
raise ValueError("Init configuration must be a string")
if check and int(math.sqrt(len(init))) != math.sqrt(len(init)):
raise ValueError(
"Init configuration length must be a power of 2")
self.size = int(math.sqrt(self.size))
self.squares = init
else:
self.squares = '.' * (self.size * self.size)
def _check_valid_cube(cube):
'''Checks if cube is one of str, NaiveCube or Cubie.Cube and returns
an instance of Cubie.Cube'''
if isinstance(cube, basestring):
c = NaiveCube()
c.set_cube(cube)
cube = c
if isinstance(cube, NaiveCube):
c = Cube()
c.from_naive_cube(cube)
cube = c
if not isinstance(cube, Cube):
raise ValueError('Cube is not one of (str, NaiveCube or Cubie.Cube)')
return cube
def solve(cube, method = Beginner.BeginnerSolver, *args, **kwargs):
if isinstance(method, basestring):
if not method in METHODS:
raise ValueError('Invalid method name, must be one of (%s)' %
', '.join(METHODS.keys())
)
method = METHODS[method]
if not issubclass(method, Solver):
raise ValueError('Method %s is not a valid Solver subclass' %
method.__class__.__name__
)
cube = _check_valid_cube(cube)
solver = method(cube)
return solver.solution(*args, **kwargs)
def _preprocess(argument):
"""Receives the argument (from the constructor), and normalizes it
into a list of Pattern objects."""
pattern_set = PatternSet()
if argument is not None:
if isinstance(argument, basestring):
argument = [argument]
for glob in argument:
if isinstance(glob, basestring):
patterns = Pattern.create(glob)
pattern_set.extend(patterns)
elif isinstance(glob, Pattern):
pattern_set.append(glob)
return pattern_set
def is_number(s):
if isinstance(s, list) and not isinstance(s, basestring):
try:
for x in s:
if isinstance(x, basestring) and ' ' in x:
raise ValueError
[float(x) for x in s]
return True
except ValueError:
return False
else:
try:
if isinstance(s, basestring) and ' ' in s:
raise ValueError
float(s)
return True
except ValueError:
return False
def _get_task_priority(tasks, task_priority):
"""Get the task `priority` corresponding to the given `task_priority`.
If `task_priority` is an integer or 'None', return it.
If `task_priority` is a str, return the priority of the task it matches.
Otherwise, raise `ValueError`.
"""
if task_priority is None:
return None
if is_integer(task_priority):
return task_priority
if isinstance(task_priority, basestring):
if task_priority in tasks:
return tasks[task_priority].priority
raise ValueError("Unrecognized task priority '{}'".format(task_priority))
def retrieve_file(self, remote_full_path, local_full_path_or_buffer):
conn = self.get_conn()
is_path = isinstance(local_full_path_or_buffer, basestring)
if is_path:
output_handle = open(local_full_path_or_buffer, 'wb')
else:
output_handle = local_full_path_or_buffer
logging.info('Retrieving file from FTP: {}'.format(remote_full_path))
conn.getfo(remote_full_path, output_handle)
logging.info('Finished retrieving file from FTP: {}'.format(
remote_full_path))
if is_path:
output_handle.close()
def _multi_dataurl_op(self, urls, ops, model=None, local_ids=None, meta=None,
payload=None, **kwargs):
""" If sending image_url or image_file strings, then we can send as json directly instead of the
multipart form. """
if urls is not None: # for feedback, this might not be required.
if not isinstance(urls, list):
urls = [urls]
self._check_batch_size(urls)
if not isinstance(urls[0], basestring):
raise Exception("urls must be strings")
data = self._setup_multi_data(ops, len(urls), model, local_ids, meta, **kwargs)
# Add some addition url specific stuff to data dict:
if urls is not None:
data['url'] = urls
if payload:
assert isinstance(payload, dict), "Addition payload must be a dict"
for (k, v) in iteritems(payload):
data[k] = v
url = self._url_for_op(ops)
kwargs = {'data': data}
raw_response = self._get_raw_response(
self._get_json_headers, self._get_json_response, url, kwargs)
return self._parse_response(raw_response)
def _compare_type(expected, result):
if isinstance(expected, basestring) and isinstance(result, basestring):
return True
if isinstance(expected, bool) and isinstance(result, bool):
return True
# bool is instance of int. return False if one type is a boolean
elif isinstance(expected, bool) != isinstance(result, bool):
return False
if isinstance(expected, (int, float)) and isinstance(result, (int, float)):
return True
if isinstance(expected, list) and isinstance(result, list):
return True
if isinstance(expected, dict) and isinstance(result, dict):
return True
if isinstance(expected, tuple) and isinstance(result, type):
return True
return False
def __init__(
self,
partition_names,
metastore_conn_id='metastore_default',
poke_interval=60*3,
*args,
**kwargs):
super(NamedHivePartitionSensor, self).__init__(
poke_interval=poke_interval, *args, **kwargs)
if isinstance(partition_names, basestring):
raise TypeError('partition_names must be an array of strings')
self.metastore_conn_id = metastore_conn_id
self.partition_names = partition_names
self.next_poke_idx = 0
def _get_json_to_kwargs(self, json_data):
"""
Augments json data before passing to the handler script.
Prefixes all keys with cbot_ value to avoid clashes + serializes
itself to JSON - for JSON parsing stuff.
:param json_data:
:return:
"""
n_data = OrderedDict()
for k in json_data:
val = json_data[k]
if k == 'command':
continue
if isinstance(val, float):
val = str(math.ceil(val))
if not isinstance(val, (str, basestring)):
val = str(val)
if val is not None:
n_data[k] = val
n_data['cbot_' + k] = val
n_data['cbot_json'] = self._json_dumps(json_data)
return n_data
def test_until_next_flags(self):
for name, (flag, builder) in lower_until_next_flags.items():
if builder is None:
continue
document = self.parse(r"\p \{} hello \p world".format(flag))
elements = document.elements
self.assertEqual(len(elements), 2)
self.assertIsInstance(elements[0], Paragraph)
self.assertEqual(len(elements[0].children), 1)
child = elements[0].children[0]
self.assertIsInstance(child, FormattedText)
self.assertEqual(len(child.children), 1)
text = child.children[0]
self.assertIsInstance(text, Text)
self.assertIsInstance(text.content, basestring)
self.assertIsInstance(elements[1], Paragraph)
def has_user_group(self, user_group_name):
"""Checks if a user group exists in the commcell with the input user group name.
Args:
user_group_name (str) -- name of the user group
Returns:
bool - boolean output whether the user group exists in the commcell or not
Raises:
SDKException:
if type of the user group name argument is not string
"""
if not isinstance(user_group_name, basestring):
raise SDKException('UserGroup', '101')
return self._user_groups and user_group_name.lower() in self._user_groups
def has_client(self, client_name):
"""Checks if a client exists in the commcell with the input client name.
Args:
client_name (str) -- name of the client
Returns:
bool - boolean output whether the client exists in the commcell or not
Raises:
SDKException:
if type of the client name argument is not string
"""
if not isinstance(client_name, basestring):
raise SDKException('Client', '101')
return self._clients and client_name.lower() in self._clients