idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
11,900
def value ( self ) : try : if isinstance ( self . __value , Expression ) : return self . __value . value return self . __value except AttributeError : return 0
Set a calculated value for this Expression . Used when writing formulas using XlsxWriter to give cells an initial value when the sheet is loaded without being calculated .
39
32
11,901
def has_value ( self ) : try : if isinstance ( self . __value , Expression ) : return self . __value . has_value return True except AttributeError : return False
return True if value has been set
40
7
11,902
def copy ( source , destination , ignore = None , adapter = None , fatal = True , logger = LOG . debug ) : return _file_op ( source , destination , _copy , adapter , fatal , logger , ignore = ignore )
Copy source - > destination
49
5
11,903
def move ( source , destination , adapter = None , fatal = True , logger = LOG . debug ) : return _file_op ( source , destination , _move , adapter , fatal , logger )
Move source - > destination
41
5
11,904
def symlink ( source , destination , adapter = None , must_exist = True , fatal = True , logger = LOG . debug ) : return _file_op ( source , destination , _symlink , adapter , fatal , logger , must_exist = must_exist )
Symlink source < - destination
59
7
11,905
def soap_attribute ( self , name , value ) : setattr ( self , name , value ) self . _attributes . add ( name )
Marks an attribute as being a part of the data defined by the soap datatype
31
18
11,906
def get_soap_object ( self , client ) : def to_soap_attribute ( attr ) : words = attr . split ( '_' ) words = words [ : 1 ] + [ word . capitalize ( ) for word in words [ 1 : ] ] return '' . join ( words ) soap_object = client . factory . create ( self . soap_name ) for attr in self . _attributes : value = getattr ( self , attr ) setattr ( soap_object , to_soap_attribute ( attr ) , value ) return soap_object
Create and return a soap service type defined for this instance
126
11
11,907
def get_soap_object ( self , client ) : record_data = super ( ) . get_soap_object ( client ) record_data . records = [ Record ( r ) . get_soap_object ( client ) for r in record_data . records ] return record_data
Override default get_soap_object behavior to account for child Record types
64
15
11,908
def handle_message_registered ( self , msg_data , host ) : response = None if msg_data [ "method" ] == "EVENT" : logger . debug ( "<%s> <euuid:%s> Event message " "received" % ( msg_data [ "cuuid" ] , msg_data [ "euuid" ] ) ) response = self . event ( msg_data [ "cuuid" ] , host , msg_data [ "euuid" ] , msg_data [ "event_data" ] , msg_data [ "timestamp" ] , msg_data [ "priority" ] ) elif msg_data [ "method" ] == "OK EVENT" : logger . debug ( "<%s> <euuid:%s> Event confirmation message " "received" % ( msg_data [ "cuuid" ] , msg_data [ "euuid" ] ) ) try : del self . event_uuids [ msg_data [ "euuid" ] ] except KeyError : logger . warning ( "<%s> <euuid:%s> Euuid does not exist in event " "buffer. Key was removed before we could process " "it." % ( msg_data [ "cuuid" ] , msg_data [ "euuid" ] ) ) elif msg_data [ "method" ] == "OK NOTIFY" : logger . debug ( "<%s> <euuid:%s> Ok notify " "received" % ( msg_data [ "cuuid" ] , msg_data [ "euuid" ] ) ) try : del self . event_uuids [ msg_data [ "euuid" ] ] except KeyError : logger . warning ( "<%s> <euuid:%s> Euuid does not exist in event " "buffer. Key was removed before we could process " "it." % ( msg_data [ "cuuid" ] , msg_data [ "euuid" ] ) ) return response
Processes messages that have been delivered by a registered client .
450
12
11,909
def autodiscover ( self , message ) : # Check to see if the client's version is the same as our own. if message [ "version" ] in self . allowed_versions : logger . debug ( "<%s> Client version matches server " "version." % message [ "cuuid" ] ) response = serialize_data ( { "method" : "OHAI Client" , "version" : self . version , "server_name" : self . server_name } , self . compression , encryption = False ) else : logger . warning ( "<%s> Client version %s does not match allowed server " "versions %s" % ( message [ "cuuid" ] , message [ "version" ] , self . version ) ) response = serialize_data ( { "method" : "BYE REGISTER" } , self . compression , encryption = False ) return response
This function simply returns the server version number as a response to the client .
192
15
11,910
def register ( self , message , host ) : # Get the client generated cuuid from the register message cuuid = message [ "cuuid" ] # Check to see if we've hit the maximum number of registrations # If we've reached the maximum limit, return a failure response to the # client. if len ( self . registry ) > self . registration_limit : logger . warning ( "<%s> Registration limit exceeded" % cuuid ) response = serialize_data ( { "method" : "BYE REGISTER" } , self . compression , encryption = False ) return response # Insert a new record in the database with the client's information data = { "host" : host [ 0 ] , "port" : host [ 1 ] , "time" : datetime . now ( ) } # Prepare an OK REGISTER response to the client to let it know that it # has registered return_msg = { "method" : "OK REGISTER" } # If the register request has a public key included in it, then include # it in the registry. if "encryption" in message and self . encryption : data [ "encryption" ] = PublicKey ( message [ "encryption" ] [ 0 ] , message [ "encryption" ] [ 1 ] ) # Add the host to the encrypted_hosts dictionary so we know to # decrypt messages from this host self . encrypted_hosts [ host ] = cuuid # If the client requested encryption and we have it enabled, send # our public key to the client return_msg [ "encryption" ] = [ self . encryption . n , self . encryption . e ] # Add the entry to the registry if cuuid in self . registry : for key in data : self . registry [ cuuid ] [ key ] = data [ key ] else : self . registry [ cuuid ] = data self . registry [ cuuid ] [ "authenticated" ] = False # Serialize our response to the client response = serialize_data ( return_msg , self . compression , encryption = False ) # For debugging, print all the current rows in the registry logger . debug ( "<%s> Registry entries:" % cuuid ) for ( key , value ) in self . registry . items ( ) : logger . debug ( "<%s> %s %s" % ( str ( cuuid ) , str ( key ) , pformat ( value ) ) ) return response
This function will register a particular client in the server s registry dictionary .
519
14
11,911
def is_registered ( self , cuuid , host ) : # Check to see if the host with the client uuid exists in the registry # table. if ( cuuid in self . registry ) and ( self . registry [ cuuid ] [ "host" ] == host ) : return True else : return False
This function will check to see if a given host with client uuid is currently registered .
68
18
11,912
def event ( self , cuuid , host , euuid , event_data , timestamp , priority ) : # Set the initial response to none response = None # If the host we're sending to is using encryption, get their key to # encrypt. if host in self . encrypted_hosts : logger . debug ( "Encrypted!" ) client_key = self . registry [ cuuid ] [ "encryption" ] else : logger . debug ( "Not encrypted :<" ) client_key = None # Get the port and host port = host [ 1 ] host = host [ 0 ] # First, we need to check if the request is coming from a registered # client. If it's not coming from a registered client, we tell them to # fuck off and register first. if not self . is_registered ( cuuid , host ) : logger . warning ( "<%s> Sending BYE EVENT: Client not registered." % cuuid ) response = serialize_data ( { "method" : "BYE EVENT" , "data" : "Not registered" } , self . compression , self . encryption , client_key ) return response # Check our stored event uuid's to see if we're already processing # this event. if euuid in self . event_uuids : logger . warning ( "<%s> Event ID is already being processed: %s" % ( cuuid , euuid ) ) # If we're already working on this event, return none so we do not # reply to the client return response # If we're not already processing this event, store the event uuid # until we receive a confirmation from the client that it received our # judgement. self . event_uuids [ euuid ] = 0 logger . debug ( "<%s> <euuid:%s> Currently processing events: " "%s" % ( cuuid , euuid , str ( self . event_uuids ) ) ) logger . debug ( "<%s> <euuid:%s> New event being processed" % ( cuuid , euuid ) ) logger . debug ( "<%s> <euuid:%s> Event Data: %s" % ( cuuid , euuid , pformat ( event_data ) ) ) # Send the event to the game middleware to determine if the event is # legal or not and to process the event in the Game Server if it is # legal. if self . middleware . event_legal ( cuuid , euuid , event_data ) : logger . debug ( "<%s> <euuid:%s> Event LEGAL. Sending judgement " "to client." % ( cuuid , euuid ) ) response = serialize_data ( { "method" : "LEGAL" , "euuid" : euuid , "priority" : priority } , self . compression , self . encryption , client_key ) # Execute the event thread = threading . Thread ( target = self . middleware . event_execute , args = ( cuuid , euuid , event_data ) ) thread . start ( ) else : logger . debug ( "<%s> <euuid:%s> Event ILLEGAL. Sending judgement " "to client." % ( cuuid , euuid ) ) response = serialize_data ( { "method" : "ILLEGAL" , "euuid" : euuid , "priority" : priority } , self . compression , self . encryption , client_key ) # Schedule a task to run in x seconds to check to see if we've timed # out in receiving a response from the client. self . listener . call_later ( self . timeout , self . retransmit , { "euuid" : euuid , "response" : response , "cuuid" : cuuid } ) return response
This function will process event packets and send them to legal checks .
839
13
11,913
def notify ( self , cuuid , event_data ) : # Generate an event uuid for the notify event euuid = str ( uuid . uuid1 ( ) ) # If the client uses encryption, get their key to encrypt if "encryption" in self . registry [ cuuid ] : client_key = self . registry [ cuuid ] [ "encryption" ] else : client_key = None logger . debug ( "<%s> <%s> Sending NOTIFY event to client with event data: " "%s" % ( str ( cuuid ) , str ( euuid ) , pformat ( event_data ) ) ) # Look up the host details based on cuuid try : ip_address = self . registry [ cuuid ] [ "host" ] except KeyError : logger . warning ( "<%s> <%s> Host not found in registry! Transmit " "Canceled" % ( str ( cuuid ) , str ( euuid ) ) ) return False try : port = self . registry [ cuuid ] [ "port" ] except KeyError : logger . warning ( "<%s> <%s> Port not found! Transmit " "Canceled" % ( str ( cuuid ) , str ( euuid ) ) ) return False # Set up the packet and address to send to packet = serialize_data ( { "method" : "NOTIFY" , "event_data" : event_data , "euuid" : euuid } , self . compression , self . encryption , client_key ) address = ( ip_address , port ) # If we're not already processing this event, store the event uuid # until we receive a confirmation from the client that it received our # notification. self . event_uuids [ euuid ] = 0 # This is the current retry attempt logger . debug ( "<%s> Currently processing events: " "%s" % ( cuuid , pformat ( self . event_uuids ) ) ) logger . debug ( "<%s> New NOTIFY event being processed:" % cuuid ) logger . debug ( "<%s> EUUID: %s" % ( cuuid , euuid ) ) logger . debug ( "<%s> Event Data: %s" % ( cuuid , pformat ( event_data ) ) ) # Send the packet to the client self . listener . send_datagram ( packet , address ) # Schedule a task to run in x seconds to check to see if we've timed # out in receiving a response from the client/ self . listener . call_later ( self . timeout , self . retransmit , { "euuid" : euuid , "response" : packet , "cuuid" : cuuid } )
This function will send a NOTIFY event to a registered client .
611
14
11,914
def once ( dispatcher , event , handle , * args ) : def shell ( dispatcher , * args ) : try : handle ( dispatcher , * args ) except Exception as e : raise e finally : dispatcher . del_map ( event , shell ) dispatcher . add_map ( event , shell , * args )
Used to do a mapping like event - > handle but handle is called just once upon event .
63
19
11,915
def mainloop ( self ) : while True : # It calls repeteadly the reactor # update method. try : self . update ( ) except Kill : # It breaks the loop # silently. # people implementing reactors from other mainloop # should implement this try: catch # suitably to their needs. break except KeyboardInterrupt : print ( self . base ) raise
This is the reactor mainloop . It is intented to be called when a reactor is installed .
75
20
11,916
def start_session ( self , b_hold_session , sig_doc_xml = None , datafile = None ) : response = self . __invoke ( 'StartSession' , { 'bHoldSession' : b_hold_session , 'SigDocXML' : sig_doc_xml or SkipValue , 'datafile' : datafile or SkipValue , # This parameter is deprecated and exists only due to historical reasons. We need to specify it as # SkipValue to keep zeep happy 'SigningProfile' : SkipValue , } ) if response [ 'Sesscode' ] : self . data_files = [ ] self . session_code = response [ 'Sesscode' ] if sig_doc_xml : self . container = PreviouslyCreatedContainer ( ) return True # If b_hold_session is set to False, response will not contain a session # in case of errors, exceptions are raised from __invoke anyway return False
Start a DigidocService session
201
7
11,917
def mobile_sign ( self , id_code , country , phone_nr , language = None , signing_profile = 'LT_TM' ) : if not ( self . container and isinstance ( self . container , PreviouslyCreatedContainer ) ) : assert self . data_files , 'To use MobileSign endpoint the application must ' 'add at least one data file to users session' response = self . __invoke ( 'MobileSign' , { 'SignerIDCode' : id_code , 'SignersCountry' : country , 'SignerPhoneNo' : phone_nr , 'Language' : self . parse_language ( language ) , 'Role' : SkipValue , 'City' : SkipValue , 'StateOrProvince' : SkipValue , 'PostalCode' : SkipValue , 'CountryName' : SkipValue , 'ServiceName' : self . service_name , 'AdditionalDataToBeDisplayed' : self . mobile_message , # Either LT or LT_TM, see: http://sk-eid.github.io/dds-documentation/api/api_docs/#mobilesign 'SigningProfile' : signing_profile , 'MessagingMode' : 'asynchClientServer' , 'AsyncConfiguration' : SkipValue , 'ReturnDocInfo' : SkipValue , 'ReturnDocData' : SkipValue , } ) return response
This can be used to add a signature to existing data files
292
12
11,918
def is_prime ( n , k = 64 ) : if n == 2 : return True if n < 2 or n % 2 == 0 : return False for i in range ( 3 , 2048 ) : # performace optimisation if n % i == 0 : return False s = 0 d = n - 1 while True : q , r = divmod ( d , 2 ) if r == 1 : break s += 1 d = q for i in range ( k ) : a = random . randint ( 2 , n - 1 ) if check_candidate ( a , d , n , s ) : return False return True
Test whether n is prime probabilisticly .
130
10
11,919
def get_prime ( bits , k = 64 ) : if bits % 8 != 0 or bits == 0 : raise ValueError ( "bits must be >= 0 and divisible by 8" ) while True : n = int . from_bytes ( os . urandom ( bits // 8 ) , "big" ) if is_prime ( n , k ) : return n
Return a random prime up to a certain length .
77
10
11,920
def make_rsa_keys ( bits = 2048 , e = 65537 , k = 64 ) : p , q = None , None while p == q : p , q = get_prime ( bits // 2 ) , get_prime ( bits // 2 ) n = p * q phi_n = phi ( n , p , q ) d = mult_inv ( e , phi_n ) return n , e , d
Create RSA key pair .
93
5
11,921
def setup ( app ) : for name , ( default , rebuild , _ ) in ref . CONFIG_VALUES . iteritems ( ) : app . add_config_value ( name , default , rebuild ) app . add_directive ( 'javaimport' , ref . JavarefImportDirective ) app . add_role ( 'javaref' , ref . JavarefRole ( app ) ) app . connect ( 'builder-inited' , initialize_env ) app . connect ( 'env-purge-doc' , ref . purge_imports ) app . connect ( 'env-merge-info' , ref . merge_imports ) app . connect ( 'build-finished' , ref . cleanup )
Register the extension with Sphinx .
158
7
11,922
def validate_env ( app ) : if not hasattr ( app . env , 'javalink_config_cache' ) : app . env . javalink_config_cache = { } for conf_attr , ( _ , _ , env_attr ) in ref . CONFIG_VALUES . iteritems ( ) : if not env_attr : continue value = getattr ( app . config , conf_attr ) cached = app . env . javalink_config_cache . get ( conf_attr , value ) app . env . javalink_config_cache [ conf_attr ] = value if value != cached : app . verbose ( '[javalink] config.%s has changed, clearing related env' , conf_attr ) delattr ( app . env , env_attr )
Purge expired values from the environment .
171
8
11,923
def find_rt_jar ( javahome = None ) : if not javahome : if 'JAVA_HOME' in os . environ : javahome = os . environ [ 'JAVA_HOME' ] elif sys . platform == 'darwin' : # The default java binary on OS X is not part of a standard Oracle # install, so building paths relative to it does not work like it # does on other platforms. javahome = _find_osx_javahome ( ) else : javahome = _get_javahome_from_java ( _find_java_binary ( ) ) rtpath = os . path . join ( javahome , 'jre' , 'lib' , 'rt.jar' ) if not os . path . isfile ( rtpath ) : msg = 'Could not find rt.jar: {} is not a file' . format ( rtpath ) raise ExtensionError ( msg ) return rtpath
Find the path to the Java standard library jar .
223
10
11,924
def filter ( self , record ) : found = self . _pattern . search ( record . getMessage ( ) ) return not found
Returns True if the record shall be logged . False otherwise .
27
12
11,925
def _get_value ( obj , key ) : if isinstance ( obj , ( list , tuple ) ) : for item in obj : v = _find_value ( key , item ) if v is not None : return v return None if isinstance ( obj , dict ) : return obj . get ( key ) if obj is not None : return getattr ( obj , key , None )
Get a value for key from obj if possible
82
9
11,926
def _find_value ( key , * args ) : for arg in args : v = _get_value ( arg , key ) if v is not None : return v
Find a value for key in any of the objects given as args
36
13
11,927
def add_search_path ( * path_tokens ) : full_path = os . path . join ( * path_tokens ) if full_path not in sys . path : sys . path . insert ( 0 , os . path . abspath ( full_path ) )
Adds a new search path from where modules can be loaded . This function is provided for test applications to add locations to the search path so any required functionality can be loaded . It helps keeping the step implementation modules simple by placing the bulk of the implementation in separate utility libraries . This function can also be used to add the application being tested to the path so its functionality can be made available for testing .
62
79
11,928
def load_script ( filename ) : path , module_name , ext = _extract_script_components ( filename ) add_search_path ( path ) return _load_module ( module_name )
Loads a python script as a module .
45
9
11,929
def parse_dates ( df , inplace = True , * args , * * kwargs ) : if not inplace : df = df . copy ( ) for c in df . columns : i = df [ c ] . first_valid_index ( ) if i is not None and type ( df [ c ] . ix [ i ] ) in ( date , datetime ) : df [ c ] = pd . to_datetime ( df [ c ] , * args , * * kwargs ) if not inplace : return df
Parse all datetime . date and datetime . datetime columns
116
14
11,930
def to_float ( * args ) : floats = [ np . array ( a , dtype = np . float32 ) for a in args ] return floats [ 0 ] if len ( floats ) == 1 else floats
cast numpy arrays to float32 if there s more than one return an array
45
16
11,931
def get_attr ( name ) : i = name . rfind ( '.' ) cls = str ( name [ i + 1 : ] ) module = str ( name [ : i ] ) mod = __import__ ( module , fromlist = [ cls ] ) return getattr ( mod , cls )
get a class or function by name
66
7
11,932
def drop_constant_column_levels ( df ) : columns = df . columns constant_levels = [ i for i , level in enumerate ( columns . levels ) if len ( level ) <= 1 ] constant_levels . reverse ( ) for i in constant_levels : columns = columns . droplevel ( i ) df . columns = columns
drop the levels of a multi - level column dataframe which are constant operates in place
73
17
11,933
def dict_diff ( dicts ) : diff_keys = set ( ) for k in union ( set ( d . keys ( ) ) for d in dicts ) : values = [ ] for d in dicts : if k not in d : diff_keys . add ( k ) break else : values . append ( d [ k ] ) if nunique ( values ) > 1 : diff_keys . add ( k ) break return [ dict_subset ( d , diff_keys ) for d in dicts ]
Subset dictionaries to keys which map to multiple values
109
11
11,934
def dict_update_union ( d1 , d2 ) : for k in d2 : if k in d1 : d1 [ k ] . update ( d2 [ k ] ) else : d1 [ k ] = d2 [ k ]
update a set - valued dictionary when key exists union sets
53
11
11,935
def compile_file ( self , infile , outfile , outdated = False , force = False ) : myfile = codecs . open ( outfile , 'w' , 'utf-8' ) if settings . DEBUG : myfile . write ( sass . compile ( filename = infile ) ) else : myfile . write ( sass . compile ( filename = infile , output_style = 'compressed' ) ) return myfile . close ( )
Process sass file .
98
5
11,936
def from_task ( cls , task ) : target = cls ( name = task . get_name ( ) , params = task . get_param_string ( ) ) return target
Create a new target representing a task and its parameters
40
10
11,937
def _base_query ( self , session ) : return session . query ( ORMTargetMarker ) . filter ( ORMTargetMarker . name == self . name ) . filter ( ORMTargetMarker . params == self . params )
Base query for a target .
52
6
11,938
def exists ( self ) : # get DB connection session = client . get_client ( ) . create_session ( ) # query for target existence ret = self . _base_query ( session ) . count ( ) > 0 session . close ( ) return ret
Check if a target exists
54
5
11,939
def create ( self ) : session = client . get_client ( ) . create_session ( ) if not self . _base_query ( session ) . count ( ) > 0 : # store a new target instance to the database marker = ORMTargetMarker ( name = self . name , params = self . params ) session . add ( marker ) session . commit ( ) session . close ( )
Create an instance of the current target in the database
84
10
11,940
def remove ( self ) : session = client . get_client ( ) . create_session ( ) if not self . _base_query ( session ) . count ( ) > 0 : session . close ( ) raise RuntimeError ( "Target does not exist, name={:s}, params={:s}" "" . format ( self . name , self . params ) ) # remove the target from the database self . _base_query ( session ) . delete ( ) session . commit ( ) session . close ( )
Remove a target
107
3
11,941
def add_uppercase ( table ) : orig = table . copy ( ) orig . update ( dict ( ( k . capitalize ( ) , v . capitalize ( ) ) for k , v in table . items ( ) ) ) return orig
Extend the table with uppercase options
50
9
11,942
def translit ( src , table = UkrainianKMU , preserve_case = True ) : src = text_type ( src ) src_is_upper = src . isupper ( ) if hasattr ( table , "DELETE_PATTERN" ) : src = table . DELETE_PATTERN . sub ( u"" , src ) if hasattr ( table , "PATTERN1" ) : src = table . PATTERN1 . sub ( lambda x : table . SPECIAL_CASES [ x . group ( ) ] , src ) if hasattr ( table , "PATTERN2" ) : src = table . PATTERN2 . sub ( lambda x : table . FIRST_CHARACTERS [ x . group ( ) ] , src ) res = src . translate ( table . MAIN_TRANSLIT_TABLE ) if src_is_upper and preserve_case : return res . upper ( ) else : return res
u Transliterates given unicode src text to transliterated variant according to a given transliteration table . Official ukrainian transliteration is used by default
202
35
11,943
def store ( self , df , attribute_columns ) : # ID start values depend on currently stored entities/attributes! entity_id_start = models . Entity . get_max_id ( self . session ) + 1 attribute_id_start = models . Attribute . get_max_id ( self . session ) + 1 # append ID and type columns df [ 'id' ] = range ( entity_id_start , entity_id_start + len ( df ) ) df [ 'type' ] = self . type # store entities df [ [ 'id' , 'type' ] ] . to_sql ( name = models . Entity . __tablename__ , con = self . client . engine , if_exists = 'append' , index = False ) # store attributes for col in attribute_columns : # ID column of df is the entity ID of the attribute attr_df = df [ [ col , 'id' ] ] . rename ( columns = { 'id' : 'entity_id' , col : 'value' } ) attr_df [ 'name' ] = col # add entity ID column, need to respect already existing entities attr_df [ 'id' ] = range ( attribute_id_start , attribute_id_start + len ( df ) ) attribute_id_start += len ( df ) # store attr_df . to_sql ( name = models . Attribute . __tablename__ , con = self . client . engine , if_exists = 'append' , index = False )
Store entities and their attributes
334
5
11,944
def run ( self ) : df = PaintingsInputData ( ) . load ( ) # rename columns df . rename ( columns = { 'paintingLabel' : 'name' } , inplace = True ) # get artist IDs, map via artist wiki ID artists = models . Entity . query_with_attributes ( 'artist' , self . client ) df [ 'artist_id' ] = df [ 'creator_wiki_id' ] . map ( artists . set_index ( 'wiki_id' ) [ 'id' ] ) # define attributes to create attribute_columns = [ 'name' , 'wiki_id' , 'area' , 'decade' , 'artist_id' ] # store entities and attributes self . store ( df , attribute_columns ) self . done ( )
Load all paintings into the database
172
6
11,945
def serialize_data ( data , compression = False , encryption = False , public_key = None ) : message = json . dumps ( data ) if compression : message = zlib . compress ( message ) message = binascii . b2a_base64 ( message ) if encryption and public_key : message = encryption . encrypt ( message , public_key ) encoded_message = str . encode ( message ) return encoded_message
Serializes normal Python datatypes into plaintext using json .
92
13
11,946
def unserialize_data ( data , compression = False , encryption = False ) : try : if encryption : data = encryption . decrypt ( data ) except Exception as err : logger . error ( "Decryption Error: " + str ( err ) ) message = False try : if compression : data = binascii . a2b_base64 ( data ) data = zlib . decompress ( data ) message = json . loads ( data ) except Exception as err : logger . error ( "Decompression Error: " + str ( err ) ) message = False decoded_message = data . decode ( ) if not encryption and not compression : message = json . loads ( decoded_message ) return message
Unserializes the packet data and converts it from json format to normal Python datatypes .
149
19
11,947
def listen ( self ) : self . listening = True if self . threading : from threading import Thread self . listen_thread = Thread ( target = self . listen_loop ) self . listen_thread . daemon = True self . listen_thread . start ( ) self . scheduler_thread = Thread ( target = self . scheduler ) self . scheduler_thread . daemon = True self . scheduler_thread . start ( ) else : self . listen_loop ( )
Starts the listen loop . If threading is enabled then the loop will be started in its own thread .
101
22
11,948
def listen_loop ( self ) : while self . listening : try : data , address = self . sock . recvfrom ( self . bufsize ) self . receive_datagram ( data , address ) if self . stats_enabled : self . stats [ 'bytes_recieved' ] += len ( data ) except socket . error as error : if error . errno == errno . WSAECONNRESET : logger . info ( "connection reset" ) else : raise logger . info ( "Shutting down the listener..." )
Starts the listen loop and executes the receieve_datagram method whenever a packet is receieved .
114
21
11,949
def scheduler ( self , sleep_time = 0.2 ) : while self . listening : # If we have any scheduled calls, execute them and remove them from # our list of scheduled calls. if self . scheduled_calls : timestamp = time . time ( ) self . scheduled_calls [ : ] = [ item for item in self . scheduled_calls if not self . time_reached ( timestamp , item ) ] time . sleep ( sleep_time ) logger . info ( "Shutting down the call scheduler..." )
Starts the scheduler to check for scheduled calls and execute them at the correct time .
113
18
11,950
def call_later ( self , time_seconds , callback , arguments ) : scheduled_call = { 'ts' : time . time ( ) + time_seconds , 'callback' : callback , 'args' : arguments } self . scheduled_calls . append ( scheduled_call )
Schedules a function to be run x number of seconds from now .
60
15
11,951
def time_reached ( self , current_time , scheduled_call ) : if current_time >= scheduled_call [ 'ts' ] : scheduled_call [ 'callback' ] ( scheduled_call [ 'args' ] ) return True else : return False
Checks to see if it s time to run a scheduled call or not .
55
16
11,952
def send_datagram ( self , message , address , message_type = "unicast" ) : if self . bufsize is not 0 and len ( message ) > self . bufsize : raise Exception ( "Datagram is too large. Messages should be " + "under " + str ( self . bufsize ) + " bytes in size." ) if message_type == "broadcast" : self . sock . setsockopt ( socket . SOL_SOCKET , socket . SO_BROADCAST , 1 ) elif message_type == "multicast" : self . sock . setsockopt ( socket . IPPROTO_IP , socket . IP_MULTICAST_TTL , 2 ) try : logger . debug ( "Sending packet" ) self . sock . sendto ( message , address ) if self . stats_enabled : self . stats [ 'bytes_sent' ] += len ( message ) except socket . error : logger . error ( "Failed to send, [Errno 101]: Network is unreachable." )
Sends a UDP datagram packet to the requested address .
224
12
11,953
def receive_datagram ( self , data , address ) : # If we do not specify an application, just print the data. if not self . app : logger . debug ( "Packet received" , address , data ) return False # Send the data we've recieved from the network and send it # to our application for processing. try : response = self . app . handle_message ( data , address ) except Exception as err : logger . error ( "Error processing message from " + str ( address ) + ":" + str ( data ) ) logger . error ( traceback . format_exc ( ) ) return False # If our application generated a response to this message, # send it to the original sender. if response : self . send_datagram ( response , address )
Executes when UDP data has been received and sends the packet data to our app to process the request .
163
21
11,954
def make_application ( ) : settings = { } application = web . Application ( [ web . url ( '/' , SimpleHandler ) ] , * * settings ) statsd . install ( application , * * { 'namespace' : 'testing' } ) return application
Create a application configured to send metrics .
56
8
11,955
def plots_html_page ( query_module ) : # page template template = jenv . get_template ( "analysis.html" ) # container for template context context = dict ( extended = config . EXTENDED ) # a database client/session to run queries in cl = client . get_client ( ) session = cl . create_session ( ) # general styling seaborn . set_style ( 'whitegrid' ) # # plot: painting area by decade, with linear regression # decade_df = query_module . decade_query ( ) pix_size = pixels_to_inches ( ( 600 , 400 ) ) ax = seaborn . lmplot ( x = 'decade' , y = 'area' , data = decade_df , size = pix_size [ 1 ] , aspect = pix_size [ 0 ] / pix_size [ 1 ] , scatter_kws = { "s" : 30 , "alpha" : 0.3 } ) ax . set ( xlabel = 'Decade' , ylabel = 'Area, m^2' ) context [ 'area_by_decade_svg' ] = fig_to_svg ( plt . gcf ( ) ) plt . close ( 'all' ) # # plot: painting area by gender, with logistic regression # if config . EXTENDED : gender_df = query_module . gender_query ( ) pix_size = pixels_to_inches ( ( 600 , 400 ) ) g = seaborn . FacetGrid ( gender_df , hue = "gender" , margin_titles = True , size = pix_size [ 1 ] , aspect = pix_size [ 0 ] / pix_size [ 1 ] ) bins = np . linspace ( 0 , 5 , 30 ) g . map ( plt . hist , "area" , bins = bins , lw = 0 , alpha = 0.5 , normed = True ) g . axes [ 0 , 0 ] . set_xlabel ( 'Area, m^2' ) g . axes [ 0 , 0 ] . set_ylabel ( 'Percentage of paintings' ) context [ 'area_by_gender_svg' ] = fig_to_svg ( plt . gcf ( ) ) plt . close ( 'all' ) # # render template # out_file = path . join ( out_dir , "analysis.html" ) html_content = template . render ( * * context ) with open ( out_file , 'w' ) as f : f . write ( html_content ) # done, clean up plt . close ( 'all' ) session . close ( )
Generate analysis output as html page
582
7
11,956
def _to_pywintypes ( row ) : def _pywintype ( x ) : if isinstance ( x , dt . date ) : return dt . datetime ( x . year , x . month , x . day , tzinfo = dt . timezone . utc ) elif isinstance ( x , ( dt . datetime , pa . Timestamp ) ) : if x . tzinfo is None : return x . replace ( tzinfo = dt . timezone . utc ) elif isinstance ( x , str ) : if re . match ( "^\d{4}-\d{2}-\d{2}$" , x ) : return "'" + x return x elif isinstance ( x , np . integer ) : return int ( x ) elif isinstance ( x , np . floating ) : return float ( x ) elif x is not None and not isinstance ( x , ( str , int , float , bool ) ) : return str ( x ) return x return [ _pywintype ( x ) for x in row ]
convert values in a row to types accepted by excel
241
11
11,957
def iterrows ( self , workbook = None ) : resolved_tables = [ ] max_height = 0 max_width = 0 # while yielding rows __formula_values is updated with any formula values set on Expressions self . __formula_values = { } for name , ( table , ( row , col ) ) in list ( self . __tables . items ( ) ) : # get the resolved 2d data array from the table # # expressions with no explicit table will use None when calling # get_table/get_table_pos, which should return the current table. # self . __tables [ None ] = ( table , ( row , col ) ) data = table . get_data ( workbook , row , col , self . __formula_values ) del self . __tables [ None ] height , width = data . shape upper_left = ( row , col ) lower_right = ( row + height - 1 , col + width - 1 ) max_height = max ( max_height , lower_right [ 0 ] + 1 ) max_width = max ( max_width , lower_right [ 1 ] + 1 ) resolved_tables . append ( ( name , data , upper_left , lower_right ) ) for row , col in self . __values . keys ( ) : max_width = max ( max_width , row + 1 ) max_height = max ( max_height , col + 1 ) # Build the whole table up-front. Doing it row by row is too slow. table = [ [ None ] * max_width for i in range ( max_height ) ] for name , data , upper_left , lower_right in resolved_tables : for i , r in enumerate ( range ( upper_left [ 0 ] , lower_right [ 0 ] + 1 ) ) : for j , c in enumerate ( range ( upper_left [ 1 ] , lower_right [ 1 ] + 1 ) ) : table [ r ] [ c ] = data [ i ] [ j ] for ( r , c ) , value in self . __values . items ( ) : if isinstance ( value , Value ) : value = value . value if isinstance ( value , Expression ) : if value . has_value : self . __formula_values [ ( r , c ) ] = value . value value = value . get_formula ( workbook , r , c ) table [ r ] [ c ] = value for row in table : yield row
Yield rows as lists of data .
535
8
11,958
def create ( context , name , content = None , file_path = None , mime = 'text/plain' , jobstate_id = None , md5 = None , job_id = None , test_id = None ) : if content and file_path : raise Exception ( 'content and file_path are mutually exclusive' ) elif not content and not file_path : raise Exception ( 'At least one of content or file_path must be specified' ) headers = { 'DCI-NAME' : name , 'DCI-MIME' : mime , 'DCI-JOBSTATE-ID' : jobstate_id , 'DCI-MD5' : md5 , 'DCI-JOB-ID' : job_id , 'DCI-TEST-ID' : test_id } headers = utils . sanitize_kwargs ( * * headers ) uri = '%s/%s' % ( context . dci_cs_api , RESOURCE ) if content : if not hasattr ( content , 'read' ) : if not isinstance ( content , bytes ) : content = content . encode ( 'utf-8' ) content = io . BytesIO ( content ) return context . session . post ( uri , headers = headers , data = content ) else : if not os . path . exists ( file_path ) : raise FileErrorException ( ) with open ( file_path , 'rb' ) as f : return context . session . post ( uri , headers = headers , data = f )
Method to create a file on the Control - Server
336
10
11,959
def register_formatter ( field_typestr ) : def decorator_register ( formatter ) : @ functools . wraps ( formatter ) def wrapped_formatter ( * args , * * kwargs ) : field_name = args [ 0 ] field = args [ 1 ] field_id = args [ 2 ] # Before running the formatter, do type checking field_type = get_type ( field_typestr ) if not isinstance ( field , field_type ) : message = ( 'Field {0} ({1!r}) is not an ' '{2} type. It is an {3}.' ) raise ValueError ( message . format ( field_name , field , field_typestr , typestring ( field ) ) ) # Run the formatter itself nodes = formatter ( * args , * * kwargs ) # Package nodes from the formatter into a section section = make_section ( section_id = field_id + '-section' , contents = nodes ) return section FIELD_FORMATTERS [ field_typestr ] = wrapped_formatter return wrapped_formatter return decorator_register
Decorate a configuration field formatter function to register it with the get_field_formatter accessor .
249
22
11,960
def format_configurablefield_nodes ( field_name , field , field_id , state , lineno ) : # Custom default target definition list that links to Task topics default_item = nodes . definition_list_item ( ) default_item . append ( nodes . term ( text = "Default" ) ) default_item_content = nodes . definition ( ) para = nodes . paragraph ( ) name = '.' . join ( ( field . target . __module__ , field . target . __name__ ) ) para += pending_task_xref ( rawsource = name ) default_item_content += para default_item += default_item_content # Definition list for key-value metadata dl = nodes . definition_list ( ) dl += default_item dl += create_field_type_item_node ( field , state ) # Doc for this ConfigurableField, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ]
Create a section node that documents a ConfigurableField config field .
246
13
11,961
def format_listfield_nodes ( field_name , field , field_id , state , lineno ) : # ListField's store their item types in the itemtype attribute itemtype_node = nodes . definition_list_item ( ) itemtype_node += nodes . term ( text = 'Item type' ) itemtype_def = nodes . definition ( ) itemtype_def += make_python_xref_nodes_for_type ( field . itemtype , state , hide_namespace = False ) itemtype_node += itemtype_def minlength_node = None if field . minLength : minlength_node = nodes . definition_list_item ( ) minlength_node += nodes . term ( text = 'Minimum length' ) minlength_def = nodes . definition ( ) minlength_def += nodes . paragraph ( text = str ( field . minLength ) ) minlength_node += minlength_def maxlength_node = None if field . maxLength : maxlength_node = nodes . definition_list_item ( ) maxlength_node += nodes . term ( text = 'Maximum length' ) maxlength_def = nodes . definition ( ) maxlength_def += nodes . paragraph ( text = str ( field . maxLength ) ) maxlength_node += maxlength_def length_node = None if field . length : length_node = nodes . definition_list_item ( ) length_node += nodes . term ( text = 'Required length' ) length_def = nodes . definition ( ) length_def += nodes . paragraph ( text = str ( field . length ) ) length_node += length_def # Type description field_type_item = nodes . definition_list_item ( ) field_type_item . append ( nodes . term ( text = "Field type" ) ) field_type_item_content = nodes . definition ( ) field_type_item_content_p = nodes . paragraph ( ) field_type_item_content_p += make_python_xref_nodes_for_type ( field . itemtype , state , hide_namespace = False ) [ 0 ] . children [ 0 ] field_type_item_content_p += nodes . Text ( ' ' , ' ' ) field_type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children [ 0 ] if field . optional : field_type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) field_type_item_content += field_type_item_content_p field_type_item += field_type_item_content # Reference target env = state . document . settings . env ref_target = create_configfield_ref_target_node ( field_id , env , lineno ) # Title is the field's attribute name title = nodes . title ( text = field_name ) title += ref_target # Definition list for key-value metadata dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item if minlength_node : dl += minlength_node if maxlength_node : dl += maxlength_node if length_node : dl += length_node # Doc for this ConfigurableField, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ]
Create a section node that documents a ListField config field .
792
12
11,962
def format_choicefield_nodes ( field_name , field , field_id , state , lineno ) : # Create a definition list for the choices choice_dl = nodes . definition_list ( ) for choice_value , choice_doc in field . allowed . items ( ) : item = nodes . definition_list_item ( ) item_term = nodes . term ( ) item_term += nodes . literal ( text = repr ( choice_value ) ) item += item_term item_definition = nodes . definition ( ) item_definition . append ( nodes . paragraph ( text = choice_doc ) ) item += item_definition choice_dl . append ( item ) choices_node = nodes . definition_list_item ( ) choices_node . append ( nodes . term ( text = 'Choices' ) ) choices_definition = nodes . definition ( ) choices_definition . append ( choice_dl ) choices_node . append ( choices_definition ) # Field type field_type_item = nodes . definition_list_item ( ) field_type_item . append ( nodes . term ( text = "Field type" ) ) field_type_item_content = nodes . definition ( ) field_type_item_content_p = nodes . paragraph ( ) field_type_item_content_p += make_python_xref_nodes_for_type ( field . dtype , state , hide_namespace = False ) [ 0 ] . children [ 0 ] field_type_item_content_p += nodes . Text ( ' ' , ' ' ) field_type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children [ 0 ] if field . optional : field_type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) field_type_item_content += field_type_item_content_p field_type_item += field_type_item_content # Definition list for key-value metadata dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item dl += choices_node # Doc for this ConfigurableField, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ]
Create a section node that documents a ChoiceField config field .
551
12
11,963
def format_rangefield_nodes ( field_name , field , field_id , state , lineno ) : # Field type field_type_item = nodes . definition_list_item ( ) field_type_item . append ( nodes . term ( text = "Field type" ) ) field_type_item_content = nodes . definition ( ) field_type_item_content_p = nodes . paragraph ( ) field_type_item_content_p += make_python_xref_nodes_for_type ( field . dtype , state , hide_namespace = False ) [ 0 ] . children [ 0 ] field_type_item_content_p += nodes . Text ( ' ' , ' ' ) field_type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children [ 0 ] if field . optional : field_type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) field_type_item_content += field_type_item_content_p field_type_item += field_type_item_content # Format definition list item for the range range_node = nodes . definition_list_item ( ) range_node += nodes . term ( text = 'Range' ) range_node_def = nodes . definition ( ) range_node_def += nodes . paragraph ( text = field . rangeString ) range_node += range_node_def # Definition list for key-value metadata dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item dl += range_node # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ]
Create a section node that documents a RangeField config field .
444
12
11,964
def format_dictfield_nodes ( field_name , field , field_id , state , lineno ) : # Custom value type field for definition list valuetype_item = nodes . definition_list_item ( ) valuetype_item = nodes . term ( text = 'Value type' ) valuetype_def = nodes . definition ( ) valuetype_def += make_python_xref_nodes_for_type ( field . itemtype , state , hide_namespace = False ) valuetype_item += valuetype_def # Definition list for key-value metadata dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += create_field_type_item_node ( field , state ) dl += create_keytype_item_node ( field , state ) dl += valuetype_item # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ]
Create a section node that documents a DictField config field .
265
13
11,965
def format_configfield_nodes ( field_name , field , field_id , state , lineno ) : # Default data type node dtype_node = nodes . definition_list_item ( ) dtype_node = nodes . term ( text = 'Data type' ) dtype_def = nodes . definition ( ) dtype_def_para = nodes . paragraph ( ) name = '.' . join ( ( field . dtype . __module__ , field . dtype . __name__ ) ) dtype_def_para += pending_config_xref ( rawsource = name ) dtype_def += dtype_def_para dtype_node += dtype_def # Definition list for key-value metadata dl = nodes . definition_list ( ) dl += dtype_node dl += create_field_type_item_node ( field , state ) # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ]
Create a section node that documents a ConfigField config field .
256
12
11,966
def format_configchoicefield_nodes ( field_name , field , field_id , state , lineno ) : # Create a definition list for the choices choice_dl = nodes . definition_list ( ) for choice_value , choice_class in field . typemap . items ( ) : item = nodes . definition_list_item ( ) item_term = nodes . term ( ) item_term += nodes . literal ( text = repr ( choice_value ) ) item += item_term item_definition = nodes . definition ( ) def_para = nodes . paragraph ( ) name = '.' . join ( ( choice_class . __module__ , choice_class . __name__ ) ) def_para += pending_config_xref ( rawsource = name ) item_definition += def_para item += item_definition choice_dl . append ( item ) choices_node = nodes . definition_list_item ( ) choices_node . append ( nodes . term ( text = 'Choices' ) ) choices_definition = nodes . definition ( ) choices_definition . append ( choice_dl ) choices_node . append ( choices_definition ) # Field type field_type_item = nodes . definition_list_item ( ) field_type_item . append ( nodes . term ( text = "Field type" ) ) field_type_item_content = nodes . definition ( ) field_type_item_content_p = nodes . paragraph ( ) if field . multi : multi_text = "Multi-selection " else : multi_text = "Single-selection " field_type_item_content_p += nodes . Text ( multi_text , multi_text ) field_type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children [ 0 ] if field . optional : field_type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) field_type_item_content += field_type_item_content_p field_type_item += field_type_item_content dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item dl += choices_node # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ]
Create a section node that documents a ConfigChoiceField config field .
568
13
11,967
def format_configdictfield_nodes ( field_name , field , field_id , state , lineno ) : # Valuetype links to a Config task topic value_item = nodes . definition_list_item ( ) value_item += nodes . term ( text = "Value type" ) value_item_def = nodes . definition ( ) value_item_def_para = nodes . paragraph ( ) name = '.' . join ( ( field . itemtype . __module__ , field . itemtype . __name__ ) ) value_item_def_para += pending_config_xref ( rawsource = name ) value_item_def += value_item_def_para value_item += value_item_def dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += create_field_type_item_node ( field , state ) dl += create_keytype_item_node ( field , state ) dl += value_item # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ]
Create a section node that documents a ConfigDictField config field .
288
14
11,968
def format_registryfield_nodes ( field_name , field , field_id , state , lineno ) : from lsst . pex . config . registry import ConfigurableWrapper # Create a definition list for the choices # This iteration is over field.registry.items(), not field.items(), so # that the directive shows the configurables, not their ConfigClasses. choice_dl = nodes . definition_list ( ) for choice_value , choice_class in field . registry . items ( ) : # Introspect the class name from item in the registry. This is harder # than it should be. Most registry items seem to fall in the first # category. Some are ConfigurableWrapper types that expose the # underlying task class through the _target attribute. if hasattr ( choice_class , '__module__' ) and hasattr ( choice_class , '__name__' ) : name = '.' . join ( ( choice_class . __module__ , choice_class . __name__ ) ) elif isinstance ( choice_class , ConfigurableWrapper ) : name = '.' . join ( ( choice_class . _target . __class__ . __module__ , choice_class . _target . __class__ . __name__ ) ) else : name = '.' . join ( ( choice_class . __class__ . __module__ , choice_class . __class__ . __name__ ) ) item = nodes . definition_list_item ( ) item_term = nodes . term ( ) item_term += nodes . literal ( text = repr ( choice_value ) ) item += item_term item_definition = nodes . definition ( ) def_para = nodes . paragraph ( ) def_para += pending_task_xref ( rawsource = name ) item_definition += def_para item += item_definition choice_dl . append ( item ) choices_node = nodes . definition_list_item ( ) choices_node . append ( nodes . term ( text = 'Choices' ) ) choices_definition = nodes . definition ( ) choices_definition . append ( choice_dl ) choices_node . append ( choices_definition ) # Field type field_type_item = nodes . definition_list_item ( ) field_type_item . append ( nodes . term ( text = "Field type" ) ) field_type_item_content = nodes . definition ( ) field_type_item_content_p = nodes . paragraph ( ) if field . multi : multi_text = "Multi-selection " else : multi_text = "Single-selection " field_type_item_content_p += nodes . Text ( multi_text , multi_text ) field_type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children [ 0 ] if field . optional : field_type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) field_type_item_content += field_type_item_content_p field_type_item += field_type_item_content dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item dl += choices_node # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ]
Create a section node that documents a RegistryField config field .
786
12
11,969
def create_field_type_item_node ( field , state ) : type_item = nodes . definition_list_item ( ) type_item . append ( nodes . term ( text = "Field type" ) ) type_item_content = nodes . definition ( ) type_item_content_p = nodes . paragraph ( ) type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children if field . optional : type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) type_item_content += type_item_content_p type_item += type_item_content return type_item
Create a definition list item node that describes a field s type .
165
13
11,970
def create_default_item_node ( field , state ) : default_item = nodes . definition_list_item ( ) default_item . append ( nodes . term ( text = "Default" ) ) default_item_content = nodes . definition ( ) default_item_content . append ( nodes . literal ( text = repr ( field . default ) ) ) default_item . append ( default_item_content ) return default_item
Create a definition list item node that describes the default value of a Field config .
93
16
11,971
def create_keytype_item_node ( field , state ) : keytype_node = nodes . definition_list_item ( ) keytype_node = nodes . term ( text = 'Key type' ) keytype_def = nodes . definition ( ) keytype_def += make_python_xref_nodes_for_type ( field . keytype , state , hide_namespace = False ) keytype_node += keytype_def return keytype_node
Create a definition list item node that describes the key type of a dict - type config field .
102
19
11,972
def create_description_node ( field , state ) : doc_container_node = nodes . container ( ) doc_container_node += parse_rst_content ( field . doc , state ) return doc_container_node
Creates docutils nodes for the Field s description built from the field s doc and optional attributes .
48
20
11,973
def create_title_node ( field_name , field , field_id , state , lineno ) : # Reference target env = state . document . settings . env ref_target = create_configfield_ref_target_node ( field_id , env , lineno ) # Title is the field's attribute name title = nodes . title ( text = field_name ) title += ref_target return title
Create docutils nodes for the configuration field s title and reference target node .
86
15
11,974
def create_configfield_ref_target_node ( target_id , env , lineno ) : target_node = nodes . target ( '' , '' , ids = [ target_id ] ) # Store these task/configurable topic nodes in the environment for later # cross referencing. if not hasattr ( env , 'lsst_configfields' ) : env . lsst_configfields = { } env . lsst_configfields [ target_id ] = { 'docname' : env . docname , 'lineno' : lineno , 'target' : target_node , } return target_node
Create a target node that marks a configuration field .
132
10
11,975
def translate_argv ( raw_args ) : kwargs = { } def get_parameter ( param_str ) : for i , a in enumerate ( raw_args ) : if a == param_str : assert len ( raw_args ) == i + 2 and raw_args [ i + 1 ] [ 0 ] != '-' , 'All arguments must have a value, e.g. `-testing true`' return raw_args [ i + 1 ] return None value = get_parameter ( '-testing' ) if value is not None and value . lower ( ) in ( 'true' , 't' , 'yes' ) : kwargs [ 'testing' ] = True value = get_parameter ( '-connect' ) if value is not None : colon = value . find ( ':' ) if colon > - 1 : kwargs [ 'host' ] = value [ 0 : colon ] kwargs [ 'port' ] = int ( value [ colon + 1 : ] ) else : kwargs [ 'host' ] = value value = get_parameter ( '-name' ) if value is not None : kwargs [ 'name' ] = value value = get_parameter ( '-group' ) if value is not None : kwargs [ 'group_name' ] = value value = get_parameter ( '-scan' ) if value in ( 'true' , 't' , 'yes' ) : kwargs [ 'scan_for_port' ] = True value = get_parameter ( '-debug' ) if value in ( 'true' , 't' , 'yes' ) : kwargs [ 'debug' ] = True return kwargs
Enables conversion from system arguments .
375
7
11,976
def _build_toctree ( self ) : dirname = posixpath . dirname ( self . _env . docname ) tree_prefix = self . options [ 'toctree' ] . strip ( ) root = posixpath . normpath ( posixpath . join ( dirname , tree_prefix ) ) docnames = [ docname for docname in self . _env . found_docs if docname . startswith ( root ) ] # Sort docnames alphabetically based on **class** name. # The standard we assume is that task doc pages are named after # their Python namespace. # NOTE: this ordering only applies to the toctree; the visual ordering # is set by `process_task_topic_list`. # NOTE: docnames are **always** POSIX-like paths class_names = [ docname . split ( '/' ) [ - 1 ] . split ( '.' ) [ - 1 ] for docname in docnames ] docnames = [ docname for docname , _ in sorted ( zip ( docnames , class_names ) , key = lambda pair : pair [ 1 ] ) ] tocnode = sphinx . addnodes . toctree ( ) tocnode [ 'includefiles' ] = docnames tocnode [ 'entries' ] = [ ( None , docname ) for docname in docnames ] tocnode [ 'maxdepth' ] = - 1 tocnode [ 'glob' ] = None tocnode [ 'hidden' ] = True return tocnode
Create a hidden toctree node with the contents of a directory prefixed by the directory name specified by the toctree directive option .
334
28
11,977
def do_GET ( self ) : self . send_response ( 200 ) self . send_header ( "Content-type" , "text/html" ) self . end_headers ( ) self . wfile . write ( bytes ( json . dumps ( self . message ) , "utf-8" ) )
Handle GET WebMethod
66
4
11,978
def serve_forever ( self , poll_interval = 0.5 ) : while self . is_alive : self . handle_request ( ) time . sleep ( poll_interval )
Cycle for webserer
42
6
11,979
def stop ( self ) : self . is_alive = False self . server_close ( ) flows . Global . LOGGER . info ( "Server Stops " + ( str ( self . server_address ) ) )
Stop the webserver
47
4
11,980
def check_scalar ( self , scalar_dict ) : table = { k : np . array ( [ v ] ) for k , v in scalar_dict . items ( ) } return self . mask ( table ) [ 0 ]
check if scalar_dict satisfy query
52
8
11,981
def dumpfile ( self , fd ) : self . start ( ) dump = DumpFile ( fd ) self . queue . append ( dump )
Dump a file through a Spin instance .
32
9
11,982
def run ( self ) : document = self . state . document if not document . settings . file_insertion_enabled : return [ document . reporter . warning ( 'File insertion disabled' , line = self . lineno ) ] try : location = self . state_machine . get_source_and_line ( self . lineno ) # Customized for RemoteCodeBlock url = self . arguments [ 0 ] reader = RemoteCodeBlockReader ( url , self . options , self . config ) text , lines = reader . read ( location = location ) retnode = nodes . literal_block ( text , text ) set_source_info ( self , retnode ) if self . options . get ( 'diff' ) : # if diff is set, set udiff retnode [ 'language' ] = 'udiff' elif 'language' in self . options : retnode [ 'language' ] = self . options [ 'language' ] retnode [ 'linenos' ] = ( 'linenos' in self . options or 'lineno-start' in self . options or 'lineno-match' in self . options ) retnode [ 'classes' ] += self . options . get ( 'class' , [ ] ) extra_args = retnode [ 'highlight_args' ] = { } if 'emphasize-lines' in self . options : hl_lines = parselinenos ( self . options [ 'emphasize-lines' ] , lines ) if any ( i >= lines for i in hl_lines ) : logger . warning ( 'line number spec is out of range(1-%d): %r' % ( lines , self . options [ 'emphasize-lines' ] ) , location = location ) extra_args [ 'hl_lines' ] = [ x + 1 for x in hl_lines if x < lines ] extra_args [ 'linenostart' ] = reader . lineno_start if 'caption' in self . options : caption = self . options [ 'caption' ] or self . arguments [ 0 ] retnode = container_wrapper ( self , retnode , caption ) # retnode will be note_implicit_target that is linked from caption # and numref. when options['name'] is provided, it should be # primary ID. self . add_name ( retnode ) return [ retnode ] except Exception as exc : return [ document . reporter . warning ( str ( exc ) , line = self . lineno ) ]
Run the remote - code - block directive .
536
9
11,983
def read_file ( self , url , location = None ) : response = requests_retry_session ( ) . get ( url , timeout = 10.0 ) response . raise_for_status ( ) text = response . text if 'tab-width' in self . options : text = text . expandtabs ( self . options [ 'tab-width' ] ) return text . splitlines ( True )
Read content from the web by overriding LiteralIncludeReader . read_file .
87
17
11,984
def verify_time ( self , now ) : return now . time ( ) >= self . start_time and now . time ( ) <= self . end_time
Verify the time
34
4
11,985
def verify_weekday ( self , now ) : return self . weekdays == "*" or str ( now . weekday ( ) ) in self . weekdays . split ( " " )
Verify the weekday
40
4
11,986
def verify_day ( self , now ) : return self . day == "*" or str ( now . day ) in self . day . split ( " " )
Verify the day
35
4
11,987
def verify_month ( self , now ) : return self . month == "*" or str ( now . month ) in self . month . split ( " " )
Verify the month
35
4
11,988
def aggregate_duplicates ( X , Y , aggregator = "mean" , precision = precision ) : if callable ( aggregator ) : pass elif "min" in aggregator . lower ( ) : aggregator = np . min elif "max" in aggregator . lower ( ) : aggregator = np . max elif "median" in aggregator . lower ( ) : aggregator = np . median elif aggregator . lower ( ) in [ "average" , "mean" ] : aggregator = np . mean elif "first" in aggregator . lower ( ) : def aggregator ( x ) : return x [ 0 ] elif "last" in aggregator . lower ( ) : def aggregator ( x ) : return x [ - 1 ] else : warnings . warn ( 'Aggregator "{}" not understood. Skipping sample ' "aggregation." . format ( aggregator ) ) return X , Y is_y_multivariate = Y . ndim > 1 X_rounded = X . round ( decimals = precision ) unique_xs = np . unique ( X_rounded , axis = 0 ) old_size = len ( X_rounded ) new_size = len ( unique_xs ) if old_size == new_size : return X , Y if not is_y_multivariate : Y = np . atleast_2d ( Y ) . T reduced_y = np . empty ( ( new_size , Y . shape [ 1 ] ) ) warnings . warn ( "Domain space duplicates caused a data reduction. " + "Original size: {} vs. New size: {}" . format ( old_size , new_size ) ) for col in range ( Y . shape [ 1 ] ) : for i , distinct_row in enumerate ( unique_xs ) : filtered_rows = np . all ( X_rounded == distinct_row , axis = 1 ) reduced_y [ i , col ] = aggregator ( Y [ filtered_rows , col ] ) if not is_y_multivariate : reduced_y = reduced_y . flatten ( ) return unique_xs , reduced_y
A function that will attempt to collapse duplicates in domain space X by aggregating values over the range space Y .
459
23
11,989
def __set_data ( self , X , Y , w = None ) : self . X = X self . Y = Y self . check_duplicates ( ) if w is not None : self . w = np . array ( w ) else : self . w = np . ones ( len ( Y ) ) * 1.0 / float ( len ( Y ) ) if self . normalization == "feature" : # This doesn't work with one-dimensional arrays on older # versions of sklearn min_max_scaler = sklearn . preprocessing . MinMaxScaler ( ) self . Xnorm = min_max_scaler . fit_transform ( np . atleast_2d ( self . X ) ) elif self . normalization == "zscore" : self . Xnorm = sklearn . preprocessing . scale ( self . X , axis = 0 , with_mean = True , with_std = True , copy = True ) else : self . Xnorm = np . array ( self . X )
Internally assigns the input data and normalizes it according to the user s specifications
219
16
11,990
def build ( self , X , Y , w = None , edges = None ) : self . reset ( ) if X is None or Y is None : return self . __set_data ( X , Y , w ) if self . debug : sys . stdout . write ( "Graph Preparation: " ) start = time . clock ( ) self . graph_rep = nglpy . Graph ( self . Xnorm , self . graph , self . max_neighbors , self . beta , connect = self . connect , ) if self . debug : end = time . clock ( ) sys . stdout . write ( "%f s\n" % ( end - start ) )
Assigns data to this object and builds the requested topological structure
144
14
11,991
def load_data_and_build ( self , filename , delimiter = "," ) : data = np . genfromtxt ( filename , dtype = float , delimiter = delimiter , names = True ) data = data . view ( np . float64 ) . reshape ( data . shape + ( - 1 , ) ) X = data [ : , 0 : - 1 ] Y = data [ : , - 1 ] self . build ( X = X , Y = Y )
Convenience function for directly working with a data file . This opens a file and reads the data into an array sets the data as an nparray and list of dimnames
102
36
11,992
def get_normed_x ( self , rows = None , cols = None ) : if rows is None : rows = list ( range ( 0 , self . get_sample_size ( ) ) ) if cols is None : cols = list ( range ( 0 , self . get_dimensionality ( ) ) ) if not hasattr ( rows , "__iter__" ) : rows = [ rows ] rows = sorted ( list ( set ( rows ) ) ) retValue = self . Xnorm [ rows , : ] return retValue [ : , cols ]
Returns the normalized input data requested by the user
121
9
11,993
def get_x ( self , rows = None , cols = None ) : if rows is None : rows = list ( range ( 0 , self . get_sample_size ( ) ) ) if cols is None : cols = list ( range ( 0 , self . get_dimensionality ( ) ) ) if not hasattr ( rows , "__iter__" ) : rows = [ rows ] rows = sorted ( list ( set ( rows ) ) ) retValue = self . X [ rows , : ] if len ( rows ) == 0 : return [ ] return retValue [ : , cols ]
Returns the input data requested by the user
128
8
11,994
def get_y ( self , indices = None ) : if indices is None : indices = list ( range ( 0 , self . get_sample_size ( ) ) ) else : if not hasattr ( indices , "__iter__" ) : indices = [ indices ] indices = sorted ( list ( set ( indices ) ) ) if len ( indices ) == 0 : return [ ] return self . Y [ indices ]
Returns the output data requested by the user
87
8
11,995
def get_weights ( self , indices = None ) : if indices is None : indices = list ( range ( 0 , self . get_sample_size ( ) ) ) else : indices = sorted ( list ( set ( indices ) ) ) if len ( indices ) == 0 : return [ ] return self . w [ indices ]
Returns the weights requested by the user
68
7
11,996
def check_duplicates ( self ) : if self . aggregator is not None : X , Y = TopologicalObject . aggregate_duplicates ( self . X , self . Y , self . aggregator ) self . X = X self . Y = Y temp_x = self . X . round ( decimals = TopologicalObject . precision ) unique_xs = len ( np . unique ( temp_x , axis = 0 ) ) # unique_ys = len(np.unique(self.Y, axis=0)) # if len(self.Y) != unique_ys: # warnings.warn('Range space has duplicates. Simulation of ' # 'simplicity may help, but artificial noise may ' # 'occur in flat regions of the domain. Sample size:' # '{} vs. Unique Records: {}'.format(len(self.Y), # unique_ys)) if len ( self . X ) != unique_xs : raise ValueError ( "Domain space has duplicates. Try using an " "aggregator function to consolidate duplicates " "into a single sample with one range value. " "e.g., " + self . __class__ . __name__ + "(aggregator='max'). " "\n\tNumber of " "Records: {}\n\tNumber of Unique Records: {}\n" . format ( len ( self . X ) , unique_xs ) )
Function to test whether duplicates exist in the input or output space . First if an aggregator function has been specified the domain space duplicates will be consolidated using the function to generate a new range value for that shared point . Otherwise it will raise a ValueError . The function will raise a warning if duplicates exist in the output space
305
67
11,997
def column_stack_2d ( data ) : return list ( list ( itt . chain . from_iterable ( _ ) ) for _ in zip ( * data ) )
Perform column - stacking on a list of 2d data blocks .
38
14
11,998
def discover_conf_py_directory ( initial_dir ) : # Create an absolute Path to work with initial_dir = pathlib . Path ( initial_dir ) . resolve ( ) # Search upwards until a conf.py is found try : return str ( _search_parents ( initial_dir ) ) except FileNotFoundError : raise
Discover the directory containing the conf . py file .
71
10
11,999
def _search_parents ( initial_dir ) : root_paths = ( '.' , '/' ) parent = pathlib . Path ( initial_dir ) while True : if _has_conf_py ( parent ) : return parent if str ( parent ) in root_paths : break parent = parent . parent msg = ( "Cannot detect a conf.py Sphinx configuration file from {!s}. " "Are you inside a Sphinx documenation repository?" ) . format ( initial_dir ) raise FileNotFoundError ( msg )
Search the initial and parent directories for a conf . py Sphinx configuration file that represents the root of a Sphinx project .
116
25