idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
30,500
def trips ( self , val ) : self . _trips = val if val is not None and not val . empty : self . _trips_i = self . _trips . set_index ( "trip_id" ) else : self . _trips_i = None
Update self . _trips_i if self . trips changes .
30,501
def calendar ( self , val ) : self . _calendar = val if val is not None and not val . empty : self . _calendar_i = self . _calendar . set_index ( "service_id" ) else : self . _calendar_i = None
Update self . _calendar_i if self . calendar changes .
30,502
def calendar_dates ( self , val ) : self . _calendar_dates = val if val is not None and not val . empty : self . _calendar_dates_g = self . _calendar_dates . groupby ( [ "service_id" , "date" ] ) else : self . _calendar_dates_g = None
Update self . _calendar_dates_g if self . calendar_dates changes .
30,503
def copy ( self ) -> "Feed" : other = Feed ( dist_units = self . dist_units ) for key in set ( cs . FEED_ATTRS ) - set ( [ "dist_units" ] ) : value = getattr ( self , key ) if isinstance ( value , pd . DataFrame ) : value = value . copy ( ) elif isinstance ( value , pd . core . groupby . DataFrameGroupBy ) : value = de...
Return a copy of this feed that is a feed with all the same attributes .
30,504
def _encode_content ( self , uri , content ) : if content is None : content = self . NONE return smart_str ( '|' . join ( [ six . text_type ( uri ) , content ] ) )
Join node uri and content as string and convert to bytes to ensure no pickling in memcached .
30,505
def _decode_content ( self , content ) : content = smart_unicode ( content ) uri , _ , content = content . partition ( u'|' ) if content == self . NONE : content = None return uri or None , content
Split node string to uri and content and convert back to unicode .
30,506
def render_node ( node , context = None , edit = True ) : output = node . render ( ** context or { } ) or u'' if edit : return u'<span data-i18n="{0}">{1}</span>' . format ( node . uri . clone ( scheme = None , ext = None , version = None ) , output ) else : return output
Render node as html for templates with edit tagging .
30,507
def get_post_data ( self , request ) : params = dict ( request . POST ) params . update ( request . FILES ) data = defaultdict ( dict ) for param in sorted ( params . keys ( ) ) : value = params [ param ] if isinstance ( value , list ) and len ( value ) <= 1 : value = value [ 0 ] if value else None prefix , _ , field =...
Collect and merge post parameters with multipart files .
30,508
def get ( self , request , uri ) : uri = self . decode_uri ( uri ) node = cio . get ( uri , lazy = False ) if node . content is None : raise Http404 return self . render_to_json ( { 'uri' : node . uri , 'content' : node . content } )
Return published node or specified version .
30,509
def post ( self , request , uri ) : uri = self . decode_uri ( uri ) data , meta = self . get_post_data ( request ) meta [ 'author' ] = auth . get_username ( request ) node = cio . set ( uri , data , publish = False , ** meta ) return self . render_to_json ( node )
Set node data for uri return rendered content .
30,510
def delete ( self , request , uri ) : uri = self . decode_uri ( uri ) uris = cio . delete ( uri ) if uri not in uris : raise Http404 return self . render_to_response ( )
Delete versioned uri and return empty text response on success .
30,511
def put ( self , request , uri ) : uri = self . decode_uri ( uri ) node = cio . publish ( uri ) if not node : raise Http404 return self . render_to_json ( node )
Publish versioned uri .
30,512
def get ( self , request , uri ) : uri = self . decode_uri ( uri ) revisions = cio . revisions ( uri ) revisions = [ list ( revision ) for revision in revisions ] return self . render_to_json ( revisions )
List uri revisions .
30,513
def get ( self , request , uri ) : uri = self . decode_uri ( uri ) node = cio . load ( uri ) return self . render_to_json ( node )
Load raw node source from storage .
30,514
def post ( self , request , ext ) : try : plugin = plugins . get ( ext ) data , meta = self . get_post_data ( request ) data = plugin . load ( data ) except UnknownPlugin : raise Http404 else : content = plugin . render ( data ) return self . render_to_response ( content )
Render data for plugin and return text response .
30,515
def set_checklists_status ( auth , args ) : global checklists_on if auth [ 'checklists' ] == "true" : checklists_on = True else : checklists_on = False if args [ '--checklists' ] : checklists_on = not checklists_on return
Set display_checklist status toggling from cli flag
30,516
def build_wsgi_environ_from_event ( event ) : params = event . get ( 'queryStringParameters' ) environ = EnvironBuilder ( method = event . get ( 'httpMethod' ) or 'GET' , path = event . get ( 'path' ) or '/' , headers = event . get ( 'headers' ) or { } , data = event . get ( 'body' ) or b'' , query_string = params or {...
Create a WSGI environment from the proxy integration event .
30,517
def wsgi_handler ( event , context , app , logger ) : environ = build_wsgi_environ_from_event ( event ) wsgi_status = [ ] wsgi_headers = [ ] logger . info ( 'Processing {} request' . format ( environ [ 'REQUEST_METHOD' ] ) ) def start_response ( status , headers ) : if len ( wsgi_status ) or len ( wsgi_headers ) : rais...
lambda handler function . This function runs the WSGI app with it and collects its response then translates the response back into the format expected by the API Gateway proxy integration .
30,518
def assume_role ( credentials , account , role ) : sts = boto3 . client ( 'sts' , aws_access_key_id = credentials [ 'accessKeyId' ] , aws_secret_access_key = credentials [ 'secretAccessKey' ] , aws_session_token = credentials [ 'sessionToken' ] , ) resp = sts . assume_role ( RoleArn = 'arn:aws:sts::{}:role/{}' . format...
Use FAWS provided credentials to assume defined role .
30,519
def get_environment ( config , stage ) : stage_data = get_stage_data ( stage , config . get ( 'stages' , { } ) ) if not stage_data : sys . exit ( NO_STAGE_DATA . format ( stage ) ) try : return stage_data [ 'environment' ] except KeyError : sys . exit ( NO_ENV_IN_STAGE . format ( stage ) )
Find default environment name in stage .
30,520
def get_account ( config , environment , stage = None ) : if environment is None and stage : environment = get_environment ( config , stage ) account = None for env in config . get ( 'environments' , [ ] ) : if env . get ( 'name' ) == environment : account = env . get ( 'account' ) role = env . get ( 'role' ) username ...
Find environment name in config object and return AWS account .
30,521
def get_aws_creds ( account , tenant , token ) : url = ( FAWS_API_URL . format ( account ) ) headers = { 'X-Auth-Token' : token , 'X-Tenant-Id' : tenant , } response = requests . post ( url , headers = headers , json = { 'credential' : { 'duration' : '3600' } } ) if not response . ok : sys . exit ( FAWS_API_ERROR . for...
Get AWS account credentials to enable access to AWS .
30,522
def get_config ( config_file ) : config_path = os . path . abspath ( config_file ) try : with open ( config_path , 'r' ) as data : config = yaml . safe_load ( data ) except IOError as exc : sys . exit ( str ( exc ) ) return config
Get config file and parse YAML into dict .
30,523
def get_rackspace_token ( username , apikey ) : auth_params = { "auth" : { "RAX-KSKEY:apiKeyCredentials" : { "username" : username , "apiKey" : apikey , } } } response = requests . post ( RS_IDENTITY_URL , json = auth_params ) if not response . ok : sys . exit ( RS_AUTH_ERROR . format ( response . status_code , respons...
Get Rackspace Identity token .
30,524
def validate_args ( args ) : if not any ( [ args . environment , args . stage , args . account ] ) : sys . exit ( NO_ACCT_OR_ENV_ERROR ) if args . environment and args . account : sys . exit ( ENV_AND_ACCT_ERROR ) if args . environment and args . role : sys . exit ( ENV_AND_ROLE_ERROR )
Validate command - line arguments .
30,525
def set_default_timeout ( timeout = None , connect_timeout = None , read_timeout = None ) : global DEFAULT_CONNECT_TIMEOUT global DEFAULT_READ_TIMEOUT DEFAULT_CONNECT_TIMEOUT = connect_timeout if connect_timeout is not None else timeout DEFAULT_READ_TIMEOUT = read_timeout if read_timeout is not None else timeout
The purpose of this function is to install default socket timeouts and retry policy for requests calls . Any requests issued through the requests wrappers defined in this module will have these automatically set unless explicitly overriden .
30,526
def request ( self , method , url , ** kwargs ) : if 'timeout' not in kwargs : if self . timeout is not None : kwargs [ 'timeout' ] = self . timeout else : kwargs [ 'timeout' ] = ( DEFAULT_CONNECT_TIMEOUT , DEFAULT_READ_TIMEOUT ) return super ( Session , self ) . request ( method = method , url = url , ** kwargs )
Send a request . If timeout is not explicitly given use the default timeouts .
30,527
def _has_streamhandler ( logger , level = None , fmt = LOG_FORMAT , stream = DEFAULT_STREAM ) : if isinstance ( level , basestring ) : level = logging . getLevelName ( level ) for handler in logger . handlers : if not isinstance ( handler , logging . StreamHandler ) : continue if handler . stream is not stream : contin...
Check the named logger for an appropriate existing StreamHandler .
30,528
def inject_request_ids_into_environment ( func ) : @ wraps ( func ) def wrapper ( event , context ) : if 'requestContext' in event : os . environ [ ENV_APIG_REQUEST_ID ] = event [ 'requestContext' ] . get ( 'requestId' , 'N/A' ) os . environ [ ENV_LAMBDA_REQUEST_ID ] = context . aws_request_id return func ( event , con...
Decorator for the Lambda handler to inject request IDs for logging .
30,529
def add_request_ids_from_environment ( logger , name , event_dict ) : if ENV_APIG_REQUEST_ID in os . environ : event_dict [ 'api_request_id' ] = os . environ [ ENV_APIG_REQUEST_ID ] if ENV_LAMBDA_REQUEST_ID in os . environ : event_dict [ 'lambda_request_id' ] = os . environ [ ENV_LAMBDA_REQUEST_ID ] return event_dict
Custom processor adding request IDs to the log event if available .
30,530
def get_logger ( name = None , level = None , stream = DEFAULT_STREAM , clobber_root_handler = True , logger_factory = None , wrapper_class = None ) : _configure_logger ( logger_factory = logger_factory , wrapper_class = wrapper_class ) log = structlog . get_logger ( name ) root_logger = logging . root if log == root_l...
Configure and return a logger with structlog and stdlib .
30,531
def validate ( token ) : token_url = TOKEN_URL_FMT . format ( token = token ) headers = { 'x-auth-token' : token , 'accept' : 'application/json' , } resp = requests . get ( token_url , headers = headers ) if not resp . status_code == 200 : raise HTTPError ( status = 401 ) return resp . json ( )
Validate token and return auth context .
30,532
def _fullmatch ( pattern , text , * args , ** kwargs ) : match = re . match ( pattern , text , * args , ** kwargs ) return match if match . group ( 0 ) == text else None
re . fullmatch is not available on Python<3 . 4 .
30,533
def _read_config_file ( args ) : stage = args . stage with open ( args . config , 'rt' ) as f : config = yaml . safe_load ( f . read ( ) ) STATE [ 'stages' ] = config [ 'stages' ] config [ 'config' ] = _decrypt_item ( config [ 'config' ] , stage = stage , key = '' , render = True ) return config [ 'stages' ] , config [...
Decrypt config file returns a tuple with stages and config .
30,534
def get_trace_id ( ) : raw_trace_id = os . environ . get ( '_X_AMZN_TRACE_ID' , '' ) trace_id_parts = raw_trace_id . split ( ';' ) trace_kwargs = { 'trace_id' : None , 'parent_id' : None , 'sampled' : False , } if trace_id_parts [ 0 ] != '' : for part in trace_id_parts : name , value = part . split ( '=' ) if name == '...
Parse X - Ray Trace ID environment variable .
30,535
def get_xray_daemon ( ) : env_value = os . environ . get ( 'AWS_XRAY_DAEMON_ADDRESS' ) if env_value is None : raise XRayDaemonNotFoundError ( ) xray_ip , xray_port = env_value . split ( ':' ) return XRayDaemon ( ip_address = xray_ip , port = int ( xray_port ) )
Parse X - Ray Daemon address environment variable .
30,536
def send_segment_document_to_xray_daemon ( segment_document ) : try : xray_daemon = get_xray_daemon ( ) except XRayDaemonNotFoundError : LOGGER . error ( 'X-Ray Daemon not running, skipping send' ) return message = u'{header}\n{document}' . format ( header = json . dumps ( XRAY_DAEMON_HEADER ) , document = json . dumps...
Format and send document to the X - Ray Daemon .
30,537
def send_subsegment_to_xray_daemon ( subsegment_id , parent_id , start_time , end_time = None , name = None , namespace = 'remote' , extra_data = None ) : extra_data = extra_data or { } trace_id = get_trace_id ( ) segment_document = { 'type' : 'subsegment' , 'id' : subsegment_id , 'trace_id' : trace_id . trace_id , 'pa...
High level function to send data to the X - Ray Daemon .
30,538
def generic_xray_wrapper ( wrapped , instance , args , kwargs , name , namespace , metadata_extractor , error_handling_type = ERROR_HANDLING_GENERIC ) : if not get_trace_id ( ) . sampled : LOGGER . debug ( 'Request not sampled by X-Ray, skipping trace' ) return wrapped ( * args , ** kwargs ) start_time = time . time ( ...
Wrapper function around existing calls to send traces to X - Ray .
30,539
def extract_function_metadata ( wrapped , instance , args , kwargs , return_value ) : LOGGER . debug ( 'Extracting function call metadata' , args = args , kwargs = kwargs , ) return { 'metadata' : { 'args' : args , 'kwargs' : kwargs , } , }
Stash the args and kwargs into the metadata of the subsegment .
30,540
def trace_xray_subsegment ( skip_args = False ) : @ wrapt . decorator def wrapper ( wrapped , instance , args , kwargs ) : metadata_extractor = ( noop_function_metadata if skip_args else extract_function_metadata ) return generic_xray_wrapper ( wrapped , instance , args , kwargs , name = get_function_name , namespace =...
Can be applied to any function or method to be traced by X - Ray .
30,541
def get_service_name ( wrapped , instance , args , kwargs ) : if 'serviceAbbreviation' not in instance . _service_model . metadata : return instance . _service_model . metadata [ 'endpointPrefix' ] return instance . _service_model . metadata [ 'serviceAbbreviation' ]
Return the AWS service name the client is communicating with .
30,542
def extract_aws_metadata ( wrapped , instance , args , kwargs , return_value ) : response = return_value LOGGER . debug ( 'Extracting AWS metadata' , args = args , kwargs = kwargs , ) if 'operation_name' in kwargs : operation_name = kwargs [ 'operation_name' ] else : operation_name = args [ 0 ] if len ( kwargs ) == 0 a...
Provide AWS metadata for improved visualization .
30,543
def xray_botocore_api_call ( wrapped , instance , args , kwargs ) : return generic_xray_wrapper ( wrapped , instance , args , kwargs , name = get_service_name , namespace = 'aws' , metadata_extractor = extract_aws_metadata , error_handling_type = ERROR_HANDLING_BOTOCORE , )
Wrapper around botocore s base client API call method .
30,544
def extract_http_metadata ( wrapped , instance , args , kwargs , return_value ) : response = return_value LOGGER . debug ( 'Extracting HTTP metadata' , args = args , kwargs = kwargs , ) if 'request' in kwargs : request = kwargs [ 'request' ] else : request = args [ 0 ] metadata = { 'http' : { 'request' : { 'method' : r...
Provide HTTP request metadata for improved visualization .
30,545
def xray_requests_send ( wrapped , instance , args , kwargs ) : return generic_xray_wrapper ( wrapped , instance , args , kwargs , name = 'requests' , namespace = 'remote' , metadata_extractor = extract_http_metadata , )
Wrapper around the requests library s low - level send method .
30,546
def set_unit_spike_features ( self , unit_id , feature_name , value ) : if isinstance ( unit_id , ( int , np . integer ) ) : if unit_id in self . get_unit_ids ( ) : if unit_id not in self . _unit_features . keys ( ) : self . _unit_features [ unit_id ] = { } if isinstance ( feature_name , str ) and len ( value ) == len ...
This function adds a unit features data set under the given features name to the given unit .
30,547
def set_unit_property ( self , unit_id , property_name , value ) : if isinstance ( unit_id , ( int , np . integer ) ) : if unit_id in self . get_unit_ids ( ) : if unit_id not in self . _unit_properties : self . _unit_properties [ unit_id ] = { } if isinstance ( property_name , str ) : self . _unit_properties [ unit_id ...
This function adds a unit property data set under the given property name to the given unit .
30,548
def set_units_property ( self , * , unit_ids = None , property_name , values ) : if unit_ids is None : unit_ids = self . get_unit_ids ( ) for i , unit in enumerate ( unit_ids ) : self . set_unit_property ( unit_id = unit , property_name = property_name , value = values [ i ] )
Sets unit property data for a list of units
30,549
def get_unit_property ( self , unit_id , property_name ) : if isinstance ( unit_id , ( int , np . integer ) ) : if unit_id in self . get_unit_ids ( ) : if unit_id not in self . _unit_properties : self . _unit_properties [ unit_id ] = { } if isinstance ( property_name , str ) : if property_name in list ( self . _unit_pr...
This function rerturns the data stored under the property name given from the given unit .
30,550
def get_units_property ( self , * , unit_ids = None , property_name ) : if unit_ids is None : unit_ids = self . get_unit_ids ( ) values = [ self . get_unit_property ( unit_id = unit , property_name = property_name ) for unit in unit_ids ] return values
Returns a list of values stored under the property name corresponding to a list of units
30,551
def get_unit_property_names ( self , unit_id = None ) : if unit_id is None : property_names = [ ] for unit_id in self . get_unit_ids ( ) : curr_property_names = self . get_unit_property_names ( unit_id ) for curr_property_name in curr_property_names : property_names . append ( curr_property_name ) property_names = sort...
Get a list of property names for a given unit or for all units if unit_id is None
30,552
def copy_unit_properties ( self , sorting , unit_ids = None ) : if unit_ids is None : unit_ids = sorting . get_unit_ids ( ) if isinstance ( unit_ids , int ) : curr_property_names = sorting . get_unit_property_names ( unit_id = unit_ids ) for curr_property_name in curr_property_names : value = sorting . get_unit_propert...
Copy unit properties from another sorting extractor to the current sorting extractor .
30,553
def copy_unit_spike_features ( self , sorting , unit_ids = None ) : if unit_ids is None : unit_ids = sorting . get_unit_ids ( ) if isinstance ( unit_ids , int ) : curr_feature_names = sorting . get_unit_spike_feature_names ( unit_id = unit_ids ) for curr_feature_name in curr_feature_names : value = sorting . get_unit_s...
Copy unit spike features from another sorting extractor to the current sorting extractor .
30,554
def get_snippets ( self , * , reference_frames , snippet_len , channel_ids = None ) : if isinstance ( snippet_len , ( tuple , list , np . ndarray ) ) : snippet_len_before = snippet_len [ 0 ] snippet_len_after = snippet_len [ 1 ] else : snippet_len_before = int ( ( snippet_len + 1 ) / 2 ) snippet_len_after = snippet_len...
This function returns data snippets from the given channels that are starting on the given frames and are the length of the given snippet lengths before and after .
30,555
def set_channel_locations ( self , channel_ids , locations ) : if len ( channel_ids ) == len ( locations ) : for i in range ( len ( channel_ids ) ) : if isinstance ( locations [ i ] , ( list , np . ndarray ) ) : location = np . asarray ( locations [ i ] ) self . set_channel_property ( channel_ids [ i ] , 'location' , l...
This function sets the location properties of each specified channel id with the corresponding locations of the passed in locations list .
30,556
def get_channel_locations ( self , channel_ids ) : locations = [ ] for channel_id in channel_ids : location = self . get_channel_property ( channel_id , 'location' ) locations . append ( location ) return locations
This function returns the location of each channel specifed by channel_ids
30,557
def set_channel_groups ( self , channel_ids , groups ) : if len ( channel_ids ) == len ( groups ) : for i in range ( len ( channel_ids ) ) : if isinstance ( groups [ i ] , int ) : self . set_channel_property ( channel_ids [ i ] , 'group' , groups [ i ] ) else : raise ValueError ( str ( groups [ i ] ) + " must be an int...
This function sets the group property of each specified channel id with the corresponding group of the passed in groups list .
30,558
def get_channel_groups ( self , channel_ids ) : groups = [ ] for channel_id in channel_ids : group = self . get_channel_property ( channel_id , 'group' ) groups . append ( group ) return groups
This function returns the group of each channel specifed by channel_ids
30,559
def set_channel_property ( self , channel_id , property_name , value ) : if isinstance ( channel_id , ( int , np . integer ) ) : if channel_id in self . get_channel_ids ( ) : if channel_id not in self . _channel_properties : self . _channel_properties [ channel_id ] = { } if isinstance ( property_name , str ) : self . ...
This function adds a property dataset to the given channel under the property name .
30,560
def get_channel_property ( self , channel_id , property_name ) : if isinstance ( channel_id , ( int , np . integer ) ) : if channel_id in self . get_channel_ids ( ) : if channel_id not in self . _channel_properties : self . _channel_properties [ channel_id ] = { } if isinstance ( property_name , str ) : if property_nam...
This function returns the data stored under the property name from the given channel .
30,561
def add_epoch ( self , epoch_name , start_frame , end_frame ) : if isinstance ( epoch_name , str ) : self . _epochs [ epoch_name ] = { 'start_frame' : int ( start_frame ) , 'end_frame' : int ( end_frame ) } else : raise ValueError ( "epoch_name must be a string" )
This function adds an epoch to your recording extractor that tracks a certain time period in your recording . It is stored in an internal dictionary of start and end frame tuples .
30,562
def remove_epoch ( self , epoch_name ) : if isinstance ( epoch_name , str ) : if epoch_name in list ( self . _epochs . keys ( ) ) : del self . _epochs [ epoch_name ] else : raise ValueError ( "This epoch has not been added" ) else : raise ValueError ( "epoch_name must be a string" )
This function removes an epoch from your recording extractor .
30,563
def get_epoch_names ( self ) : epoch_names = list ( self . _epochs . keys ( ) ) if not epoch_names : pass else : epoch_start_frames = [ ] for epoch_name in epoch_names : epoch_info = self . get_epoch_info ( epoch_name ) start_frame = epoch_info [ 'start_frame' ] epoch_start_frames . append ( start_frame ) epoch_names =...
This function returns a list of all the epoch names in your recording
30,564
def get_epoch_info ( self , epoch_name ) : if isinstance ( epoch_name , str ) : if epoch_name in list ( self . _epochs . keys ( ) ) : epoch_info = self . _epochs [ epoch_name ] return epoch_info else : raise ValueError ( "This epoch has not been added" ) else : raise ValueError ( "epoch_name must be a string" )
This function returns the start frame and end frame of the epoch in a dict .
30,565
def get_epoch ( self , epoch_name ) : epoch_info = self . get_epoch_info ( epoch_name ) start_frame = epoch_info [ 'start_frame' ] end_frame = epoch_info [ 'end_frame' ] from . SubRecordingExtractor import SubRecordingExtractor return SubRecordingExtractor ( parent_recording = self , start_frame = start_frame , end_fra...
This function returns a SubRecordingExtractor which is a view to the given epoch
30,566
def exclude_units ( self , unit_ids ) : root_ids = [ ] for i in range ( len ( self . _roots ) ) : root_id = self . _roots [ i ] . unit_id root_ids . append ( root_id ) if ( set ( unit_ids ) . issubset ( set ( root_ids ) ) and len ( unit_ids ) > 0 ) : indices_to_be_deleted = [ ] for unit_id in unit_ids : root_index = ro...
This function deletes roots from the curation tree according to the given unit_ids
30,567
def merge_units ( self , unit_ids ) : root_ids = [ ] for i in range ( len ( self . _roots ) ) : root_id = self . _roots [ i ] . unit_id root_ids . append ( root_id ) indices_to_be_deleted = [ ] if ( set ( unit_ids ) . issubset ( set ( root_ids ) ) and len ( unit_ids ) > 1 ) : all_feature_names = [ ] for unit_id in unit...
This function merges two roots from the curation tree according to the given unit_ids . It creates a new unit_id and root that has the merged roots as children .
30,568
def split_unit ( self , unit_id , indices ) : root_ids = [ ] for i in range ( len ( self . _roots ) ) : root_id = self . _roots [ i ] . unit_id root_ids . append ( root_id ) if ( unit_id in root_ids ) : indices_1 = np . sort ( np . asarray ( list ( set ( indices ) ) ) ) root_index = root_ids . index ( unit_id ) new_chi...
This function splits a root from the curation tree according to the given unit_id and indices . It creates two new unit_ids and roots that have the split root as a child . This function splits the spike train of the root by the given indices .
30,569
def read_python ( path ) : from six import exec_ path = Path ( path ) . absolute ( ) assert path . is_file ( ) with path . open ( 'r' ) as f : contents = f . read ( ) metadata = { } exec_ ( contents , { } , metadata ) metadata = { k . lower ( ) : v for ( k , v ) in metadata . items ( ) } return metadata
Parses python scripts in a dictionary
30,570
def save_probe_file ( recording , probe_file , format = None , radius = 100 , dimensions = None ) : probe_file = Path ( probe_file ) if not probe_file . parent . is_dir ( ) : probe_file . parent . mkdir ( ) if probe_file . suffix == '.csv' : with probe_file . open ( 'w' ) as f : if 'location' in recording . get_channel...
Saves probe file from the channel information of the given recording extractor
30,571
def write_binary_dat_format ( recording , save_path , time_axis = 0 , dtype = None , chunksize = None ) : save_path = Path ( save_path ) if save_path . suffix == '' : save_path = save_path . parent / ( save_path . name + '.dat' ) if chunksize is None : traces = recording . get_traces ( ) if dtype is not None : traces =...
Saves the traces of a recording extractor in binary . dat format .
30,572
def openBiocamFile ( filename , verbose = False ) : rf = h5py . File ( filename , 'r' ) recVars = rf . require_group ( '3BRecInfo/3BRecVars/' ) nFrames = recVars [ 'NRecFrames' ] [ 0 ] samplingRate = recVars [ 'SamplingRate' ] [ 0 ] signalInv = recVars [ 'SignalInversion' ] [ 0 ] chipVars = rf . require_group ( '3BRecI...
Open a Biocam hdf5 file read and return the recording info pick te correct method to access raw data and return this to the caller .
30,573
def countries ( ) : global _countries if not _countries : v = { } _countries = v try : from pytz import country_names for k , n in country_names . items ( ) : v [ k . upper ( ) ] = n except Exception : pass return _countries
get country dictionar from pytz and add some extra .
30,574
def countryccys ( ) : global _country_ccys if not _country_ccys : v = { } _country_ccys = v ccys = currencydb ( ) for c in eurozone : v [ c ] = 'EUR' for c in ccys . values ( ) : if c . default_country : v [ c . default_country ] = c . code return _country_ccys
Create a dictionary with keys given by countries ISO codes and values given by their currencies
30,575
def set_country_map ( cfrom , cto , name = None , replace = True ) : global _country_maps cdb = countries ( ) cfrom = str ( cfrom ) . upper ( ) c = cdb . get ( cfrom ) if c : if name : c = name cto = str ( cto ) . upper ( ) if cto in cdb : raise CountryError ( 'Country %s already in database' % cto ) cdb [ cto ] = c _c...
Set a mapping between a country code to another code
30,576
def set_new_country ( code , ccy , name ) : code = str ( code ) . upper ( ) cdb = countries ( ) if code in cdb : raise CountryError ( 'Country %s already in database' % code ) ccys = currencydb ( ) ccy = str ( ccy ) . upper ( ) if ccy not in ccys : raise CountryError ( 'Currency %s not in database' % ccy ) cdb [ code ]...
Add new country code to database
30,577
def run ( self ) : data_path = self . arguments [ 0 ] header = self . options . get ( 'header' , True ) bits = data_path . split ( '.' ) name = bits [ - 1 ] path = '.' . join ( bits [ : - 1 ] ) node = table_node ( ) code = None try : module = import_module ( path ) except Exception : code = '<p>Could not import %s</p>'...
Implements the directive
30,578
def todate ( val ) : if not val : raise ValueError ( "Value not provided" ) if isinstance ( val , datetime ) : return val . date ( ) elif isinstance ( val , date ) : return val else : try : ival = int ( val ) sval = str ( ival ) if len ( sval ) == 8 : return yyyymmdd2date ( val ) elif len ( sval ) == 5 : return juldate...
Convert val to a datetime . date instance by trying several conversion algorithm . If it fails it raise a ValueError exception .
30,579
def components ( self ) : p = '' neg = self . totaldays < 0 y = self . years m = self . months w = self . weeks d = self . days if y : p = '%sY' % abs ( y ) if m : p = '%s%sM' % ( p , abs ( m ) ) if w : p = '%s%sW' % ( p , abs ( w ) ) if d : p = '%s%sD' % ( p , abs ( d ) ) return '-' + p if neg else p
The period string
30,580
def simple ( self ) : if self . _days : return '%sD' % self . totaldays elif self . months : return '%sM' % self . _months elif self . years : return '%sY' % self . years else : return ''
A string representation with only one period delimiter .
30,581
def swap ( self , c2 ) : inv = False c1 = self if c1 . order > c2 . order : ct = c1 c1 = c2 c2 = ct inv = True return inv , c1 , c2
put the order of currencies as market standard
30,582
def as_cross ( self , delimiter = '' ) : if self . order > usd_order : return 'USD%s%s' % ( delimiter , self . code ) else : return '%s%sUSD' % ( self . code , delimiter )
Return a cross rate representation with respect USD .
30,583
def POST ( self , path , body , xml = True ) : url = self . _absolute_url ( path ) headers = dict ( self . headers ) if xml : headers [ 'Content-Type' ] = 'application/xml' headers [ 'Accept' ] = 'application/xml' else : headers [ 'Content-Type' ] = 'application/json' headers [ 'Accept' ] = 'application/json' resp = re...
Raw POST to the MISP server
30,584
def GET ( self , path ) : url = self . _absolute_url ( path ) resp = requests . get ( url , headers = self . headers , verify = self . verify_ssl ) if resp . status_code != 200 : raise MispTransportError ( 'GET %s: returned status=%d' , path , resp . status_code ) return resp . content
Raw GET to the MISP server
30,585
def from_attribute ( attr ) : assert attr is not MispAttribute prop = MispShadowAttribute ( ) prop . distribution = attr . distribution prop . type = attr . type prop . comment = attr . comment prop . value = attr . value prop . category = attr . category prop . to_ids = attr . to_ids return prop
Converts an attribute into a shadow attribute .
30,586
def active_processes ( self , use_cache = True ) : LOGGER . debug ( 'Checking active processes (cache: %s)' , use_cache ) if self . can_use_process_cache ( use_cache ) : return self . _active_cache [ 1 ] active_processes , dead_processes = list ( ) , list ( ) for consumer in self . consumers : processes = list ( self ....
Return a list of all active processes pruning dead ones
30,587
def calculate_stats ( self , data ) : timestamp = data [ 'timestamp' ] del data [ 'timestamp' ] stats = self . consumer_stats_counter ( ) consumer_stats = dict ( ) for name in data . keys ( ) : consumer_stats [ name ] = self . consumer_stats_counter ( ) consumer_stats [ name ] [ 'processes' ] = self . process_count ( n...
Calculate the stats data for our process level data .
30,588
def can_use_process_cache ( self , use_cache ) : return ( use_cache and self . _active_cache and self . _active_cache [ 0 ] > ( time . time ( ) - self . poll_interval ) )
Returns True if the process cache can be used
30,589
def check_process_counts ( self ) : LOGGER . debug ( 'Checking minimum consumer process levels' ) for name in self . consumers : processes_needed = self . process_spawn_qty ( name ) if processes_needed : LOGGER . info ( 'Need to spawn %i processes for %s' , processes_needed , name ) self . start_processes ( name , proc...
Check for the minimum consumer process levels and start up new processes needed .
30,590
def collect_results ( self , data_values ) : self . last_poll_results [ 'timestamp' ] = self . poll_data [ 'timestamp' ] consumer_name = data_values [ 'consumer_name' ] del data_values [ 'consumer_name' ] process_name = data_values [ 'name' ] del data_values [ 'name' ] if consumer_name not in self . last_poll_results :...
Receive the data from the consumers polled and process it .
30,591
def consumer_stats_counter ( ) : return { process . Process . ERROR : 0 , process . Process . PROCESSED : 0 , process . Process . REDELIVERED : 0 }
Return a new consumer stats counter instance .
30,592
def get_consumer_process ( self , consumer , name ) : return self . consumers [ consumer ] . processes . get ( name )
Get the process object for the specified consumer and process name .
30,593
def get_consumer_cfg ( config , only , qty ) : consumers = dict ( config . application . Consumers or { } ) if only : for key in list ( consumers . keys ( ) ) : if key != only : del consumers [ key ] if qty : consumers [ only ] [ 'qty' ] = qty return consumers
Get the consumers config possibly filtering the config if only or qty is set .
30,594
def is_dead ( self , proc , name ) : LOGGER . debug ( 'Checking %s (%r)' , name , proc ) try : status = proc . status ( ) except psutil . NoSuchProcess : LOGGER . debug ( 'NoSuchProcess: %s (%r)' , name , proc ) return True LOGGER . debug ( 'Process %s (%s) status: %r (Unresponsive Count: %s)' , name , proc . pid , sta...
Checks to see if the specified process is dead .
30,595
def kill_processes ( self ) : LOGGER . critical ( 'Max shutdown exceeded, forcibly exiting' ) processes = self . active_processes ( False ) while processes : for proc in self . active_processes ( False ) : if int ( proc . pid ) != int ( os . getpid ( ) ) : LOGGER . warning ( 'Killing %s (%s)' , proc . name , proc . pid...
Gets called on shutdown by the timer when too much time has gone by calling the terminate method instead of nicely asking for the consumers to stop .
30,596
def log_stats ( self ) : if not self . stats . get ( 'counts' ) : if self . consumers : LOGGER . info ( 'Did not receive any stats data from children' ) return if self . poll_data [ 'processes' ] : LOGGER . warning ( '%i process(es) did not respond with stats: %r' , len ( self . poll_data [ 'processes' ] ) , self . pol...
Output the stats to the LOGGER .
30,597
def new_consumer ( self , config , consumer_name ) : return Consumer ( 0 , dict ( ) , config . get ( 'qty' , self . DEFAULT_CONSUMER_QTY ) , config . get ( 'queue' , consumer_name ) )
Return a consumer dict for the given name and configuration .
30,598
def new_process ( self , consumer_name ) : process_name = '%s-%s' % ( consumer_name , self . new_process_number ( consumer_name ) ) kwargs = { 'config' : self . config . application , 'consumer_name' : consumer_name , 'profile' : self . profile , 'daemon' : False , 'stats_queue' : self . stats_queue , 'logging_config' ...
Create a new consumer instances
30,599
def new_process_number ( self , name ) : self . consumers [ name ] . last_proc_num += 1 return self . consumers [ name ] . last_proc_num
Increment the counter for the process id number for a given consumer configuration .