idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
12,900 | def password_link_expired ( self , now = None ) : if not now : now = datetime . datetime . utcnow ( ) return self . password_link_expires < now | Check if password link expired |
12,901 | def add_role ( self , role ) : schema = RoleSchema ( ) ok = schema . process ( role ) if not ok or not role . id : err = 'Role must be valid and saved before adding to user' raise x . UserException ( err ) self . __roles . append ( role ) | Add role to user Role must be valid and saved first otherwise will raise an exception . |
12,902 | def has_role ( self , role_or_handle ) : if not isinstance ( role_or_handle , str ) : return role_or_handle in self . roles has_role = False for role in self . roles : if role . handle == role_or_handle : has_role = True break return has_role | Checks if user has role |
12,903 | def push ( remote = 'origin' , branch = 'master' ) : print ( cyan ( "Pulling changes from repo ( %s / %s)..." % ( remote , branch ) ) ) local ( "git push %s %s" % ( remote , branch ) ) | git push commit |
12,904 | def pull ( remote = 'origin' , branch = 'master' ) : print ( cyan ( "Pulling changes from repo ( %s / %s)..." % ( remote , branch ) ) ) local ( "git pull %s %s" % ( remote , branch ) ) | git pull commit |
12,905 | def sync ( remote = 'origin' , branch = 'master' ) : pull ( branch , remote ) push ( branch , remote ) print ( cyan ( "Git Synced!" ) ) | git pull and push commit |
12,906 | def update ( tournament , match , attachment , ** params ) : api . fetch ( "PUT" , "tournaments/%s/matches/%s/attachments/%s" % ( tournament , match , attachment ) , "match_attachment" , ** params ) | Update the attributes of a match attachment . |
12,907 | def count_row ( engine , table ) : return engine . execute ( select ( [ func . count ( ) ] ) . select_from ( table ) ) . fetchone ( ) [ 0 ] | Return number of rows in a table . |
12,908 | def get_providers ( self ) : if self . providers : return self . providers providers = dict ( ) for provider in self . config : configurator = provider . lower ( ) + '_config' if not hasattr ( self , configurator ) : err = 'Provider [{}] not recognized' . format ( provider ) raise ValueError ( err ) provider_config = self . config [ provider ] configurator = getattr ( self , configurator ) providers [ provider ] = configurator ( id = provider_config . get ( 'id' ) , secret = provider_config . get ( 'secret' ) , scope = provider_config . get ( 'scope' ) , offline = provider_config . get ( 'offline' ) ) self . providers = providers return self . providers | Get OAuth providers Returns a dictionary of oauth applications ready to be registered with flask oauth extension at application bootstrap . |
12,909 | def token_getter ( provider , token = None ) : session_key = provider + '_token' if token is None : token = session . get ( session_key ) return token | Generic token getter for all the providers |
12,910 | def register_token_getter ( self , provider ) : app = oauth . remote_apps [ provider ] decorator = getattr ( app , 'tokengetter' ) def getter ( token = None ) : return self . token_getter ( provider , token ) decorator ( getter ) | Register callback to retrieve token from session |
12,911 | def vkontakte_config ( self , id , secret , scope = None , offline = False , ** _ ) : if scope is None : scope = 'email,offline' if offline : scope += ',offline' token_params = dict ( scope = scope ) config = dict ( request_token_url = None , access_token_url = 'https://oauth.vk.com/access_token' , authorize_url = 'https://oauth.vk.com/authorize' , base_url = 'https://api.vk.com/method/' , consumer_key = id , consumer_secret = secret , request_token_params = token_params ) return config | Get config dictionary for vkontakte oauth |
12,912 | def instagram_config ( self , id , secret , scope = None , ** _ ) : scope = scope if scope else 'basic' token_params = dict ( scope = scope ) config = dict ( access_token_url = '/oauth/access_token/' , authorize_url = '/oauth/authorize/' , base_url = 'https://api.instagram.com/' , consumer_key = id , consumer_secret = secret , request_token_params = token_params ) return config | Get config dictionary for instagram oauth |
12,913 | def convert ( self , chain_id , residue_id , from_scheme , to_scheme ) : from_scheme = from_scheme . lower ( ) to_scheme = to_scheme . lower ( ) assert ( from_scheme in ResidueRelatrix . schemes ) assert ( to_scheme in ResidueRelatrix . schemes ) return self . _convert ( chain_id , residue_id , from_scheme , to_scheme ) | The API conversion function . This converts between the different residue ID schemes . |
12,914 | def _convert ( self , chain_id , residue_id , from_scheme , to_scheme ) : if from_scheme == 'rosetta' : atom_id = self . rosetta_to_atom_sequence_maps . get ( chain_id , { } ) [ residue_id ] if to_scheme == 'atom' : return atom_id else : return self . _convert ( chain_id , atom_id , 'atom' , to_scheme ) if from_scheme == 'atom' : if to_scheme == 'rosetta' : return self . atom_to_rosetta_sequence_maps . get ( chain_id , { } ) [ residue_id ] else : seqres_id = self . atom_to_seqres_sequence_maps . get ( chain_id , { } ) [ residue_id ] if to_scheme == 'seqres' : return seqres_id return self . convert ( chain_id , seqres_id , 'seqres' , to_scheme ) if from_scheme == 'seqres' : if to_scheme == 'uniparc' : return self . seqres_to_uniparc_sequence_maps . get ( chain_id , { } ) [ residue_id ] else : atom_id = self . seqres_to_atom_sequence_maps . get ( chain_id , { } ) [ residue_id ] if to_scheme == 'atom' : return atom_id return self . convert ( chain_id , atom_id , 'atom' , to_scheme ) if from_scheme == 'uniparc' : seqres_id = self . uniparc_to_seqres_sequence_maps . get ( chain_id , { } ) [ residue_id ] if to_scheme == 'seqres' : return seqres_id else : return self . _convert ( chain_id , seqres_id , 'seqres' , to_scheme ) raise Exception ( "We should never reach this line." ) | The actual private conversion function . |
12,915 | def convert_from_rosetta ( self , residue_id , to_scheme ) : assert ( type ( residue_id ) == types . IntType ) chain_id = None for c , sequence in self . rosetta_sequences . iteritems ( ) : for id , r in sequence : if r . ResidueID == residue_id : assert ( chain_id == None ) chain_id = c if chain_id : return self . convert ( chain_id , residue_id , 'rosetta' , to_scheme ) else : return None | A simpler conversion function to convert from Rosetta numbering without requiring the chain identifier . |
12,916 | def _validate ( self ) : self . _validate_fasta_vs_seqres ( ) self . _validate_mapping_signature ( ) self . _validate_id_types ( ) self . _validate_residue_types ( ) | Validate the mappings . |
12,917 | def _validate_id_types ( self ) : for sequences in [ self . uniparc_sequences , self . fasta_sequences , self . seqres_sequences , self . rosetta_sequences ] : for chain_id , sequence in sequences . iteritems ( ) : sequence_id_types = set ( map ( type , sequence . ids ( ) ) ) if sequence_id_types : assert ( len ( sequence_id_types ) == 1 ) assert ( sequence_id_types . pop ( ) == types . IntType ) for chain_id , sequence in self . atom_sequences . iteritems ( ) : sequence_id_types = set ( map ( type , sequence . ids ( ) ) ) assert ( len ( sequence_id_types ) == 1 ) sequence_id_type = sequence_id_types . pop ( ) assert ( sequence_id_type == types . StringType or sequence_id_type == types . UnicodeType ) | Check that the ID types are integers for Rosetta SEQRES and UniParc sequences and 6 - character PDB IDs for the ATOM sequences . |
12,918 | def _validate_residue_types ( self ) : for chain_id , sequence_map in self . rosetta_to_atom_sequence_maps . iteritems ( ) : rosetta_sequence = self . rosetta_sequences [ chain_id ] atom_sequence = self . atom_sequences [ chain_id ] for rosetta_id , atom_id , _ in sequence_map : assert ( rosetta_sequence [ rosetta_id ] . ResidueAA == atom_sequence [ atom_id ] . ResidueAA ) for chain_id , sequence_map in self . atom_to_seqres_sequence_maps . iteritems ( ) : atom_sequence = self . atom_sequences [ chain_id ] seqres_sequence = self . seqres_sequences [ chain_id ] for atom_id , seqres_id , _ in sorted ( sequence_map ) : assert ( atom_sequence [ atom_id ] . ResidueAA == seqres_sequence [ seqres_id ] . ResidueAA ) for chain_id , sequence_map in self . seqres_to_uniparc_sequence_maps . iteritems ( ) : if self . pdb_chain_to_uniparc_chain_mapping . get ( chain_id ) : seqres_sequence = self . seqres_sequences [ chain_id ] uniparc_sequence = self . uniparc_sequences [ self . pdb_chain_to_uniparc_chain_mapping [ chain_id ] ] for seqres_id , uniparc_id_resid_pair , substitution_match in sequence_map : uniparc_id = uniparc_id_resid_pair [ 1 ] if substitution_match and substitution_match . clustal == 1 : assert ( seqres_sequence [ seqres_id ] . ResidueAA == uniparc_sequence [ uniparc_id ] . ResidueAA ) | Make sure all the residue types map through translation . |
12,919 | def _create_sequences ( self ) : try : self . pdb . construct_pdb_to_rosetta_residue_map ( self . rosetta_scripts_path , rosetta_database_path = self . rosetta_database_path , cache_dir = self . cache_dir ) except PDBMissingMainchainAtomsException : self . pdb_to_rosetta_residue_map_error = True if self . pdb_id not in do_not_use_the_sequence_aligner : self . uniparc_sequences = self . PDB_UniParc_SA . uniparc_sequences else : self . uniparc_sequences = self . sifts . get_uniparc_sequences ( ) self . fasta_sequences = self . FASTA . get_sequences ( self . pdb_id ) self . seqres_sequences = self . pdb . seqres_sequences self . atom_sequences = self . pdb . atom_sequences if self . pdb_to_rosetta_residue_map_error : self . rosetta_sequences = { } for c in self . atom_sequences . keys ( ) : self . rosetta_sequences [ c ] = Sequence ( ) else : self . rosetta_sequences = self . pdb . rosetta_sequences uniparc_pdb_chain_mapping = { } if self . pdb_id not in do_not_use_the_sequence_aligner : for pdb_chain_id , matches in self . PDB_UniParc_SA . clustal_matches . iteritems ( ) : if matches : uniparc_chain_id = matches . keys ( ) [ 0 ] assert ( len ( matches ) == 1 ) uniparc_pdb_chain_mapping [ uniparc_chain_id ] = uniparc_pdb_chain_mapping . get ( uniparc_chain_id , [ ] ) uniparc_pdb_chain_mapping [ uniparc_chain_id ] . append ( pdb_chain_id ) else : for pdb_chain_id , uniparc_chain_ids in self . sifts . get_pdb_chain_to_uniparc_id_map ( ) . iteritems ( ) : for uniparc_chain_id in uniparc_chain_ids : uniparc_pdb_chain_mapping [ uniparc_chain_id ] = uniparc_pdb_chain_mapping . get ( uniparc_chain_id , [ ] ) uniparc_pdb_chain_mapping [ uniparc_chain_id ] . append ( pdb_chain_id ) for uniparc_chain_id , pdb_chain_ids in uniparc_pdb_chain_mapping . iteritems ( ) : sequence_type = set ( [ self . seqres_sequences [ p ] . sequence_type for p in pdb_chain_ids ] ) assert ( len ( sequence_type ) == 1 ) sequence_type = sequence_type . pop ( ) assert ( self . uniparc_sequences [ uniparc_chain_id ] . sequence_type == None ) self . uniparc_sequences [ uniparc_chain_id ] . set_type ( sequence_type ) for p in pdb_chain_ids : self . pdb_chain_to_uniparc_chain_mapping [ p ] = uniparc_chain_id for chain_id , sequence in self . seqres_sequences . iteritems ( ) : self . fasta_sequences [ chain_id ] . set_type ( sequence . sequence_type ) | Get all of the Sequences - Rosetta ATOM SEQRES FASTA UniParc . |
12,920 | def search ( cls , query_string , options = None , enable_facet_discovery = False , return_facets = None , facet_options = None , facet_refinements = None , deadline = None , ** kwargs ) : search_class = cls . search_get_class_names ( ) [ - 1 ] query_string += ' ' + 'class_name:%s' % ( search_class , ) q = search . Query ( query_string = query_string , options = options , enable_facet_discovery = enable_facet_discovery , return_facets = return_facets , facet_options = facet_options , facet_refinements = facet_refinements ) index = cls . search_get_index ( ) return index . search ( q , deadline = deadline , ** kwargs ) | Searches the index . Conveniently searches only for documents that belong to instances of this class . |
12,921 | def search_update_index ( self ) : doc_id = self . search_get_document_id ( self . key ) fields = [ search . AtomField ( 'class_name' , name ) for name in self . search_get_class_names ( ) ] index = self . search_get_index ( ) if self . searchable_fields is None : searchable_fields = [ ] for field , prop in self . _properties . items ( ) : if field == 'class' : continue for class_ , field_type in SEARCHABLE_PROPERTY_TYPES . items ( ) : if isinstance ( prop , class_ ) : searchable_fields . append ( field ) else : searchable_fields = self . searchable_fields for f in set ( searchable_fields ) : prop = self . _properties [ f ] value = getattr ( self , f ) field = None field_found = False for class_ , field_type in SEARCHABLE_PROPERTY_TYPES . items ( ) : if isinstance ( prop , class_ ) : field_found = True if value is not None : if isinstance ( value , list ) or isinstance ( value , tuple ) or isinstance ( value , set ) : for v in value : field = field_type ( name = f , value = v ) elif isinstance ( value , ndb . Key ) : field = field_type ( name = f , value = value . urlsafe ( ) ) else : field = field_type ( name = f , value = value ) if not field_found : raise ValueError ( 'Cannot find field type for %r on %r' % ( prop , self . __class__ ) ) if field is not None : fields . append ( field ) document = search . Document ( doc_id , fields = fields ) index . put ( document ) | Updates the search index for this instance . |
12,922 | def search_get_class_names ( cls ) : if hasattr ( cls , '_class_key' ) : class_names = [ ] for n in cls . _class_key ( ) : class_names . append ( n ) return class_names else : return [ cls . __name__ ] | Returns class names for use in document indexing . |
12,923 | def from_urlsafe ( cls , urlsafe ) : try : key = ndb . Key ( urlsafe = urlsafe ) except : return None obj = key . get ( ) if obj and isinstance ( obj , cls ) : return obj | Returns an instance of the model from a urlsafe string . |
12,924 | def get_from_search_doc ( cls , doc_id ) : if hasattr ( doc_id , 'doc_id' ) : doc_id = doc_id . doc_id return cls . from_urlsafe ( doc_id ) | Returns an instance of the model from a search document id . |
12,925 | def _pre_delete_hook ( cls , key ) : if cls . searching_enabled : doc_id = cls . search_get_document_id ( key ) index = cls . search_get_index ( ) index . delete ( doc_id ) | Removes instance from index . |
12,926 | def process_answer ( self , user , item , asked , answered , time , answer , response_time , guess , ** kwargs ) : pass | This method is used during the answer streaming and is called after the predictive model for each answer . |
12,927 | def _get_sz_info ( self ) : if 'None' == self . _state : return None cmd = 'show virtual-service detail name guestshell+' got = self . cli ( cmd ) got = got [ 'TABLE_detail' ] [ 'ROW_detail' ] sz_cpu = int ( got [ 'cpu_reservation' ] ) sz_disk = int ( got [ 'disk_reservation' ] ) sz_memory = int ( got [ 'memory_reservation' ] ) self . sz_has = _guestshell . Resources ( cpu = sz_cpu , memory = sz_memory , disk = sz_disk ) | Obtains the current resource allocations assumes that the guestshell is in an Activated state |
12,928 | def fractal_dimension ( image ) : pixels = [ ] for i in range ( image . shape [ 0 ] ) : for j in range ( image . shape [ 1 ] ) : if image [ i , j ] > 0 : pixels . append ( ( i , j ) ) lx = image . shape [ 1 ] ly = image . shape [ 0 ] pixels = np . array ( pixels ) if len ( pixels ) < 2 : return 0 scales = np . logspace ( 1 , 4 , num = 20 , endpoint = False , base = 2 ) Ns = [ ] for scale in scales : H , edges = np . histogramdd ( pixels , bins = ( np . arange ( 0 , lx , scale ) , np . arange ( 0 , ly , scale ) ) ) H_sum = np . sum ( H > 0 ) if H_sum == 0 : H_sum = 1 Ns . append ( H_sum ) coeffs = np . polyfit ( np . log ( scales ) , np . log ( Ns ) , 1 ) hausdorff_dim = - coeffs [ 0 ] return hausdorff_dim | Estimates the fractal dimension of an image with box counting . Counts pixels with value 0 as empty and everything else as non - empty . Input image has to be grayscale . |
12,929 | def channel_portion ( image , channel ) : rgb = [ ] for i in range ( 3 ) : rgb . append ( image [ : , : , i ] . astype ( int ) ) ch = rgb . pop ( channel ) relative_values = ch - np . sum ( rgb , axis = 0 ) / 2 relative_values = np . maximum ( np . zeros ( ch . shape ) , relative_values ) return float ( np . average ( relative_values ) / 255 ) | Estimates the amount of a color relative to other colors . |
12,930 | def intensity ( image ) : if len ( image . shape ) > 2 : image = cv2 . cvtColor ( image , cv2 . COLOR_RGB2GRAY ) / 255 elif issubclass ( image . dtype . type , np . integer ) : image /= 255 return float ( np . sum ( image ) / np . prod ( image . shape ) ) | Calculates the average intensity of the pixels in an image . Accepts both RGB and grayscale images . |
12,931 | def sliding_window ( sequence , win_size , step = 1 ) : try : it = iter ( sequence ) except TypeError : raise ValueError ( "sequence must be iterable." ) if not isinstance ( win_size , int ) : raise ValueError ( "type(win_size) must be int." ) if not isinstance ( step , int ) : raise ValueError ( "type(step) must be int." ) if step > win_size : raise ValueError ( "step must not be larger than win_size." ) if win_size > len ( sequence ) : raise ValueError ( "win_size must not be larger than sequence length." ) num_chunks = ( ( len ( sequence ) - win_size ) / step ) + 1 for i in range ( 0 , num_chunks * step , step ) : yield sequence [ i : i + win_size ] | Returns a generator that will iterate through the defined chunks of input sequence . Input sequence must be iterable . |
12,932 | def dna_to_re ( seq ) : seq = seq . replace ( 'K' , '[GT]' ) seq = seq . replace ( 'M' , '[AC]' ) seq = seq . replace ( 'R' , '[AG]' ) seq = seq . replace ( 'Y' , '[CT]' ) seq = seq . replace ( 'S' , '[CG]' ) seq = seq . replace ( 'W' , '[AT]' ) seq = seq . replace ( 'B' , '[CGT]' ) seq = seq . replace ( 'V' , '[ACG]' ) seq = seq . replace ( 'H' , '[ACT]' ) seq = seq . replace ( 'D' , '[AGT]' ) seq = seq . replace ( 'X' , '[GATC]' ) seq = seq . replace ( 'N' , '[GATC]' ) return re . compile ( seq ) | Return a compiled regular expression that will match anything described by the input sequence . For example a sequence that contains a N matched any base at that position . |
12,933 | def case_highlight ( seq , subseq ) : return re . subs ( subseq . lower ( ) , subseq . upper ( ) , seq . lower ( ) ) | Highlights all instances of subseq in seq by making them uppercase and everything else lowercase . |
12,934 | def index_relations ( sender , pid_type , json = None , record = None , index = None , ** kwargs ) : if not json : json = { } pid = PersistentIdentifier . query . filter ( PersistentIdentifier . object_uuid == record . id , PersistentIdentifier . pid_type == pid_type , ) . one_or_none ( ) relations = None if pid : relations = serialize_relations ( pid ) if relations : json [ 'relations' ] = relations return json | Add relations to the indexed record . |
12,935 | def index_siblings ( pid , include_pid = False , children = None , neighbors_eager = False , eager = False , with_deposits = True ) : assert not ( neighbors_eager and eager ) , if children is None : parent_pid = PIDNodeVersioning ( pid = pid ) . parents . first ( ) children = PIDNodeVersioning ( pid = parent_pid ) . children . all ( ) objid = str ( pid . object_uuid ) children = [ str ( p . object_uuid ) for p in children ] idx = children . index ( objid ) if objid in children else len ( children ) if include_pid : left = children [ : idx + 1 ] else : left = children [ : idx ] right = children [ idx + 1 : ] if eager : eager_uuids = left + right bulk_uuids = [ ] elif neighbors_eager : eager_uuids = left [ - 1 : ] + right [ : 1 ] bulk_uuids = left [ : - 1 ] + right [ 1 : ] else : eager_uuids = [ ] bulk_uuids = left + right def get_dep_uuids ( rec_uuids ) : return [ str ( PersistentIdentifier . get ( 'depid' , Record . get_record ( id_ ) [ '_deposit' ] [ 'id' ] ) . object_uuid ) for id_ in rec_uuids ] if with_deposits : eager_uuids += get_dep_uuids ( eager_uuids ) bulk_uuids += get_dep_uuids ( bulk_uuids ) for id_ in eager_uuids : RecordIndexer ( ) . index_by_id ( id_ ) if bulk_uuids : RecordIndexer ( ) . bulk_index ( bulk_uuids ) | Send sibling records of the passed pid for indexing . |
12,936 | def iter_paths ( self , pathnames = None , mapfunc = None ) : pathnames = pathnames or self . _pathnames if self . recursive and not pathnames : pathnames = [ '.' ] elif not pathnames : yield [ ] if mapfunc is not None : for mapped_paths in map ( mapfunc , pathnames ) : for path in mapped_paths : if self . recursive and ( os . path . isdir ( path ) or os . path . islink ( path ) ) : for t in os . walk ( path , followlinks = self . follow_symlinks ) : for filename , values in self . iglob ( os . path . join ( t [ 0 ] , '*' ) ) : yield filename , values else : empty_glob = True for filename , values in self . iglob ( path ) : yield filename , values empty_glob = False if empty_glob : yield path , None else : for path in pathnames : if self . recursive and ( os . path . isdir ( path ) or os . path . islink ( path ) ) : for t in os . walk ( path , followlinks = self . follow_symlinks ) : for filename , values in self . iglob ( os . path . join ( t [ 0 ] , '*' ) ) : yield filename , values else : empty_glob = True for filename , values in self . iglob ( path ) : yield filename , values empty_glob = False if empty_glob : yield path , None | Special iteration on paths . Yields couples of path and items . If a expanded path doesn t match with any files a couple with path and None is returned . |
12,937 | def check_stat ( self , path ) : statinfo = os . stat ( path ) st_mtime = datetime . fromtimestamp ( statinfo . st_mtime ) if platform . system ( ) == 'Linux' : check = st_mtime >= self . start_dt else : st_ctime = datetime . fromtimestamp ( statinfo . st_ctime ) check = st_mtime >= self . start_dt and st_ctime <= self . end_dt if not check : logger . info ( "file %r not in datetime period!" , path ) return check | Checks logfile stat information for excluding files not in datetime period . On Linux it s possible to checks only modification time because file creation info are not available so it s possible to exclude only older files . In Unix BSD systems and windows information about file creation date and times are available so is possible to exclude too newer files . |
12,938 | def add ( self , files , items ) : if isinstance ( files , ( str , bytes ) ) : files = iter ( [ files ] ) for pathname in files : try : values = self . _filemap [ pathname ] except KeyError : self . _filemap [ pathname ] = items else : values . extend ( items ) | Add a list of files with a reference to a list of objects . |
12,939 | def recruit ( self ) : participants = Participant . query . with_entities ( Participant . status ) . all ( ) if not self . networks ( full = False ) : print "All networks are full, closing recruitment." self . recruiter ( ) . close_recruitment ( ) elif [ p for p in participants if p . status < 100 ] : print "People are still participating: not recruiting." elif ( len ( [ p for p in participants if p . status == 101 ] ) % self . generation_size ) == 0 : print "Recruiting another generation." self . recruiter ( ) . recruit_participants ( n = self . generation_size ) else : print "not recruiting." | Recruit more participants . |
12,940 | def data_check ( self , participant ) : participant_id = participant . uniqueid nodes = Node . query . filter_by ( participant_id = participant_id ) . all ( ) if len ( nodes ) != self . experiment_repeats + self . practice_repeats : print ( "Error: Participant has {} nodes. Data check failed" . format ( len ( nodes ) ) ) return False nets = [ n . network_id for n in nodes ] if len ( nets ) != len ( set ( nets ) ) : print "Error: Participant participated in the same network \ multiple times. Data check failed" return False if None in [ n . fitness for n in nodes ] : print "Error: some of participants nodes are missing a fitness. \ Data check failed." return False if None in [ n . score for n in nodes ] : print "Error: some of participants nodes are missing a score. \ Data check failed" return False return True | Check a participants data . |
12,941 | def add_node_to_network ( self , node , network ) : network . add_node ( node ) node . receive ( ) environment = network . nodes ( type = Environment ) [ 0 ] environment . connect ( whom = node ) gene = node . infos ( type = LearningGene ) [ 0 ] . contents if ( gene == "social" ) : prev_agents = RogersAgent . query . filter ( and_ ( RogersAgent . failed == False , RogersAgent . network_id == network . id , RogersAgent . generation == node . generation - 1 ) ) . all ( ) parent = random . choice ( prev_agents ) parent . connect ( whom = node ) parent . transmit ( what = Meme , to_whom = node ) elif ( gene == "asocial" ) : environment . transmit ( to_whom = node ) else : raise ValueError ( "{} has invalid learning gene value of {}" . format ( node , gene ) ) node . receive ( ) | Add participant s node to a network . |
12,942 | def create_state ( self , proportion ) : if random . random ( ) < 0.5 : proportion = 1 - proportion State ( origin = self , contents = proportion ) | Create an environmental state . |
12,943 | def step ( self ) : current_state = max ( self . infos ( type = State ) , key = attrgetter ( 'creation_time' ) ) current_contents = float ( current_state . contents ) new_contents = 1 - current_contents info_out = State ( origin = self , contents = new_contents ) transformations . Mutation ( info_in = current_state , info_out = info_out ) | Prompt the environment to change . |
12,944 | def print_subprocess_output ( subp ) : if subp : if subp . errorcode != 0 : print ( '<error errorcode="%s">' % str ( subp . errorcode ) ) print ( subp . stderr ) print ( "</error>" ) print_tag ( 'stdout' , '\n%s\n' % subp . stdout ) else : print_tag ( 'success' , '\n%s\n' % subp . stdout ) print_tag ( 'warnings' , '\n%s\n' % subp . stderr ) | Prints the stdout and stderr output . |
12,945 | def get_all ( self , force_download = False ) : cl = self . client return [ cl . get_item ( item , force_download ) for item in self . item_urls ] | Retrieve the metadata for all items in this list from the server as Item objects |
12,946 | def get_item ( self , item_index , force_download = False ) : return self . client . get_item ( self . item_urls [ item_index ] , force_download ) | Retrieve the metadata for a specific item in this ItemGroup |
12,947 | def refresh ( self ) : refreshed = self . client . get_item_list ( self . url ( ) ) self . item_urls = refreshed . urls ( ) self . list_name = refreshed . name ( ) return self | Update this ItemList by re - downloading it from the server |
12,948 | def append ( self , items ) : resp = self . client . add_to_item_list ( items , self . url ( ) ) self . refresh ( ) return resp | Add some items to this ItemList and save the changes to the server |
12,949 | def get_document ( self , index = 0 ) : try : return Document ( self . metadata ( ) [ 'alveo:documents' ] [ index ] , self . client ) except IndexError : raise ValueError ( 'No document exists for this item with index: ' + str ( index ) ) | Return the metadata for the specified document as a Document object |
12,950 | def get_primary_text ( self , force_download = False ) : return self . client . get_primary_text ( self . url ( ) , force_download ) | Retrieve the primary text for this item from the server |
12,951 | def get_annotations ( self , atype = None , label = None ) : return self . client . get_item_annotations ( self . url ( ) , atype , label ) | Retrieve the annotations for this item from the server |
12,952 | def get_content ( self , force_download = False ) : return self . client . get_document ( self . url ( ) , force_download ) | Retrieve the content for this Document from the server |
12,953 | def download_content ( self , dir_path = '' , filename = None , force_download = False ) : if filename is None : filename = self . get_filename ( ) path = os . path . join ( dir_path , filename ) data = self . client . get_document ( self . url ( ) , force_download ) with open ( path , 'wb' ) as f : f . write ( data ) return path | Download the content for this document to a file |
12,954 | def generic_ref_formatter ( view , context , model , name , lazy = False ) : try : if lazy : rel_model = getattr ( model , name ) . fetch ( ) else : rel_model = getattr ( model , name ) except ( mongoengine . DoesNotExist , AttributeError ) as e : return Markup ( '<span class="label label-danger">Error</span> <small>%s</small>' % e ) if rel_model is None : return '' try : return Markup ( '<a href="%s">%s</a>' % ( url_for ( '%s.details_view' % rel_model . __class__ . __name__ . lower ( ) , id = rel_model . id , ) , rel_model , ) ) except werkzeug . routing . BuildError as e : return Markup ( '<span class="label label-danger">Error</span> <small>%s</small>' % e ) | For GenericReferenceField and LazyGenericReferenceField |
12,955 | def generic_document_type_formatter ( view , context , model , name ) : _document_model = model . get ( 'document' ) . document_type url = _document_model . get_admin_list_url ( ) return Markup ( '<a href="%s">%s</a>' % ( url , _document_model . __name__ ) ) | Return AdminLog . document field wrapped in URL to its list view . |
12,956 | def return_page ( page ) : try : hit_id = request . args [ 'hit_id' ] assignment_id = request . args [ 'assignment_id' ] worker_id = request . args [ 'worker_id' ] mode = request . args [ 'mode' ] return render_template ( page , hit_id = hit_id , assignment_id = assignment_id , worker_id = worker_id , mode = mode ) except : try : participant_id = request . args [ 'participant_id' ] return render_template ( page , participant_id = participant_id ) except : return error_response ( error_type = "{} args missing" . format ( page ) ) | Return a rendered template . |
12,957 | def quitter ( ) : exp = experiment ( session ) exp . log ( "Quitter route was hit." ) return Response ( dumps ( { "status" : "success" } ) , status = 200 , mimetype = 'application/json' ) | Overide the psiTurk quitter route . |
12,958 | def ad_address ( mode , hit_id ) : if mode == "debug" : address = '/complete' elif mode in [ "sandbox" , "live" ] : username = os . getenv ( 'psiturk_access_key_id' , config . get ( "psiTurk Access" , "psiturk_access_key_id" ) ) password = os . getenv ( 'psiturk_secret_access_id' , config . get ( "psiTurk Access" , "psiturk_secret_access_id" ) ) try : req = requests . get ( 'https://api.psiturk.org/api/ad/lookup/' + hit_id , auth = ( username , password ) ) except : raise ValueError ( 'api_server_not_reachable' ) else : if req . status_code == 200 : hit_address = req . json ( ) [ 'ad_id' ] else : raise ValueError ( "something here" ) if mode == "sandbox" : address = ( 'https://sandbox.ad.psiturk.org/complete/' + str ( hit_address ) ) elif mode == "live" : address = 'https://ad.psiturk.org/complete/' + str ( hit_address ) else : raise ValueError ( "Unknown mode: {}" . format ( mode ) ) return success_response ( field = "address" , data = address , request_type = "ad_address" ) | Get the address of the ad on AWS . |
12,959 | def connect ( node_id , other_node_id ) : exp = experiment ( session ) direction = request_parameter ( parameter = "direction" , default = "to" ) if type ( direction == Response ) : return direction node = models . Node . query . get ( node_id ) if node is None : return error_response ( error_type = "/node/connect, node does not exist" ) other_node = models . Node . query . get ( other_node_id ) if other_node is None : return error_response ( error_type = "/node/connect, other node does not exist" , participant = node . participant ) try : vectors = node . connect ( whom = other_node , direction = direction ) for v in vectors : assign_properties ( v ) exp . vector_post_request ( node = node , vectors = vectors ) session . commit ( ) except : return error_response ( error_type = "/vector POST server error" , status = 403 , participant = node . participant ) return success_response ( field = "vectors" , data = [ v . __json__ ( ) for v in vectors ] , request_type = "vector post" ) | Connect to another node . |
12,960 | def get_info ( node_id , info_id ) : exp = experiment ( session ) node = models . Node . query . get ( node_id ) if node is None : return error_response ( error_type = "/info, node does not exist" ) info = models . Info . query . get ( info_id ) if info is None : return error_response ( error_type = "/info GET, info does not exist" , participant = node . participant ) elif ( info . origin_id != node . id and info . id not in [ t . info_id for t in node . transmissions ( direction = "incoming" , status = "received" ) ] ) : return error_response ( error_type = "/info GET, forbidden info" , status = 403 , participant = node . participant ) try : exp . info_get_request ( node = node , infos = info ) session . commit ( ) except : return error_response ( error_type = "/info GET server error" , status = 403 , participant = node . participant ) return success_response ( field = "info" , data = info . __json__ ( ) , request_type = "info get" ) | Get a specific info . |
12,961 | def transformation_post ( node_id , info_in_id , info_out_id ) : exp = experiment ( session ) transformation_type = request_parameter ( parameter = "transformation_type" , parameter_type = "known_class" , default = models . Transformation ) if type ( transformation_type ) == Response : return transformation_type node = models . Node . query . get ( node_id ) if node is None : return error_response ( error_type = "/transformation POST, node does not exist" ) info_in = models . Info . query . get ( info_in_id ) if info_in is None : return error_response ( error_type = "/transformation POST, info_in does not exist" , participant = node . participant ) info_out = models . Info . query . get ( info_out_id ) if info_out is None : return error_response ( error_type = "/transformation POST, info_out does not exist" , participant = node . participant ) try : transformation = transformation_type ( info_in = info_in , info_out = info_out ) assign_properties ( transformation ) session . commit ( ) exp . transformation_post_request ( node = node , transformation = transformation ) session . commit ( ) except : return error_response ( error_type = "/tranaformation POST failed" , participant = node . participant ) return success_response ( field = "transformation" , data = transformation . __json__ ( ) , request_type = "transformation post" ) | Transform an info . |
12,962 | def api_notifications ( ) : event_type = request . values [ 'Event.1.EventType' ] assignment_id = request . values [ 'Event.1.AssignmentId' ] db . logger . debug ( 'rq: Queueing %s with id: %s for worker_function' , event_type , assignment_id ) q . enqueue ( worker_function , event_type , assignment_id , None ) db . logger . debug ( 'rq: Submitted Queue Length: %d (%s)' , len ( q ) , ', ' . join ( q . job_ids ) ) return success_response ( request_type = "notification" ) | Receive MTurk REST notifications . |
12,963 | def process ( source , target , rdfsonly , base = None , logger = logging ) : for link in source . match ( ) : s , p , o = link [ : 3 ] if s == ( base or '' ) + '@docheader' : continue if p in RESOURCE_MAPPING : p = RESOURCE_MAPPING [ p ] if o in RESOURCE_MAPPING : o = RESOURCE_MAPPING [ o ] if p == VERSA_BASEIRI + 'refines' : tlinks = list ( source . match ( s , TYPE_REL ) ) if tlinks : if tlinks [ 0 ] [ TARGET ] == VERSA_BASEIRI + 'Resource' : p = I ( RDFS_NAMESPACE + 'subClassOf' ) elif tlinks [ 0 ] [ TARGET ] == VERSA_BASEIRI + 'Property' : p = I ( RDFS_NAMESPACE + 'subPropertyOf' ) if p == VERSA_BASEIRI + 'properties' : suri = I ( iri . absolutize ( s , base ) ) if base else s target . add ( ( URIRef ( o ) , URIRef ( RDFS_NAMESPACE + 'domain' ) , URIRef ( suri ) ) ) continue if p == VERSA_BASEIRI + 'value' : if o not in [ 'Literal' , 'IRI' ] : ouri = I ( iri . absolutize ( o , base ) ) if base else o target . add ( ( URIRef ( s ) , URIRef ( RDFS_NAMESPACE + 'range' ) , URIRef ( ouri ) ) ) continue s = URIRef ( s ) p = RDF . type if p == TYPE_REL else URIRef ( p ) o = URIRef ( o ) if isinstance ( o , I ) else Literal ( o ) if not rdfsonly or p . startswith ( RDF_NAMESPACE ) or p . startswith ( RDFS_NAMESPACE ) : target . add ( ( s , p , o ) ) return | Prepare a statement into a triple ready for rdflib graph |
12,964 | def write ( models , base = None , graph = None , rdfsonly = False , prefixes = None , logger = logging ) : prefixes = prefixes or { } g = graph or rdflib . Graph ( ) g . bind ( 'v' , VNS ) for k , v in prefixes . items ( ) : g . bind ( k , v ) for m in models : base_out = m . base process ( m , g , rdfsonly , base = base_out , logger = logger ) return g | See the command line help |
12,965 | def routing_feature ( app ) : app . url_map . converters [ 'regex' ] = RegexConverter urls = app . name . rsplit ( '.' , 1 ) [ 0 ] + '.urls.urls' try : urls = import_string ( urls ) except ImportError as e : err = 'Failed to import {}. If it exists, check that it does not ' err += 'import something non-existent itself! ' err += 'Try to manually import it to debug.' raise ImportError ( err . format ( urls ) ) for route in urls . keys ( ) : route_options = urls [ route ] route_options [ 'rule' ] = route app . add_url_rule ( ** route_options ) | Add routing feature Allows to define application routes un urls . py file and use lazy views . Additionally enables regular exceptions in route definitions |
12,966 | def undoable ( method ) : def undoable_method ( self , * args ) : return self . do ( Command ( self , method , * args ) ) return undoable_method | Decorator undoable allows an instance method to be undone . |
12,967 | def get_template_directory ( self ) : dir = os . path . join ( os . path . dirname ( __file__ ) , 'templates' ) return dir | Get path to migrations templates This will get used when you run the db init command |
12,968 | async def pull_metrics ( self , event_fn , loop = None ) : if self . lazy and not self . ready : return None logger = self . get_logger ( ) ts = timer ( ) logger . trace ( "Waiting for process event" ) result = await self . process ( event_fn ) td = int ( timer ( ) - ts ) logger . trace ( "It took: {}ms" . format ( td ) ) self . _last_run = current_ts ( ) return result | Method called by core . Should not be overwritten . |
12,969 | def ready ( self ) : logger = self . get_logger ( ) now = current_ts ( ) logger . trace ( "Current time: {0}" . format ( now ) ) logger . trace ( "Last Run: {0}" . format ( self . _last_run ) ) delta = ( now - self . _last_run ) logger . trace ( "Delta: {0}, Interval: {1}" . format ( delta , self . interval * 1000 ) ) return delta > self . interval * 1000 | Function used when agent is lazy . It is being processed only when ready condition is satisfied |
12,970 | def create_jwt ( self , expires_in = None ) : s = utils . sign_jwt ( data = { "id" : self . user . id } , secret_key = get_jwt_secret ( ) , salt = get_jwt_salt ( ) , expires_in = expires_in or get_jwt_ttl ( ) ) return s | Create a secure timed JWT token that can be passed . It save the user id which later will be used to retrieve the data |
12,971 | def sendgmail ( self , subject , recipients , plaintext , htmltext = None , cc = None , debug = False , useMIMEMultipart = True , gmail_account = 'kortemmelab@gmail.com' , pw_filepath = None ) : smtpserver = smtplib . SMTP ( "smtp.gmail.com" , 587 ) smtpserver . ehlo ( ) smtpserver . starttls ( ) smtpserver . ehlo gmail_account = 'kortemmelab@gmail.com' if pw_filepath : smtpserver . login ( gmail_account , read_file ( pw_filepath ) ) else : smtpserver . login ( gmail_account , read_file ( 'pw' ) ) for recipient in recipients : if htmltext : msg = MIMEText ( htmltext , 'html' ) msg [ 'From' ] = gmail_account msg [ 'To' ] = recipient msg [ 'Subject' ] = subject smtpserver . sendmail ( gmail_account , recipient , msg . as_string ( ) ) else : header = 'To:' + recipient + '\n' + 'From: ' + gmail_account + '\n' + 'Subject:' + subject + '\n' msg = header + '\n ' + plaintext + '\n\n' smtpserver . sendmail ( gmail_account , recipient , msg ) smtpserver . close ( ) | For this function to work the password for the gmail user must be colocated with this file or passed in . |
12,972 | def show_one ( request , post_process_fun , object_class , id , template = 'common_json.html' ) : obj = get_object_or_404 ( object_class , pk = id ) json = post_process_fun ( request , obj ) return render_json ( request , json , template = template , help_text = show_one . __doc__ ) | Return object of the given type with the specified identifier . |
12,973 | def show_more ( request , post_process_fun , get_fun , object_class , should_cache = True , template = 'common_json.html' , to_json_kwargs = None ) : if not should_cache and 'json_orderby' in request . GET : return render_json ( request , { 'error' : "Can't order the result according to the JSON field, because the caching for this type of object is turned off. See the documentation." } , template = 'questions_json.html' , help_text = show_more . __doc__ , status = 501 ) if not should_cache and 'all' in request . GET : return render_json ( request , { 'error' : "Can't get all objects, because the caching for this type of object is turned off. See the documentation." } , template = 'questions_json.html' , help_text = show_more . __doc__ , status = 501 ) if to_json_kwargs is None : to_json_kwargs = { } time_start = time_lib ( ) limit = min ( int ( request . GET . get ( 'limit' , 10 ) ) , 100 ) page = int ( request . GET . get ( 'page' , 0 ) ) try : objs = get_fun ( request , object_class ) if 'db_orderby' in request . GET : objs = objs . order_by ( ( '-' if 'desc' in request . GET else '' ) + request . GET [ 'db_orderby' ] . strip ( '/' ) ) if 'all' not in request . GET and 'json_orderby' not in request . GET : objs = objs [ page * limit : ( page + 1 ) * limit ] cache_key = 'proso_common_sql_json_%s' % hashlib . sha1 ( ( str ( objs . query ) + str ( to_json_kwargs ) ) . encode ( ) ) . hexdigest ( ) cached = cache . get ( cache_key ) if should_cache and cached : list_objs = json_lib . loads ( cached ) else : list_objs = [ x . to_json ( ** to_json_kwargs ) for x in list ( objs ) ] if should_cache : cache . set ( cache_key , json_lib . dumps ( list_objs ) , 60 * 60 * 24 * 30 ) LOGGER . debug ( 'loading objects in show_more view took %s seconds' , ( time_lib ( ) - time_start ) ) json = post_process_fun ( request , list_objs ) if 'json_orderby' in request . GET : time_before_json_sort = time_lib ( ) json . sort ( key = lambda x : ( - 1 if 'desc' in request . GET else 1 ) * x [ request . GET [ 'json_orderby' ] ] ) if 'all' not in request . GET : json = json [ page * limit : ( page + 1 ) * limit ] LOGGER . debug ( 'sorting objects according to JSON field took %s seconds' , ( time_lib ( ) - time_before_json_sort ) ) return render_json ( request , json , template = template , help_text = show_more . __doc__ ) except EmptyResultSet : return render_json ( request , [ ] , template = template , help_text = show_more . __doc__ ) | Return list of objects of the given type . |
12,974 | def log ( request ) : if request . method == "POST" : log_dict = json_body ( request . body . decode ( "utf-8" ) ) if 'message' not in log_dict : return HttpResponseBadRequest ( 'There is no message to log!' ) levels = { 'debug' : JAVASCRIPT_LOGGER . debug , 'info' : JAVASCRIPT_LOGGER . info , 'warn' : JAVASCRIPT_LOGGER . warn , 'error' : JAVASCRIPT_LOGGER . error , } log_fun = JAVASCRIPT_LOGGER . info if 'level' in log_dict : log_fun = levels [ log_dict [ 'level' ] ] log_fun ( log_dict [ 'message' ] , extra = { 'request' : request , 'user' : request . user . id if request . user . is_authenticated ( ) else None , 'client_data' : json_lib . dumps ( log_dict . get ( 'data' , { } ) ) , } ) return HttpResponse ( 'ok' , status = 201 ) else : return render_json ( request , { } , template = 'common_log_service.html' , help_text = log . __doc__ ) | Log an event from the client to the server . |
12,975 | def custom_config ( request ) : if request . method == 'POST' : config_dict = json_body ( request . body . decode ( 'utf-8' ) ) CustomConfig . objects . try_create ( config_dict [ 'app_name' ] , config_dict [ 'key' ] , config_dict [ 'value' ] , request . user . id , config_dict . get ( 'condition_key' ) if config_dict . get ( 'condition_key' ) else None , urllib . parse . unquote ( config_dict . get ( 'condition_value' ) ) if config_dict . get ( 'condition_value' ) else None ) return config ( request ) else : return render_json ( request , { } , template = 'common_custom_config.html' , help_text = custom_config . __doc__ ) | Save user - specific configuration property . |
12,976 | def languages ( request ) : return render_json ( request , settings . LANGUAGE_DOMAINS if hasattr ( settings , 'LANGUAGE_DOMAINS' ) else { "error" : "Languages are not set. (Set LANGUAGE_DOMAINS in settings.py)" } , template = 'common_json.html' , help_text = languages . __doc__ ) | Returns languages that are available in the system . |
12,977 | def channel_to_id ( slack , channel ) : channels = slack . api_call ( 'channels.list' ) . get ( 'channels' ) or [ ] groups = slack . api_call ( 'groups.list' ) . get ( 'groups' ) or [ ] if not channels and not groups : raise RuntimeError ( "Couldn't get channels and groups." ) ids = [ c [ 'id' ] for c in channels + groups if c [ 'name' ] == channel ] if not ids : raise ValueError ( f"Couldn't find #{channel}" ) return ids [ 0 ] | Surely there s a better way to do this ... |
12,978 | def send_message ( slack ) : channel = input ( 'Which channel would you like to message? ' ) message = input ( 'What should the message be? ' ) channel_id = channel_to_id ( slack , channel ) print ( f"Sending message to #{channel} (id: {channel_id})!" ) slack . rtm_send_message ( channel_id , message ) | Prompt for and send a message to a channel . |
12,979 | def parse_device ( lines ) : name , status_line , device = parse_device_header ( lines . pop ( 0 ) ) if not status_line : status_line = lines . pop ( 0 ) status = parse_device_status ( status_line , device [ "personality" ] ) bitmap = None resync = None for line in lines : if line . startswith ( " bitmap:" ) : bitmap = parse_device_bitmap ( line ) elif line . startswith ( " [" ) : resync = parse_device_resync_progress ( line ) elif line . startswith ( " \tresync=" ) : resync = parse_device_resync_standby ( line ) else : raise NotImplementedError ( "unknown device line: {0}" . format ( line ) ) device . update ( { "status" : status , "bitmap" : bitmap , "resync" : resync , } ) return ( name , device ) | Parse all the lines of a device block . |
12,980 | def match_etag ( etag , header , weak = False ) : if etag is None : return False m = etag_re . match ( etag ) if not m : raise ValueError ( "Not a well-formed ETag: '%s'" % etag ) ( is_weak , etag ) = m . groups ( ) parsed_header = parse_etag_header ( header ) if parsed_header == '*' : return True if is_weak and not weak : return False if weak : return etag in [ t [ 1 ] for t in parsed_header ] else : return etag in [ t [ 1 ] for t in parsed_header if not t [ 0 ] ] | Try to match an ETag against a header value . |
12,981 | def datetime_to_httpdate ( dt ) : if isinstance ( dt , ( int , float ) ) : return format_date_time ( dt ) elif isinstance ( dt , datetime ) : return format_date_time ( datetime_to_timestamp ( dt ) ) else : raise TypeError ( "expected datetime.datetime or timestamp (int/float)," " got '%s'" % dt ) | Convert datetime . datetime or Unix timestamp to HTTP date . |
12,982 | def timedelta_to_httpdate ( td ) : if isinstance ( td , ( int , float ) ) : return format_date_time ( time . time ( ) + td ) elif isinstance ( td , timedelta ) : return format_date_time ( time . time ( ) + total_seconds ( td ) ) else : raise TypeError ( "expected datetime.timedelta or number of seconds" "(int/float), got '%s'" % td ) | Convert datetime . timedelta or number of seconds to HTTP date . |
12,983 | def cache_control ( max_age = None , private = False , public = False , s_maxage = None , must_revalidate = False , proxy_revalidate = False , no_cache = False , no_store = False ) : if all ( [ private , public ] ) : raise ValueError ( "'private' and 'public' are mutually exclusive" ) if isinstance ( max_age , timedelta ) : max_age = int ( total_seconds ( max_age ) ) if isinstance ( s_maxage , timedelta ) : s_maxage = int ( total_seconds ( s_maxage ) ) directives = [ ] if public : directives . append ( 'public' ) if private : directives . append ( 'private' ) if max_age is not None : directives . append ( 'max-age=%d' % max_age ) if s_maxage is not None : directives . append ( 's-maxage=%d' % s_maxage ) if no_cache : directives . append ( 'no-cache' ) if no_store : directives . append ( 'no-store' ) if must_revalidate : directives . append ( 'must-revalidate' ) if proxy_revalidate : directives . append ( 'proxy-revalidate' ) return ', ' . join ( directives ) | Generate the value for a Cache - Control header . |
12,984 | def get_incidents ( self ) -> Union [ list , bool ] : brotts_entries_left = True incidents_today = [ ] url = self . url while brotts_entries_left : requests_response = requests . get ( url , params = self . parameters ) rate_limited = requests_response . headers . get ( 'x-ratelimit-reset' ) if rate_limited : print ( "You have been rate limited until " + time . strftime ( '%Y-%m-%d %H:%M:%S%z' , time . localtime ( rate_limited ) ) ) return False requests_response = requests_response . json ( ) incidents = requests_response . get ( "data" ) if not incidents : break datetime_today = datetime . date . today ( ) datetime_today_as_time = time . strptime ( str ( datetime_today ) , "%Y-%m-%d" ) today_date_ymd = self . _get_datetime_as_ymd ( datetime_today_as_time ) for incident in incidents : incident_pubdate = incident [ "pubdate_iso8601" ] incident_date = time . strptime ( incident_pubdate , "%Y-%m-%dT%H:%M:%S%z" ) incident_date_ymd = self . _get_datetime_as_ymd ( incident_date ) if today_date_ymd == incident_date_ymd : incidents_today . append ( incident ) else : brotts_entries_left = False break if requests_response . get ( "links" ) : url = requests_response [ "links" ] [ "next_page_url" ] else : break return incidents_today | Get today s incidents . |
12,985 | def from_template ( args ) : project_name = args . name template = args . template with tarfile . open ( template ) as tar : prefix = os . path . commonprefix ( tar . getnames ( ) ) check_template ( tar . getnames ( ) , prefix ) tar . extractall ( project_name , members = get_members ( tar , prefix ) ) | Create a new oct project from existing template |
12,986 | def from_oct ( args ) : project_name = args . name env = Environment ( loader = PackageLoader ( 'oct.utilities' , 'templates' ) ) config_content = env . get_template ( 'configuration/config.json' ) . render ( script_name = 'v_user.py' ) script_content = env . get_template ( 'scripts/v_user.j2' ) . render ( ) try : os . makedirs ( project_name ) os . makedirs ( os . path . join ( project_name , 'test_scripts' ) ) os . makedirs ( os . path . join ( project_name , 'templates' ) ) os . makedirs ( os . path . join ( project_name , 'templates' , 'img' ) ) shutil . copytree ( os . path . join ( BASE_DIR , 'templates' , 'css' ) , os . path . join ( project_name , 'templates' , 'css' ) ) shutil . copytree ( os . path . join ( BASE_DIR , 'templates' , 'javascript' ) , os . path . join ( project_name , 'templates' , 'scripts' ) ) shutil . copytree ( os . path . join ( BASE_DIR , 'templates' , 'fonts' ) , os . path . join ( project_name , 'templates' , 'fonts' ) ) shutil . copy ( os . path . join ( BASE_DIR , 'templates' , 'html' , 'report.html' ) , os . path . join ( project_name , 'templates' ) ) except OSError : print ( 'ERROR: can not create directory for %r' % project_name , file = sys . stderr ) raise with open ( os . path . join ( project_name , 'config.json' ) , 'w' ) as f : f . write ( config_content ) with open ( os . path . join ( project_name , 'test_scripts' , 'v_user.py' ) , 'w' ) as f : f . write ( script_content ) | Create a new oct project |
12,987 | def as_data_frame ( self ) -> pandas . DataFrame : header_gene = { } header_multiplex = { } headr_transitions = { } for gene in self . influence_graph . genes : header_gene [ gene ] = repr ( gene ) header_multiplex [ gene ] = f"active multiplex on {gene!r}" headr_transitions [ gene ] = f"K_{gene!r}" columns = defaultdict ( list ) for state in self . table . keys ( ) : for gene in self . influence_graph . genes : columns [ header_gene [ gene ] ] . append ( state [ gene ] ) columns [ header_multiplex [ gene ] ] . append ( self . _repr_multiplexes ( gene , state ) ) columns [ headr_transitions [ gene ] ] . append ( self . _repr_transition ( gene , state ) ) header = list ( header_gene . values ( ) ) + list ( header_multiplex . values ( ) ) + list ( headr_transitions . values ( ) ) return pandas . DataFrame ( columns , columns = header ) | Create a panda DataFrame representation of the resource table . |
12,988 | def create ( self , r , r_ , R = 200 ) : x , y = give_dots ( R , r , r_ , spins = 20 ) xy = np . array ( [ x , y ] ) . T xy = np . array ( np . around ( xy ) , dtype = np . int64 ) xy = xy [ ( xy [ : , 0 ] >= - 250 ) & ( xy [ : , 1 ] >= - 250 ) & ( xy [ : , 0 ] < 250 ) & ( xy [ : , 1 ] < 250 ) ] xy = xy + 250 img = np . ones ( [ 500 , 500 ] , dtype = np . uint8 ) img [ : ] = 255 img [ xy [ : , 0 ] , xy [ : , 1 ] ] = 0 img = misc . imresize ( img , [ self . img_size , self . img_size ] ) fimg = img / 255.0 return fimg | Create new spirograph image with given arguments . Returned image is scaled to agent s preferred image size . |
12,989 | def hedonic_value ( self , novelty ) : lmax = gaus_pdf ( self . desired_novelty , self . desired_novelty , 4 ) pdf = gaus_pdf ( novelty , self . desired_novelty , 4 ) return pdf / lmax | Given the agent s desired novelty how good the novelty value is . |
12,990 | def evaluate ( self , artifact ) : if self . desired_novelty > 0 : return self . hedonic_value ( self . novelty ( artifact . obj ) ) return self . novelty ( artifact . obj ) / self . img_size , None | Evaluate the artifact with respect to the agents short term memory . |
12,991 | def learn ( self , spiro , iterations = 1 ) : for i in range ( iterations ) : self . stmem . train_cycle ( spiro . obj . flatten ( ) ) | Train short term memory with given spirograph . |
12,992 | def plot_places ( self ) : from matplotlib import pyplot as plt fig , ax = plt . subplots ( ) x = [ ] y = [ ] if len ( self . arg_history ) > 1 : xs = [ ] ys = [ ] for p in self . arg_history : xs . append ( p [ 0 ] ) ys . append ( p [ 1 ] ) ax . plot ( xs , ys , color = ( 0.0 , 0.0 , 1.0 , 0.1 ) ) for a in self . A : if a . self_criticism == 'pass' : args = a . framings [ a . creator ] [ 'args' ] x . append ( args [ 0 ] ) y . append ( args [ 1 ] ) sc = ax . scatter ( x , y , marker = "x" , color = 'red' ) ax . set_xlim ( [ - 200 , 200 ] ) ax . set_ylim ( [ - 200 , 200 ] ) agent_vars = "{}_{}_{}{}_last={}_stmem=list{}_veto={}_sc={}_jump={}_sw={}_mr={}_maxN" . format ( self . name , self . age , self . env_learning_method , self . env_learning_amount , self . env_learn_on_add , self . stmem . length , self . _novelty_threshold , self . _own_threshold , self . jump , self . search_width , self . move_radius ) if self . logger is not None : imname = os . path . join ( self . logger . folder , '{}.png' . format ( agent_vars ) ) plt . savefig ( imname ) plt . close ( ) fname = os . path . join ( self . logger . folder , '{}.txt' . format ( agent_vars ) ) with open ( fname , "w" ) as f : f . write ( " " . join ( [ str ( e ) for e in xs ] ) ) f . write ( "\n" ) f . write ( " " . join ( [ str ( e ) for e in ys ] ) ) f . write ( "\n" ) f . write ( " " . join ( [ str ( e ) for e in x ] ) ) f . write ( "\n" ) f . write ( " " . join ( [ str ( e ) for e in y ] ) ) f . write ( "\n" ) else : plt . show ( ) | Plot places where the agent has been and generated a spirograph . |
12,993 | def destroy ( self , folder = None ) : ameans = [ ( 0 , 0 , 0 ) for _ in range ( 3 ) ] ret = [ self . save_info ( folder , ameans ) ] aiomas . run ( until = self . stop_slaves ( folder ) ) self . _pool . close ( ) self . _pool . terminate ( ) self . _pool . join ( ) self . _env . shutdown ( ) return ret | Destroy the environment and the subprocesses . |
12,994 | def add ( self , r ) : id = r . get_residue_id ( ) if self . order : last_id = self . order [ - 1 ] if id in self . order : raise colortext . Exception ( 'Warning: using code to "allow for multiresidue noncanonicals" - check this case manually.' ) id = '%s.%d' % ( str ( id ) , self . special_insertion_count ) self . special_insertion_count += 1 assert ( r . Chain == self . sequence [ last_id ] . Chain ) assert ( r . residue_type == self . sequence [ last_id ] . residue_type ) self . order . append ( id ) self . sequence [ id ] = r | Takes an id and a Residue r and adds them to the Sequence . |
12,995 | def set_type ( self , sequence_type ) : if not ( self . sequence_type ) : for id , r in self . sequence . iteritems ( ) : assert ( r . residue_type == None ) r . residue_type = sequence_type self . sequence_type = sequence_type | Set the type of a Sequence if it has not been set . |
12,996 | def from_sequence ( chain , list_of_residues , sequence_type = None ) : s = Sequence ( sequence_type ) count = 1 for ResidueAA in list_of_residues : s . add ( Residue ( chain , count , ResidueAA , sequence_type ) ) count += 1 return s | Takes in a chain identifier and protein sequence and returns a Sequence object of Residues indexed from 1 . |
12,997 | def substitution_scores_match ( self , other ) : overlap = set ( self . substitution_scores . keys ( ) ) . intersection ( set ( other . substitution_scores . keys ( ) ) ) for k in overlap : if not ( self . substitution_scores [ k ] == None or other . substitution_scores [ k ] == None ) : if self . substitution_scores [ k ] != other . substitution_scores [ k ] : return False return True | Check to make sure that the substitution scores agree . If one map has a null score and the other has a non - null score we trust the other s score and vice versa . |
12,998 | def merge ( self , other ) : our_element_frequencies = self . items their_element_frequencies = other . items for element_name , freq in sorted ( our_element_frequencies . iteritems ( ) ) : our_element_frequencies [ element_name ] = max ( our_element_frequencies . get ( element_name , 0 ) , their_element_frequencies . get ( element_name , 0 ) ) for element_name , freq in sorted ( their_element_frequencies . iteritems ( ) ) : if element_name not in our_element_frequencies : our_element_frequencies [ element_name ] = their_element_frequencies [ element_name ] | Merge two element counters . For all elements we take the max count from both counters . |
12,999 | def dump ( self , obj , fp ) : if not validate ( obj , self . _raw_schema ) : raise AvroTypeException ( self . _avro_schema , obj ) fastavro_write_data ( fp , obj , self . _raw_schema ) | Serializes obj as an avro - format byte stream to the provided fp file - like object stream . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.