def annotate_function_with_types(f): if hasattr(f, '_orig_arg_names'): arg_names = f._orig_arg_names else: arg_names = f.__code__.co_varnames[0:f.__code__.co_argcount] argtypes = [] for name in arg_names: arg_type = types.get(name, 'any') if arg_type not in VALID_ARG_TYPES: raise ValueError( "Argument type %s is not valid, must be one of %s, " "for argument %s" % (arg_type, VALID_ARG_TYPES, name)) argtypes.append(arg_type) for n in types: if n not in arg_names and n != 'result': raise ValueError("Type specified for unknown argument " + n) return_type = types.get('result', 'float') if return_type not in VALID_RETURN_TYPES: raise ValueError("Result type %s is not valid, " "must be one of %s" % (return_type, VALID_RETURN_TYPES)) f._arg_types = argtypes f._return_type = return_type f._orig_arg_names = arg_names f._annotation_attributes = getattr( f, '_annotation_attributes', []) + ['_arg_types', '_return_type'] return f
def __init__(self, data=None, uncertainty=None, unit=None, dtype=None, definition=None, reference=None, filename=None, encoder=None, checksum=None, comment=None, value=None): if data is None and value is None: raise TypeError("either data or value has to be set") if data is not None and value is not None: raise TypeError("only one of data or value can be set") self._dtype = dtype self._property = None self._unit = unit self._uncertainty = uncertainty self._dtype = dtype self._definition = definition self._reference = reference self._filename = filename self._comment = comment self._encoder = encoder if value is not None: # assign value directly (through property would raise a change-event) self._value = types.get(value, self._dtype, self._encoder) elif data is not None: if dtype is None: self._dtype = types.infer_dtype(data) self._value = data self._checksum_type = None if checksum is not None: self.checksum = checksum
def make_lob_object(response): '''This function converts the response to a LobObject and returns it ''' types = { 'service': Service, 'address': Address, 'packaging': Packaging, 'setting': Setting, 'object': Object, 'job': Job, 'postcard': Postcard, 'bank_account': BankAccount, 'check': Check } if not response: return None if isinstance(response, list): return [make_lob_object(response=data) for data in response] if not response.get('object', None): # object info not present so will make # LobObject with constituents objects data = {} for key in response.keys(): if isinstance(response[key], dict): data[key] = make_lob_object(response=response.get(key)) else: data[key] = response.get(key) return LobObject(data) if response.get('object') == 'list': # list to be returned return [make_lob_object(response=d) for d in response.get('data')] else: return types.get(response.get('object', ''), LobObject)(response)
def convert_to_stripe_object(resp, api_key): types = { "charge": Charge, "customer": Customer, "invoice": Invoice, "invoiceitem": InvoiceItem, "plan": Plan, "coupon": Coupon, "token": Token, "event": Event, "transfer": Transfer, } if isinstance(resp, list): return [convert_to_stripe_object(i, api_key) for i in resp] elif isinstance(resp, dict): resp = resp.copy() klass_name = resp.get("object") if isinstance(klass_name, basestring): klass = types.get(klass_name, StripeObject) else: klass = StripeObject return klass.construct_from(resp, api_key) else: return resp
def convert_to_stripe_object(resp, api_key): types = { 'charge': Charge, 'customer': Customer, 'invoice': Invoice, 'invoiceitem': InvoiceItem, 'plan': Plan, 'coupon': Coupon, 'token': Token, 'event': Event, 'transfer': Transfer } if isinstance(resp, list): return [convert_to_stripe_object(i, api_key) for i in resp] elif isinstance(resp, dict): resp = resp.copy() klass_name = resp.get('object') if isinstance(klass_name, basestring): klass = types.get(klass_name, StripeObject) else: klass = StripeObject return klass.construct_from(resp, api_key) else: return resp
def __init__(self, data=None, uncertainty=None, unit=None, dtype=None, definition=None, reference=None, filename=None, encoder=None, checksum=None, comment=None, value=None): if data is None and value is None: raise TypeError("either data or value has to be set") if data is not None and value is not None: raise TypeError("only one of data or value can be set") self._property = None self._unit = unit self._uncertainty = uncertainty self._dtype = dtype self._definition = definition self._reference = reference self._filename = filename self._comment = comment self._encoder = encoder if value is not None: # assign value directly (through property would raise a change-event) self._value = types.get(value, self._dtype, self._encoder) elif data is not None: if dtype is None: self._dtype = types.infer_dtype(data) self._value = data self._checksum_type = None if checksum is not None: self.checksum = checksum
def convert_to_easypost_object(response, api_key, parent=None, name=None): types = { 'Address': Address, 'ScanForm': ScanForm, 'CustomsItem': CustomsItem, 'CustomsInfo': CustomsInfo, 'Parcel': Parcel, 'Shipment': Shipment, 'Insurance': Insurance, 'Rate': Rate, 'Refund': Refund, 'Batch': Batch, 'Event': Event, 'Tracker': Tracker, 'Pickup': Pickup, 'Order': Order, 'PickupRate': PickupRate, 'PostageLabel': PostageLabel, 'CarrierAccount': CarrierAccount, 'User': User } prefixes = { 'adr': Address, 'sf': ScanForm, 'evt': Event, 'cstitem': CustomsItem, 'cstinfo': CustomsInfo, 'prcl': Parcel, 'shp': Shipment, 'ins': Insurance, 'rate': Rate, 'rfnd': Refund, 'batch': Batch, 'trk': Tracker, 'order': Order, 'pickup': Pickup, 'pickuprate': PickupRate, 'pl': PostageLabel, 'ca': CarrierAccount, 'user': User } if isinstance(response, list): return [convert_to_easypost_object(r, api_key, parent) for r in response] elif isinstance(response, dict): response = response.copy() cls_name = response.get('object', EasyPostObject) cls_id = response.get('id', None) if isinstance(cls_name, six.string_types): cls = types.get(cls_name, EasyPostObject) elif cls_id is not None: cls = prefixes.get(cls_id[0:cls_id.find('_')], EasyPostObject) else: cls = EasyPostObject return cls.construct_from(response, api_key, parent, name) else: return response
def convert_to_easypost_object(response, api_key, parent=None, name=None): types = { 'Address': Address, 'ScanForm': ScanForm, 'CustomsItem': CustomsItem, 'CustomsInfo': CustomsInfo, 'Parcel': Parcel, 'Shipment': Shipment, 'Rate': Rate, 'Refund': Refund, 'Batch': Batch, 'Event': Event, 'Tracker': Tracker, 'Pickup': Pickup, 'Order': Order, 'PickupRate': PickupRate, 'PostageLabel': PostageLabel, 'CarrierAccount': CarrierAccount, 'User': User } prefixes = { 'adr': Address, 'sf': ScanForm, 'evt': Event, 'cstitem': CustomsItem, 'cstinfo': CustomsInfo, 'prcl': Parcel, 'shp': Shipment, 'rate': Rate, 'rfnd': Refund, 'batch': Batch, 'trk': Tracker, 'order': Order, 'pickup': Pickup, 'pickuprate': PickupRate, 'pl': PostageLabel, 'ca': CarrierAccount, 'user': User } if isinstance(response, list): return [ convert_to_easypost_object(r, api_key, parent) for r in response ] elif isinstance(response, dict): response = response.copy() cls_name = response.get('object', EasyPostObject) cls_id = response.get('id', None) if isinstance(cls_name, six.string_types): cls = types.get(cls_name, EasyPostObject) elif cls_id is not None: cls = prefixes.get(cls_id[0:cls_id.find('_')], EasyPostObject) else: cls = EasyPostObject return cls.construct_from(response, api_key, parent, name) else: return response
def iterate_derived_type(name, pre, post, f): global types l = f.findall(name) for t in l: id_ = t.get("id") type_ = t.get("type") type_str = types.get(type_) if type(type_str) == str: types[id_] = pre + type_str + post
def getTypeAndEncoding(filename, types, encodings, defaultType): p, ext = os.path.splitext(filename) ext = ext.lower() if encodings.has_key(ext): enc = encodings[ext] ext = os.path.splitext(p)[1].lower() else: enc = None type = types.get(ext, defaultType) return type, enc
def dtype(self, new_type): # check if this is a valid type if not types.valid_type(new_type): raise AttributeError("'%s' is not a valid type." % new_type) # we convert the value if possible old_type = self._dtype old_value = types.set(self._value, self._dtype, self._encoder) try: new_value = types.get(old_value, new_type, self._encoder) except: # cannot convert, try the other way around try: old_value = types.set(self._value, new_type, self._encoder) new_value = types.get(old_value, new_type, self._encoder) except: #doesn't work either, therefore refuse raise ValueError("cannot convert '%s' from '%s' to '%s'" % (self.value, old_type, new_type)) self._value = new_value self._dtype = new_type
def convert_to_stripe_object(resp, api_key): types = { 'charge' : Charge, 'customer' : Customer, 'invoice' : Invoice, 'invoiceitem' : InvoiceItem } if isinstance(resp, list): return [convert_to_stripe_object(i, api_key) for i in resp] elif isinstance(resp, dict): resp = resp.copy() klass_name = resp.get('object') klass = types.get(klass_name, StripeObject) return klass.construct_from(resp, api_key) else: return resp
def add_table(self, name, columns, type_map=None, if_not_exists=False): """Add add a new table to the database. For instance you could do this: self.add_table('data', {'id':'integer', 'source':'text', 'pubmed':'integer'})""" # Check types mapping # if type_map is None and isinstance(columns, dict): types = columns if type_map is None: types = {} # Safe or unsafe # if if_not_exists: query = 'CREATE TABLE IF NOT EXISTS "%s" (%s);' else: query = 'CREATE table "%s" (%s);' # Do it # cols = ','.join(['"' + c + '"' + ' ' + types.get(c, 'text') for c in columns]) self.own_cursor.execute(query % (self.main_table, cols))
def convert_to_easypost_object(response, api_key): types = { 'Address': Address, 'ScanForm': ScanForm, 'CustomsItem': CustomsItem, 'CustomsInfo': CustomsInfo, 'Parcel': Parcel, 'Shipment': Shipment, 'Rate': Rate, 'Refund': Refund, 'Batch': Batch, 'Event': Event, 'Tracker': Tracker, 'Pickup': Pickup, 'Order': Order, 'PickupRate': PickupRate, 'PostageLabel': PostageLabel } prefixes = { 'adr': Address, 'sf': ScanForm, 'evt': Event, 'cstitem': CustomsItem, 'cstinfo': CustomsInfo, 'prcl': Parcel, 'shp': Shipment, 'rate': Rate, 'rfnd': Refund, 'batch': Batch, 'trk': Tracker, 'order': Order, 'pickup': Pickup, 'pickuprate': PickupRate, 'pl': PostageLabel } if isinstance(response, list): return [convert_to_easypost_object(i, api_key) for i in response] elif isinstance(response, dict): response = response.copy() cls_name = response.get('object', EasyPostObject) cls_id = response.get('id', None) if isinstance(cls_name, basestring): cls = types.get(cls_name, EasyPostObject) elif cls_id != None: cls = prefixes.get(cls_id[0:cls_id.find('_')], EasyPostObject) else: cls = EasyPostObject return cls.construct_from(response, api_key) else: return response
def add_table(self, name, columns, type_map=None, if_not_exists=False): """Add add a new table to the database. For instance you could do this: self.add_table('data', {'id':'integer', 'source':'text', 'pubmed':'integer'})""" # Check types mapping # if type_map is None and isinstance(columns, dict): types = columns if type_map is None: types = {} # Safe or unsafe # if if_not_exists: query = 'CREATE TABLE IF NOT EXISTS "%s" (%s);' else: query = 'CREATE table "%s" (%s);' # Do it # cols = ','.join( ['"' + c + '"' + ' ' + types.get(c, 'text') for c in columns]) self.own_cursor.execute(query % (self.main_table, cols))
def annotate_function_with_types(f): if hasattr(f, '_orig_arg_names'): arg_names = f._orig_arg_names else: arg_names = f.func_code.co_varnames[0:f.func_code.co_argcount] argtypes = [] for name in arg_names: arg_type = types.get(name, 'any') if arg_type not in VALID_ARG_TYPES: raise ValueError("Argument type %s is not valid, must be one of %s, " "for argument %s" % (arg_type, VALID_ARG_TYPES, name)) argtypes.append(arg_type) for n in types.keys(): if n not in arg_names and n!='result': raise ValueError("Type specified for unknown argument "+n) return_type = types.get('result', 'float') if return_type not in VALID_RETURN_TYPES: raise ValueError("Result type %s is not valid, " "must be one of %s" % (return_type, VALID_RETURN_TYPES)) f._arg_types = argtypes f._return_type = return_type f._orig_arg_names = arg_names f._annotation_attributes = getattr(f, '_annotation_attributes', [])+['_arg_types', '_return_type'] return f
def convert_to_stripe_object(resp, api_key): types = { 'charge' : Charge, 'customer' : Customer, 'invoice' : Invoice, 'invoiceitem' : InvoiceItem, 'plan' : Plan, 'coupon': Coupon, 'token' : Token, 'event': Event } if isinstance(resp, list): return [convert_to_stripe_object(i, api_key) for i in resp] elif isinstance(resp, dict): resp = resp.copy() klass_name = resp.get('object') if isinstance(klass_name, basestring): klass = types.get(klass_name, StripeObject) else: klass = StripeObject return klass.construct_from(resp, api_key) else: return resp
def convert_to_paysio_object(resp, api_key, headers=None): types = { 'charge' : Charge, 'customer' : Customer, 'wallet': Wallet, 'reward': Reward, 'event': Event, 'list': ListObject, 'log': Log, 'payout': Payout, 'coupon': Coupon, } if isinstance(resp, list): return [convert_to_paysio_object(i, api_key) for i in resp] elif isinstance(resp, dict): resp = resp.copy() klass_name = resp.get('object') if isinstance(klass_name, basestring): klass = types.get(klass_name, PaysioObject) else: klass = PaysioObject obj = klass.construct_from(resp, api_key) obj._last_response_headers = headers return obj else: return resp
def __debugfunction(self, debug_type, debug_msg): if not self.verbose: return types = {pycurl.INFOTYPE_DATA_IN: 'Input data', pycurl.INFOTYPE_DATA_OUT: 'Output data', pycurl.INFOTYPE_HEADER_IN: 'Input header', pycurl.INFOTYPE_HEADER_OUT: 'Output header', pycurl.INFOTYPE_TEXT: 'Text',} debug_str = types.get(debug_type) try: unicode(debug_msg, 'utf-8') except UnicodeError: pass else: fd = file('/tmp/debug.curl', 'a') fd.write("debug(%s): %s \n" % (debug_str, str(debug_msg)))
def type_map(code): global ti global types global filename if ti == 0: ti = 1 types = {} f = ET.parse(filename) iterate_type("FundamentalType", f) iterate_type("Typedef", f) iterate_type("Class", f) iterate_type("Struct", f) iterate_derived_type("CvQualifiedType", "const ", "", f) iterate_derived_type("ReferenceType", "", "&", f) iterate_derived_type("PointerType", "", "*", f) out = types.get(code) if type(out) == str: return out else: return code
def date(self, new_value): self._date = types.get(new_value, "date")
def value(self, new_string): self._value = types.get(new_string, self._dtype, self._encoder)