idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
5,700 | def rem2ics ( ) : # pylint: disable=maybe-no-member from argparse import ArgumentParser , FileType from dateutil . parser import parse from sys import stdin , stdout parser = ArgumentParser ( description = 'Converter from Remind to iCalendar syntax.' ) parser . add_argument ( '-s' , '--startdate' , type = lambda s : pa... | Command line tool to convert from Remind to iCalendar | 500 | 12 |
5,701 | def ics2rem ( ) : from argparse import ArgumentParser , FileType from sys import stdin , stdout parser = ArgumentParser ( description = 'Converter from iCalendar to Remind syntax.' ) parser . add_argument ( '-l' , '--label' , help = 'Label for every Remind entry' ) parser . add_argument ( '-p' , '--priority' , type = i... | Command line tool to convert from iCalendar to Remind | 525 | 12 |
5,702 | def _parse_remind ( self , filename , lines = '' ) : files = { } reminders = { } if lines : filename = '-' files [ filename ] = lines reminders [ filename ] = { } cmd = [ 'remind' , '-l' , '-s%d' % self . _month , '-b1' , '-y' , '-r' , filename , str ( self . _startdate ) ] try : rem = Popen ( cmd , stdin = PIPE , stdo... | Calls remind and parses the output into a dict | 574 | 11 |
5,703 | def _parse_remind_line ( self , line , text ) : event = { } line = line . split ( None , 6 ) dat = [ int ( f ) for f in line [ 0 ] . split ( '/' ) ] if line [ 4 ] != '*' : start = divmod ( int ( line [ 4 ] ) , 60 ) event [ 'dtstart' ] = [ datetime ( dat [ 0 ] , dat [ 1 ] , dat [ 2 ] , start [ 0 ] , start [ 1 ] , tzinfo... | Parse a line of remind output into a dict | 427 | 10 |
5,704 | def _interval ( dates ) : interval = ( dates [ 1 ] - dates [ 0 ] ) . days last = dates [ 0 ] for dat in dates [ 1 : ] : if ( dat - last ) . days != interval : return 0 last = dat return interval | Return the distance between all dates and 0 if they are different | 56 | 12 |
5,705 | def _gen_dtend_rrule ( dtstarts , vevent ) : interval = Remind . _interval ( dtstarts ) if interval > 0 and interval % 7 == 0 : rset = rrule . rruleset ( ) rset . rrule ( rrule . rrule ( freq = rrule . WEEKLY , interval = interval // 7 , count = len ( dtstarts ) ) ) vevent . rruleset = rset elif interval > 1 : rset = r... | Generate an rdate or rrule from a list of dates and add it to the vevent | 492 | 20 |
5,706 | def _gen_vevent ( self , event , vevent ) : vevent . add ( 'dtstart' ) . value = event [ 'dtstart' ] [ 0 ] vevent . add ( 'dtstamp' ) . value = datetime . fromtimestamp ( self . _mtime ) vevent . add ( 'summary' ) . value = event [ 'msg' ] vevent . add ( 'uid' ) . value = event [ 'uid' ] if 'class' in event : vevent . ... | Generate vevent from given event | 445 | 7 |
5,707 | def _update ( self ) : update = not self . _reminders with self . _lock : for fname in self . _reminders : if getmtime ( fname ) > self . _mtime : update = True break if update : self . _reminders = self . _parse_remind ( self . _filename ) | Reload Remind files if the mtime is newer | 72 | 11 |
5,708 | def get_uids ( self , filename = None ) : self . _update ( ) if filename : if filename not in self . _reminders : return [ ] return self . _reminders [ filename ] . keys ( ) return [ uid for uids in self . _reminders . values ( ) for uid in uids ] | UIDs of all reminders in the file excluding included files If a filename is specified only it s UIDs are return otherwise all . | 72 | 26 |
5,709 | def to_vobjects ( self , filename , uids = None ) : self . _update ( ) if not uids : uids = self . _reminders [ filename ] items = [ ] for uid in uids : cal = iCalendar ( ) self . _gen_vevent ( self . _reminders [ filename ] [ uid ] , cal . add ( 'vevent' ) ) etag = md5 ( ) etag . update ( self . _reminders [ filename ... | Return iCal objects and etags of all Remind entries in uids | 154 | 15 |
5,710 | def to_vobject ( self , filename = None , uid = None ) : self . _update ( ) cal = iCalendar ( ) if uid : self . _gen_vevent ( self . _reminders [ filename ] [ uid ] , cal . add ( 'vevent' ) ) elif filename : for event in self . _reminders [ filename ] . values ( ) : self . _gen_vevent ( event , cal . add ( 'vevent' ) )... | Return iCal object of Remind lines If filename and UID are specified the vObject only contains that event . If only a filename is specified the vObject contains all events in the file . Otherwise the vObject contains all all objects of all files associated with the Remind object . | 155 | 56 |
5,711 | def stdin_to_vobject ( self , lines ) : cal = iCalendar ( ) for event in self . _parse_remind ( '-' , lines ) [ '-' ] . values ( ) : self . _gen_vevent ( event , cal . add ( 'vevent' ) ) return cal | Return iCal object of the Remind commands in lines | 68 | 11 |
5,712 | def _parse_rruleset ( rruleset ) : # pylint: disable=protected-access if rruleset . _rrule [ 0 ] . _freq == 0 : return [ ] rep = [ ] if rruleset . _rrule [ 0 ] . _byweekday and len ( rruleset . _rrule [ 0 ] . _byweekday ) > 1 : rep . append ( '*1' ) elif rruleset . _rrule [ 0 ] . _freq == rrule . DAILY : rep . append (... | Convert from iCal rrule to Remind recurrence syntax | 469 | 13 |
5,713 | def _event_duration ( vevent ) : if hasattr ( vevent , 'dtend' ) : return vevent . dtend . value - vevent . dtstart . value elif hasattr ( vevent , 'duration' ) and vevent . duration . value : return vevent . duration . value return timedelta ( 0 ) | unify dtend and duration to the duration of the given vevent | 74 | 15 |
5,714 | def to_remind ( self , vevent , label = None , priority = None , tags = None , tail = None , sep = " " , postdate = None , posttime = None ) : remind = [ 'REM' ] trigdates = None if hasattr ( vevent , 'rrule' ) : trigdates = Remind . _parse_rruleset ( vevent . rruleset ) dtstart = vevent . dtstart . value # If we don't... | Generate a Remind command from the given vevent | 754 | 11 |
5,715 | def to_reminders ( self , ical , label = None , priority = None , tags = None , tail = None , sep = " " , postdate = None , posttime = None ) : if not hasattr ( ical , 'vevent_list' ) : return '' reminders = [ self . to_remind ( vevent , label , priority , tags , tail , sep , postdate , posttime ) for vevent in ical . ... | Return Remind commands for all events of a iCalendar | 109 | 12 |
5,716 | def append_vobject ( self , ical , filename = None ) : if not filename : filename = self . _filename elif filename not in self . _reminders : return with self . _lock : outdat = self . to_reminders ( ical ) open ( filename , 'a' ) . write ( outdat ) return Remind . _get_uid ( outdat ) | Append a Remind command generated from the iCalendar to the file | 83 | 15 |
5,717 | def remove ( self , uid , filename = None ) : if not filename : filename = self . _filename elif filename not in self . _reminders : return uid = uid . split ( '@' ) [ 0 ] with self . _lock : rem = open ( filename ) . readlines ( ) for ( index , line ) in enumerate ( rem ) : if uid == md5 ( line [ : - 1 ] . encode ( 'u... | Remove the Remind command with the uid from the file | 130 | 12 |
5,718 | def move_vobject ( self , uid , from_file , to_file ) : if from_file not in self . _reminders or to_file not in self . _reminders : return uid = uid . split ( '@' ) [ 0 ] with self . _lock : rem = open ( from_file ) . readlines ( ) for ( index , line ) in enumerate ( rem ) : if uid == md5 ( line [ : - 1 ] . encode ( 'u... | Move the Remind command with the uid from from_file to to_file | 158 | 17 |
5,719 | def expand_include ( filename ) : open_files = set ( ) def _expand_include_rec ( filename ) : if filename in open_files : raise RuntimeError ( 'Recursive include statement detected for ' 'file: ' + filename ) else : open_files . add ( filename ) with open ( filename ) as open_file : for line in open_file : line_strippe... | Expand the content of a file into a string . | 231 | 11 |
5,720 | def to_json ( self ) : self . logger . debug ( "Returning json info" ) individual_info = { 'family_id' : self . family , 'id' : self . individual_id , 'sex' : str ( self . sex ) , 'phenotype' : str ( self . phenotype ) , 'mother' : self . mother , 'father' : self . father , 'extra_info' : self . extra_info } return ind... | Return the individual info in a dictionary for json . | 101 | 10 |
5,721 | def to_madeline ( self ) : #Convert sex to madeleine type self . logger . debug ( "Returning madeline info" ) if self . sex == 1 : madeline_gender = 'M' elif self . sex == 2 : madeline_gender = 'F' else : madeline_gender = '.' #Convert father to madeleine type if self . father == '0' : madeline_father = '.' else : made... | Return the individual info in a madeline formated string | 278 | 11 |
5,722 | def module_name_from_path ( folder_name , verbose = False ) : # strip off endings folder_name = folder_name . split ( '.pyc' ) [ 0 ] folder_name = folder_name . split ( '.py' ) [ 0 ] folder_name = os . path . normpath ( folder_name ) path = folder_name + '/' package = get_python_package ( path ) # path = folder_name mo... | takes in a path to a folder or file and return the module path and the path to the module | 592 | 21 |
5,723 | def explore_package ( module_name ) : packages = [ ] loader = pkgutil . get_loader ( module_name ) for sub_module in pkgutil . walk_packages ( [ os . path . dirname ( loader . get_filename ( ) ) ] , prefix = module_name + '.' ) : _ , sub_module_name , _ = sub_module packages . append ( sub_module_name ) return packages | returns all the packages in the module | 94 | 8 |
5,724 | def generate_from_directory ( cls , directory ) : files = [ os . path . join ( directory , f ) for f in os . listdir ( directory ) if os . path . isfile ( os . path . join ( directory , f ) ) ] return cls ( files ) | Create a parser by defining which input files it will read from . | 62 | 13 |
5,725 | def get_density ( self ) : strc = self . get_output_structure ( ) density = sum ( strc . get_masses ( ) ) / strc . get_volume ( ) * 1.660539040 return Property ( scalars = [ Scalar ( value = density ) ] , units = "g/(cm^3)" ) | Compute the density from the output structure | 77 | 8 |
5,726 | def get_number_of_atoms ( self ) : strc = self . get_output_structure ( ) if not strc : return None return Property ( scalars = [ Scalar ( value = len ( strc ) ) ] , units = "/unit cell" ) | Get the number of atoms in the calculated structure . | 60 | 10 |
5,727 | def load_b26_file ( file_name ) : # file_name = "Z:\Lab\Cantilever\Measurements\\tmp_\\a" assert os . path . exists ( file_name ) with open ( file_name , 'r' ) as infile : data = yaml . safe_load ( infile ) return data | loads a . b26 file into a dictionary | 76 | 9 |
5,728 | def recv_message ( self , debug = False ) : if debug : packet = self . sock . recv ( 1024 ) # reads how many bytes to read hexdump ( packet ) packet_length_data = self . sock . recv ( 4 ) # reads how many bytes to read if len ( packet_length_data ) < 4 : raise Exception ( "Nothing in the socket!" ) packet_length = stru... | Reading socket and receiving message from server . Check the CRC32 . | 524 | 13 |
5,729 | def get_category_lists ( self , init_kwargs = None , additional_parents_aliases = None ) : if self . _category_editor is not None : # Return editor lists instead of plain lists if it's enabled. return self . _category_editor . get_lists ( ) from . toolbox import get_category_lists init_kwargs = init_kwargs or { } catli... | Returns a list of CategoryList objects associated with this model instance . | 169 | 13 |
5,730 | def enable_category_lists_editor ( self , request , editor_init_kwargs = None , additional_parents_aliases = None , lists_init_kwargs = None , handler_init_kwargs = None ) : from . toolbox import CategoryRequestHandler additional_parents_aliases = additional_parents_aliases or [ ] lists_init_kwargs = lists_init_kwargs ... | Enables editor functionality for categories of this object . | 243 | 10 |
5,731 | def add_to_category ( self , category , user ) : init_kwargs = { 'category' : category , 'creator' : user , 'linked_object' : self } tie = self . categories . model ( * * init_kwargs ) # That's a model of Tie. tie . save ( ) return tie | Add this model instance to a category . | 70 | 8 |
5,732 | def remove_from_category ( self , category ) : ctype = ContentType . objects . get_for_model ( self ) self . categories . model . objects . filter ( category = category , content_type = ctype , object_id = self . id ) . delete ( ) | Removes this object from a given category . | 61 | 9 |
5,733 | def get_ties_for_categories_qs ( cls , categories , user = None , status = None ) : if not isinstance ( categories , list ) : categories = [ categories ] category_ids = [ ] for category in categories : if isinstance ( category , models . Model ) : category_ids . append ( category . id ) else : category_ids . append ( c... | Returns a QuerySet of Ties for the given categories . | 188 | 12 |
5,734 | def get_from_category_qs ( cls , category ) : ids = cls . get_ties_for_categories_qs ( category ) . values_list ( 'object_id' ) . distinct ( ) filter_kwargs = { 'id__in' : [ i [ 0 ] for i in ids ] } return cls . objects . filter ( * * filter_kwargs ) | Returns a QuerySet of objects of this type associated with the given category . | 88 | 15 |
5,735 | def main ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( "-f" , "--file" , required = True , help = "input file" , type = str ) parser . add_argument ( "-l" , "--locus" , required = True , help = "Locus" , type = str ) parser . add_argument ( "-k" , "--kir" , help = "Option for running with KIR" , ... | This is run if file is directly executed but not if imported as module . Having this in a separate function allows importing the file into interactive python and still able to execute the function for testing | 582 | 37 |
5,736 | def _push_subtree ( self , leaves : List [ bytes ] ) : size = len ( leaves ) if count_bits_set ( size ) != 1 : raise ValueError ( "invalid subtree with size != 2^k: %s" % size ) # in general we want the highest bit, but here it's also the lowest bit # so just reuse that code instead of writing a new highest_bit_set() s... | Extend with a full subtree < = the current minimum subtree . | 292 | 15 |
5,737 | def resolve ( obj , pointer , registry = None ) : registry = LocalRegistry ( obj , registry or { } ) local = DocumentPointer ( pointer ) if local . document : registry [ local . document ] = obj local . document = '<local>' return registry . resolve ( local ) | resolve a local object | 62 | 5 |
5,738 | def addUrlScheme ( self , url ) : #@TODO: validate invalid url format according to http://oembed.com/ if not isinstance ( url , str ) : raise TypeError ( 'url must be a string value' ) if not url in self . _urlSchemes : self . _urlSchemes [ url ] = OEmbedUrlScheme ( url ) | Add a url scheme to this endpoint . It takes a url string and create the OEmbedUrlScheme object internally . | 83 | 25 |
5,739 | def match ( self , url ) : try : urlSchemes = self . _urlSchemes . itervalues ( ) # Python 2 except AttributeError : urlSchemes = self . _urlSchemes . values ( ) # Python 3 for urlScheme in urlSchemes : if urlScheme . match ( url ) : return True return False | Try to find if url matches against any of the schemes within this endpoint . | 75 | 15 |
5,740 | def request ( self , url , * * opt ) : params = opt params [ 'url' ] = url urlApi = self . _urlApi if 'format' in params and self . _implicitFormat : urlApi = self . _urlApi . replace ( '{format}' , params [ 'format' ] ) del params [ 'format' ] if '?' in urlApi : return "%s&%s" % ( urlApi , urllib . urlencode ( params ... | Format the input url and optional parameters and provides the final url where to get the given resource . | 138 | 19 |
5,741 | def get ( self , url , * * opt ) : return self . fetch ( self . request ( url , * * opt ) ) | Convert the resource url to a complete url and then fetch the data from it . | 28 | 17 |
5,742 | def fetch ( self , url ) : opener = self . _urllib . build_opener ( ) opener . addheaders = self . _requestHeaders . items ( ) response = opener . open ( url ) headers = response . info ( ) raw = response . read ( ) raw = raw . decode ( 'utf8' ) if not 'Content-Type' in headers : raise OEmbedError ( 'Missing mime-type ... | Fetch url and create a response object according to the mime - type . | 264 | 16 |
5,743 | def embed ( self , url , format = 'json' , * * opt ) : if format not in [ 'json' , 'xml' ] : raise OEmbedInvalidRequest ( 'Format must be json or xml' ) opt [ 'format' ] = format return self . _request ( url , * * opt ) | Get an OEmbedResponse from one of the providers configured in this consumer according to the resource url . | 68 | 21 |
5,744 | def connect ( portname , baudrate ) : global SERPORT try : SERPORT = serial . Serial ( portname , baudrate , timeout = 0.1 ) except : raise HerkulexError ( "could not open the serial port" ) | Connect to the Herkulex bus | 54 | 8 |
5,745 | def checksum1 ( data , stringlength ) : value_buffer = 0 for count in range ( 0 , stringlength ) : value_buffer = value_buffer ^ data [ count ] return value_buffer & 0xFE | Calculate Checksum 1 | 47 | 6 |
5,746 | def send_data ( data ) : datalength = len ( data ) csm1 = checksum1 ( data , datalength ) csm2 = checksum2 ( csm1 ) data . insert ( 0 , 0xFF ) data . insert ( 1 , 0xFF ) data . insert ( 5 , csm1 ) data . insert ( 6 , csm2 ) stringtosend = "" for i in range ( len ( data ) ) : byteformat = '%02X' % data [ i ] stringtosen... | Send data to herkulex | 173 | 7 |
5,747 | def clear_errors ( ) : data = [ ] data . append ( 0x0B ) data . append ( BROADCAST_ID ) data . append ( RAM_WRITE_REQ ) data . append ( STATUS_ERROR_RAM ) data . append ( BYTE2 ) data . append ( 0x00 ) data . append ( 0x00 ) send_data ( data ) | Clears the errors register of all Herkulex servos | 83 | 13 |
5,748 | def scale ( input_value , input_min , input_max , out_min , out_max ) : # Figure out how 'wide' each range is input_span = input_max - input_min output_span = out_max - out_min # Convert the left range into a 0-1 range (float) valuescaled = float ( input_value - input_min ) / float ( input_span ) # Convert the 0-1 rang... | scale a value from one range to another | 120 | 8 |
5,749 | def scan_servos ( ) : servos = [ ] for servo_id in range ( 0x00 , 0xFE ) : model = get_model ( servo_id ) if model : servos += [ ( servo_id , model ) ] return servos | Scan for the herkulex servos connected | 60 | 10 |
5,750 | def get_model ( servoid ) : data = [ ] data . append ( 0x09 ) data . append ( servoid ) data . append ( EEP_READ_REQ ) data . append ( MODEL_NO1_EEP ) data . append ( BYTE1 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 12 ) return ord ( rxdata [ 9 ] ) & 0xFF except : raise HerkulexError ( "could not... | Get the servo model | 116 | 5 |
5,751 | def get_servo_status ( self ) : data = [ ] data . append ( 0x09 ) data . append ( self . servoid ) data . append ( RAM_READ_REQ ) data . append ( STATUS_ERROR_RAM ) data . append ( BYTE1 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 12 ) return ord ( rxdata [ 9 ] ) & 0xFF except : raise HerkulexErro... | Get the error status of servo | 118 | 7 |
5,752 | def get_servo_status_detail ( self ) : data = [ ] data . append ( 0x09 ) data . append ( self . servoid ) data . append ( RAM_READ_REQ ) data . append ( STATUS_DETAIL_RAM ) data . append ( BYTE1 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 12 ) return ord ( rxdata [ 9 ] ) & 0xFF except HerkulexErro... | Get the detailed error status of servo | 127 | 8 |
5,753 | def set_led ( self , colorcode ) : data = [ ] data . append ( 0x0A ) data . append ( self . servoid ) data . append ( RAM_WRITE_REQ ) data . append ( LED_CONTROL_RAM ) data . append ( 0x01 ) data . append ( colorcode ) send_data ( data ) | Set the LED Color of Herkulex | 78 | 9 |
5,754 | def brake_on ( self ) : data = [ ] data . append ( 0x0A ) data . append ( self . servoid ) data . append ( RAM_WRITE_REQ ) data . append ( TORQUE_CONTROL_RAM ) data . append ( 0x01 ) data . append ( 0x40 ) send_data ( data ) | Set the Brakes of Herkulex | 78 | 9 |
5,755 | def torque_off ( self ) : data = [ ] data . append ( 0x0A ) data . append ( self . servoid ) data . append ( RAM_WRITE_REQ ) data . append ( TORQUE_CONTROL_RAM ) data . append ( 0x01 ) data . append ( 0x00 ) send_data ( data ) | Set the torques of Herkulex to zero | 78 | 11 |
5,756 | def torque_on ( self ) : data = [ ] data . append ( 0x0A ) data . append ( self . servoid ) data . append ( RAM_WRITE_REQ ) data . append ( TORQUE_CONTROL_RAM ) data . append ( 0x01 ) data . append ( 0x60 ) send_data ( data ) | Enable the torques of Herkulex | 78 | 9 |
5,757 | def get_torque_state ( self ) : data = [ ] data . append ( 0x09 ) data . append ( self . servoid ) data . append ( RAM_READ_REQ ) data . append ( TORQUE_CONTROL_RAM ) data . append ( BYTE2 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 13 ) return bool ( ord ( rxdata [ 9 ] ) ) except HerkulexError : ... | get the torque state of motor | 125 | 6 |
5,758 | def set_servo_position ( self , goalposition , goaltime , led ) : goalposition_msb = int ( goalposition ) >> 8 goalposition_lsb = int ( goalposition ) & 0xff data = [ ] data . append ( 0x0C ) data . append ( self . servoid ) data . append ( I_JOG_REQ ) data . append ( goalposition_lsb ) data . append ( goalposition_msb... | Set the position of Herkulex | 128 | 8 |
5,759 | def get_servo_position ( self ) : #global SERPORT data = [ ] data . append ( 0x09 ) data . append ( self . servoid ) data . append ( RAM_READ_REQ ) data . append ( CALIBRATED_POSITION_RAM ) data . append ( BYTE2 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 13 ) if ( self . servomodel == 0x06 ) or (... | Gets the current position of Herkulex | 230 | 10 |
5,760 | def get_servo_temperature ( self ) : data = [ ] data . append ( 0x09 ) data . append ( self . servoid ) data . append ( RAM_READ_REQ ) data . append ( TEMPERATURE_RAM ) data . append ( BYTE2 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 13 ) return ord ( rxdata [ 9 ] ) except HerkulexError : raise H... | Gets the current temperature of Herkulex | 120 | 10 |
5,761 | def get_servo_torque ( self ) : data = [ ] data . append ( 0x09 ) data . append ( self . servoid ) data . append ( RAM_READ_REQ ) data . append ( PWM_RAM ) data . append ( BYTE2 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 13 ) if ord ( rxdata [ 10 ] ) <= 127 : return ( ( ord ( rxdata [ 10 ] ) & 0x... | Gets the current torque of Herkulex | 199 | 10 |
5,762 | def set_servo_speed ( self , goalspeed , led ) : if goalspeed > 0 : goalspeed_msb = ( int ( goalspeed ) & 0xFF00 ) >> 8 goalspeed_lsb = int ( goalspeed ) & 0xff elif goalspeed < 0 : goalspeed_msb = 64 + ( 255 - ( ( int ( goalspeed ) & 0xFF00 ) >> 8 ) ) goalspeed_lsb = ( abs ( goalspeed ) & 0xff ) #print goalspeed_msb,g... | Set the Herkulex in continuous rotation mode | 208 | 10 |
5,763 | def set_position_p ( self , pvalue ) : pvalue_msb = int ( pvalue ) >> 8 pvalue_lsb = int ( pvalue ) & 0xff data = [ ] data . append ( 0x0B ) data . append ( self . servoid ) data . append ( RAM_WRITE_REQ ) data . append ( POSITION_KP_RAM ) data . append ( BYTE2 ) data . append ( pvalue_lsb ) data . append ( pvalue_msb ... | Set the P gain of the position PID | 120 | 8 |
5,764 | def set_position_i ( self , ivalue ) : ivalue_msb = int ( ivalue ) >> 8 ivalue_lsb = int ( ivalue ) & 0xff data = [ ] data . append ( 0x0B ) data . append ( self . servoid ) data . append ( RAM_WRITE_REQ ) data . append ( POSITION_KI_RAM ) data . append ( BYTE2 ) data . append ( ivalue_lsb ) data . append ( ivalue_msb ... | Set the I gain of the position PID | 126 | 8 |
5,765 | def set_position_d ( self , dvalue ) : dvalue_msb = int ( dvalue ) >> 8 dvalue_lsb = int ( dvalue ) & 0xff data = [ ] data . append ( 0x0B ) data . append ( self . servoid ) data . append ( RAM_WRITE_REQ ) data . append ( POSITION_KD_RAM ) data . append ( BYTE2 ) data . append ( dvalue_lsb ) data . append ( dvalue_msb ... | Set the D gain of the PID | 120 | 7 |
5,766 | def get_position_p ( self ) : data = [ ] data . append ( 0x09 ) data . append ( self . servoid ) data . append ( RAM_READ_REQ ) data . append ( POSITION_KP_RAM ) data . append ( BYTE2 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 13 ) return ( ord ( rxdata [ 10 ] ) * 256 ) + ( ord ( rxdata [ 9 ] ) &... | Get the P value of the current PID for position | 138 | 10 |
5,767 | def get_position_i ( self ) : data = [ ] data . append ( 0x09 ) data . append ( self . servoid ) data . append ( RAM_READ_REQ ) data . append ( POSITION_KI_RAM ) data . append ( BYTE2 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 13 ) return ( ord ( rxdata [ 10 ] ) * 256 ) + ( ord ( rxdata [ 9 ] ) &... | Get the I value of the current PID for position | 137 | 10 |
5,768 | def get_position_d ( self ) : data = [ ] data . append ( 0x09 ) data . append ( self . servoid ) data . append ( RAM_READ_REQ ) data . append ( POSITION_KD_RAM ) data . append ( BYTE2 ) send_data ( data ) rxdata = [ ] try : rxdata = SERPORT . read ( 13 ) return ( ord ( rxdata [ 10 ] ) * 256 ) + ( ord ( rxdata [ 9 ] ) &... | Get the D value of the current PID for position | 138 | 10 |
5,769 | def save_pid_eeprom ( self ) : pval = self . get_position_p ( ) ival = self . get_position_i ( ) dval = self . get_position_d ( ) #write P value pvalue_msb = int ( pval ) >> 8 pvalue_lsb = int ( pval ) & 0xff data_p = [ ] data_p . append ( 0x0B ) data_p . append ( self . servoid ) data_p . append ( EEP_WRITE_REQ ) data... | saves the PID values from RAM to EEPROM | 441 | 11 |
5,770 | def get_servo_angle ( self ) : servoposition = self . get_servo_position ( ) if ( self . servomodel == 0x06 ) or ( self . servomodel == 0x04 ) : return scale ( servoposition , 10627 , 22129 , - 159.9 , 159.6 ) else : return scale ( servoposition , 21 , 1002 , - 150 , 150 ) | Gets the current angle of the servo in degrees | 93 | 11 |
5,771 | def disable_logging ( func ) : return func handler = logging . NullHandler ( ) @ wraps ( func ) def wrapper ( * args , * * kwargs ) : logger = logging . getLogger ( ) logger . addHandler ( handler ) resp = func ( * args , * * kwargs ) logger . removeHandler ( handler ) return resp return wrapper | Temporary disable logging . | 77 | 5 |
5,772 | def format_output ( func ) : return func @ wraps ( func ) def wrapper ( * args , * * kwargs ) : try : response = func ( * args , * * kwargs ) except Exception as error : print ( colored ( error , 'red' ) , file = sys . stderr ) sys . exit ( 1 ) else : print ( response ) sys . exit ( 0 ) return wrapper | Format output . | 87 | 3 |
5,773 | def start ( self , * args , * * kwargs ) : self . _stop = False super ( ReadProbes , self ) . start ( * args , * * kwargs ) | start the read_probe thread | 41 | 7 |
5,774 | def quit ( self , * args , * * kwargs ) : # real signature unknown self . _stop = True super ( ReadProbes , self ) . quit ( * args , * * kwargs ) | quit the read_probe thread | 45 | 7 |
5,775 | def _set_current_subscript ( self , active ) : current_subscript = self . sender ( ) if active : for subscript_name in list ( self . _current_subscript_stage [ 'subscript_exec_count' ] . keys ( ) ) : if subscript_name == current_subscript . name : self . _current_subscript_stage [ 'subscript_exec_count' ] [ subscript_n... | sets the current subscript and keeps a counter of how ofter a particular subscript has been executed this information is usefull when implementing a status update or plotting functions that depend on which subscript is being executed | 373 | 39 |
5,776 | def remaining_time ( self ) : elapsed_time = ( datetime . datetime . now ( ) - self . start_time ) . total_seconds ( ) # safety to avoid devision by zero if self . progress == 0 : self . progress = 1 estimated_total_time = 100. / self . progress * elapsed_time return datetime . timedelta ( seconds = max ( estimated_tot... | estimates the time remaining until script is finished | 95 | 9 |
5,777 | def stop ( self ) : for subscript in list ( self . scripts . values ( ) ) : subscript . stop ( ) print ( ( '--- stopping: ' , self . name ) ) self . _abort = True | stops itself and all the subscript | 46 | 7 |
5,778 | def get_script_module ( script_information , package = 'pylabcontrol' , verbose = False ) : module , _ , _ , _ , _ , _ , _ = Script . get_script_information ( script_information = script_information , package = package , verbose = verbose ) return module | wrapper to get the module for a script | 68 | 8 |
5,779 | def duplicate ( self ) : # get settings of script class_of_script = self . __class__ script_name = self . name script_instruments = self . instruments sub_scripts = self . scripts script_settings = self . settings log_function = self . log_function data_path = self . data_path #create a new instance of same script type... | create an copy of the script | 317 | 6 |
5,780 | def plot_validate ( self , figure_list ) : axes_list = self . get_axes_layout_validate ( figure_list ) self . _plot_validate ( axes_list ) | plots the data contained in self . data which should be a dictionary or a deque of dictionaries for the latter use the last entry | 45 | 28 |
5,781 | def uniqueof20 ( k , rep = 10000 ) : alphabet = 'ACDEFGHIKLMNPQRSTVWY' reps = [ len ( set ( random . choice ( alphabet ) for i in range ( k ) ) ) for j in range ( rep ) ] return sum ( reps ) / len ( reps ) | Sample k times out of alphabet how many different? | 67 | 10 |
5,782 | def extract ( obj , pointer , bypass_ref = False ) : return Pointer ( pointer ) . extract ( obj , bypass_ref ) | Extract member or element of obj according to pointer . | 29 | 11 |
5,783 | def aa_counts ( aln , weights = None , gap_chars = '-.' ) : if weights is None : counts = Counter ( ) for rec in aln : seq_counts = Counter ( str ( rec . seq ) ) counts . update ( seq_counts ) else : if weights == True : # For convenience weights = sequence_weights ( aln ) else : assert len ( weights ) == len ( aln ) ,... | Calculate the amino acid frequencies in a set of SeqRecords . | 195 | 16 |
5,784 | def aa_frequencies ( aln , weights = None , gap_chars = '-.' ) : counts = aa_counts ( aln , weights , gap_chars ) # Reduce to frequencies scale = 1.0 / sum ( counts . values ( ) ) return dict ( ( aa , cnt * scale ) for aa , cnt in counts . iteritems ( ) ) | Frequency of each residue type in an alignment . | 87 | 10 |
5,785 | def blocks ( aln , threshold = 0.5 , weights = None ) : assert len ( aln ) if weights == False : def pct_nongaps ( col ) : return 1 - ( float ( col . count ( '-' ) ) / len ( col ) ) else : if weights in ( None , True ) : weights = sequence_weights ( aln , 'avg1' ) def pct_nongaps ( col ) : assert len ( col ) == len ( w... | Remove gappy columns from an alignment . | 296 | 8 |
5,786 | def col_counts ( col , weights = None , gap_chars = '-.' ) : cnt = defaultdict ( float ) for aa , wt in zip ( col , weights ) : if aa not in gap_chars : cnt [ aa ] += wt return cnt | Absolute counts of each residue type in a single column . | 66 | 12 |
5,787 | def remove_empty_cols ( records ) : # In case it's a generator, turn it into a list records = list ( records ) seqstrs = [ str ( rec . seq ) for rec in records ] clean_cols = [ col for col in zip ( * seqstrs ) if not all ( c == '-' for c in col ) ] clean_seqs = [ '' . join ( row ) for row in zip ( * clean_cols ) ] for ... | Remove all - gap columns from aligned SeqRecords . | 191 | 12 |
5,788 | def to_graph ( alnfname , weight_func ) : import networkx G = networkx . Graph ( ) aln = AlignIO . read ( alnfname , 'fasta' ) for i , arec in enumerate ( aln ) : for brec in aln [ i + 1 : ] : ident = weight_func ( str ( arec . seq ) , str ( brec . seq ) ) G . add_edge ( arec . id , brec . id , weight = ident ) return ... | Create a NetworkX graph from a sequence alignment . | 115 | 10 |
5,789 | def guidance_UV ( index ) : if 0 < index < 3 : guidance = "Low exposure. No protection required. You can safely stay outside" elif 2 < index < 6 : guidance = "Moderate exposure. Seek shade during midday hours, cover up and wear sunscreen" elif 5 < index < 8 : guidance = "High exposure. Seek shade during midday hours, c... | Return Met Office guidance regarding UV exposure based on UV index | 145 | 11 |
5,790 | def parse_sitelist ( sitelist ) : sites = [ ] for site in sitelist [ "Locations" ] [ "Location" ] : try : ident = site [ "id" ] name = site [ "name" ] except KeyError : ident = site [ "@id" ] # Difference between loc-spec and text for some reason name = site [ "@name" ] if "latitude" in site : lat = float ( site [ "lat... | Return list of Site instances from retrieved sitelist data | 142 | 10 |
5,791 | def _query ( self , data_category , resource_category , field , request , step , isotime = None ) : rest_url = "/" . join ( [ HOST , data_category , resource_category , field , DATA_TYPE , request ] ) query_string = "?" + "&" . join ( [ "res=" + step , "time=" + isotime if isotime is not None else "" , "key=" + self . ... | Request and return data from DataPoint RESTful API . | 129 | 11 |
5,792 | def stand_alone_imagery ( self ) : return json . loads ( self . _query ( IMAGE , FORECAST , SURFACE_PRESSURE , CAPABILITIES , "" ) . decode ( errors = "replace" ) ) | Returns capabilities data for stand alone imagery and includes URIs for the images . | 50 | 15 |
5,793 | def map_overlay_forecast ( self ) : return json . loads ( self . _query ( LAYER , FORECAST , ALL , CAPABILITIES , "" ) . decode ( errors = "replace" ) ) | Returns capabilities data for forecast map overlays . | 48 | 9 |
5,794 | def map_overlay_obs ( self ) : return json . loads ( self . _query ( LAYER , OBSERVATIONS , ALL , CAPABILITIES , "" ) . decode ( errors = "replace" ) ) | Returns capabilities data for observation map overlays . | 49 | 9 |
5,795 | def load_and_append ( instrument_dict , instruments = None , raise_errors = False ) : if instruments is None : instruments = { } updated_instruments = { } updated_instruments . update ( instruments ) loaded_failed = { } for instrument_name , instrument_class_name in instrument_dict . items ( ) : instrument_settings = N... | load instrument from instrument_dict and append to instruments | 591 | 10 |
5,796 | def fail ( self , reason , obj , pointer = None ) : pointer = pointer_join ( pointer ) err = ValidationError ( reason , obj , pointer ) if self . fail_fast : raise err else : self . errors . append ( err ) return err | Called when validation fails . | 55 | 6 |
5,797 | def get_locus ( sequences , kir = False , verbose = False , refdata = None , evalue = 10 ) : if not refdata : refdata = ReferenceData ( ) file_id = str ( randomid ( ) ) input_fasta = file_id + ".fasta" output_xml = file_id + ".xml" SeqIO . write ( sequences , input_fasta , "fasta" ) blastn_cline = NcbiblastnCommandline... | Gets the locus of the sequence by running blastn | 353 | 12 |
5,798 | def address ( self ) -> str : return str ( self . _public_key . to_address ( net_query ( self . network ) ) ) | generate an address from pubkey | 32 | 7 |
5,799 | def sign_transaction ( self , txins : Union [ TxOut ] , tx : MutableTransaction ) -> MutableTransaction : solver = P2pkhSolver ( self . _private_key ) return tx . spend ( txins , [ solver for i in txins ] ) | sign the parent txn outputs P2PKH | 64 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.