idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
18,900
def read_and_redirect ( request , notification_id ) : notification_page = reverse ( 'notifications:all' ) next_page = request . GET . get ( 'next' , notification_page ) if is_safe_url ( next_page ) : target = next_page else : target = notification_page try : user_nf = request . user . notifications . get ( pk = notification_id ) if not user_nf . read : user_nf . mark_as_read ( ) except Notification . DoesNotExist : pass return HttpResponseRedirect ( target )
Marks the supplied notification as read and then redirects to the supplied URL from the next URL parameter .
131
21
18,901
def get_motion_detection ( self ) : url = ( '%s/ISAPI/System/Video/inputs/' 'channels/1/motionDetection' ) % self . root_url try : response = self . hik_request . get ( url , timeout = CONNECT_TIMEOUT ) except ( requests . exceptions . RequestException , requests . exceptions . ConnectionError ) as err : _LOGGING . error ( 'Unable to fetch MotionDetection, error: %s' , err ) self . motion_detection = None return self . motion_detection if response . status_code == requests . codes . unauthorized : _LOGGING . error ( 'Authentication failed' ) self . motion_detection = None return self . motion_detection if response . status_code != requests . codes . ok : # If we didn't receive 200, abort _LOGGING . debug ( 'Unable to fetch motion detection.' ) self . motion_detection = None return self . motion_detection try : tree = ET . fromstring ( response . text ) ET . register_namespace ( "" , self . namespace ) enabled = tree . find ( self . element_query ( 'enabled' ) ) if enabled is not None : self . _motion_detection_xml = tree self . motion_detection = { 'true' : True , 'false' : False } [ enabled . text ] return self . motion_detection except AttributeError as err : _LOGGING . error ( 'Entire response: %s' , response . text ) _LOGGING . error ( 'There was a problem: %s' , err ) self . motion_detection = None return self . motion_detection
Fetch current motion state from camera
374
7
18,902
def _set_motion_detection ( self , enable ) : url = ( '%s/ISAPI/System/Video/inputs/' 'channels/1/motionDetection' ) % self . root_url enabled = self . _motion_detection_xml . find ( self . element_query ( 'enabled' ) ) if enabled is None : _LOGGING . error ( "Couldn't find 'enabled' in the xml" ) _LOGGING . error ( 'XML: %s' , ET . tostring ( self . _motion_detection_xml ) ) return enabled . text = 'true' if enable else 'false' xml = ET . tostring ( self . _motion_detection_xml ) try : response = self . hik_request . put ( url , data = xml , timeout = CONNECT_TIMEOUT ) except ( requests . exceptions . RequestException , requests . exceptions . ConnectionError ) as err : _LOGGING . error ( 'Unable to set MotionDetection, error: %s' , err ) return if response . status_code == requests . codes . unauthorized : _LOGGING . error ( 'Authentication failed' ) return if response . status_code != requests . codes . ok : # If we didn't receive 200, abort _LOGGING . error ( 'Unable to set motion detection: %s' , response . text ) self . motion_detection = enable
Set desired motion detection state on camera
312
7
18,903
def add_update_callback ( self , callback , sensor ) : self . _updateCallbacks . append ( [ callback , sensor ] ) _LOGGING . debug ( 'Added update callback to %s on %s' , callback , sensor )
Register as callback for when a matching device sensor changes .
52
11
18,904
def initialize ( self ) : device_info = self . get_device_info ( ) if device_info is None : self . name = None self . cam_id = None self . event_states = None return for key in device_info : if key == 'deviceName' : self . name = device_info [ key ] elif key == 'deviceID' : if len ( device_info [ key ] ) > 10 : self . cam_id = device_info [ key ] else : self . cam_id = uuid . uuid4 ( ) events_available = self . get_event_triggers ( ) if events_available : for event , channel_list in events_available . items ( ) : for channel in channel_list : try : self . event_states . setdefault ( SENSOR_MAP [ event . lower ( ) ] , [ ] ) . append ( [ False , channel , 0 , datetime . datetime . now ( ) ] ) except KeyError : # Sensor type doesn't have a known friendly name # We can't reliably handle it at this time... _LOGGING . warning ( 'Sensor type "%s" is unsupported.' , event ) _LOGGING . debug ( 'Initialized Dictionary: %s' , self . event_states ) else : _LOGGING . debug ( 'No Events available in dictionary.' ) self . get_motion_detection ( )
Initialize deviceInfo and available events .
303
8
18,905
def get_event_triggers ( self ) : events = { } nvrflag = False event_xml = [ ] url = '%s/ISAPI/Event/triggers' % self . root_url try : response = self . hik_request . get ( url , timeout = CONNECT_TIMEOUT ) if response . status_code == requests . codes . not_found : # Try alternate URL for triggers _LOGGING . debug ( 'Using alternate triggers URL.' ) url = '%s/Event/triggers' % self . root_url response = self . hik_request . get ( url ) except ( requests . exceptions . RequestException , requests . exceptions . ConnectionError ) as err : _LOGGING . error ( 'Unable to fetch events, error: %s' , err ) return None if response . status_code != 200 : # If we didn't recieve 200, abort return None # pylint: disable=too-many-nested-blocks try : content = ET . fromstring ( response . text ) if content [ 0 ] . find ( self . element_query ( 'EventTrigger' ) ) : event_xml = content [ 0 ] . findall ( self . element_query ( 'EventTrigger' ) ) elif content . find ( self . element_query ( 'EventTrigger' ) ) : # This is either an NVR or a rebadged camera event_xml = content . findall ( self . element_query ( 'EventTrigger' ) ) for eventtrigger in event_xml : ettype = eventtrigger . find ( self . element_query ( 'eventType' ) ) # Catch empty xml defintions if ettype is None : break etnotify = eventtrigger . find ( self . element_query ( 'EventTriggerNotificationList' ) ) etchannel = None etchannel_num = 0 for node_name in CHANNEL_NAMES : etchannel = eventtrigger . find ( self . element_query ( node_name ) ) if etchannel is not None : try : # Need to make sure this is actually a number etchannel_num = int ( etchannel . text ) if etchannel_num > 1 : # Must be an nvr nvrflag = True break except ValueError : # Field must not be an integer pass if etnotify : for notifytrigger in etnotify : ntype = notifytrigger . find ( self . element_query ( 'notificationMethod' ) ) if ntype . text == 'center' or ntype . text == 'HTTP' : """ If we got this far we found an event that we want to track. """ events . setdefault ( ettype . text , [ ] ) . append ( etchannel_num ) except ( AttributeError , ET . ParseError ) as err : _LOGGING . error ( 'There was a problem finding an element: %s' , err ) return None if nvrflag : self . device_type = NVR_DEVICE else : self . device_type = CAM_DEVICE _LOGGING . debug ( 'Processed %s as %s Device.' , self . cam_id , self . device_type ) _LOGGING . debug ( 'Found events: %s' , events ) self . hik_request . close ( ) return events
Returns dict of supported events . Key = Event Type List = Channels that have that event activated
714
19
18,906
def get_device_info ( self ) : device_info = { } url = '%s/ISAPI/System/deviceInfo' % self . root_url using_digest = False try : response = self . hik_request . get ( url , timeout = CONNECT_TIMEOUT ) if response . status_code == requests . codes . unauthorized : _LOGGING . debug ( 'Basic authentication failed. Using digest.' ) self . hik_request . auth = HTTPDigestAuth ( self . usr , self . pwd ) using_digest = True response = self . hik_request . get ( url ) if response . status_code == requests . codes . not_found : # Try alternate URL for deviceInfo _LOGGING . debug ( 'Using alternate deviceInfo URL.' ) url = '%s/System/deviceInfo' % self . root_url response = self . hik_request . get ( url ) # Seems to be difference between camera and nvr, they can't seem to # agree if they should 404 or 401 first if not using_digest and response . status_code == requests . codes . unauthorized : _LOGGING . debug ( 'Basic authentication failed. Using digest.' ) self . hik_request . auth = HTTPDigestAuth ( self . usr , self . pwd ) using_digest = True response = self . hik_request . get ( url ) except ( requests . exceptions . RequestException , requests . exceptions . ConnectionError ) as err : _LOGGING . error ( 'Unable to fetch deviceInfo, error: %s' , err ) return None if response . status_code == requests . codes . unauthorized : _LOGGING . error ( 'Authentication failed' ) return None if response . status_code != requests . codes . ok : # If we didn't receive 200, abort _LOGGING . debug ( 'Unable to fetch device info.' ) return None try : tree = ET . fromstring ( response . text ) # Try to fetch namespace from XML nmsp = tree . tag . split ( '}' ) [ 0 ] . strip ( '{' ) self . namespace = nmsp if nmsp . startswith ( 'http' ) else XML_NAMESPACE _LOGGING . debug ( 'Using Namespace: %s' , self . namespace ) for item in tree : tag = item . tag . split ( '}' ) [ 1 ] device_info [ tag ] = item . text return device_info except AttributeError as err : _LOGGING . error ( 'Entire response: %s' , response . text ) _LOGGING . error ( 'There was a problem: %s' , err ) return None
Parse deviceInfo into dictionary .
596
7
18,907
def watchdog_handler ( self ) : _LOGGING . debug ( '%s Watchdog expired. Resetting connection.' , self . name ) self . watchdog . stop ( ) self . reset_thrd . set ( )
Take care of threads if wachdog expires .
48
10
18,908
def disconnect ( self ) : _LOGGING . debug ( 'Disconnecting from stream: %s' , self . name ) self . kill_thrd . set ( ) self . thrd . join ( ) _LOGGING . debug ( 'Event stream thread for %s is stopped' , self . name ) self . kill_thrd . clear ( )
Disconnect from event stream .
78
6
18,909
def alert_stream ( self , reset_event , kill_event ) : _LOGGING . debug ( 'Stream Thread Started: %s, %s' , self . name , self . cam_id ) start_event = False parse_string = "" fail_count = 0 url = '%s/ISAPI/Event/notification/alertStream' % self . root_url # pylint: disable=too-many-nested-blocks while True : try : stream = self . hik_request . get ( url , stream = True , timeout = ( CONNECT_TIMEOUT , READ_TIMEOUT ) ) if stream . status_code == requests . codes . not_found : # Try alternate URL for stream url = '%s/Event/notification/alertStream' % self . root_url stream = self . hik_request . get ( url , stream = True ) if stream . status_code != requests . codes . ok : raise ValueError ( 'Connection unsucessful.' ) else : _LOGGING . debug ( '%s Connection Successful.' , self . name ) fail_count = 0 self . watchdog . start ( ) for line in stream . iter_lines ( ) : # _LOGGING.debug('Processing line from %s', self.name) # filter out keep-alive new lines if line : str_line = line . decode ( "utf-8" , "ignore" ) # New events start with --boundry if str_line . find ( '<EventNotificationAlert' ) != - 1 : # Start of event message start_event = True parse_string += str_line elif str_line . find ( '</EventNotificationAlert>' ) != - 1 : # Message end found found parse_string += str_line start_event = False if parse_string : tree = ET . fromstring ( parse_string ) self . process_stream ( tree ) self . update_stale ( ) parse_string = "" else : if start_event : parse_string += str_line if kill_event . is_set ( ) : # We were asked to stop the thread so lets do so. break elif reset_event . is_set ( ) : # We need to reset the connection. raise ValueError ( 'Watchdog failed.' ) if kill_event . is_set ( ) : # We were asked to stop the thread so lets do so. _LOGGING . debug ( 'Stopping event stream thread for %s' , self . name ) self . watchdog . stop ( ) self . hik_request . close ( ) return elif reset_event . is_set ( ) : # We need to reset the connection. raise ValueError ( 'Watchdog failed.' ) except ( ValueError , requests . exceptions . ConnectionError , requests . exceptions . ChunkedEncodingError ) as err : fail_count += 1 reset_event . clear ( ) _LOGGING . warning ( '%s Connection Failed (count=%d). Waiting %ss. Err: %s' , self . name , fail_count , ( fail_count * 5 ) + 5 , err ) parse_string = "" self . watchdog . stop ( ) self . hik_request . close ( ) time . sleep ( 5 ) self . update_stale ( ) time . sleep ( fail_count * 5 ) continue
Open event stream .
725
4
18,910
def process_stream ( self , tree ) : try : etype = SENSOR_MAP [ tree . find ( self . element_query ( 'eventType' ) ) . text . lower ( ) ] estate = tree . find ( self . element_query ( 'eventState' ) ) . text echid = tree . find ( self . element_query ( 'channelID' ) ) if echid is None : # Some devices use a different key echid = tree . find ( self . element_query ( 'dynChannelID' ) ) echid = int ( echid . text ) ecount = tree . find ( self . element_query ( 'activePostCount' ) ) . text except ( AttributeError , KeyError , IndexError ) as err : _LOGGING . error ( 'Problem finding attribute: %s' , err ) return # Take care of keep-alive if len ( etype ) > 0 and etype == 'Video Loss' : self . watchdog . pet ( ) # Track state if it's in the event list. if len ( etype ) > 0 : state = self . fetch_attributes ( etype , echid ) if state : # Determine if state has changed # If so, publish, otherwise do nothing estate = ( estate == 'active' ) old_state = state [ 0 ] attr = [ estate , echid , int ( ecount ) , datetime . datetime . now ( ) ] self . update_attributes ( etype , echid , attr ) if estate != old_state : self . publish_changes ( etype , echid ) self . watchdog . pet ( )
Process incoming event stream packets .
353
6
18,911
def update_stale ( self ) : # Some events don't post an inactive XML, only active. # If we don't get an active update for 5 seconds we can # assume the event is no longer active and update accordingly. for etype , echannels in self . event_states . items ( ) : for eprop in echannels : if eprop [ 3 ] is not None : sec_elap = ( ( datetime . datetime . now ( ) - eprop [ 3 ] ) . total_seconds ( ) ) # print('Seconds since last update: {}'.format(sec_elap)) if sec_elap > 5 and eprop [ 0 ] is True : _LOGGING . debug ( 'Updating stale event %s on CH(%s)' , etype , eprop [ 1 ] ) attr = [ False , eprop [ 1 ] , eprop [ 2 ] , datetime . datetime . now ( ) ] self . update_attributes ( etype , eprop [ 1 ] , attr ) self . publish_changes ( etype , eprop [ 1 ] )
Update stale active statuses
240
5
18,912
def publish_changes ( self , etype , echid ) : _LOGGING . debug ( '%s Update: %s, %s' , self . name , etype , self . fetch_attributes ( etype , echid ) ) signal = 'ValueChanged.{}' . format ( self . cam_id ) sender = '{}.{}' . format ( etype , echid ) if dispatcher : dispatcher . send ( signal = signal , sender = sender ) self . _do_update_callback ( '{}.{}.{}' . format ( self . cam_id , etype , echid ) )
Post updates for specified event type .
137
7
18,913
def start ( self ) : self . _timer = Timer ( self . time , self . handler ) self . _timer . daemon = True self . _timer . start ( ) return
Starts the watchdog timer .
39
6
18,914
def flip_motion ( self , value ) : if value : self . cam . enable_motion_detection ( ) else : self . cam . disable_motion_detection ( )
Toggle motion detection
39
4
18,915
def update_callback ( self , msg ) : print ( 'Callback: {}' . format ( msg ) ) print ( '{}:{} @ {}' . format ( self . name , self . _sensor_state ( ) , self . _sensor_last_update ( ) ) )
get updates .
63
3
18,916
def render ( self , renderer = None , * * kwargs ) : return Markup ( get_renderer ( current_app , renderer ) ( * * kwargs ) . visit ( self ) )
Render the navigational item using a renderer .
46
10
18,917
def visit_object ( self , node ) : if current_app . debug : return tags . comment ( 'no implementation in {} to render {}' . format ( self . __class__ . __name__ , node . __class__ . __name__ , ) ) return ''
Fallback rendering for objects .
58
6
18,918
def register_renderer ( app , id , renderer , force = True ) : renderers = app . extensions . setdefault ( 'nav_renderers' , { } ) if force : renderers [ id ] = renderer else : renderers . setdefault ( id , renderer )
Registers a renderer on the application .
62
9
18,919
def get_renderer ( app , id ) : renderer = app . extensions . get ( 'nav_renderers' , { } ) [ id ] if isinstance ( renderer , tuple ) : mod_name , cls_name = renderer mod = import_module ( mod_name ) cls = mod for name in cls_name . split ( '.' ) : cls = getattr ( cls , name ) return cls return renderer
Retrieve a renderer .
99
6
18,920
def init_app ( self , app ) : if not hasattr ( app , 'extensions' ) : app . extensions = { } app . extensions [ 'nav' ] = self app . add_template_global ( self . elems , 'nav' ) # register some renderers for args in self . _renderers : register_renderer ( app , * args )
Initialize an application .
80
5
18,921
def navigation ( self , id = None ) : def wrapper ( f ) : self . register_element ( id or f . __name__ , f ) return f return wrapper
Function decorator for navbar registration .
36
8
18,922
def renderer ( self , id = None , force = True ) : def _ ( cls ) : name = cls . __name__ sn = name [ 0 ] + re . sub ( r'([A-Z])' , r'_\1' , name [ 1 : ] ) self . _renderers . append ( ( id or sn . lower ( ) , cls , force ) ) return cls return _
Class decorator for Renderers .
91
7
18,923
def parse_time ( time ) : if isinstance ( time , datetime . datetime ) : return time return datetime . datetime . strptime ( time , DATETIME_FORMAT_OPENVPN )
Parses date and time from input string in OpenVPN logging format .
48
15
18,924
def decrypt ( self , key , dev_addr ) : sequence_counter = int ( self . FCntUp ) return loramac_decrypt ( self . payload_hex , sequence_counter , key , dev_addr )
Decrypt the actual payload in this LoraPayload .
48
12
18,925
def parse ( self ) : status = Status ( ) self . expect_line ( Status . client_list . label ) status . updated_at = self . expect_tuple ( Status . updated_at . label ) status . client_list . update ( { text_type ( c . real_address ) : c for c in self . _parse_fields ( Client , Status . routing_table . label ) } ) status . routing_table . update ( { text_type ( r . virtual_address ) : r for r in self . _parse_fields ( Routing , Status . global_stats . label ) } ) status . global_stats = GlobalStats ( ) status . global_stats . max_bcast_mcast_queue_len = self . expect_tuple ( GlobalStats . max_bcast_mcast_queue_len . label ) self . expect_line ( self . terminator ) return status
Parses the status log .
198
7
18,926
def parse_status ( status_log , encoding = 'utf-8' ) : if isinstance ( status_log , bytes ) : status_log = status_log . decode ( encoding ) parser = LogParser . fromstring ( status_log ) return parser . parse ( )
Parses the status log of OpenVPN .
59
10
18,927
def version ( self ) : res = self . client . service . Version ( ) return '.' . join ( [ ustr ( x ) for x in res [ 0 ] ] )
Return version of the TR DWE .
38
8
18,928
def system_info ( self ) : res = self . client . service . SystemInfo ( ) res = { ustr ( x [ 0 ] ) : x [ 1 ] for x in res [ 0 ] } to_str = lambda arr : '.' . join ( [ ustr ( x ) for x in arr [ 0 ] ] ) res [ 'OSVersion' ] = to_str ( res [ 'OSVersion' ] ) res [ 'RuntimeVersion' ] = to_str ( res [ 'RuntimeVersion' ] ) res [ 'Version' ] = to_str ( res [ 'Version' ] ) res [ 'Name' ] = ustr ( res [ 'Name' ] ) res [ 'Server' ] = ustr ( res [ 'Server' ] ) res [ 'LocalNameCheck' ] = ustr ( res [ 'LocalNameCheck' ] ) res [ 'UserHostAddress' ] = ustr ( res [ 'UserHostAddress' ] ) return res
Return system information .
207
4
18,929
def sources ( self ) : res = self . client . service . Sources ( self . userdata , 0 ) return [ ustr ( x [ 0 ] ) for x in res [ 0 ] ]
Return available sources of data .
41
6
18,930
def status ( self , record = None ) : if record is not None : self . last_status = { 'Source' : ustr ( record [ 'Source' ] ) , 'StatusType' : ustr ( record [ 'StatusType' ] ) , 'StatusCode' : record [ 'StatusCode' ] , 'StatusMessage' : ustr ( record [ 'StatusMessage' ] ) , 'Request' : ustr ( record [ 'Instrument' ] ) } return self . last_status
Extract status from the retrieved data and save it as a property of an object . If record with data is not specified then the status of previous operation is returned .
107
33
18,931
def construct_request ( ticker , fields = None , date = None , date_from = None , date_to = None , freq = None ) : if isinstance ( ticker , basestring ) : request = ticker elif hasattr ( ticker , '__len__' ) : request = ',' . join ( ticker ) else : raise ValueError ( 'ticker should be either string or list/array of strings' ) if fields is not None : if isinstance ( fields , basestring ) : request += '~=' + fields elif isinstance ( fields , list ) and len ( fields ) > 0 : request += '~=' + ',' . join ( fields ) if date is not None : request += '~@' + pd . to_datetime ( date ) . strftime ( '%Y-%m-%d' ) else : if date_from is not None : request += '~' + pd . to_datetime ( date_from ) . strftime ( '%Y-%m-%d' ) if date_to is not None : request += '~:' + pd . to_datetime ( date_to ) . strftime ( '%Y-%m-%d' ) if freq is not None : request += '~' + freq return request
Construct a request string for querying TR DWE .
289
11
18,932
def fetch ( self , tickers , fields = None , date = None , date_from = None , date_to = None , freq = 'D' , only_data = True , static = False ) : if static : query = self . construct_request ( tickers , fields , date , freq = 'REP' ) else : query = self . construct_request ( tickers , fields , date , date_from , date_to , freq ) raw = self . request ( query ) if static : data , metadata = self . parse_record_static ( raw ) elif isinstance ( tickers , basestring ) or len ( tickers ) == 1 : data , metadata = self . parse_record ( raw ) elif hasattr ( tickers , '__len__' ) : metadata = pd . DataFrame ( ) data = { } for indx in range ( len ( tickers ) ) : dat , meta = self . parse_record ( raw , indx ) data [ tickers [ indx ] ] = dat metadata = metadata . append ( meta , ignore_index = False ) data = pd . concat ( data ) else : raise DatastreamException ( ( 'First argument should be either ticker or ' 'list of tickers' ) ) if only_data : return data else : return data , metadata
Fetch data from TR DWE .
288
8
18,933
def get_OHLCV ( self , ticker , date = None , date_from = None , date_to = None ) : data , meta = self . fetch ( ticker + "~OHLCV" , None , date , date_from , date_to , 'D' , only_data = False ) return data
Get Open High Low Close prices and daily Volume for a given ticker .
71
15
18,934
def get_constituents ( self , index_ticker , date = None , only_list = False ) : if date is not None : str_date = pd . to_datetime ( date ) . strftime ( '%m%y' ) else : str_date = '' # Note: ~XREF is equal to the following large request # ~REP~=DSCD,EXMNEM,GEOG,GEOGC,IBTKR,INDC,INDG,INDM,INDX,INDXEG,INDXFS,INDXL, # INDXS,ISIN,ISINID,LOC,MNEM,NAME,SECD,TYPE fields = '~REP~=NAME' if only_list else '~XREF' query = 'L' + index_ticker + str_date + fields raw = self . request ( query ) res , metadata = self . parse_record_static ( raw ) return res
Get a list of all constituents of a given index .
205
11
18,935
def check_encoding_chars ( encoding_chars ) : if not isinstance ( encoding_chars , collections . MutableMapping ) : raise InvalidEncodingChars required = { 'FIELD' , 'COMPONENT' , 'SUBCOMPONENT' , 'REPETITION' , 'ESCAPE' } missing = required - set ( encoding_chars . keys ( ) ) if missing : raise InvalidEncodingChars ( 'Missing required encoding chars' ) values = [ v for k , v in encoding_chars . items ( ) if k in required ] if len ( values ) > len ( set ( values ) ) : raise InvalidEncodingChars ( 'Found duplicate encoding chars' )
Validate the given encoding chars
156
6
18,936
def check_validation_level ( validation_level ) : if validation_level not in ( VALIDATION_LEVEL . QUIET , VALIDATION_LEVEL . STRICT , VALIDATION_LEVEL . TOLERANT ) : raise UnknownValidationLevel
Validate the given validation level
59
6
18,937
def load_library ( version ) : check_version ( version ) module_name = SUPPORTED_LIBRARIES [ version ] lib = sys . modules . get ( module_name ) if lib is None : lib = importlib . import_module ( module_name ) return lib
Load the correct module according to the version
60
8
18,938
def load_reference ( name , element_type , version ) : lib = load_library ( version ) ref = lib . get ( name , element_type ) return ref
Look for an element of the given type name and version and return its reference structure
36
16
18,939
def find_reference ( name , element_types , version ) : lib = load_library ( version ) ref = lib . find ( name , element_types ) return ref
Look for an element of the given name and version into the given types and return its reference structure
36
19
18,940
def get_date_info ( value ) : fmt = _get_date_format ( value ) dt_value = _datetime_obj_factory ( value , fmt ) return dt_value , fmt
Returns the datetime object and the format of the date in input
46
13
18,941
def get_timestamp_info ( value ) : value , offset = _split_offset ( value ) fmt , microsec = _get_timestamp_format ( value ) dt_value = _datetime_obj_factory ( value , fmt ) return dt_value , fmt , offset , microsec
Returns the datetime object the format the offset and the microsecond of the timestamp in input
67
18
18,942
def get_datetime_info ( value ) : date_value , offset = _split_offset ( value ) date_format = _get_date_format ( date_value [ : 8 ] ) try : timestamp_form , microsec = _get_timestamp_format ( date_value [ 8 : ] ) except ValueError : if not date_value [ 8 : ] : # if it's empty timestamp_form , microsec = '' , 4 else : raise ValueError ( '{0} is not an HL7 valid date value' . format ( value ) ) fmt = '{0}{1}' . format ( date_format , timestamp_form ) dt_value = _datetime_obj_factory ( date_value , fmt ) return dt_value , fmt , offset , microsec
Returns the datetime object the format the offset and the microsecond of the datetime in input
174
19
18,943
def is_base_datatype ( datatype , version = None ) : if version is None : version = get_default_version ( ) lib = load_library ( version ) return lib . is_base_datatype ( datatype )
Check if the given datatype is a base datatype of the specified version
55
17
18,944
def get_ordered_children ( self ) : ordered_keys = self . element . ordered_children if self . element . ordered_children is not None else [ ] children = [ self . indexes . get ( k , None ) for k in ordered_keys ] return children
Return the list of children ordered according to the element structure
57
11
18,945
def insert ( self , index , child , by_name_index = - 1 ) : if self . _can_add_child ( child ) : try : if by_name_index == - 1 : self . indexes [ child . name ] . append ( child ) else : self . indexes [ child . name ] . insert ( by_name_index , child ) except KeyError : self . indexes [ child . name ] = [ child ] self . list . insert ( index , child )
Add the child at the given index
104
7
18,946
def append ( self , child ) : if self . _can_add_child ( child ) : if self . element == child . parent : self . _remove_from_traversal_index ( child ) self . list . append ( child ) try : self . indexes [ child . name ] . append ( child ) except KeyError : self . indexes [ child . name ] = [ child ] elif self . element == child . traversal_parent : try : self . traversal_indexes [ child . name ] . append ( child ) except KeyError : self . traversal_indexes [ child . name ] = [ child ]
Append the given child
136
5
18,947
def set ( self , name , value , index = - 1 ) : # just copy the first element of the ElementProxy (e.g. message.pid = message2.pid) if isinstance ( value , ElementProxy ) : value = value [ 0 ] . to_er7 ( ) name = name . upper ( ) reference = None if name is None else self . element . find_child_reference ( name ) child_ref , child_name = ( None , None ) if reference is None else ( reference [ 'ref' ] , reference [ 'name' ] ) if isinstance ( value , basestring ) : # if the value is a basestring, parse it child = self . element . parse_child ( value , child_name = child_name , reference = child_ref ) elif isinstance ( value , Element ) : # it is already an instance of Element child = value elif isinstance ( value , BaseDataType ) : child = self . create_element ( name , False , reference ) child . value = value else : raise ChildNotValid ( value , child_name ) if child . name != child_name : # e.g. message.pid = Segment('SPM') is forbidden raise ChildNotValid ( value , child_name ) child_to_remove = self . child_at_index ( child_name , index ) if child_to_remove is None : self . append ( child ) else : self . replace_child ( child_to_remove , child ) # a set has been called, change the temporary parent to be the actual one self . element . set_parent_to_traversal ( )
Assign the value to the child having the given name at the index position
355
15
18,948
def remove ( self , child ) : try : if self . element == child . traversal_parent : self . _remove_from_traversal_index ( child ) else : self . _remove_from_index ( child ) self . list . remove ( child ) except : raise
Remove the given child from both child list and child indexes
61
11
18,949
def remove_by_name ( self , name , index = 0 ) : child = self . child_at_index ( name , index ) self . remove ( child ) return child
Remove the child having the given name at the given position
38
11
18,950
def child_at_index ( self , name , index ) : def _finder ( n , i ) : try : return self . indexes [ n ] [ i ] except ( KeyError , IndexError ) : try : return self . traversal_indexes [ n ] [ i ] except ( KeyError , IndexError ) : return None child = _finder ( name , index ) child_name = None if name is None else self . _find_name ( name ) if child_name != name : child = _finder ( child_name , index ) return child
Return the child named name at the given index
119
9
18,951
def create_element ( self , name , traversal_parent = False , reference = None ) : if reference is None : reference = self . element . find_child_reference ( name ) if reference is not None : cls = reference [ 'cls' ] element_name = reference [ 'name' ] kwargs = { 'reference' : reference [ 'ref' ] , 'validation_level' : self . element . validation_level , 'version' : self . element . version } if not traversal_parent : kwargs [ 'parent' ] = self . element else : kwargs [ 'traversal_parent' ] = self . element return cls ( element_name , * * kwargs ) else : raise ChildNotFound ( name )
Create an element having the given name
167
7
18,952
def _find_name ( self , name ) : name = name . upper ( ) element = self . element . find_child_reference ( name ) return element [ 'name' ] if element is not None else None
Find the reference of a child having the given name
46
10
18,953
def get_structure ( element , reference = None ) : if reference is None : try : reference = load_reference ( element . name , element . classname , element . version ) except ( ChildNotFound , KeyError ) : raise InvalidName ( element . classname , element . name ) if not isinstance ( reference , collections . Sequence ) : raise Exception return ElementFinder . _parse_structure ( element , reference )
Get the element structure
91
4
18,954
def _parse_structure ( element , reference ) : data = { 'reference' : reference } content_type = reference [ 0 ] # content type can be sequence, choice or leaf if content_type in ( 'sequence' , 'choice' ) : children = reference [ 1 ] ordered_children = [ ] structure = { } structure_by_longname = { } repetitions = { } counters = collections . defaultdict ( int ) for c in children : child_name , child_ref , cardinality , cls = c k = child_name if child_name not in structure else '{0}_{1}' . format ( child_name , counters [ child_name ] ) structure [ k ] = { "ref" : child_ref , "name" : k , "cls" : element . child_classes [ cls ] } try : structure_by_longname [ child_ref [ 3 ] ] = structure [ k ] except IndexError : pass counters [ child_name ] += 1 repetitions [ k ] = cardinality ordered_children . append ( k ) data [ 'repetitions' ] = repetitions data [ 'ordered_children' ] = ordered_children data [ 'structure_by_name' ] = structure data [ 'structure_by_longname' ] = structure_by_longname if len ( reference ) > 5 : datatype , long_name , table , max_length = reference [ 2 : ] data [ 'datatype' ] = datatype data [ 'table' ] = table data [ 'long_name' ] = long_name return data
Parse the given reference
349
5
18,955
def to_mllp ( self , encoding_chars = None , trailing_children = False ) : if encoding_chars is None : encoding_chars = self . encoding_chars return "{0}{1}{2}{3}{2}" . format ( MLLP_ENCODING_CHARS . SB , self . to_er7 ( encoding_chars , trailing_children ) , MLLP_ENCODING_CHARS . CR , MLLP_ENCODING_CHARS . EB )
Returns the er7 representation of the message wrapped with mllp encoding characters
113
15
18,956
def get_app ( self ) : # First see to connection stack ctx = connection_stack . top if ctx is not None : return ctx . app # Next return app from instance cache if self . app is not None : return self . app # Something went wrong, in most cases app just not instantiated yet # and we cannot locate it raise RuntimeError ( 'Flask application not registered on Redis instance ' 'and no applcation bound to current context' )
Get current app from Flast stack to use .
99
10
18,957
def init_app ( self , app , config_prefix = None ) : # Put redis to application extensions if 'redis' not in app . extensions : app . extensions [ 'redis' ] = { } # Which config prefix to use, custom or default one? self . config_prefix = config_prefix = config_prefix or 'REDIS' # No way to do registration two times if config_prefix in app . extensions [ 'redis' ] : raise ValueError ( 'Already registered config prefix {0!r}.' . format ( config_prefix ) ) # Start reading configuration, define converters to use and key func # to prepend config prefix to key value converters = { 'port' : int } convert = lambda arg , value : ( converters [ arg ] ( value ) if arg in converters else value ) key = lambda param : '{0}_{1}' . format ( config_prefix , param ) # Which redis connection class to use? klass = app . config . get ( key ( 'CLASS' ) , RedisClass ) # Import connection class if it stil path notation if isinstance ( klass , string_types ) : klass = import_string ( klass ) # Should we use URL configuration url = app . config . get ( key ( 'URL' ) ) # If should, parse URL and store values to application config to later # reuse if necessary if url : urlparse . uses_netloc . append ( 'redis' ) url = urlparse . urlparse ( url ) # URL could contains host, port, user, password and db values app . config [ key ( 'HOST' ) ] = url . hostname app . config [ key ( 'PORT' ) ] = url . port or 6379 app . config [ key ( 'USER' ) ] = url . username app . config [ key ( 'PASSWORD' ) ] = url . password db = url . path . replace ( '/' , '' ) app . config [ key ( 'DB' ) ] = db if db . isdigit ( ) else None # Host is not a mandatory key if you want to use connection pool. But # when present and starts with file:// or / use it as unix socket path host = app . config . get ( key ( 'HOST' ) ) if host and ( host . startswith ( 'file://' ) or host . startswith ( '/' ) ) : app . config . pop ( key ( 'HOST' ) ) app . config [ key ( 'UNIX_SOCKET_PATH' ) ] = host args = self . _build_connection_args ( klass ) kwargs = dict ( [ ( arg , convert ( arg , app . config [ key ( arg . upper ( ) ) ] ) ) for arg in args if key ( arg . upper ( ) ) in app . config ] ) # Initialize connection and store it to extensions connection = klass ( * * kwargs ) app . extensions [ 'redis' ] [ config_prefix ] = connection # Include public methods to current instance self . _include_public_methods ( connection )
Actual method to read redis settings from app configuration initialize Redis connection and copy all public connection methods to current instance .
671
25
18,958
def _build_connection_args ( self , klass ) : bases = [ base for base in klass . __bases__ if base is not object ] all_args = [ ] for cls in [ klass ] + bases : try : args = inspect . getfullargspec ( cls . __init__ ) . args except AttributeError : args = inspect . getargspec ( cls . __init__ ) . args for arg in args : if arg in all_args : continue all_args . append ( arg ) all_args . remove ( 'self' ) return all_args
Read connection args spec exclude self from list of possible
128
10
18,959
def _include_public_methods ( self , connection ) : for attr in dir ( connection ) : value = getattr ( connection , attr ) if attr . startswith ( '_' ) or not callable ( value ) : continue self . __dict__ [ attr ] = self . _wrap_public_method ( attr )
Include public methods from Redis connection to current instance .
76
12
18,960
def prepare ( self ) : self . __make_scubadir ( ) if self . is_remote_docker : ''' Docker is running remotely (e.g. boot2docker on OSX). We don't need to do any user setup whatsoever. TODO: For now, remote instances won't have any .scubainit See: https://github.com/JonathonReinhart/scuba/issues/17 ''' raise ScubaError ( 'Remote docker not supported (DOCKER_HOST is set)' ) # Docker is running natively self . __setup_native_run ( ) # Apply environment vars from .scuba.yml self . env_vars . update ( self . context . environment )
Prepare to run the docker command
158
7
18,961
def add_env ( self , name , val ) : if name in self . env_vars : raise KeyError ( name ) self . env_vars [ name ] = val
Add an environment variable to the docker run invocation
39
9
18,962
def __locate_scubainit ( self ) : pkg_path = os . path . dirname ( __file__ ) self . scubainit_path = os . path . join ( pkg_path , 'scubainit' ) if not os . path . isfile ( self . scubainit_path ) : raise ScubaError ( 'scubainit not found at "{}"' . format ( self . scubainit_path ) )
Determine path to scubainit binary
104
10
18,963
def __load_config ( self ) : # top_path is where .scuba.yml is found, and becomes the top of our bind mount. # top_rel is the relative path from top_path to the current working directory, # and is where we'll set the working directory in the container (relative to # the bind mount point). try : top_path , top_rel = find_config ( ) self . config = load_config ( os . path . join ( top_path , SCUBA_YML ) ) except ConfigNotFoundError as cfgerr : # SCUBA_YML can be missing if --image was given. # In this case, we assume a default config if not self . image_override : raise ScubaError ( str ( cfgerr ) ) top_path , top_rel = os . getcwd ( ) , '' self . config = ScubaConfig ( image = None ) except ConfigError as cfgerr : raise ScubaError ( str ( cfgerr ) ) # Mount scuba root directory at the same path in the container... self . add_volume ( top_path , top_path ) # ...and set the working dir relative to it self . set_workdir ( os . path . join ( top_path , top_rel ) ) self . add_env ( 'SCUBA_ROOT' , top_path )
Find and load . scuba . yml
299
9
18,964
def __make_scubadir ( self ) : self . __scubadir_hostpath = tempfile . mkdtemp ( prefix = 'scubadir' ) self . __scubadir_contpath = '/.scuba' self . add_volume ( self . __scubadir_hostpath , self . __scubadir_contpath )
Make temp directory where all ancillary files are bind - mounted
83
13
18,965
def __setup_native_run ( self ) : # These options are appended to mounted volume arguments # NOTE: This tells Docker to re-label the directory for compatibility # with SELinux. See `man docker-run` for more information. self . vol_opts = [ 'z' ] # Pass variables to scubainit self . add_env ( 'SCUBAINIT_UMASK' , '{:04o}' . format ( get_umask ( ) ) ) if not self . as_root : self . add_env ( 'SCUBAINIT_UID' , os . getuid ( ) ) self . add_env ( 'SCUBAINIT_GID' , os . getgid ( ) ) if self . verbose : self . add_env ( 'SCUBAINIT_VERBOSE' , 1 ) # Copy scubainit into the container # We make a copy because Docker 1.13 gets pissed if we try to re-label # /usr, and Fedora 28 gives an AVC denial. scubainit_cpath = self . copy_scubadir_file ( 'scubainit' , self . scubainit_path ) # Hooks for name in ( 'root' , 'user' , ) : self . __generate_hook_script ( name ) # allocate TTY if scuba's output is going to a terminal # and stdin is not redirected if sys . stdout . isatty ( ) and sys . stdin . isatty ( ) : self . add_option ( '--tty' ) # Process any aliases try : context = self . config . process_command ( self . user_command ) except ConfigError as cfgerr : raise ScubaError ( str ( cfgerr ) ) if self . image_override : context . image = self . image_override if not context . script : # No user-provided command; we want to run the image's default command verbose_msg ( 'No user command; getting command from image' ) default_cmd = get_image_command ( context . image ) if not default_cmd : raise ScubaError ( 'No command given and no image-specified command' ) verbose_msg ( '{} Cmd: "{}"' . format ( context . image , default_cmd ) ) context . script = [ shell_quote_cmd ( default_cmd ) ] # Make scubainit the real entrypoint, and use the defined entrypoint as # the docker command (if it exists) self . add_option ( '--entrypoint={}' . format ( scubainit_cpath ) ) self . docker_cmd = [ ] if self . entrypoint_override is not None : # --entrypoint takes precedence if self . entrypoint_override != '' : self . docker_cmd = [ self . entrypoint_override ] elif context . entrypoint is not None : # then .scuba.yml if context . entrypoint != '' : self . docker_cmd = [ context . entrypoint ] else : ep = get_image_entrypoint ( context . image ) if ep : self . docker_cmd = ep # The user command is executed via a generated shell script with self . open_scubadir_file ( 'command.sh' , 'wt' ) as f : self . docker_cmd += [ '/bin/sh' , f . container_path ] writeln ( f , '#!/bin/sh' ) writeln ( f , '# Auto-generated from scuba' ) writeln ( f , 'set -e' ) for cmd in context . script : writeln ( f , cmd ) self . context = context
Normally if the user provides no command to docker run the image s default CMD is run . Because we set the entrypiont scuba must emulate the default behavior itself .
808
36
18,966
def open_scubadir_file ( self , name , mode ) : path = os . path . join ( self . __scubadir_hostpath , name ) assert not os . path . exists ( path ) # Make any directories required mkdir_p ( os . path . dirname ( path ) ) f = File ( path , mode ) f . container_path = os . path . join ( self . __scubadir_contpath , name ) return f
Opens a file in the scubadir
103
10
18,967
def copy_scubadir_file ( self , name , source ) : dest = os . path . join ( self . __scubadir_hostpath , name ) assert not os . path . exists ( dest ) shutil . copy2 ( source , dest ) return os . path . join ( self . __scubadir_contpath , name )
Copies source into the scubadir
78
9
18,968
def format_cmdline ( args , maxwidth = 80 ) : # Leave room for the space and backslash at the end of each line maxwidth -= 2 def lines ( ) : line = '' for a in ( shell_quote ( a ) for a in args ) : # If adding this argument will make the line too long, # yield the current line, and start a new one. if len ( line ) + len ( a ) + 1 > maxwidth : yield line line = '' # Append this argument to the current line, separating # it by a space from the existing arguments. if line : line += ' ' + a else : line = a yield line return ' \\\n' . join ( lines ( ) )
Format args into a shell - quoted command line .
153
10
18,969
def parse_env_var ( s ) : parts = s . split ( '=' , 1 ) if len ( parts ) == 2 : k , v = parts return ( k , v ) k = parts [ 0 ] return ( k , os . getenv ( k , '' ) )
Parse an environment variable string
60
6
18,970
def __wrap_docker_exec ( func ) : def call ( * args , * * kwargs ) : try : return func ( * args , * * kwargs ) except OSError as e : if e . errno == errno . ENOENT : raise DockerExecuteError ( 'Failed to execute docker. Is it installed?' ) raise return call
Wrap a function to raise DockerExecuteError on ENOENT
80
14
18,971
def docker_inspect ( image ) : args = [ 'docker' , 'inspect' , '--type' , 'image' , image ] p = Popen ( args , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) stdout , stderr = p . communicate ( ) stdout = stdout . decode ( 'utf-8' ) stderr = stderr . decode ( 'utf-8' ) if not p . returncode == 0 : if 'no such image' in stderr . lower ( ) : raise NoSuchImageError ( image ) raise DockerError ( 'Failed to inspect image: {}' . format ( stderr . strip ( ) ) ) return json . loads ( stdout ) [ 0 ]
Inspects a docker image
170
6
18,972
def docker_pull ( image ) : args = [ 'docker' , 'pull' , image ] # If this fails, the default docker stdout/stderr looks good to the user. ret = call ( args ) if ret != 0 : raise DockerError ( 'Failed to pull image "{}"' . format ( image ) )
Pulls an image
71
4
18,973
def get_image_command ( image ) : info = docker_inspect_or_pull ( image ) try : return info [ 'Config' ] [ 'Cmd' ] except KeyError as ke : raise DockerError ( 'Failed to inspect image: JSON result missing key {}' . format ( ke ) )
Gets the default command for an image
66
8
18,974
def get_image_entrypoint ( image ) : info = docker_inspect_or_pull ( image ) try : return info [ 'Config' ] [ 'Entrypoint' ] except KeyError as ke : raise DockerError ( 'Failed to inspect image: JSON result missing key {}' . format ( ke ) )
Gets the image entrypoint
68
6
18,975
def make_vol_opt ( hostdir , contdir , options = None ) : vol = '--volume={}:{}' . format ( hostdir , contdir ) if options != None : if isinstance ( options , str ) : options = ( options , ) vol += ':' + ',' . join ( options ) return vol
Generate a docker volume option
71
6
18,976
def find_config ( ) : cross_fs = 'SCUBA_DISCOVERY_ACROSS_FILESYSTEM' in os . environ path = os . getcwd ( ) rel = '' while True : if os . path . exists ( os . path . join ( path , SCUBA_YML ) ) : return path , rel if not cross_fs and os . path . ismount ( path ) : msg = '{} not found here or any parent up to mount point {}' . format ( SCUBA_YML , path ) + '\nStopping at filesystem boundary (SCUBA_DISCOVERY_ACROSS_FILESYSTEM not set).' raise ConfigNotFoundError ( msg ) # Traverse up directory hierarchy path , rest = os . path . split ( path ) if not rest : raise ConfigNotFoundError ( '{} not found here or any parent directories' . format ( SCUBA_YML ) ) # Accumulate the relative path back to where we started rel = os . path . join ( rest , rel )
Search up the diretcory hierarchy for . scuba . yml
236
14
18,977
def _process_script_node ( node , name ) : if isinstance ( node , basestring ) : # The script is just the text itself return [ node ] if isinstance ( node , dict ) : # There must be a "script" key, which must be a list of strings script = node . get ( 'script' ) if not script : raise ConfigError ( "{}: must have a 'script' subkey" . format ( name ) ) if isinstance ( script , list ) : return script if isinstance ( script , basestring ) : return [ script ] raise ConfigError ( "{}.script: must be a string or list" . format ( name ) ) raise ConfigError ( "{}: must be string or dict" . format ( name ) )
Process a script - type node
162
6
18,978
def process_command ( self , command ) : result = ScubaContext ( ) result . script = None result . image = self . image result . entrypoint = self . entrypoint result . environment = self . environment . copy ( ) if command : alias = self . aliases . get ( command [ 0 ] ) if not alias : # Command is not an alias; use it as-is. result . script = [ shell_quote_cmd ( command ) ] else : # Using an alias # Does this alias override the image and/or entrypoint? if alias . image : result . image = alias . image if alias . entrypoint is not None : result . entrypoint = alias . entrypoint # Merge/override the environment if alias . environment : result . environment . update ( alias . environment ) if len ( alias . script ) > 1 : # Alias is a multiline script; no additional # arguments are allowed in the scuba invocation. if len ( command ) > 1 : raise ConfigError ( 'Additional arguments not allowed with multi-line aliases' ) result . script = alias . script else : # Alias is a single-line script; perform substituion # and add user arguments. command . pop ( 0 ) result . script = [ alias . script [ 0 ] + ' ' + shell_quote_cmd ( command ) ] result . script = flatten_list ( result . script ) return result
Processes a user command using aliases
297
7
18,979
def open ( self , filename ) : # Ensure old file is closed before opening a new one self . close ( ) self . _f = open ( filename , 'rb' ) self . _dbtype = struct . unpack ( 'B' , self . _f . read ( 1 ) ) [ 0 ] self . _dbcolumn = struct . unpack ( 'B' , self . _f . read ( 1 ) ) [ 0 ] self . _dbyear = struct . unpack ( 'B' , self . _f . read ( 1 ) ) [ 0 ] self . _dbmonth = struct . unpack ( 'B' , self . _f . read ( 1 ) ) [ 0 ] self . _dbday = struct . unpack ( 'B' , self . _f . read ( 1 ) ) [ 0 ] self . _ipv4dbcount = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ] self . _ipv4dbaddr = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ] self . _ipv6dbcount = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ] self . _ipv6dbaddr = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ] self . _ipv4indexbaseaddr = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ] self . _ipv6indexbaseaddr = struct . unpack ( '<I' , self . _f . read ( 4 ) ) [ 0 ]
Opens a database file
372
5
18,980
def _parse_addr ( self , addr ) : ipv = 0 try : socket . inet_pton ( socket . AF_INET6 , addr ) # Convert ::FFFF:x.y.z.y to IPv4 if addr . lower ( ) . startswith ( '::ffff:' ) : try : socket . inet_pton ( socket . AF_INET , addr ) ipv = 4 except : ipv = 6 else : ipv = 6 except : socket . inet_pton ( socket . AF_INET , addr ) ipv = 4 return ipv
Parses address and returns IP version . Raises exception on invalid argument
125
15
18,981
def rates_for_location ( self , postal_code , location_deets = None ) : request = self . _get ( "rates/" + postal_code , location_deets ) return self . responder ( request )
Shows the sales tax rates for a given location .
49
11
18,982
def tax_for_order ( self , order_deets ) : request = self . _post ( 'taxes' , order_deets ) return self . responder ( request )
Shows the sales tax that should be collected for a given order .
40
14
18,983
def list_orders ( self , params = None ) : request = self . _get ( 'transactions/orders' , params ) return self . responder ( request )
Lists existing order transactions .
36
6
18,984
def show_order ( self , order_id ) : request = self . _get ( 'transactions/orders/' + str ( order_id ) ) return self . responder ( request )
Shows an existing order transaction .
42
7
18,985
def create_order ( self , order_deets ) : request = self . _post ( 'transactions/orders' , order_deets ) return self . responder ( request )
Creates a new order transaction .
40
7
18,986
def update_order ( self , order_id , order_deets ) : request = self . _put ( "transactions/orders/" + str ( order_id ) , order_deets ) return self . responder ( request )
Updates an existing order transaction .
51
7
18,987
def delete_order ( self , order_id ) : request = self . _delete ( "transactions/orders/" + str ( order_id ) ) return self . responder ( request )
Deletes an existing order transaction .
41
7
18,988
def list_refunds ( self , params = None ) : request = self . _get ( 'transactions/refunds' , params ) return self . responder ( request )
Lists existing refund transactions .
40
6
18,989
def show_refund ( self , refund_id ) : request = self . _get ( 'transactions/refunds/' + str ( refund_id ) ) return self . responder ( request )
Shows an existing refund transaction .
45
7
18,990
def create_refund ( self , refund_deets ) : request = self . _post ( 'transactions/refunds' , refund_deets ) return self . responder ( request )
Creates a new refund transaction .
43
7
18,991
def update_refund ( self , refund_id , refund_deets ) : request = self . _put ( 'transactions/refunds/' + str ( refund_id ) , refund_deets ) return self . responder ( request )
Updates an existing refund transaction .
55
7
18,992
def delete_refund ( self , refund_id ) : request = self . _delete ( 'transactions/refunds/' + str ( refund_id ) ) return self . responder ( request )
Deletes an existing refund transaction .
45
7
18,993
def list_customers ( self , params = None ) : request = self . _get ( 'customers' , params ) return self . responder ( request )
Lists existing customers .
35
5
18,994
def show_customer ( self , customer_id ) : request = self . _get ( 'customers/' + str ( customer_id ) ) return self . responder ( request )
Shows an existing customer .
41
6
18,995
def create_customer ( self , customer_deets ) : request = self . _post ( 'customers' , customer_deets ) return self . responder ( request )
Creates a new customer .
39
6
18,996
def update_customer ( self , customer_id , customer_deets ) : request = self . _put ( "customers/" + str ( customer_id ) , customer_deets ) return self . responder ( request )
Updates an existing customer .
50
6
18,997
def delete_customer ( self , customer_id ) : request = self . _delete ( "customers/" + str ( customer_id ) ) return self . responder ( request )
Deletes an existing customer .
40
6
18,998
def validate_address ( self , address_deets ) : request = self . _post ( 'addresses/validate' , address_deets ) return self . responder ( request )
Validates a customer address and returns back a collection of address matches .
41
14
18,999
def validate ( self , vat_deets ) : request = self . _get ( 'validation' , vat_deets ) return self . responder ( request )
Validates an existing VAT identification number against VIES .
38
11