idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
32,200
def frombinary ( self , s ) : entrylen = struct . calcsize ( self . ENTRYSTRUCT ) p = 0 while p < len ( s ) : ( slen , dpos , dlen , ulen , flag , typcd ) = struct . unpack ( self . ENTRYSTRUCT , s [ p : p + entrylen ] ) nmlen = slen - entrylen p = p + entrylen ( nm , ) = struct . unpack ( `nmlen` + 's' , s [ p : p + n...
Decode the binary string into an in memory list .
32,201
def tobinary ( self ) : entrylen = struct . calcsize ( self . ENTRYSTRUCT ) rslt = [ ] for ( dpos , dlen , ulen , flag , typcd , nm ) in self . data : nmlen = len ( nm ) + 1 toclen = nmlen + entrylen if toclen % 16 == 0 : pad = '\0' else : padlen = 16 - ( toclen % 16 ) pad = '\0' * padlen nmlen = nmlen + padlen rslt . ...
Return self as a binary string .
32,202
def add ( self , dpos , dlen , ulen , flag , typcd , nm ) : self . data . append ( ( dpos , dlen , ulen , flag , typcd , nm ) )
Add an entry to the table of contents .
32,203
def find ( self , name ) : for i , nm in enumerate ( self . data ) : if nm [ - 1 ] == name : return i return - 1
Return the index of the toc entry with name NAME .
32,204
def checkmagic ( self ) : if self . len : self . lib . seek ( self . start + self . len , 0 ) else : self . lib . seek ( 0 , 2 ) filelen = self . lib . tell ( ) if self . len : self . lib . seek ( self . start + self . len - self . TRLLEN , 0 ) else : self . lib . seek ( - self . TRLLEN , 2 ) ( magic , totallen , tocpo...
Verify that self is a valid CArchive .
32,205
def loadtoc ( self ) : self . toc = self . TOCTMPLT ( ) self . lib . seek ( self . pkgstart + self . tocpos ) tocstr = self . lib . read ( self . toclen ) self . toc . frombinary ( tocstr )
Load the table of contents into memory .
32,206
def extract ( self , name ) : if type ( name ) == type ( '' ) : ndx = self . toc . find ( name ) if ndx == - 1 : return None else : ndx = name ( dpos , dlen , ulen , flag , typcd , nm ) = self . toc . get ( ndx ) self . lib . seek ( self . pkgstart + dpos ) rslt = self . lib . read ( dlen ) if flag == 2 : global AES im...
Get the contents of an entry .
32,207
def contents ( self ) : rslt = [ ] for ( dpos , dlen , ulen , flag , typcd , nm ) in self . toc : rslt . append ( nm ) return rslt
Return the names of the entries
32,208
def add ( self , entry ) : ( nm , pathnm , flag , typcd ) = entry [ : 4 ] try : if typcd in ( 'o' , 'd' ) : s = '' flag = 0 elif typcd == 's' : s = open ( pathnm , 'rU' ) . read ( ) s = s + '\n\0' else : s = open ( pathnm , 'rb' ) . read ( ) except IOError : print "Cannot find ('%s', '%s', %s, '%s')" % ( nm , pathnm , ...
Add an ENTRY to the CArchive .
32,209
def save_toc ( self , tocpos ) : self . tocpos = tocpos tocstr = self . toc . tobinary ( ) self . toclen = len ( tocstr ) self . lib . write ( tocstr )
Save the table of contents to disk .
32,210
def save_trailer ( self , tocpos ) : totallen = tocpos + self . toclen + self . TRLLEN pyvers = sys . version_info [ 0 ] * 10 + sys . version_info [ 1 ] trl = struct . pack ( self . TRLSTRUCT , self . MAGIC , totallen , tocpos , self . toclen , pyvers ) self . lib . write ( trl )
Save the trailer to disk .
32,211
def openEmbedded ( self , name ) : ndx = self . toc . find ( name ) if ndx == - 1 : raise KeyError , "Member '%s' not found in %s" % ( name , self . path ) ( dpos , dlen , ulen , flag , typcd , nm ) = self . toc . get ( ndx ) if flag : raise ValueError , "Cannot open compressed archive %s in place" return CArchive ( se...
Open a CArchive of name NAME embedded within this CArchive .
32,212
def _find_hstreaming ( ) : global WARNED_HADOOP_HOME , HADOOP_STREAMING_PATH_CACHE if HADOOP_STREAMING_PATH_CACHE : return HADOOP_STREAMING_PATH_CACHE try : search_root = os . environ [ 'HADOOP_HOME' ] except KeyError : search_root = '/' cmd = 'find %s -name hadoop*streaming*.jar' % ( search_root ) p = subprocess . Pop...
Finds the whole path to the hadoop streaming jar .
32,213
def _listeq_to_dict ( jobconfs ) : if not isinstance ( jobconfs , dict ) : jobconfs = dict ( x . split ( '=' , 1 ) for x in jobconfs ) return dict ( ( str ( k ) , str ( v ) ) for k , v in jobconfs . items ( ) )
Convert iterators of key = val into a dictionary with later values taking priority .
32,214
def launch_frozen ( in_name , out_name , script_path , frozen_tar_path = None , temp_path = '_hadoopy_temp' , cache = True , check_script = False , ** kw ) : if ( ( 'files' in kw and isinstance ( kw [ 'files' ] , ( str , unicode ) ) ) or ( 'jobconfs' in kw and isinstance ( kw [ 'jobconfs' ] , ( str , unicode ) ) ) or (...
Freezes a script and then launches it .
32,215
def include_library ( libname ) : if exclude_list : if exclude_list . search ( libname ) and not include_list . search ( libname ) : return False else : return True else : return True
Check if a dynamic library should be included with application or not .
32,216
def mac_set_relative_dylib_deps ( libname ) : from PyInstaller . lib . macholib import util from PyInstaller . lib . macholib . MachO import MachO if os . path . basename ( libname ) in _BOOTLOADER_FNAMES : return def match_func ( pth ) : if not util . in_system_path ( pth ) : return os . path . join ( '@executable_pat...
On Mac OS X set relative paths to dynamic library dependencies of libname .
32,217
def from_settings ( settings ) : connection_type = settings . get ( 'RABBITMQ_CONNECTION_TYPE' , RABBITMQ_CONNECTION_TYPE ) queue_name = settings . get ( 'RABBITMQ_QUEUE_NAME' , RABBITMQ_QUEUE_NAME ) connection_parameters = settings . get ( 'RABBITMQ_CONNECTION_PARAMETERS' , RABBITMQ_CONNECTION_PARAMETERS ) connection ...
Factory method that returns an instance of channel
32,218
def setup_rabbitmq ( self ) : if not self . rabbitmq_key : self . rabbitmq_key = '{}:start_urls' . format ( self . name ) self . server = connection . from_settings ( self . crawler . settings ) self . crawler . signals . connect ( self . spider_idle , signal = signals . spider_idle ) self . crawler . signals . connect...
Setup RabbitMQ connection .
32,219
def schedule_next_request ( self ) : req = self . next_request ( ) if req : self . crawler . engine . crawl ( req , spider = self )
Schedules a request if exists .
32,220
def set_flags ( obj , flag_field , flags ) : for flag in flags : if flag [ 1 ] & flag_field : obj . __dict__ [ flag [ 0 ] ] = True else : obj . __dict__ [ flag [ 0 ] ] = False
Will process the flags and set attributes in the object accordingly .
32,221
def ask_pascal_16 ( self , next_rva_ptr ) : length = self . __get_pascal_16_length ( ) if length == ( next_rva_ptr - ( self . rva_ptr + 2 ) ) / 2 : self . length = length return True return False
The next RVA is taken to be the one immediately following this one . Such RVA could indicate the natural end of the string and will be checked with the possible length contained in the first word .
32,222
def add ( self , txt , indent = 0 ) : if isinstance ( txt , unicode ) : try : txt = str ( txt ) except UnicodeEncodeError : s = [ ] for c in txt : try : s . append ( str ( c ) ) except UnicodeEncodeError : s . append ( repr ( c ) ) txt = '' . join ( s ) self . text . append ( ' ' * indent + txt )
Adds some text no newline will be appended . The text can be indented with the optional argument indent .
32,223
def contains_offset ( self , offset ) : if self . PointerToRawData is None : return False return ( adjust_FileAlignment ( self . PointerToRawData , self . pe . OPTIONAL_HEADER . FileAlignment ) <= offset < adjust_FileAlignment ( self . PointerToRawData , self . pe . OPTIONAL_HEADER . FileAlignment ) + self . SizeOfRawD...
Check whether the section contains the file offset provided .
32,224
def parse_resource_entry ( self , rva ) : try : data = self . get_data ( rva , Structure ( self . __IMAGE_RESOURCE_DIRECTORY_ENTRY_format__ ) . sizeof ( ) ) except PEFormatError , excp : return None resource = self . __unpack_data__ ( self . __IMAGE_RESOURCE_DIRECTORY_ENTRY_format__ , data , file_offset = self . get_of...
Parse a directory entry from the resources directory .
32,225
def parse_imports ( self , original_first_thunk , first_thunk , forwarder_chain ) : imported_symbols = [ ] ilt = self . get_import_table ( original_first_thunk ) iat = self . get_import_table ( first_thunk ) if ( not iat or len ( iat ) == 0 ) and ( not ilt or len ( ilt ) == 0 ) : raise PEFormatError ( 'Invalid Import T...
Parse the imported symbols . It will fill a list which will be available as the dictionary attribute imports . Its keys will be the DLL names and the values all the symbols imported from that object .
32,226
def get_data ( self , rva = 0 , length = None ) : s = self . get_section_by_rva ( rva ) if length : end = rva + length else : end = None if not s : if rva < len ( self . header ) : return self . header [ rva : end ] if rva < len ( self . __data__ ) : return self . __data__ [ rva : end ] raise PEFormatError , 'data at R...
Get data regardless of the section where it lies on . Given a RVA and the size of the chunk to retrieve this method will find the section where the data lies and return the data .
32,227
def get_rva_from_offset ( self , offset ) : s = self . get_section_by_offset ( offset ) if not s : if self . sections : lowest_rva = min ( [ adjust_SectionAlignment ( s . VirtualAddress , self . OPTIONAL_HEADER . SectionAlignment , self . OPTIONAL_HEADER . FileAlignment ) for s in self . sections ] ) if offset < lowest...
Get the RVA corresponding to this file offset .
32,228
def get_offset_from_rva ( self , rva ) : s = self . get_section_by_rva ( rva ) if not s : if rva < len ( self . __data__ ) : return rva raise PEFormatError , 'data at RVA can\'t be fetched. Corrupt header?' return s . get_offset_from_rva ( rva )
Get the file offset corresponding to this RVA . Given a RVA this method will find the section where the data lies and return the offset within the file .
32,229
def get_string_at_rva ( self , rva ) : s = self . get_section_by_rva ( rva ) if not s : return self . get_string_from_data ( 0 , self . __data__ [ rva : rva + MAX_STRING_LENGTH ] ) return self . get_string_from_data ( 0 , s . get_data ( rva , length = MAX_STRING_LENGTH ) )
Get an ASCII string located at the given address .
32,230
def get_string_from_data ( self , offset , data ) : b = None try : b = data [ offset ] except IndexError : return '' s = '' while ord ( b ) : s += b offset += 1 try : b = data [ offset ] except IndexError : break return s
Get an ASCII string from within the data .
32,231
def set_bytes_at_rva ( self , rva , data ) : offset = self . get_physical_by_rva ( rva ) if not offset : raise False return self . set_bytes_at_offset ( offset , data )
Overwrite with the given string the bytes at the file offset corresponding to the given RVA . Return True if successful False otherwise . It can fail if the offset is outside the file s boundaries .
32,232
def merge_modified_section_data ( self ) : for section in self . sections : section_data_start = adjust_FileAlignment ( section . PointerToRawData , self . OPTIONAL_HEADER . FileAlignment ) section_data_end = section_data_start + section . SizeOfRawData if section_data_start < len ( self . __data__ ) and section_data_e...
Update the PE image content with any individual section data that has been modified .
32,233
def is_driver ( self ) : if hasattr ( self , 'DIRECTORY_ENTRY_IMPORT' ) : if set ( ( 'ntoskrnl.exe' , 'hal.dll' , 'ndis.sys' , 'bootvid.dll' , 'kdcom.dll' ) ) . intersection ( [ imp . dll . lower ( ) for imp in self . DIRECTORY_ENTRY_IMPORT ] ) : return True return False
Check whether the file is a Windows driver . This will return true only if there are reliable indicators of the image being a driver .
32,234
def _copytree ( src , dst ) : try : os . makedirs ( dst ) except OSError : pass for file in os . listdir ( src ) : try : shutil . copy2 ( '%s/%s' % ( src , file ) , '%s/%s' % ( dst , file ) ) except IOError , e : try : shutil . copytree ( '%s/%s' % ( src , file ) , '%s/%s' % ( dst , file ) ) except OSError : raise e
Similar to shutils . copytree except that dst is already there
32,235
def _md5_file ( fn , block_size = 1048576 ) : h = hashlib . md5 ( ) with open ( fn ) as fp : d = 1 while d : d = fp . read ( block_size ) h . update ( d ) return h . hexdigest ( )
Builds the MD5 of a file block by block
32,236
def freeze_script ( script_path , cache = True , temp_path = '_hadoopy_temp' ) : script_abspath = os . path . abspath ( script_path ) if not os . path . exists ( script_abspath ) : raise ValueError ( 'Script [%s] does not exist.' % script_abspath ) try : if not cache : raise KeyError cmds , frozen_tar_path = FREEZE_CAC...
Freezes a script puts it on hdfs and gives you the path
32,237
def freeze ( script_path , target_dir = 'frozen' , ** kw ) : cmds = [ ] freeze_start_time = time . time ( ) logging . debug ( '/\\%s%s Output%s/\\' % ( '-' * 10 , 'Pyinstaller' , '-' * 10 ) ) orig_dir = os . path . abspath ( '.' ) script_path = os . path . abspath ( script_path ) try : os . chdir ( target_dir ) cmds +=...
Wraps pyinstaller and provides an easy to use interface
32,238
def freeze_to_tar ( script_path , freeze_fn , extra_files = None ) : if not extra_files : extra_files = [ ] freeze_dir = tempfile . mkdtemp ( ) try : cmds = freeze ( script_path , target_dir = freeze_dir ) if freeze_fn . endswith ( '.tar.gz' ) : mode = 'w|gz' elif freeze_fn . endswith ( '.tar' ) : mode = 'w' else : rai...
Freezes a script to a . tar or . tar . gz file
32,239
def mobile_template ( template ) : def decorator ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : ctx = stack . top if ctx is not None and hasattr ( ctx , 'request' ) : request = ctx . request is_mobile = getattr ( request , 'MOBILE' , None ) kwargs [ 'template' ] = re . sub ( r'{(.+?)}' , r'\1' i...
Mark a function as mobile - ready and pass a mobile template if MOBILE .
32,240
def mobilized ( normal_fn ) : def decorator ( mobile_fn ) : @ functools . wraps ( mobile_fn ) def wrapper ( * args , ** kwargs ) : ctx = stack . top if ctx is not None and hasattr ( ctx , 'request' ) : request = ctx . request if not request . MOBILE : return normal_fn ( * args , ** kwargs ) return mobile_fn ( * args , ...
Replace a view function with a normal and mobile view .
32,241
def format_output ( instances , flag ) : out = [ ] line_format = '{0}\t{1}\t{2}\t{3}' name_len = _get_max_name_len ( instances ) + 3 if flag : line_format = '{0:<' + str ( name_len + 5 ) + '}{1:<16}{2:<65}{3:<16}' for i in instances : endpoint = "{0}:{1}" . format ( i [ 'Endpoint' ] [ 'Address' ] , i [ 'Endpoint' ] [ '...
return formatted string per instance
32,242
def ls ( ctx , list_formatted ) : session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) rds = session . client ( 'rds' ) instances = rds . describe_db_instances ( ) out = format_output ( instances [ 'DBInstances' ] , list_formatted ) click . echo ( '\n' . join ( out ) )
List RDS instances
32,243
def ls ( ctx , name ) : session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) client = session . client ( 'emr' ) results = client . list_clusters ( ClusterStates = [ 'RUNNING' , 'STARTING' , 'BOOTSTRAPPING' , 'WAITING' ] ) for cluster in results [ 'Clusters' ] : click . echo ( "{0}\t{1}\t{2}" . format ( cluste...
List EMR instances
32,244
def ssh ( ctx , cluster_id , key_file ) : session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) client = session . client ( 'emr' ) result = client . describe_cluster ( ClusterId = cluster_id ) target_dns = result [ 'Cluster' ] [ 'MasterPublicDnsName' ] ssh_options = '-o StrictHostKeyChecking=no -o ServerAliveI...
SSH login to EMR master node
32,245
def rm ( ctx , cluster_id ) : session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) client = session . client ( 'emr' ) try : result = client . describe_cluster ( ClusterId = cluster_id ) target_dns = result [ 'Cluster' ] [ 'MasterPublicDnsName' ] flag = click . prompt ( "Are you sure you want to terminate {0}:...
Terminate a EMR cluster
32,246
def get_tag_value ( x , key ) : if x is None : return '' result = [ y [ 'Value' ] for y in x if y [ 'Key' ] == key ] if result : return result [ 0 ] return ''
Get a value from tag
32,247
def ls ( ctx , name , list_formatted ) : session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) ec2 = session . resource ( 'ec2' ) if name == '*' : instances = ec2 . instances . filter ( ) else : condition = { 'Name' : 'tag:Name' , 'Values' : [ name ] } instances = ec2 . instances . filter ( Filters = [ conditio...
List EC2 instances
32,248
def up ( ctx , instance_id ) : session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) ec2 = session . resource ( 'ec2' ) try : instance = ec2 . Instance ( instance_id ) instance . start ( ) except botocore . exceptions . ClientError as e : click . echo ( "Invalid instance ID {0} ({1})" . format ( instance_id , e...
Start EC2 instance
32,249
def create_ssh_command ( session , instance_id , instance_name , username , key_file , port , ssh_options , use_private_ip , gateway_instance_id , gateway_username ) : ec2 = session . resource ( 'ec2' ) if instance_id is not None : try : instance = ec2 . Instance ( instance_id ) hostname = _get_instance_ip_address ( in...
Create SSH Login command string
32,250
def ssh ( ctx , instance_id , instance_name , username , key_file , port , ssh_options , private_ip , gateway_instance_id , gateway_username , dry_run ) : session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) if instance_id is None and instance_name is None : click . echo ( "One of --instance-id/-i or --instanc...
SSH to EC2 instance
32,251
def ls ( ctx , name , list_instances ) : session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) client = session . client ( 'elb' ) inst = { 'LoadBalancerDescriptions' : [ ] } if name == '*' : inst = client . describe_load_balancers ( ) else : try : inst = client . describe_load_balancers ( LoadBalancerNames = [...
List ELB instances
32,252
def ls ( ctx , name , list_formatted ) : session = create_session ( ctx . obj [ 'AWS_PROFILE_NAME' ] ) client = session . client ( 'autoscaling' ) if name == "*" : groups = client . describe_auto_scaling_groups ( ) else : groups = client . describe_auto_scaling_groups ( AutoScalingGroupNames = [ name , ] ) out = format...
List AutoScaling groups
32,253
def authenticate ( self , provider ) : callback_url = url_for ( ".callback" , provider = provider , _external = True ) provider = self . get_provider ( provider ) session [ 'next' ] = request . args . get ( 'next' ) or '' return provider . authorize ( callback_url )
Starts OAuth authorization flow will redirect to 3rd party site .
32,254
def callback ( self , provider ) : provider = self . get_provider ( provider ) try : return provider . authorized_handler ( self . login ) ( provider = provider ) except OAuthException as ex : logging . error ( "Data: %s" , ex . data ) raise
Handles 3rd party callback and processes it s data
32,255
def register ( model , fields , restrict_to = None , manager = None , properties = None , contexts = None ) : if not contexts : contexts = { } global _REGISTRY _REGISTRY [ model ] = { 'fields' : fields , 'contexts' : contexts , 'restrict_to' : restrict_to , 'manager' : manager , 'properties' : properties , } for field ...
Tell vinaigrette which fields on a Django model should be translated .
32,256
def get_page_numbers ( current_page , num_pages ) : if current_page <= 2 : start_page = 1 else : start_page = current_page - 2 if num_pages <= 4 : end_page = num_pages else : end_page = start_page + 4 if end_page > num_pages : end_page = num_pages pages = [ ] if current_page != 1 : pages . append ( 'first' ) pages . ap...
Default callable for page listing . Produce a Digg - style pagination .
32,257
def _get_po_paths ( locales = [ ] ) : basedirs = [ os . path . join ( 'conf' , 'locale' ) , 'locale' ] if os . environ . get ( 'DJANGO_SETTINGS_MODULE' ) : from django . conf import settings basedirs . extend ( settings . LOCALE_PATHS ) basedirs = set ( map ( os . path . abspath , filter ( os . path . isdir , basedirs ...
Returns paths to all relevant po files in the current project .
32,258
def show_pageitems ( _ , token ) : if len ( token . contents . split ( ) ) != 1 : msg = '%r tag takes no arguments' % token . contents . split ( ) [ 0 ] raise template . TemplateSyntaxError ( msg ) return ShowPageItemsNode ( )
Show page items .
32,259
def user_error ( status_code , title , detail , pointer ) : response = { 'errors' : [ { 'status' : status_code , 'source' : { 'pointer' : '{0}' . format ( pointer ) } , 'title' : title , 'detail' : detail , } ] , 'jsonapi' : { 'version' : '1.0' } , 'meta' : { 'sqlalchemy_jsonapi_version' : __version__ } } return json ....
Create and return a general user error response that is jsonapi compliant .
32,260
def override ( original , results ) : overrides = [ v for fn , v in results if v is not None ] if len ( overrides ) == 0 : return original return overrides [ - 1 ]
If a receiver to a signal returns a value we override the original value with the last returned value .
32,261
def default ( self , value ) : if isinstance ( value , uuid . UUID ) : return str ( value ) elif isinstance ( value , datetime . datetime ) : return value . isoformat ( ) elif callable ( value ) : return str ( value ) return json . JSONEncoder . default ( self , value )
Handle UUID datetime and callables .
32,262
def init_app ( self , app , sqla , namespace = 'api' , route_prefix = '/api' ) : self . app = app self . sqla = sqla self . _setup_adapter ( namespace , route_prefix )
Initialize the adapter if it hasn t already been initialized .
32,263
def wrap_handler ( self , api_types , methods , endpoints ) : def wrapper ( fn ) : @ wraps ( fn ) def wrapped ( * args , ** kwargs ) : return fn ( * args , ** kwargs ) for api_type in api_types : for method in methods : for endpoint in endpoints : key = ( api_type , method , endpoint ) self . _handler_chains . setdefau...
Allow for a handler to be wrapped in a chain .
32,264
def _call_next ( self , handler_chain ) : def wrapped ( * args , ** kwargs ) : if len ( handler_chain ) == 1 : return handler_chain [ 0 ] ( * args , ** kwargs ) else : return handler_chain [ 0 ] ( self . _call_next ( handler_chain [ 1 : ] ) , * args , ** kwargs ) return wrapped
Generates an express - like chain for handling requests .
32,265
def _setup_adapter ( self , namespace , route_prefix ) : self . serializer = JSONAPI ( self . sqla . Model , prefix = '{}://{}{}' . format ( self . app . config [ 'PREFERRED_URL_SCHEME' ] , self . app . config [ 'SERVER_NAME' ] , route_prefix ) ) for view in views : method , endpoint = view pattern = route_prefix + end...
Initialize the serializer and loop through the views to generate them .
32,266
def _generate_view ( self , method , endpoint ) : def new_view ( ** kwargs ) : if method == Method . GET : data = request . args else : content_length = request . headers . get ( 'content-length' , 0 ) if content_length and int ( content_length ) > 0 : content_type = request . headers . get ( 'content-type' , None ) if...
Generate a view for the specified method and endpoint .
32,267
def _render_resource ( self , resource ) : if not resource : return None if not isinstance ( resource , self . model ) : raise TypeError ( 'Resource(s) type must be the same as the serializer model type.' ) top_level_members = { } try : top_level_members [ 'id' ] = str ( getattr ( resource , self . primary_key ) ) exce...
Renders a resource s top level members based on json - api spec .
32,268
def _render_attributes ( self , resource ) : attributes = { } attrs_to_ignore = set ( ) for key , relationship in resource . __mapper__ . relationships . items ( ) : attrs_to_ignore . update ( set ( [ column . name for column in relationship . local_columns ] ) . union ( { key } ) ) if self . dasherize : mapped_fields ...
Render the resources s attributes .
32,269
def _render_relationships ( self , resource ) : relationships = { } related_models = resource . __mapper__ . relationships . keys ( ) primary_key_val = getattr ( resource , self . primary_key ) if self . dasherize : mapped_relationships = { x : dasherize ( underscore ( x ) ) for x in related_models } else : mapped_rela...
Render the resource s relationships .
32,270
def attr_descriptor ( action , * names ) : if isinstance ( action , AttributeActions ) : action = [ action ] def wrapped ( fn ) : if not hasattr ( fn , '__jsonapi_action__' ) : fn . __jsonapi_action__ = set ( ) fn . __jsonapi_desc_for_attrs__ = set ( ) fn . __jsonapi_desc_for_attrs__ |= set ( names ) fn . __jsonapi_act...
Wrap a function that allows for getting or setting of an attribute . This allows for specific handling of an attribute when it comes to serializing and deserializing .
32,271
def relationship_descriptor ( action , * names ) : if isinstance ( action , RelationshipActions ) : action = [ action ] def wrapped ( fn ) : if not hasattr ( fn , '__jsonapi_action__' ) : fn . __jsonapi_action__ = set ( ) fn . __jsonapi_desc_for_rels__ = set ( ) fn . __jsonapi_desc_for_rels__ |= set ( names ) fn . __js...
Wrap a function for modification of a relationship . This allows for specific handling for serialization and deserialization .
32,272
def check_permission ( instance , field , permission ) : if not get_permission_test ( instance , field , permission ) ( instance ) : raise PermissionDeniedError ( permission , instance , instance , field )
Check a permission for a given instance or field . Raises an error if denied .
32,273
def get_attr_desc ( instance , attribute , action ) : descs = instance . __jsonapi_attribute_descriptors__ . get ( attribute , { } ) if action == AttributeActions . GET : check_permission ( instance , attribute , Permissions . VIEW ) return descs . get ( action , lambda x : getattr ( x , attribute ) ) check_permission ...
Fetch the appropriate descriptor for the attribute .
32,274
def get_rel_desc ( instance , key , action ) : descs = instance . __jsonapi_rel_desc__ . get ( key , { } ) if action == RelationshipActions . GET : check_permission ( instance , key , Permissions . VIEW ) return descs . get ( action , lambda x : getattr ( x , key ) ) elif action == RelationshipActions . APPEND : check_...
Fetch the appropriate descriptor for the relationship .
32,275
def _check_json_data ( self , json_data ) : if not isinstance ( json_data , dict ) : raise BadRequestError ( 'Request body should be a JSON hash' ) if 'data' not in json_data . keys ( ) : raise BadRequestError ( 'Request should contain data key' )
Ensure that the request body is both a hash and has a data key .
32,276
def _fetch_resource ( self , session , api_type , obj_id , permission ) : if api_type not in self . models . keys ( ) : raise ResourceTypeNotFoundError ( api_type ) obj = session . query ( self . models [ api_type ] ) . get ( obj_id ) if obj is None : raise ResourceNotFoundError ( self . models [ api_type ] , obj_id ) ...
Fetch a resource by type and id also doing a permission check .
32,277
def _render_short_instance ( self , instance ) : check_permission ( instance , None , Permissions . VIEW ) return { 'type' : instance . __jsonapi_type__ , 'id' : instance . id }
For those very short versions of resources we have this .
32,278
def _check_instance_relationships_for_delete ( self , instance ) : check_permission ( instance , None , Permissions . DELETE ) for rel_key , rel in instance . __mapper__ . relationships . items ( ) : check_permission ( instance , rel_key , Permissions . EDIT ) if rel . cascade . delete : if rel . direction == MANYTOONE...
Ensure we are authorized to delete this and all cascaded resources .
32,279
def _parse_fields ( self , query ) : field_args = { k : v for k , v in query . items ( ) if k . startswith ( 'fields[' ) } fields = { } for k , v in field_args . items ( ) : fields [ k [ 7 : - 1 ] ] = v . split ( ',' ) return fields
Parse the querystring args for fields .
32,280
def _parse_include ( self , include ) : ret = { } for item in include : if '.' in item : local , remote = item . split ( '.' , 1 ) else : local = item remote = None ret . setdefault ( local , [ ] ) if remote : ret [ local ] . append ( remote ) return ret
Parse the querystring args or parent includes for includes .
32,281
def _parse_page ( self , query ) : args = { k [ 5 : - 1 ] : v for k , v in query . items ( ) if k . startswith ( 'page[' ) } if { 'number' , 'size' } == set ( args . keys ( ) ) : if not args [ 'number' ] . isdecimal ( ) or not args [ 'size' ] . isdecimal ( ) : raise BadRequestError ( 'Page query parameters must be inte...
Parse the querystring args for pagination .
32,282
def delete_relationship ( self , session , data , api_type , obj_id , rel_key ) : model = self . _fetch_model ( api_type ) resource = self . _fetch_resource ( session , api_type , obj_id , Permissions . EDIT ) relationship = self . _get_relationship ( resource , rel_key , Permissions . DELETE ) self . _check_json_data ...
Delete a resource or multiple resources from a to - many relationship .
32,283
def get_collection ( self , session , query , api_key ) : model = self . _fetch_model ( api_key ) include = self . _parse_include ( query . get ( 'include' , '' ) . split ( ',' ) ) fields = self . _parse_fields ( query ) included = { } sorts = query . get ( 'sort' , '' ) . split ( ',' ) order_by = [ ] collection = sess...
Fetch a collection of resources of a specified type .
32,284
def get_relationship ( self , session , query , api_type , obj_id , rel_key ) : resource = self . _fetch_resource ( session , api_type , obj_id , Permissions . VIEW ) if rel_key not in resource . __jsonapi_map_to_py__ . keys ( ) : raise RelationshipNotFoundError ( resource , resource , rel_key ) py_key = resource . __j...
Fetch a collection of related resource types and ids .
32,285
def patch_relationship ( self , session , json_data , api_type , obj_id , rel_key ) : model = self . _fetch_model ( api_type ) resource = self . _fetch_resource ( session , api_type , obj_id , Permissions . EDIT ) if rel_key not in resource . __jsonapi_map_to_py__ . keys ( ) : raise RelationshipNotFoundError ( resource...
Replacement of relationship values .
32,286
def post_relationship ( self , session , json_data , api_type , obj_id , rel_key ) : model = self . _fetch_model ( api_type ) resource = self . _fetch_resource ( session , api_type , obj_id , Permissions . EDIT ) if rel_key not in resource . __jsonapi_map_to_py__ . keys ( ) : raise RelationshipNotFoundError ( resource ...
Append to a relationship .
32,287
def map_event_code ( event_code ) : event_code = int ( event_code ) if 1100 <= event_code <= 1199 : return ALARM_GROUP elif 3100 <= event_code <= 3199 : return ALARM_END_GROUP elif 1300 <= event_code <= 1399 : return PANEL_FAULT_GROUP elif 3300 <= event_code <= 3399 : return PANEL_RESTORE_GROUP elif 1400 <= event_code ...
Map a specific event_code to an event group .
32,288
def set_active ( self , active ) : url = CONST . AUTOMATION_EDIT_URL url = url . replace ( '$AUTOMATIONID$' , self . automation_id ) self . _automation [ 'is_active' ] = str ( int ( active ) ) response = self . _abode . send_request ( method = "put" , url = url , data = self . _automation ) response_object = json . loa...
Activate and deactivate an automation .
32,289
def trigger ( self , only_manual = True ) : if not self . is_quick_action and only_manual : raise AbodeException ( ( ERROR . TRIGGER_NON_QUICKACTION ) ) url = CONST . AUTOMATION_APPLY_URL url = url . replace ( '$AUTOMATIONID$' , self . automation_id ) self . _abode . send_request ( method = "put" , url = url , data = s...
Trigger a quick - action automation .
32,290
def refresh ( self ) : url = CONST . AUTOMATION_ID_URL url = url . replace ( '$AUTOMATIONID$' , self . automation_id ) response = self . _abode . send_request ( method = "get" , url = url ) response_object = json . loads ( response . text ) if isinstance ( response_object , ( tuple , list ) ) : response_object = respon...
Refresh the automation .
32,291
def update ( self , automation ) : self . _automation . update ( { k : automation [ k ] for k in automation if self . _automation . get ( k ) } )
Update the internal automation json .
32,292
def desc ( self ) : active = 'inactive' if self . is_active : active = 'active' return '{0} (ID: {1}) - {2} - {3}' . format ( self . name , self . automation_id , self . type , active )
Get a short description of the automation .
32,293
def _get_numeric_status ( self , key ) : value = self . _get_status ( key ) if value and any ( i . isdigit ( ) for i in value ) : return float ( re . sub ( "[^0-9.]" , "" , value ) ) return None
Extract the numeric value from the statuses object .
32,294
def temp_unit ( self ) : if CONST . UNIT_FAHRENHEIT in self . _get_status ( CONST . TEMP_STATUS_KEY ) : return CONST . UNIT_FAHRENHEIT elif CONST . UNIT_CELSIUS in self . _get_status ( CONST . TEMP_STATUS_KEY ) : return CONST . UNIT_CELSIUS return None
Get unit of temp .
32,295
def humidity_unit ( self ) : if CONST . UNIT_PERCENT in self . _get_status ( CONST . HUMI_STATUS_KEY ) : return CONST . UNIT_PERCENT return None
Get unit of humidity .
32,296
def lux_unit ( self ) : if CONST . UNIT_LUX in self . _get_status ( CONST . LUX_STATUS_KEY ) : return CONST . LUX return None
Get unit of lux .
32,297
def switch_on ( self ) : success = self . set_status ( CONST . STATUS_ON_INT ) if success : self . _json_state [ 'status' ] = CONST . STATUS_OPEN return success
Open the valve .
32,298
def switch_off ( self ) : success = self . set_status ( CONST . STATUS_OFF_INT ) if success : self . _json_state [ 'status' ] = CONST . STATUS_CLOSED return success
Close the valve .
32,299
def set_origin ( self , origin = None ) : if origin : self . _origin = origin . encode ( ) else : self . _origin = None
Set the Origin header .