idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
10,700
def binarize_signal ( signal , treshold = "auto" , cut = "higher" ) : if treshold == "auto" : treshold = ( np . max ( np . array ( signal ) ) - np . min ( np . array ( signal ) ) ) / 2 signal = list ( signal ) binary_signal = [ ] for i in range ( len ( signal ) ) : if cut == "higher" : if signal [ i ] > treshold : bina...
Binarize a channel based on a continuous channel .
10,701
def localize_events ( events_channel , treshold = "auto" , cut = "higher" , time_index = None ) : events_channel = binarize_signal ( events_channel , treshold = treshold , cut = cut ) events = { "onsets" : [ ] , "durations" : [ ] } if time_index is not None : events [ "onsets_time" ] = [ ] index = 0 for key , g in ( gr...
Find the onsets of all events based on a continuous signal .
10,702
def find_events ( events_channel , treshold = "auto" , cut = "higher" , time_index = None , number = "all" , after = 0 , before = None , min_duration = 1 ) : events = localize_events ( events_channel , treshold = treshold , cut = cut , time_index = time_index ) if len ( events [ "onsets" ] ) == 0 : print ( "NeuroKit wa...
Find and select events based on a continuous signal .
10,703
def plot_events_in_signal ( signal , events_onsets , color = "red" , marker = None ) : df = pd . DataFrame ( signal ) ax = df . plot ( ) def plotOnSignal ( x , color , marker = None ) : if ( marker is None ) : plt . axvline ( x = event , color = color ) else : plt . plot ( x , signal [ x ] , marker , color = color ) ev...
Plot events in signal .
10,704
def eda_scr ( signal , sampling_rate = 1000 , treshold = 0.1 , method = "fast" ) : if method == "slow" : gradient = np . gradient ( signal ) size = int ( 0.1 * sampling_rate ) smooth , _ = biosppy . tools . smoother ( signal = gradient , kernel = 'bartlett' , size = size , mirror = True ) zeros , = biosppy . tools . ze...
Skin - Conductance Responses extraction algorithm .
10,705
def add_response ( self , response , value ) : if value != "stop" : self . X = pd . concat ( [ self . X , pd . DataFrame ( { "Signal" : [ value ] } ) ] ) self . y = np . array ( list ( self . y ) + [ response ] ) if len ( set ( list ( self . y ) ) ) > 1 : self . model = self . fit_model ( self . X , self . y )
Add response to staircase .
10,706
def create_epochs ( data , events_onsets , sampling_rate = 1000 , duration = 1 , onset = 0 , index = None ) : if isinstance ( duration , list ) or isinstance ( duration , np . ndarray ) : duration = np . array ( duration ) else : duration = np . array ( [ duration ] * len ( events_onsets ) ) if isinstance ( onset , lis...
Epoching a dataframe .
10,707
def interpolate ( values , value_times , sampling_rate = 1000 ) : initial_index = value_times [ 0 ] value_times = np . array ( value_times ) - initial_index spline = scipy . interpolate . splrep ( x = value_times , y = values , k = 3 , s = 0 ) x = np . arange ( 0 , value_times [ - 1 ] , 1 ) signal = scipy . interpolate...
3rd order spline interpolation .
10,708
def find_peaks ( signal ) : derivative = np . gradient ( signal , 2 ) peaks = np . where ( np . diff ( np . sign ( derivative ) ) ) [ 0 ] return ( peaks )
Locate peaks based on derivative .
10,709
def eeg_name_frequencies ( freqs ) : freqs = list ( freqs ) freqs_names = [ ] for freq in freqs : if freq < 1 : freqs_names . append ( "UltraLow" ) elif freq <= 3 : freqs_names . append ( "Delta" ) elif freq <= 7 : freqs_names . append ( "Theta" ) elif freq <= 9 : freqs_names . append ( "Alpha1/Mu" ) elif freq <= 12 : ...
Name frequencies according to standart classifications .
10,710
def normal_range ( mean , sd , treshold = 1.28 ) : bottom = mean - sd * treshold top = mean + sd * treshold return ( bottom , top )
Returns a bottom and a top limit on a normal distribution portion based on a treshold .
10,711
def find_following_duplicates ( array ) : array = array [ : ] uniques = [ ] for i in range ( len ( array ) ) : if i == 0 : uniques . append ( True ) else : if array [ i ] == array [ i - 1 ] : uniques . append ( False ) else : uniques . append ( True ) return ( uniques )
Find the duplicates that are following themselves .
10,712
def find_closest_in_list ( number , array , direction = "both" , strictly = False ) : if direction == "both" : closest = min ( array , key = lambda x : abs ( x - number ) ) if direction == "smaller" : if strictly is True : closest = max ( x for x in array if x < number ) else : closest = max ( x for x in array if x <= ...
Find the closest number in the array from x .
10,713
def emg_process ( emg , sampling_rate = 1000 , emg_names = None , envelope_freqs = [ 10 , 400 ] , envelope_lfreq = 4 , activation_treshold = "default" , activation_n_above = 0.25 , activation_n_below = 1 ) : if emg_names is None : if isinstance ( emg , pd . DataFrame ) : emg_names = emg . columns . values emg = np . ar...
Automated processing of EMG signal .
10,714
def emg_linear_envelope ( emg , sampling_rate = 1000 , freqs = [ 10 , 400 ] , lfreq = 4 ) : r emg = emg_tkeo ( emg ) if np . size ( freqs ) == 2 : b , a = scipy . signal . butter ( 2 , np . array ( freqs ) / ( sampling_rate / 2. ) , btype = 'bandpass' ) emg = scipy . signal . filtfilt ( b , a , emg ) if np . size ( lfr...
r Calculate the linear envelope of a signal .
10,715
def emg_find_activation ( envelope , sampling_rate = 1000 , threshold = 0 , n_above = 0.25 , n_below = 1 ) : n_above = n_above * sampling_rate n_below = n_below * sampling_rate envelope = np . atleast_1d ( envelope ) . astype ( 'float64' ) envelope [ np . isnan ( envelope ) ] = - np . inf inds = np . nonzero ( envelope...
Detects onset in data based on amplitude threshold .
10,716
def ecg_find_peaks ( signal , sampling_rate = 1000 ) : rpeaks , = biosppy . ecg . hamilton_segmenter ( np . array ( signal ) , sampling_rate = sampling_rate ) rpeaks , = biosppy . ecg . correct_rpeaks ( signal = np . array ( signal ) , rpeaks = rpeaks , sampling_rate = sampling_rate , tol = 0.05 ) return ( rpeaks )
Find R peaks indices on the ECG channel .
10,717
def ecg_wave_detector ( ecg , rpeaks ) : q_waves = [ ] p_waves = [ ] q_waves_starts = [ ] s_waves = [ ] t_waves = [ ] t_waves_starts = [ ] t_waves_ends = [ ] for index , rpeak in enumerate ( rpeaks [ : - 3 ] ) : try : epoch_before = np . array ( ecg ) [ int ( rpeaks [ index - 1 ] ) : int ( rpeak ) ] epoch_before = epoc...
Returns the localization of the P Q T waves . This function needs massive help!
10,718
def ecg_systole ( ecg , rpeaks , t_waves_ends ) : waves = np . array ( [ "" ] * len ( ecg ) ) waves [ rpeaks ] = "R" waves [ t_waves_ends ] = "T" systole = [ 0 ] current = 0 for index , value in enumerate ( waves [ 1 : ] ) : if waves [ index - 1 ] == "R" : current = 1 if waves [ index - 1 ] == "T" : current = 0 systole...
Returns the localization of systoles and diastoles .
10,719
def plot_eeg_erp_topo ( all_epochs , colors = None ) : all_evokeds = eeg_to_all_evokeds ( all_epochs ) data = { } for participant , epochs in all_evokeds . items ( ) : for cond , epoch in epochs . items ( ) : data [ cond ] = [ ] for participant , epochs in all_evokeds . items ( ) : for cond , epoch in epochs . items ( ...
Plot butterfly plot .
10,720
def save_nk_object ( obj , filename = "file" , path = "" , extension = "nk" , compress = False , compatibility = - 1 ) : if compress is True : with gzip . open ( path + filename + "." + extension , 'wb' ) as name : pickle . dump ( obj , name , protocol = compatibility ) else : with open ( path + filename + "." + extens...
Save whatever python object to a pickled file .
10,721
def read_nk_object ( filename , path = "" ) : filename = path + filename try : with open ( filename , 'rb' ) as name : file = pickle . load ( name ) except pickle . UnpicklingError : with gzip . open ( filename , 'rb' ) as name : file = pickle . load ( name ) except ModuleNotFoundError : try : file = pd . read_pickle (...
Read a pickled file .
10,722
def find_creation_date ( path ) : if platform . system ( ) == 'Windows' : return ( os . path . getctime ( path ) ) else : stat = os . stat ( path ) try : return ( stat . st_birthtime ) except AttributeError : print ( "Neuropsydia error: get_creation_date(): We're probably on Linux. No easy way to get creation dates her...
Try to get the date that a file was created falling back to when it was last modified if that s not possible .
10,723
def _register ( self , obj ) : session = None while session is None or session in self . sessions : session = random . randint ( 1000000 , 9999999 ) self . sessions [ session ] = obj return session
Creates a random but unique session handle for a session object register it in the sessions dictionary and return the value
10,724
def _return_handler ( self , ret_value , func , arguments ) : logger . debug ( '%s%s -> %r' , func . __name__ , _args_to_str ( arguments ) , ret_value , extra = self . _logging_extra ) try : ret_value = StatusCode ( ret_value ) except ValueError : pass self . _last_status = ret_value session = None if func . __name__ n...
Check return values for errors and warnings .
10,725
def clear ( self , session ) : try : sess = self . sessions [ session ] except KeyError : return constants . StatusCode . error_invalid_object return sess . clear ( )
Clears a device .
10,726
def gpib_command ( self , session , command_byte ) : try : return self . sessions [ session ] . gpib_command ( command_byte ) except KeyError : return constants . StatusCode . error_invalid_object
Write GPIB command byte on the bus .
10,727
def assert_trigger ( self , session , protocol ) : try : return self . sessions [ session ] . assert_trigger ( protocol ) except KeyError : return constants . StatusCode . error_invalid_object
Asserts software or hardware trigger .
10,728
def unlock ( self , session ) : try : sess = self . sessions [ session ] except KeyError : return StatusCode . error_invalid_object return sess . unlock ( )
Relinquishes a lock for the specified resource .
10,729
def find_raw_devices ( vendor = None , product = None , serial_number = None , custom_match = None , ** kwargs ) : def is_usbraw ( dev ) : if custom_match and not custom_match ( dev ) : return False return bool ( find_interfaces ( dev , bInterfaceClass = 0xFF , bInterfaceSubClass = 0xFF ) ) return find_devices ( vendor...
Find connected USB RAW devices . See usbutil . find_devices for more info .
10,730
def write ( self , data ) : begin , end , size = 0 , 0 , len ( data ) bytes_sent = 0 raw_write = super ( USBRawDevice , self ) . write while not end > size : begin = end end = begin + self . RECV_CHUNK bytes_sent += raw_write ( data [ begin : end ] ) return bytes_sent
Send raw bytes to the instrument .
10,731
def read ( self , size ) : raw_read = super ( USBRawDevice , self ) . read received = bytearray ( ) while not len ( received ) >= size : resp = raw_read ( self . RECV_CHUNK ) received . extend ( resp ) return bytes ( received )
Read raw bytes from the instrument .
10,732
def _find_listeners ( ) : for i in range ( 31 ) : try : if gpib . listener ( BOARD , i ) and gpib . ask ( BOARD , 1 ) != i : yield i except gpib . GpibError as e : logger . debug ( "GPIB error in _find_listeners(): %s" , repr ( e ) )
Find GPIB listeners .
10,733
def find_devices ( vendor = None , product = None , serial_number = None , custom_match = None , ** kwargs ) : kwargs = kwargs or { } attrs = { } if isinstance ( vendor , str ) : attrs [ 'manufacturer' ] = vendor elif vendor is not None : kwargs [ 'idVendor' ] = vendor if isinstance ( product , str ) : attrs [ 'product...
Find connected USB devices matching certain keywords .
10,734
def get_referenced_object ( prev_obj , obj , dot_separated_name , desired_type = None ) : from textx . scoping import Postponed assert prev_obj or not type ( obj ) is list names = dot_separated_name . split ( "." ) match = re . match ( r'parent\((\w+)\)' , names [ 0 ] ) if match : next_obj = obj desired_parent_typename...
get objects based on a path
10,735
def get_referenced_object_as_list ( prev_obj , obj , dot_separated_name , desired_type = None ) : res = get_referenced_object ( prev_obj , obj , dot_separated_name , desired_type ) if res is None : return [ ] elif type ( res ) is list : return res else : return [ res ]
Same as get_referenced_object but always returns a list .
10,736
def load_model ( self , the_metamodel , filename , is_main_model , encoding = 'utf-8' , add_to_local_models = True ) : if not self . local_models . has_model ( filename ) : if self . all_models . has_model ( filename ) : new_model = self . all_models . filename_to_model [ filename ] else : new_model = the_metamodel . i...
load a single model
10,737
def check ( ctx , meta_model_file , model_file , ignore_case ) : debug = ctx . obj [ 'debug' ] check_model ( meta_model_file , model_file , debug , ignore_case )
Check validity of meta - model and optionally model .
10,738
def get_entity_mm ( ) : type_builtins = { 'integer' : SimpleType ( None , 'integer' ) , 'string' : SimpleType ( None , 'string' ) } entity_mm = metamodel_from_file ( join ( this_folder , 'entity.tx' ) , classes = [ SimpleType ] , builtins = type_builtins ) return entity_mm
Builds and returns a meta - model for Entity language .
10,739
def sm_to_dot ( model ) : dot_str = HEADER first = True for state in model . states : dot_str += '{}[label="{{{}{}|{}}}"]\n' . format ( id ( state ) , r"-\> " if first else "" , state . name , "\\n" . join ( action . name for action in state . actions ) ) first = False for transition in state . transitions : dot_str +=...
Transforms given state machine model to dot str .
10,740
def get_language ( language_name ) : langs = list ( pkg_resources . iter_entry_points ( group = LANG_EP , name = language_name ) ) if not langs : raise TextXError ( 'Language "{}" is not registered.' . format ( language_name ) ) if len ( langs ) > 1 : raise TextXError ( 'Language "{}" registered multiple times:\n{}' . ...
Returns a callable that instantiates meta - model for the given language .
10,741
def get_model ( obj ) : p = obj while hasattr ( p , 'parent' ) : p = p . parent return p
Finds model root element for the given object .
10,742
def get_parent_of_type ( typ , obj ) : if type ( typ ) is not text : typ = typ . __name__ while hasattr ( obj , 'parent' ) : obj = obj . parent if obj . __class__ . __name__ == typ : return obj
Finds first object up the parent chain of the given type . If no parent of the given type exists None is returned .
10,743
def get_model_parser ( top_rule , comments_model , ** kwargs ) : class TextXModelParser ( Parser ) : def __init__ ( self , * args , ** kwargs ) : super ( TextXModelParser , self ) . __init__ ( * args , ** kwargs ) self . parser_model = Sequence ( nodes = [ top_rule , EOF ( ) ] , rule_name = 'Model' , root = True ) self...
Creates model parser for the given language .
10,744
def resolve_one_step ( self ) : metamodel = self . parser . metamodel current_crossrefs = self . parser . _crossrefs new_crossrefs = [ ] self . delayed_crossrefs = [ ] resolved_crossref_count = 0 default_scope = DefaultScopeProvider ( ) for obj , attr , crossref in current_crossrefs : if ( get_model ( obj ) == self . m...
Resolves model references .
10,745
def python_type ( textx_type_name ) : return { 'ID' : text , 'BOOL' : bool , 'INT' : int , 'FLOAT' : float , 'STRICTFLOAT' : float , 'STRING' : text , 'NUMBER' : float , 'BASETYPE' : text , } . get ( textx_type_name , textx_type_name )
Return Python type from the name of base textx type .
10,746
def language_from_str ( language_def , metamodel ) : if type ( language_def ) is not text : raise TextXError ( "textX accepts only unicode strings." ) if metamodel . debug : metamodel . dprint ( "*** PARSING LANGUAGE DEFINITION ***" ) if metamodel . debug in textX_parsers : parser = textX_parsers [ metamodel . debug ] ...
Constructs parser and initializes metamodel from language description given in textX language .
10,747
def second_textx_model ( self , model_parser ) : if self . grammar_parser . debug : self . grammar_parser . dprint ( "RESOLVING MODEL PARSER: second_pass" ) self . _resolve_rule_refs ( self . grammar_parser , model_parser ) self . _determine_rule_types ( model_parser . metamodel ) self . _resolve_cls_refs ( self . gram...
Cross reference resolving for parser model .
10,748
def _resolve_rule_refs ( self , grammar_parser , model_parser ) : def _resolve_rule ( rule ) : if not isinstance ( rule , RuleCrossRef ) and rule in resolved_rules : return rule resolved_rules . add ( rule ) if grammar_parser . debug : grammar_parser . dprint ( "Resolving rule: {}" . format ( rule ) ) if type ( rule ) ...
Resolves parser ParsingExpression crossrefs .
10,749
def match_abstract_str ( cls ) : def r ( s ) : if s . root : if s in visited or s . rule_name in ALL_TYPE_NAMES or ( hasattr ( s , '_tx_class' ) and s . _tx_class . _tx_type is not RULE_MATCH ) : return s . rule_name visited . add ( s ) if isinstance ( s , Match ) : result = text ( s ) elif isinstance ( s , OrderedChoi...
For a given abstract or match rule meta - class returns a nice string representation for the body .
10,750
def metamodel_from_str ( lang_desc , metamodel = None , ** kwargs ) : if not metamodel : metamodel = TextXMetaModel ( ** kwargs ) language_from_str ( lang_desc , metamodel ) return metamodel
Creates a new metamodel from the textX description given as a string .
10,751
def metamodel_from_file ( file_name , ** kwargs ) : with codecs . open ( file_name , 'r' , 'utf-8' ) as f : lang_desc = f . read ( ) metamodel = metamodel_from_str ( lang_desc = lang_desc , file_name = file_name , ** kwargs ) return metamodel
Creates new metamodel from the given file .
10,752
def _init_class ( self , cls , peg_rule , position , position_end = None , inherits = None , root = False , rule_type = RULE_MATCH ) : cls . _tx_metamodel = self cls . _tx_attrs = OrderedDict ( ) cls . _tx_inh_by = inherits if inherits else [ ] cls . _tx_position = position cls . _tx_position_end = position if position...
Setup meta - class special attributes namespaces etc . This is called both for textX created classes as well as user classes .
10,753
def _cls_fqn ( self , cls ) : ns = self . _namespace_stack [ - 1 ] if ns in [ '__base__' , None ] : return cls . __name__ else : return ns + '.' + cls . __name__
Returns fully qualified name for the class based on current namespace and the class name .
10,754
def _new_cls_attr ( self , clazz , name , cls = None , mult = MULT_ONE , cont = True , ref = False , bool_assignment = False , position = 0 ) : attr = MetaAttr ( name , cls , mult , cont , ref , bool_assignment , position ) clazz . _tx_attrs [ name ] = attr return attr
Creates new meta attribute of this class .
10,755
def convert ( self , value , _type ) : return self . type_convertors . get ( _type , lambda x : x ) ( value )
Convert instances of textx types and match rules to python types .
10,756
def register_obj_processors ( self , obj_processors ) : self . obj_processors = obj_processors self . type_convertors . update ( obj_processors )
Object processors are callables that will be called after each successful model object construction . Those callables receive model object as its parameter . Registration of new object processors will replace previous .
10,757
def interpret ( self ) : self . print_menu ( ) while True : try : event = input ( ) if event == 'q' : return event = int ( event ) event = self . model . events [ event - 1 ] except Exception : print ( 'Invalid input' ) self . event ( event ) self . print_menu ( )
Main interpreter loop .
10,758
def find_font ( font_name ) : if font_name in STANDARD_FONT_NAMES : return font_name , True elif font_name in _registered_fonts : return font_name , _registered_fonts [ font_name ] NOT_FOUND = ( None , False ) try : registerFont ( TTFont ( font_name , '%s.ttf' % font_name ) ) _registered_fonts [ font_name ] = True retu...
Return the font and a Boolean indicating if the match is exact .
10,759
def svg2rlg ( path , ** kwargs ) : "Convert an SVG file to an RLG Drawing object." unzipped = False if isinstance ( path , str ) and os . path . splitext ( path ) [ 1 ] . lower ( ) == ".svgz" : with gzip . open ( path , 'rb' ) as f_in , open ( path [ : - 1 ] , 'wb' ) as f_out : shutil . copyfileobj ( f_in , f_out ) pat...
Convert an SVG file to an RLG Drawing object .
10,760
def parseMultiAttributes ( self , line ) : attrs = line . split ( ';' ) attrs = [ a . strip ( ) for a in attrs ] attrs = filter ( lambda a : len ( a ) > 0 , attrs ) new_attrs = { } for a in attrs : k , v = a . split ( ':' ) k , v = [ s . strip ( ) for s in ( k , v ) ] new_attrs [ k ] = v return new_attrs
Try parsing compound attribute string .
10,761
def findAttr ( self , svgNode , name ) : if self . css_rules is not None and not svgNode . attrib . get ( '__rules_applied' , False ) : if isinstance ( svgNode , NodeTracker ) : svgNode . apply_rules ( self . css_rules ) else : ElementWrapper ( svgNode ) . apply_rules ( self . css_rules ) attr_value = svgNode . attrib ...
Search an attribute with some name in some node or above .
10,762
def getAllAttributes ( self , svgNode ) : "Return a dictionary of all attributes of svgNode or those inherited by it." dict = { } if node_name ( svgNode . getparent ( ) ) == 'g' : dict . update ( self . getAllAttributes ( svgNode . getparent ( ) ) ) style = svgNode . attrib . get ( "style" ) if style : d = self . parse...
Return a dictionary of all attributes of svgNode or those inherited by it .
10,763
def convertTransform ( self , svgAttr ) : line = svgAttr . strip ( ) ops = line [ : ] brackets = [ ] indices = [ ] for i , lin in enumerate ( line ) : if lin in "()" : brackets . append ( i ) for i in range ( 0 , len ( brackets ) , 2 ) : bi , bj = brackets [ i ] , brackets [ i + 1 ] subline = line [ bi + 1 : bj ] subli...
Parse transform attribute string .
10,764
def convertLength ( self , svgAttr , percentOf = 100 , em_base = 12 ) : "Convert length to points." text = svgAttr if not text : return 0.0 if ' ' in text . replace ( ',' , ' ' ) . strip ( ) : logger . debug ( "Only getting first value of %s" % text ) text = text . replace ( ',' , ' ' ) . split ( ) [ 0 ] if text . ends...
Convert length to points .
10,765
def convertLengthList ( self , svgAttr ) : return [ self . convertLength ( a ) for a in self . split_attr_list ( svgAttr ) ]
Convert a list of lengths .
10,766
def convertColor ( self , svgAttr ) : "Convert string to a RL color object." predefined = "aqua black blue fuchsia gray green lime maroon navy " predefined = predefined + "olive orange purple red silver teal white yellow " predefined = predefined + "lawngreen indianred aquamarine lightgreen brown" text = svgAttr if not...
Convert string to a RL color object .
10,767
def get_clippath ( self , node ) : def get_path_from_node ( node ) : for child in node . getchildren ( ) : if node_name ( child ) == 'path' : group = self . shape_converter . convertShape ( 'path' , NodeTracker ( child ) ) return group . contents [ - 1 ] else : return get_path_from_node ( child ) clip_path = node . get...
Return the clipping Path object referenced by the node clip - path attribute if any .
10,768
def applyTransformOnGroup ( self , transform , group ) : tr = self . attrConverter . convertTransform ( transform ) for op , values in tr : if op == "scale" : if not isinstance ( values , tuple ) : values = ( values , values ) group . scale ( * values ) elif op == "translate" : if isinstance ( values , ( int , float ) ...
Apply an SVG transformation to a RL Group shape .
10,769
def applyStyleOnShape ( self , shape , node , only_explicit = False ) : "Apply style attributes of a sequence of nodes to an RL shape." mappingN = ( ( "fill" , "fillColor" , "convertColor" , "black" ) , ( "fill-opacity" , "fillOpacity" , "convertOpacity" , 1 ) , ( "fill-rule" , "_fillRule" , "convertFillRule" , "nonzer...
Apply styles from an SVG element to an RLG shape . If only_explicit is True only attributes really present are applied .
10,770
def split_floats ( op , min_num , value ) : floats = [ float ( seq ) for seq in re . findall ( r'(-?\d*\.?\d*(?:e[+-]\d+)?)' , value ) if seq ] res = [ ] for i in range ( 0 , len ( floats ) , min_num ) : if i > 0 and op in { 'm' , 'M' } : op = 'l' if op == 'm' else 'L' res . extend ( [ op , floats [ i : i + min_num ] ]...
Split value a list of numbers as a string to a list of float numbers .
10,771
def normalise_svg_path ( attr ) : ops = { 'A' : 7 , 'a' : 7 , 'Q' : 4 , 'q' : 4 , 'T' : 2 , 't' : 2 , 'S' : 4 , 's' : 4 , 'M' : 2 , 'L' : 2 , 'm' : 2 , 'l' : 2 , 'H' : 1 , 'V' : 1 , 'h' : 1 , 'v' : 1 , 'C' : 6 , 'c' : 6 , 'Z' : 0 , 'z' : 0 , } op_keys = ops . keys ( ) result = [ ] groups = re . split ( '([achlmqstvz])'...
Normalise SVG path .
10,772
def convert_quadratic_to_cubic_path ( q0 , q1 , q2 ) : c0 = q0 c1 = ( q0 [ 0 ] + 2. / 3 * ( q1 [ 0 ] - q0 [ 0 ] ) , q0 [ 1 ] + 2. / 3 * ( q1 [ 1 ] - q0 [ 1 ] ) ) c2 = ( c1 [ 0 ] + 1. / 3 * ( q2 [ 0 ] - q0 [ 0 ] ) , c1 [ 1 ] + 1. / 3 * ( q2 [ 1 ] - q0 [ 1 ] ) ) c3 = q2 return c0 , c1 , c2 , c3
Convert a quadratic Bezier curve through q0 q1 q2 to a cubic one .
10,773
def client_start ( request , socket , context ) : CLIENTS [ socket . session . session_id ] = ( request , socket , context )
Adds the client triple to CLIENTS .
10,774
def client_end ( request , socket , context ) : for channel in socket . channels : events . on_unsubscribe . send ( request , socket , context , channel ) events . on_finish . send ( request , socket , context ) for channel in socket . channels [ : ] : socket . unsubscribe ( channel ) del CLIENTS [ socket . session . s...
Handles cleanup when a session ends for the given client triple . Sends unsubscribe and finish events actually unsubscribes from any channels subscribed to and removes the client triple from CLIENTS .
10,775
def client_end_all ( ) : for request , socket , context in CLIENTS . values ( ) [ : ] : client_end ( request , socket , context )
Performs cleanup on all clients - called by runserver_socketio when the server is shut down or reloaded .
10,776
def subscribe ( self , channel ) : if channel in self . channels : return False CHANNELS [ channel ] . append ( self . socket . session . session_id ) self . channels . append ( channel ) return True
Add the channel to this socket s channels and to the list of subscribed session IDs for the channel . Return False if already subscribed otherwise True .
10,777
def unsubscribe ( self , channel ) : try : CHANNELS [ channel ] . remove ( self . socket . session . session_id ) self . channels . remove ( channel ) except ValueError : return False return True
Remove the channel from this socket s channels and from the list of subscribed session IDs for the channel . Return False if not subscribed otherwise True .
10,778
def broadcast_channel ( self , message , channel = None ) : if channel is None : channels = self . channels else : channels = [ channel ] for channel in channels : for subscriber in CHANNELS [ channel ] : if subscriber != self . socket . session . session_id : session = self . socket . handler . server . sessions [ sub...
Send the given message to all subscribers for the channel given . If no channel is given send to the subscribers for all the channels that this socket is subscribed to .
10,779
def send_and_broadcast_channel ( self , message , channel = None ) : self . send ( message ) self . broadcast_channel ( message , channel )
Shortcut for a socket to broadcast to all sockets subscribed to a channel and itself .
10,780
def message ( request , socket , context , message ) : room = get_object_or_404 ( ChatRoom , id = message [ "room" ] ) if message [ "action" ] == "start" : name = strip_tags ( message [ "name" ] ) user , created = room . users . get_or_create ( name = name ) if not created : socket . send ( { "action" : "in-use" } ) el...
Event handler for a room receiving a message . First validates a joining user s name and sends them the list of users .
10,781
def finish ( request , socket , context ) : try : user = context [ "user" ] except KeyError : return left = { "action" : "leave" , "name" : user . name , "id" : user . id } socket . broadcast_channel ( left ) user . delete ( )
Event handler for a socket session ending in a room . Broadcast the user leaving and delete them from the DB .
10,782
def send ( session_id , message ) : try : socket = CLIENTS [ session_id ] [ 1 ] except KeyError : raise NoSocket ( "There is no socket with the session ID: " + session_id ) socket . send ( message )
Send a message to the socket for the given session ID .
10,783
def broadcast ( message ) : try : socket = CLIENTS . values ( ) [ 0 ] [ 1 ] except IndexError : raise NoSocket ( "There are no clients." ) socket . send_and_broadcast ( message )
Find the first socket and use it to broadcast to all sockets including the socket itself .
10,784
def broadcast_channel ( message , channel ) : try : socket = CLIENTS [ CHANNELS . get ( channel , [ ] ) [ 0 ] ] [ 1 ] except ( IndexError , KeyError ) : raise NoSocket ( "There are no clients on the channel: " + channel ) socket . send_and_broadcast_channel ( message , channel )
Find the first socket for the given channel and use it to broadcast to the channel including the socket itself .
10,785
def format_log ( request , message_type , message ) : from django_socketio . settings import MESSAGE_LOG_FORMAT if MESSAGE_LOG_FORMAT is None : return None now = datetime . now ( ) . replace ( microsecond = 0 ) args = dict ( request . META , TYPE = message_type , MESSAGE = message , TIME = now ) return ( MESSAGE_LOG_FO...
Formats a log message similar to gevent s pywsgi request logging .
10,786
def get_handler ( self , * args , ** options ) : handler = WSGIHandler ( ) try : from django . contrib . staticfiles . handlers import StaticFilesHandler except ImportError : return handler use_static_handler = options . get ( 'use_static_handler' , True ) insecure_serving = options . get ( 'insecure_serving' , False )...
Returns the django . contrib . staticfiles handler .
10,787
def send ( self , request , socket , context , * args ) : for handler , pattern in self . handlers : no_channel = not pattern and not socket . channels if self . name . endswith ( "subscribe" ) and pattern : matches = [ pattern . match ( args [ 0 ] ) ] else : matches = [ pattern . match ( c ) for c in socket . channels...
When an event is sent run all relevant handlers . Relevant handlers are those without a channel pattern when the given socket is not subscribed to any particular channel or the handlers with a channel pattern that matches any of the channels that the given socket is subscribed to .
10,788
def rooms ( request , template = "rooms.html" ) : context = { "rooms" : ChatRoom . objects . all ( ) } return render ( request , template , context )
Homepage - lists all rooms .
10,789
def room ( request , slug , template = "room.html" ) : context = { "room" : get_object_or_404 ( ChatRoom , slug = slug ) } return render ( request , template , context )
Show a room .
10,790
def create ( request ) : name = request . POST . get ( "name" ) if name : room , created = ChatRoom . objects . get_or_create ( name = name ) return redirect ( room ) return redirect ( rooms )
Handles post from the Add room form on the homepage and redirects to the new room .
10,791
def add_outer_solar_system ( sim ) : Gfac = 1. / 0.01720209895 if sim . G is not None : Gfac *= math . sqrt ( sim . G ) sim . add ( m = 1.00000597682 , x = - 4.06428567034226e-3 , y = - 6.08813756435987e-3 , z = - 1.66162304225834e-6 , vx = + 6.69048890636161e-6 * Gfac , vy = - 6.33922479583593e-6 * Gfac , vz = - 3.132...
Add the planet of the outer Solar System as a test problem . Data taken from NASA Horizons .
10,792
def get_color ( color ) : if isinstance ( color , tuple ) and len ( color ) == 3 : return color try : import matplotlib . colors as mplcolors except : raise ImportError ( "Error importing matplotlib. If running from within a jupyter notebook, try calling '%matplotlib inline' beforehand." ) try : hexcolor = mplcolors . ...
Takes a string for a color name defined in matplotlib and returns of a 3 - tuple of RGB values . Will simply return passed value if it s a tuple of length three .
10,793
def fading_line ( x , y , color = 'black' , alpha_initial = 1. , alpha_final = 0. , glow = False , ** kwargs ) : try : from matplotlib . collections import LineCollection from matplotlib . colors import LinearSegmentedColormap import numpy as np except : raise ImportError ( "Error importing matplotlib and/or numpy. Plo...
Returns a matplotlib LineCollection connecting the points in the x and y lists with a single color and alpha varying from alpha_initial to alpha_final along the line . Can pass any kwargs you can pass to LineCollection like linewidgth .
10,794
def _getSnapshotIndex ( self , t ) : if t > self . tmax or t < self . tmin : raise ValueError ( "Requested time outside of baseline stored in binary file." ) l = 0 r = len ( self ) while True : bi = l + ( r - l ) // 2 if self . t [ bi ] > t : r = bi else : l = bi if r - 1 <= l : bi = l break return bi , self . t [ bi ]
Return the index for the snapshot just before t
10,795
def getSimulations ( self , times , ** kwargs ) : for t in times : yield self . getSimulation ( t , ** kwargs )
A generator to quickly access many simulations . The arguments are the same as for getSimulation .
10,796
def copy ( self ) : np = Particle ( ) memmove ( byref ( np ) , byref ( self ) , sizeof ( self ) ) return np
Returns a deep copy of the particle . The particle is not added to any simulation by default .
10,797
def takeScreenshot ( self , times = None , prefix = "./screenshot" , resetCounter = False , archive = None , mode = "snapshot" ) : self . archive = archive if resetCounter : self . screenshotcountall = 0 self . screenshotprefix = prefix self . screenshotcount = 0 self . overlay = "REBOUND" self . screenshot = "" if arc...
Take one or more screenshots of the widget and save the images to a file . The images can be used to create a video .
10,798
def coordinates ( self ) : i = self . _coordinates for name , _i in COORDINATES . items ( ) : if i == _i : return name return i
Get or set the internal coordinate system .
10,799
def getWidget ( self , ** kwargs ) : from . widget import Widget from ipywidgets import DOMWidget from IPython . display import display , HTML if not hasattr ( self , '_widgets' ) : self . _widgets = [ ] def display_heartbeat ( simp ) : for w in self . _widgets : w . refresh ( simp , isauto = 1 ) self . visualization =...
Wrapper function that returns a new widget attached to this simulation .