query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
convert int to bool
python
def convert_to_bool(x: Any, default: bool = None) -> bool: """ Transforms its input to a ``bool`` (or returns ``default`` if ``x`` is falsy but not itself a boolean). Accepts various common string versions. """ if isinstance(x, bool): return x if not x: # None, zero, blank string... return default try: return int(x) != 0 except (TypeError, ValueError): pass try: return float(x) != 0 except (TypeError, ValueError): pass if not isinstance(x, str): raise Exception("Unknown thing being converted to bool: {!r}".format(x)) x = x.upper() if x in ["Y", "YES", "T", "TRUE"]: return True if x in ["N", "NO", "F", "FALSE"]: return False raise Exception("Unknown thing being converted to bool: {!r}".format(x))
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L43-L73
convert int to bool
python
def to_bool(value): """Convert string value to bool.""" bool_value = False if str(value).lower() in ['1', 'true']: bool_value = True return bool_value
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_utils.py#L285-L290
convert int to bool
python
def _to_bool(value): """Convert string value to bool.""" bool_value = False if str(value).lower() in ['1', 'true']: bool_value = True return bool_value
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_profile.py#L55-L60
convert int to bool
python
def convert_int(value, parameter): ''' Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, int): return value try: return int(value) except Exception as e: raise ValueError(str(e))
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L41-L53
convert int to bool
python
def convert_bool(string): """Check whether string is boolean. """ if string == 'True': return True, True elif string == 'False': return True, False else: return False, False
https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/readwrite.py#L591-L599
convert int to bool
python
def to_bool(value): """ Convert a value to boolean :param value: the value to convert :type value: any type :return: a boolean value :rtype: a boolean """ if value is None: return None if isinstance(value, bool): return value elif isinstance(value, str): if value=="no": return False elif value=="yes": return True
https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/mappings.py#L19-L35
convert int to bool
python
def to_int(s): """ converts a string to an integer >>> to_int('1_000_000') 1000000 >>> to_int('1e6') 1000000 >>> to_int('1000') 1000 """ try: return int(s.replace('_', '')) except ValueError: return int(ast.literal_eval(s))
https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/cli.py#L8-L23
convert int to bool
python
def convert_string(string): """Convert string to int, float or bool. """ if is_int(string): return int(string) elif is_float(string): return float(string) elif convert_bool(string)[0]: return convert_bool(string)[1] elif string == 'None': return None else: return string
https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/readwrite.py#L602-L614
convert int to bool
python
def to_int(value: str, default: T = None) -> Union[int, Optional[T]]: """Convert given value to int. If conversion failed, return default value without raising Exception. :param value: Value to convert to int. :param default: Default value to use in case of failed conversion. """ try: return int(value) except (TypeError, ValueError): return default
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/utils.py#L35-L46
convert int to bool
python
def string_to_int( s ): """Convert a string of bytes into an integer, as per X9.62.""" result = 0 for c in s: if not isinstance(c, int): c = ord( c ) result = 256 * result + c return result
https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ecdsa.py#L169-L175
convert int to bool
python
def to_bool(s): """ Convert string `s` into a boolean. `s` can be 'true', 'True', 1, 'false', 'False', 0. Examples: >>> to_bool("true") True >>> to_bool("0") False >>> to_bool(True) True """ if isinstance(s, bool): return s elif s.lower() in ['true', '1']: return True elif s.lower() in ['false', '0']: return False else: raise ValueError("Can't cast '%s' to bool" % (s))
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/src/ansiblecmdb/util.py#L64-L85
convert int to bool
python
def to_bool(value): ''' Transform a value into a boolean with the following rules: - a boolean is returned untouched - a string value should match any casinf of 'true' to be True - an integer should be superior to zero to be True - all other values are False ''' if isinstance(value, bool): return value elif isinstance(value, basestring): return value.lower() == 'true' or value.lower() == 't' elif isinstance(value, int): return value > 0 else: return False
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L182-L198
convert int to bool
python
def string_to_num(s: str): """Converts a string to an int/float Returns ``None`` if it can't be converted >>> string_to_num('5') 5 >>> string_to_num('5.2') 5.2 >>> string_to_num(10) 10 >>> string_to_num(10.1) 10.1 >>> string_to_num('this is not a string') is None True """ if isinstance(s, (int, float)): return s if s.isdigit(): return int(s) try: return float(s) except ValueError: return None
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L148-L171
convert int to bool
python
def to_bool(value): # type: (Any) -> bool """ Convert a value into a bool but handle "truthy" strings eg, yes, true, ok, y """ if isinstance(value, _compat.string_types): return value.upper() in ('Y', 'YES', 'T', 'TRUE', '1', 'OK') return bool(value)
https://github.com/python-odin/odinweb/blob/198424133584acc18cb41c8d18d91f803abc810f/odinweb/utils.py#L43-L50
convert int to bool
python
def convert(self, value, param, ctx): """ Convert value to int. """ self.gandi = ctx.obj value = click.Choice.convert(self, value, param, ctx) return int(value)
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/params.py#L198-L202
convert int to bool
python
def to_int(value, default=_marker): """Tries to convert the value to int. Truncates at the decimal point if the value is a float :param value: The value to be converted to an int :return: The resulting int or default """ if is_floatable(value): value = to_float(value) try: return int(value) except (TypeError, ValueError): if default is None: return default if default is not _marker: return to_int(default) fail("Value %s cannot be converted to int" % repr(value))
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/api/__init__.py#L1257-L1273
convert int to bool
python
def to_int(value, default=0): """ Tries to convert the value passed in as an int. If no success, returns the default value passed in :param value: the string to convert to integer :param default: the default fallback :return: int representation of the value passed in """ try: return int(value) except (TypeError, ValueError): return to_int(default, default=0)
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/utils/__init__.py#L779-L790
convert int to bool
python
def to_bool(self, value): """ Converts a sheet string value to a boolean value. Needed because of utf-8 conversions """ try: value = value.lower() except: pass try: value = value.encode('utf-8') except: pass try: value = int(value) except: pass if value in ('true', 1): return True else: return False
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/exportimport/setupdata/__init__.py#L181-L201
convert int to bool
python
def to_int(self, number, default=0): """Returns an integer """ try: return int(number) except (KeyError, ValueError): return self.to_int(default, 0)
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/idserver/view.py#L115-L121
convert int to bool
python
def to_bool(value: Any) -> bool: """Convert string or other Python object to boolean. **Rationalle** Passing flags is one of the most common cases of using environment vars and as values are strings we need to have an easy way to convert them to boolean Python value. Without this function int or float string values can be converted as false positives, e.g. ``bool('0') => True``, but using this function ensure that digit flag be properly converted to boolean value. :param value: String or other value. """ return bool(strtobool(value) if isinstance(value, str) else value)
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/utils.py#L17-L32
convert int to bool
python
def int_to_string( x ): """Convert integer x into a string of bytes, as per X9.62.""" assert x >= 0 if x == 0: return b('\0') result = [] while x: ordinal = x & 0xFF result.append(int2byte(ordinal)) x >>= 8 result.reverse() return b('').join(result)
https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ecdsa.py#L155-L166
convert int to bool
python
def _convert_bool_array(self, array): """ cfitsio reads as characters 'T' and 'F' -- convert to real boolean If input is a fits bool, convert to numpy boolean """ output = (array.view(numpy.int8) == ord('T')).astype(numpy.bool) return output
https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/hdu/table.py#L1344-L1351
convert int to bool
python
def to_int(value: str) -> int: """ Robust to integer conversion, handling hex values, string representations, and special cases like `0x`. """ if is_0x_prefixed(value): if len(value) == 2: return 0 else: return int(value, 16) else: return int(value)
https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/_utils/normalization.py#L105-L116
convert int to bool
python
def convert_to_int(x: Any, default: int = None) -> int: """ Transforms its input into an integer, or returns ``default``. """ try: return int(x) except (TypeError, ValueError): return default
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L76-L83
convert int to bool
python
def convert_to_bool(text): """ Convert a few common variations of "true" and "false" to boolean :param text: string to test :return: boolean :raises: ValueError """ # handle "1" and "0" try: return bool(int(text)) except: pass text = str(text).lower() if text == "true": return True if text == "yes": return True if text == "false": return False if text == "no": return False raise ValueError
https://github.com/bitcraft/PyTMX/blob/3fb9788dd66ecfd0c8fa0e9f38c582337d89e1d9/pytmx/pytmx.py#L98-L121
convert int to bool
python
def to_inttuple(bitstr): """Convert from bit string likes '01011' to int tuple likes (0, 1, 0, 1, 1) Args: bitstr (str, Counter, dict): String which is written in "0" or "1". If all keys are bitstr, Counter or dict are also can be converted by this function. Returns: tuple of int, Counter, dict: Converted bits. If bitstr is Counter or dict, returns the Counter or dict which contains {converted key: original value}. Raises: ValueError: If bitstr type is unexpected or bitstr contains illegal character. """ if isinstance(bitstr, str): return tuple(int(b) for b in bitstr) if isinstance(bitstr, Counter): return Counter({tuple(int(b) for b in k): v for k, v in bitstr.items()}) if isinstance(bitstr, dict): return {tuple(int(b) for b in k): v for k, v in bitstr.items()} raise ValueError("bitstr type shall be `str`, `Counter` or `dict`")
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/utils.py#L18-L39
convert int to bool
python
def to_bool(s, fallback=None): """ :param str s: str to be converted to bool, e.g. "1", "0", "true", "false" :param T fallback: if s is not recognized as a bool :return: boolean value, or fallback :rtype: bool|T """ if not s: return fallback s = s.lower() if s in ["1", "true", "yes", "y"]: return True if s in ["0", "false", "no", "n"]: return False return fallback
https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L513-L527
convert int to bool
python
def float2int(x): """ converts floats to int when only float() is not enough. :param x: float """ if not pd.isnull(x): if is_numeric(x): x=int(x) return x
https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_nums.py#L69-L78
convert int to bool
python
def as_bool(s): """ Convert a string into a boolean. >>> assert as_bool(True) is True and as_bool("Yes") is True and as_bool("false") is False """ if s in (False, True): return s # Assume string s = s.lower() if s in ("yes", "true"): return True elif s in ("no", "false"): return False else: raise ValueError("Don't know how to convert type %s: %s into a boolean" % (type(s), s))
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/utils.py#L24-L38
convert int to bool
python
def _char2int(char): """ translate characters to integer values (upper and lower case)""" if char.isdigit(): return int(float(char)) if char.isupper(): return int(char, 36) else: return 26 + int(char, 36)
https://github.com/mommermi/callhorizons/blob/fdd7ad9e87cac107c1b7f88e594d118210da3b1a/callhorizons/callhorizons.py#L46-L53
convert int to bool
python
def get_int(value, default, test_fn=None): """Convert value to integer. :param value: Integer value. :param default: Default value on failed conversion. :param test_fn: Constraint function. Use default if returns ``False``. :return: Integer value. :rtype: ``int`` """ try: converted = int(value) except ValueError: return default test_fn = test_fn if test_fn else lambda x: True return converted if test_fn(converted) else default
https://github.com/ryan-roemer/django-cloud-browser/blob/b06cdd24885a6309e843ed924dbf1705b67e7f48/cloud_browser/common.py#L23-L38
convert int to bool
python
def convert_bytes_to_ints(in_bytes, num): """Convert a byte array into an integer array. The number of bytes forming an integer is defined by num :param in_bytes: the input bytes :param num: the number of bytes per int :return the integer array""" out_arr = [] for i in range(len(in_bytes)//num): val = in_bytes[i * num:i * num + num] unpacked = struct.unpack(mmtf.utils.constants.NUM_DICT[num], val) out_arr.append(unpacked[0]) return out_arr
https://github.com/rcsb/mmtf-python/blob/899bb877ca1b32a9396803d38c5bf38a2520754e/mmtf/converters/converters.py#L9-L20
convert int to bool
python
def convert_ints_to_bytes(in_ints, num): """Convert an integer array into a byte arrays. The number of bytes forming an integer is defined by num :param in_ints: the input integers :param num: the number of bytes per int :return the integer array""" out_bytes= b"" for val in in_ints: out_bytes+=struct.pack(mmtf.utils.constants.NUM_DICT[num], val) return out_bytes
https://github.com/rcsb/mmtf-python/blob/899bb877ca1b32a9396803d38c5bf38a2520754e/mmtf/converters/converters.py#L22-L32
convert int to bool
python
def convert_to_int(value, from_base): """ Convert value to an int. :param value: the value to convert :type value: sequence of int :param int from_base: base of value :returns: the conversion result :rtype: int :raises ConvertError: if from_base is less than 2 :raises ConvertError: if elements in value outside bounds Preconditions: * all integers in value must be at least 0 * all integers in value must be less than from_base * from_base must be at least 2 Complexity: O(len(value)) """ if from_base < 2: raise BasesValueError( from_base, "from_base", "must be greater than 2" ) if any(x < 0 or x >= from_base for x in value): raise BasesValueError( value, "value", "elements must be at least 0 and less than %s" % from_base ) return reduce(lambda x, y: x * from_base + y, value, 0)
https://github.com/mulkieran/justbases/blob/dd52ff4b3d11609f54b2673599ee4eeb20f9734f/src/justbases/_nats.py#L59-L91
convert int to bool
python
def _isint(string): """ >>> _isint("123") True >>> _isint("123.45") False """ return type(string) is int or \ (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \ _isconvertible(int, string)
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/extern/tabulate.py#L254-L263
convert int to bool
python
def _str_to_bool(str_): """Convert string to bool (in argparse context).""" if str_.lower() not in ['true', 'false', 'none']: raise ValueError('Need bool; got %r' % str_) return {'true': True, 'false': False, 'none': None}[str_.lower()]
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/enumerator_generator.py#L24-L28
convert int to bool
python
def convert_to_int(value): """Attempts to convert a specified value to an integer :param value: Content to be converted into an integer :type value: string or int """ if not value: return None # Apart from numbers also accept values that end with px if isinstance(value, str): value = value.strip(' px') try: return int(value) except (TypeError, ValueError): return None
https://github.com/michaelhelmick/lassie/blob/b929f78d7e545cff5fb42eb5edfcaf396456f1ee/lassie/utils.py#L31-L48
convert int to bool
python
def _isint(string): """ >>> _isint("123") True >>> _isint("123.45") False """ return type(string) is int or \ (isinstance(string, _binary_type) or isinstance(string, string_types)) and \ _isconvertible(int, string)
https://github.com/solvebio/solvebio-python/blob/b29614643043afd19c1d8074e8f25c6700d51a73/solvebio/utils/tabulate.py#L160-L170
convert int to bool
python
def _integer_to_interval(arg, unit='s'): """ Convert integer interval with the same inner type Parameters ---------- unit : {'Y', 'M', 'W', 'D', 'h', 'm', s', 'ms', 'us', 'ns'} Returns ------- interval : interval value expression """ op = ops.IntervalFromInteger(arg, unit) return op.to_expr()
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/api.py#L1350-L1363
convert int to bool
python
def to_int(value=None, hexstr=None, text=None): """ Converts value to it's integer representation. Values are converted this way: * value: * bytes: big-endian integer * bool: True => 1, False => 0 * hexstr: interpret hex as integer * text: interpret as string of digits, like '12' => 12 """ assert_one_val(value, hexstr=hexstr, text=text) if hexstr is not None: return int(hexstr, 16) elif text is not None: return int(text) elif isinstance(value, bytes): return big_endian_to_int(value) elif isinstance(value, str): raise TypeError("Pass in strings with keyword hexstr or text") else: return int(value)
https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L118-L141
convert int to bool
python
def _bool_encode(self, d): """ Converts bool values to lowercase strings """ for k, v in d.items(): if isinstance(v, bool): d[k] = str(v).lower() return d
https://github.com/evansherlock/nytimesarticle/blob/89f551699ffb11f71b47271246d350a1043e9326/nytimesarticle.py#L46-L55
convert int to bool
python
def str_to_bool(value): """ Converts string truthy/falsey strings to a bool Empty strings are false """ if isinstance(value, basestring): value = value.strip().lower() if value in ['true', 't', 'yes', 'y']: return True elif value in ['false', 'f', 'no', 'n', '']: return False else: raise NotImplementedError("Unknown bool %s" % value) return value
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/config.py#L7-L21
convert int to bool
python
def int_to_var_bytes(x): """Converts an integer to a bitcoin variable length integer as a bytearray :param x: the integer to convert """ if x < 253: return intbytes.to_bytes(x, 1) elif x < 65536: return bytearray([253]) + intbytes.to_bytes(x, 2)[::-1] elif x < 4294967296: return bytearray([254]) + intbytes.to_bytes(x, 4)[::-1] else: return bytearray([255]) + intbytes.to_bytes(x, 8)[::-1]
https://github.com/wiggzz/siggy/blob/bfb67cbc9da3e4545b3e882bf7384fa265e6d6c1/siggy/siggy.py#L36-L48
convert int to bool
python
def is_int(value): """ Check if value is an int :type value: int, str, bytes, float, Decimal >>> is_int(123), is_int('123'), is_int(Decimal('10')) (True, True, True) >>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1')) (False, False, False) >>> is_int(object) Traceback (most recent call last): TypeError: """ ensure_instance(value, (int, str, bytes, float, Decimal)) if isinstance(value, int): return True elif isinstance(value, float): return False elif isinstance(value, Decimal): return str(value).isdigit() elif isinstance(value, (str, bytes)): return value.isdigit() raise ValueError()
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L455-L478
convert int to bool
python
def to_int(b:Any)->Union[int,List[int]]: "Convert `b` to an int or list of ints (if `is_listy`); raises exception if not convertible" if is_listy(b): return [to_int(x) for x in b] else: return int(b)
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L61-L64
convert int to bool
python
def fast_int( x, key=lambda x: x, _uni=unicodedata.digit, _first_char=POTENTIAL_FIRST_CHAR, ): """ Convert a string to a int quickly, return input as-is if not possible. We don't need to accept all input that the real fast_int accepts because natsort is controlling what is passed to this function. Parameters ---------- x : str String to attempt to convert to an int. key : callable Single-argument function to apply to *x* if conversion fails. Returns ------- *str* or *int* """ if x[0] in _first_char: try: return long(x) except ValueError: try: return _uni(x, key(x)) if len(x) == 1 else key(x) except TypeError: # pragma: no cover return key(x) else: try: return _uni(x, key(x)) if len(x) == 1 else key(x) except TypeError: # pragma: no cover return key(x)
https://github.com/SethMMorton/natsort/blob/ea0d37ef790b42c424a096e079edd9ea0d5717e3/natsort/compat/fake_fastnumbers.py#L89-L125
convert int to bool
python
def convert(self, argument): """Returns the int value of argument.""" if _is_integer_type(argument): return argument elif isinstance(argument, six.string_types): base = 10 if len(argument) > 2 and argument[0] == '0': if argument[1] == 'o': base = 8 elif argument[1] == 'x': base = 16 return int(argument, base) else: raise TypeError('Expect argument to be a string or int, found {}'.format( type(argument)))
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L254-L268
convert int to bool
python
def conv_to_float(indata, inf_str=''): """Try to convert an arbitrary string to a float. Specify what will be replaced with "Inf". Args: indata (str): String which contains a float inf_str (str): If string contains something other than a float, and you want to replace it with float("Inf"), specify that string here. Returns: float: Converted string representation """ if indata.strip() == inf_str: outdata = float('Inf') else: try: outdata = float(indata) except: raise ValueError('Unable to convert {} to float'.format(indata)) return outdata
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/utils.py#L854-L874
convert int to bool
python
def get_int(self): """ Fetch an int from the stream. :return: a 32-bit unsigned `int`. """ byte = self.get_bytes(1) if byte == max_byte: return util.inflate_long(self.get_binary()) byte += self.get_bytes(3) return struct.unpack('>I', byte)[0]
https://github.com/NikolayDachev/jadm/blob/12bb550445edfcd87506f7cba7a6a35d413c5511/lib/paramiko-1.14.1/paramiko/message.py#L132-L142
convert int to bool
python
def get_bool(self, key, default=None): u""" Возвращает значение, приведенное к булеву """ return self.get_converted( key, ConversionTypeEnum.BOOL, default=default)
https://github.com/damirazo/py-config-parser/blob/8dd6efb659b6541713875b15910ca0474723382a/config_parser/parser.py#L148-L153
convert int to bool
python
def _convert_name(self, name): """Convert ``name`` to int if it looks like an int. Otherwise, return it as is. """ if re.search('^\d+$', name): if len(name) > 1 and name[0] == '0': # Don't treat strings beginning with "0" as ints return name return int(name) return name
https://github.com/PSU-OIT-ARC/django-local-settings/blob/758810fbd9411c2046a187afcac6532155cac694/local_settings/settings.py#L251-L262
convert int to bool
python
def int_0_inf(cls, string): '''Convert string to int. If ``inf`` is supplied, it returns ``0``. ''' if string == 'inf': return 0 try: value = int(string) except ValueError as error: raise argparse.ArgumentTypeError(error) if value < 0: raise argparse.ArgumentTypeError(_('Value must not be negative.')) else: return value
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/options.py#L104-L120
convert int to bool
python
def bigint_to_string(val): """ Converts @val to a string if it is a big integer (|>2**53-1|) @val: #int or #float -> #str if @val is a big integer, otherwise @val """ if isinstance(val, _NUMBERS) and not abs(val) <= 2**53-1: return str(val) return val
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/strings.py#L91-L100
convert int to bool
python
def _string_to_int(self, string): """ Convert a string to a number, using the given alphabet.. """ number = 0 for char in string[::-1]: number = number * self._alpha_len + self._alphabet.index(char) return number
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/shortuuid/__init__.py#L30-L37
convert int to bool
python
def to_int( primitive: Primitives = None, hexstr: HexStr = None, text: str = None ) -> int: """ Converts value to its integer representation. Values are converted this way: * primitive: * bytes, bytearrays: big-endian integer * bool: True => 1, False => 0 * hexstr: interpret hex as integer * text: interpret as string of digits, like '12' => 12 """ if hexstr is not None: return int(hexstr, 16) elif text is not None: return int(text) elif isinstance(primitive, (bytes, bytearray)): return big_endian_to_int(primitive) elif isinstance(primitive, str): raise TypeError("Pass in strings with keyword hexstr or text") elif isinstance(primitive, (int, bool)): return int(primitive) else: raise TypeError( "Invalid type. Expected one of int/bool/str/bytes/bytearray. Got " "{0}".format(type(primitive)) )
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/conversions.py#L46-L74
convert int to bool
python
def num2varint(num): """ Converts a number to a variable length Int. Used for array length header :param: {number} num - The number :return: {string} hexstring of the variable Int. """ # if (typeof num !== 'number') throw new Error('VarInt must be numeric') # if (num < 0) throw new RangeError('VarInts are unsigned (> 0)') # if (!Number.isSafeInteger(num)) throw new RangeError('VarInt must be a safe integer') if num < 0xfd: return num2hexstring(num) elif num <= 0xffff: # uint16 return 'fd' + num2hexstring(number=num, size=2, little_endian=True) elif num <= 0xffffffff: # uint32 return 'fe' + num2hexstring(number=num, size=4, little_endian=True) else: # uint64 return 'ff' + num2hexstring(number=num, size=8, little_endian=True)
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/utils.py#L50-L70
convert int to bool
python
def to_int(self): """ Rounds off and converts (x,y,w,h) to int :return: a Box object with all integer values """ coord = [int(round(x)) for x in self.xy_coord()] return self.from_xy(coord[0], coord[1], coord[2], coord[3])
https://github.com/gmichaeljaison/cv-utils/blob/a8251c870165a7428d8c468a6436aa41d0cf7c09/cv_utils/bbox.py#L225-L231
convert int to bool
python
def get_int(self, key, default=None): u""" Возвращает значение, приведенное к числовому """ return self.get_converted( key, ConversionTypeEnum.INTEGER, default=default)
https://github.com/damirazo/py-config-parser/blob/8dd6efb659b6541713875b15910ca0474723382a/config_parser/parser.py#L141-L146
convert int to bool
python
def int_bytes(cls, string): '''Convert string describing size to int.''' if string[-1] in ('k', 'm'): value = cls.int_0_inf(string[:-1]) unit = string[-1] if unit == 'k': value *= 2 ** 10 else: value *= 2 ** 20 return value else: return cls.int_0_inf(string)
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/options.py#L123-L134
convert int to bool
python
def _implicit_convert(cls, arg): """Implicit conversion used for binary operations, comparisons, functions, etc. Return value should be an instance of BigFloat.""" # ints, long and floats mix freely with BigFloats, and are # converted exactly. if isinstance(arg, six.integer_types) or isinstance(arg, float): return cls.exact(arg) elif isinstance(arg, BigFloat): return arg else: raise TypeError("Unable to convert argument %s of type %s " "to BigFloat" % (arg, type(arg)))
https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L858-L871
convert int to bool
python
def element_to_int(element, attribute=None): """Convert ``element`` object to int. If attribute is not given, convert ``element.text``. :param element: ElementTree element :param attribute: attribute name :type attribute: str :returns: integer :rtype: int """ if attribute is not None: return int(element.get(attribute)) else: return int(element.text)
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_helper.py#L111-L123
convert int to bool
python
def __to_float(val, digits): """Convert val into float with digits decimal.""" try: return round(float(val), digits) except (ValueError, TypeError): return float(0)
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L97-L102
convert int to bool
python
def convert_attrs_to_bool(obj: Any, attrs: Iterable[str], default: bool = None) -> None: """ Applies :func:`convert_to_bool` to the specified attributes of an object, modifying it in place. """ for a in attrs: setattr(obj, a, convert_to_bool(getattr(obj, a), default=default))
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L90-L98
convert int to bool
python
def bin_to_int(string): """Convert a one element byte string to signed int for python 2 support.""" if isinstance(string, str): return struct.unpack("b", string)[0] else: return struct.unpack("b", bytes([string]))[0]
https://github.com/citruz/beacontools/blob/15a83e9750d0a4393f8a36868e07f6d9458253fe/beacontools/utils.py#L71-L76
convert int to bool
python
def str_to_num(i, exact_match=True): """ Attempts to convert a str to either an int or float """ # TODO: Cleanup -- this is really ugly if not isinstance(i, str): return i try: if not exact_match: return int(i) elif str(int(i)) == i: return int(i) elif str(float(i)) == i: return float(i) else: pass except ValueError: pass return i
https://github.com/rtluckie/seria/blob/8ae4f71237e69085d8f974a024720f45b34ab963/seria/utils.py#L3-L21
convert int to bool
python
def _convert_number(self, number): """Converts a number to float or int as appropriate""" number = float(number) return int(number) if number.is_integer() else float(number)
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/api.py#L46-L50
convert int to bool
python
def int_to_bytes(int_, width = None): """ .. _int_to_bytes: Converts the ``int`` ``int_`` to a ``bytes`` object. ``len(result) == width``. If ``width`` is None, a number of bytes that is able to hold the number is choosen, depending on ``int_.bit_length()``. See also: bytes_to_int_ """ if(width == None): width = int_.bit_length() byts = math.ceil(width / 8) return bytes([ (int_ >> (shift * 8)) & 0xff for shift in range(byts)])
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/engine_tools/conversions.py#L10-L25
convert int to bool
python
def do_int(value, default=0): """Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. """ try: return int(value) except (TypeError, ValueError): # this quirk is necessary so that "42.23"|int gives 42. try: return int(float(value)) except (TypeError, ValueError): return default
https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/filters.py#L405-L417
convert int to bool
python
def to_bool(x): """"Converts to a boolean in a semantically meaningful way.""" if isinstance(x, bool): return x elif isinstance(x, str): return False if x.lower() in _FALSES else True else: return bool(x)
https://github.com/Cadair/jupyter_environment_kernels/blob/3da304550b511bda7d5d39280379b5ca39bb31bc/environment_kernels/activate_helper.py#L445-L452
convert int to bool
python
def normalize_int(value: IntConvertible) -> int: """ Robust to integer conversion, handling hex values, string representations, and special cases like `0x`. """ if is_integer(value): return cast(int, value) elif is_bytes(value): return big_endian_to_int(value) elif is_hex(value) and is_0x_prefixed(value): value = cast(str, value) if len(value) == 2: return 0 else: return int(value, 16) elif is_string(value): return int(value) else: raise TypeError("Unsupported type: Got `{0}`".format(type(value)))
https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/_utils/normalization.py#L72-L90
convert int to bool
python
def convert_bytes_to_ints(in_bytes, num): """Convert a byte array into an integer array. The number of bytes forming an integer is defined by num :param in_bytes: the input bytes :param num: the number of bytes per int :return the integer array""" dt = numpy.dtype('>i' + str(num)) return numpy.frombuffer(in_bytes, dt)
https://github.com/rcsb/mmtf-python/blob/899bb877ca1b32a9396803d38c5bf38a2520754e/mmtf/converters/numpy_converters.py#L7-L15
convert int to bool
python
def convert_float(value, parameter): ''' Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, float): return value try: return float(value) except Exception as e: raise ValueError(str(e))
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L59-L71
convert int to bool
python
def bytes_to_int(bytes_, width = None): """ .. _bytes_to_int: Converts the ``bytes`` object ``bytes_`` to an ``int``. If ``width`` is none, ``width = len(byte_) * 8`` is choosen. See also: int_to_bytes_ *Example* >>> from py_register_machine2.engine_tools.conversions import * >>> i = 4012 >>> int_to_bytes(i) b'\xac\x0f' >>> bytes_to_int(int_to_bytes(i)) == i True """ if(width == None): width = len(bytes_) else: width = width // 8 if(width > len(bytes_)): padding = b"\x00" * (width - len(bytes_)) bytes_ = bytes_ + padding ints = [ (int_ << (shift * 8)) for shift, int_ in enumerate(bytes_[:width])] return sum(ints)
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/engine_tools/conversions.py#L27-L54
convert int to bool
python
def toint(number): """ Helper to return rounded int for a float or just the int it self. """ if isinstance(number, float): number = round(number, 0) return int(number)
https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/pial/helpers.py#L6-L12
convert int to bool
python
def _convert_to_float_if_possible(s): """ A small helper function to convert a string to a numeric value if appropriate :param s: the string to be converted :type s: str """ try: ret = float(s) except (ValueError, TypeError): ret = s return ret
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/operators/check_operator.py#L98-L110
convert int to bool
python
def to_bool(self, invert=False): """Return the truth value of each element.""" if invert: def function(x, y): return False if x else True else: def function(x, y): return True if x else False return self.operation(None, function)
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/traces/timeseries.py#L830-L838
convert int to bool
python
def _to_number(cls, string): """Convert string to int or float.""" try: if float(string) - int(string) == 0: return int(string) return float(string) except ValueError: try: return float(string) except ValueError: return string
https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/api.py#L35-L45
convert int to bool
python
def intToBin(i): """ Integer to two bytes """ # divide in two parts (bytes) i1 = i % 256 i2 = int(i / 256) # make string (little endian) return i.to_bytes(2, byteorder='little')
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/images2gif.py#L140-L146
convert int to bool
python
def to_int(self): """Convert vector to an integer, if possible. This is only useful for arrays filled with zero/one entries. """ num = self.to_uint() if num and self._items[-1].unbox(): return num - (1 << self.size) else: return num
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L696-L705
convert int to bool
python
def _convert_to_bytes(type_name, value): """Convert a typed value to a binary array""" int_types = {'uint8_t': 'B', 'int8_t': 'b', 'uint16_t': 'H', 'int16_t': 'h', 'uint32_t': 'L', 'int32_t': 'l'} type_name = type_name.lower() if type_name not in int_types and type_name not in ['string', 'binary']: raise ArgumentError('Type must be a known integer type, integer type array, string', known_integers=int_types.keys(), actual_type=type_name) if type_name == 'string': #value should be passed as a string bytevalue = bytes(value) elif type_name == 'binary': bytevalue = bytes(value) else: bytevalue = struct.pack("<%s" % int_types[type_name], value) return bytevalue
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L378-L396
convert int to bool
python
def cast_to_number_or_bool(inputstr): """Cast a string to int, float or bool. Return original string if it can't be converted. Scientific expression is converted into float. """ if inputstr.strip().lower() == "true": return True elif inputstr.strip().lower() == "false": return False try: return int(inputstr) except ValueError: try: return float(inputstr) except ValueError: return inputstr
https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/util.py#L68-L84
convert int to bool
python
def to_bool(value): """Converts human boolean-like values to Python boolean. Falls back to :class:`bool` when ``value`` is not recognized. :param value: the value to convert :returns: ``True`` if value is truthy, ``False`` otherwise :rtype: bool """ cases = { '0': False, 'false': False, 'no': False, '1': True, 'true': True, 'yes': True, } value = value.lower() if isinstance(value, basestring) else value return cases.get(value, bool(value))
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/helpers.py#L48-L67
convert int to bool
python
def num_to_var_int(x): """ (bitcoin-specific): convert an integer into a variable-length integer """ x = int(x) if x < 253: return from_int_to_byte(x) elif x < 65536: return from_int_to_byte(253) + encode(x, 256, 2)[::-1] elif x < 4294967296: return from_int_to_byte(254) + encode(x, 256, 4)[::-1] else: return from_int_to_byte(255) + encode(x, 256, 8)[::-1]
https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/encoding.py#L133-L148
convert int to bool
python
def to_integer(value, ctx): """ Tries conversion of any value to an integer """ if isinstance(value, bool): return 1 if value else 0 elif isinstance(value, int): return value elif isinstance(value, Decimal): try: val = int(value.to_integral_exact(ROUND_HALF_UP)) if isinstance(val, int): return val except ArithmeticError: pass elif isinstance(value, str): try: return int(value) except ValueError: pass raise EvaluationError("Can't convert '%s' to an integer" % str(value))
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L29-L50
convert int to bool
python
def text_to_bool(value: str) -> bool: """ Tries to convert a text value to a bool. If unsuccessful returns if value is None or not :param value: Value to check """ try: return bool(strtobool(value)) except (ValueError, AttributeError): return value is not None
https://github.com/notifiers/notifiers/blob/6dd8aafff86935dbb4763db9c56f9cdd7fc08b65/notifiers/utils/helpers.py#L9-L18
convert int to bool
python
def getbool(self, key, **kwargs): """ Gets the setting value as a :func:`bool` by cleverly recognizing true values. :rtype: bool """ def _string_to_bool(s): if isinstance(s, str): if s.strip().lower() in ('true', 't', '1'): return True elif s.strip().lower() in ('false', 'f', '0', 'None', 'null', ''): return False raise ValueError('Unable to get boolean value of "{}".'.format(s)) #end if return bool(s) #end def return self.get(key, cast_func=_string_to_bool, **kwargs)
https://github.com/skylander86/ycsettings/blob/3f363673a6cb1823ebb18c4d640d87aa49202344/ycsettings/settings.py#L292-L310
convert int to bool
python
def to_int(value: Any) -> int: """ Cast a value as its equivalent int for indy predicate argument. Raise ValueError for any input but int, stringified int, or boolean. :param value: value to coerce. """ if isinstance(value, (bool, int)): return int(value) return int(str(value))
https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/indytween.py#L111-L121
convert int to bool
python
def to_bool(value, do_raise=True): """Convert a string to a boolean value. If the string consists of digits, the integer value of the string is coerced to a boolean value. Otherwise, any of the strings "t", "true", "on", "y", and "yes" are considered True and any of the strings "f", "false", "off", "n", and "no" are considered False. A ValueError will be raised for any other value. """ value = value.lower() # Try it as an integer if value.isdigit(): return bool(int(value)) # OK, check it against the true/false values... if value in _str_true: return True elif value in _str_false: return False # Not recognized if do_raise: raise ValueError("invalid literal for to_bool(): %r" % value) return False
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/config.py#L228-L254
convert int to bool
python
def to_boolean(value): """ Args: value (str | unicode | None): Value to convert to bool Returns: (bool): Deduced boolean value """ if value is not None: if str(value).lower() in TRUE_TOKENS: return True vfloat = to_number(float, value) if vfloat is not None: return bool(vfloat) return False
https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/config.py#L353-L369
convert int to bool
python
def intToBin(i): """ Integer to two bytes """ # devide in two parts (bytes) i1 = i % 256 i2 = int(i / 256) # make string (little endian) return chr(i1) + chr(i2)
https://github.com/thumbor/thumbor/blob/558ccdd6e3bc29e1c9ee3687372c4b3eb05ac607/thumbor/engines/extensions/pil.py#L132-L138
convert int to bool
python
def convert(self, argument): """Converts the argument to a boolean; raise ValueError on errors.""" if isinstance(argument, str): if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) if argument == bool_argument: # The argument is a valid boolean (True, False, 0, or 1), and not just # something that always converts to bool (list, string, int, etc.). return bool_argument raise ValueError('Non-boolean argument to boolean flag', argument)
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/argument_parser.py#L270-L284
convert int to bool
python
def _tofloat(obj): """Convert to float if object is a float string.""" if "inf" in obj.lower().strip(): return obj try: return int(obj) except ValueError: try: return float(obj) except ValueError: return obj
https://github.com/pmacosta/pcsv/blob/cd1588c19b0cd58c38bc672e396db940f88ffbd7/pcsv/csv_file.py#L64-L74
convert int to bool
python
def str2int(self, num): """Converts a string into an integer. If possible, the built-in python conversion will be used for speed purposes. :param num: A string that will be converted to an integer. :rtype: integer :raise ValueError: when *num* is invalid """ radix, alphabet = self.radix, self.alphabet if radix <= 36 and alphabet[:radix].lower() == BASE85[:radix].lower(): return int(num, radix) ret = 0 lalphabet = alphabet[:radix] for char in num: if char not in lalphabet: raise ValueError("invalid literal for radix2int() with radix " "%d: '%s'" % (radix, num)) ret = ret * radix + self.cached_map[char] return ret
https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/numconv.py#L83-L105
convert int to bool
python
def cbool(value, strict=True): ''' converts a value to true or false. Python's default bool() function does not handle 'true' of 'false' strings ''' return_val = value if is_not_null(value): if isinstance(value, bool): return_val = value else: value = str(value) if value.lower() in ['true', '1', 't', 'y', 'yes']: return_val = True elif value.lower() in ['false', '0', 'n', 'no', 'f']: return_val = False else: if strict: return_val = None else: if strict: return_val = None return return_val
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L218-L237
convert int to bool
python
def safe_int_conv(number): """Safely convert a single number to integer.""" try: return int(np.array(number).astype(int, casting='safe')) except TypeError: raise ValueError('cannot safely convert {} to integer'.format(number))
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/util/normalize.py#L366-L371
convert int to bool
python
def str2bool(value): """ Args: value - text to be converted to boolean True values: y, yes, true, t, on, 1 False values: n, no, false, off, 0 """ try: if isinstance(value, (str, unicode)): return bool(util.strtobool(value)) except NameError: # python 3 if isinstance(value, str): return bool(util.strtobool(value)) return bool(value)
https://github.com/tchellomello/python-amcrest/blob/ed842139e234de2eaf6ee8fb480214711cde1249/src/amcrest/utils.py#L41-L54
convert int to bool
python
def int_convert(base): '''Convert a string to an integer. The string may start with a sign. It may be of a base other than 10. If may start with a base indicator, 0#nnnn, which we assume should override the specified base. It may also have other non-numeric characters that we can ignore. ''' CHARS = '0123456789abcdefghijklmnopqrstuvwxyz' def f(string, match, base=base): if string[0] == '-': sign = -1 else: sign = 1 if string[0] == '0' and len(string) > 2: if string[1] in 'bB': base = 2 elif string[1] in 'oO': base = 8 elif string[1] in 'xX': base = 16 else: # just go with the base specifed pass chars = CHARS[:base] string = re.sub('[^%s]' % chars, '', string.lower()) return sign * int(string, base) return f
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/parse.py#L462-L496
convert int to bool
python
def to_int16(y1, y2): """Convert two 8 bit bytes to a signed 16 bit integer.""" x = (y1) | (y2 << 8) if x >= 32768: x = -(65536 - x) return x
https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/spacemouse.py#L45-L50
convert int to bool
python
def to_bool(text): ''' Convert the string name of a boolean to that boolean value. ''' downcased_text = six.text_type(text).strip().lower() if downcased_text == 'false': return False elif downcased_text == 'true': return True return text
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L182-L192
convert int to bool
python
def _env_to_bool(val): """ Convert *val* to a bool if it's not a bool in the first place. """ if isinstance(val, bool): return val val = val.strip().lower() if val in ("1", "true", "yes"): return True return False
https://github.com/hynek/environ_config/blob/d61c0822bf0b6516932534e0496bd3f360a3e5e2/src/environ/_environ_config.py#L68-L78