idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
29,100 | def find_disulfide_bridges ( self , threshold = 3.0 ) : if self . structure : parsed = self . structure else : parsed = self . parse_structure ( ) if not parsed : log . error ( '{}: unable to open structure to find S-S bridges' . format ( self . id ) ) return disulfide_bridges = ssbio . protein . structure . properties... | Run Biopython s search_ss_bonds to find potential disulfide bridges for each chain and store in ChainProp . |
29,101 | def get_polypeptide_within ( self , chain_id , resnum , angstroms , only_protein = True , use_ca = False , custom_coord = None , return_resnums = False ) : if self . structure : parsed = self . structure else : parsed = self . parse_structure ( ) residue_list = ssbio . protein . structure . properties . residues . with... | Get a Polypeptide object of the amino acids within X angstroms of the specified chain + residue number . |
29,102 | def get_seqprop_within ( self , chain_id , resnum , angstroms , only_protein = True , use_ca = False , custom_coord = None , return_resnums = False ) : polypep , resnums = self . get_polypeptide_within ( chain_id = chain_id , resnum = resnum , angstroms = angstroms , use_ca = use_ca , only_protein = only_protein , cust... | Get a SeqProp object of the amino acids within X angstroms of the specified chain + residue number . |
29,103 | def get_dssp_annotations ( self , outdir , force_rerun = False ) : if self . structure : parsed = self . structure else : parsed = self . parse_structure ( ) if not parsed : log . error ( '{}: unable to open structure to run DSSP' . format ( self . id ) ) return log . debug ( '{}: running DSSP' . format ( self . id ) )... | Run DSSP on this structure and store the DSSP annotations in the corresponding ChainProp SeqRecords |
29,104 | def get_freesasa_annotations ( self , outdir , include_hetatms = False , force_rerun = False ) : if self . file_type != 'pdb' : log . error ( '{}: unable to run freesasa with "{}" file type. Please change file type to "pdb"' . format ( self . id , self . file_type ) ) return if self . structure : parsed = self . struct... | Run freesasa on this structure and store the calculated properties in the corresponding ChainProps |
29,105 | def view_structure ( self , only_chains = None , opacity = 1.0 , recolor = False , gui = False ) : if ssbio . utils . is_ipynb ( ) : import nglview as nv else : raise EnvironmentError ( 'Unable to display structure - not running in a Jupyter notebook environment' ) if not self . structure_file : raise ValueError ( "Str... | Use NGLviewer to display a structure in a Jupyter notebook |
29,106 | def label_TM_tmhmm_residue_numbers_and_leaflets ( tmhmm_seq ) : TM_number_dict = { } T_index = [ ] T_residue = [ ] residue_count = 1 for residue_label in tmhmm_seq : if residue_label == 'T' : T_residue . append ( residue_count ) residue_count = residue_count + 1 TM_number_dict . update ( { 'T_residue' : T_residue } ) T... | Determine the residue numbers of the TM - helix residues that cross the membrane and label them by leaflet . |
29,107 | def biopython_protein_scale ( inseq , scale , custom_scale_dict = None , window = 7 ) : if scale == 'kd_hydrophobicity' : scale_dict = kd_hydrophobicity_one elif scale == 'bulkiness' : scale_dict = bulkiness_one elif scale == 'custom' : scale_dict = custom_scale_dict else : raise ValueError ( 'Scale not available' ) in... | Use Biopython to calculate properties using a sliding window over a sequence given a specific scale to use . |
29,108 | def biopython_protein_analysis ( inseq ) : inseq = ssbio . protein . sequence . utils . cast_to_str ( inseq ) analysed_seq = ProteinAnalysis ( inseq ) info_dict = { } info_dict [ 'amino_acids_content-biop' ] = analysed_seq . count_amino_acids ( ) info_dict [ 'amino_acids_percent-biop' ] = analysed_seq . get_amino_acids... | Utiize Biopython s ProteinAnalysis module to return general sequence properties of an amino acid string . |
29,109 | def emboss_pepstats_on_fasta ( infile , outfile = '' , outdir = '' , outext = '.pepstats' , force_rerun = False ) : outfile = ssbio . utils . outfile_maker ( inname = infile , outname = outfile , outdir = outdir , outext = outext ) program = 'pepstats' pepstats_args = '-sequence="{}" -outfile="{}"' . format ( infile , ... | Run EMBOSS pepstats on a FASTA file . |
29,110 | def emboss_pepstats_parser ( infile ) : with open ( infile ) as f : lines = f . read ( ) . split ( '\n' ) info_dict = { } for l in lines [ 38 : 47 ] : info = l . split ( '\t' ) cleaninfo = list ( filter ( lambda x : x != '' , info ) ) prop = cleaninfo [ 0 ] num = cleaninfo [ 2 ] percent = float ( cleaninfo [ - 1 ] ) / ... | Get dictionary of pepstats results . |
29,111 | def load_strain ( self , strain_id , strain_genome_file ) : strain_gp = GEMPRO ( gem_name = strain_id , genome_path = strain_genome_file , write_protein_fasta_files = False ) self . strains . append ( strain_gp ) return self . strains . get_by_id ( strain_id ) | Load a strain as a new GEM - PRO by its ID and associated genome file . Stored in the strains attribute . |
29,112 | def download_patric_genomes ( self , ids , force_rerun = False ) : ids = ssbio . utils . force_list ( ids ) counter = 0 log . info ( 'Downloading sequences from PATRIC...' ) for patric_id in tqdm ( ids ) : f = ssbio . databases . patric . download_coding_sequences ( patric_id = patric_id , seqtype = 'protein' , outdir ... | Download genome files from PATRIC given a list of PATRIC genome IDs and load them as strains . |
29,113 | def _pare_down_model ( self , strain_gempro , genes_to_remove ) : strain_genes = [ x . id for x in strain_gempro . genes ] genes_to_remove . extend ( self . missing_in_orthology_matrix ) genes_to_remove = list ( set ( genes_to_remove ) . intersection ( set ( strain_genes ) ) ) if len ( genes_to_remove ) == 0 : log . in... | Mark genes as non - functional in a GEM - PRO . If there is a COBRApy model associated with it the COBRApy method delete_model_genes is utilized to delete genes . |
29,114 | def _load_strain_sequences ( self , strain_gempro ) : if self . _orthology_matrix_has_sequences : strain_sequences = self . df_orthology_matrix [ strain_gempro . id ] . to_dict ( ) else : log . debug ( '{}: loading strain genome CDS file' . format ( strain_gempro . genome_path ) ) strain_sequences = SeqIO . index ( str... | Load strain sequences from the orthology matrix into the base model for comparisons and into the strain - specific model itself . |
29,115 | def build_strain_specific_models ( self , save_models = False ) : if len ( self . df_orthology_matrix ) == 0 : raise RuntimeError ( 'Empty orthology matrix' ) for strain_gempro in tqdm ( self . strains ) : log . debug ( '{}: building strain specific model' . format ( strain_gempro . id ) ) logging . disable ( logging .... | Using the orthologous genes matrix create and modify the strain specific models based on if orthologous genes exist . |
29,116 | def align_orthologous_genes_pairwise ( self , gapopen = 10 , gapextend = 0.5 ) : for ref_gene in tqdm ( self . reference_gempro . genes ) : if len ( ref_gene . protein . sequences ) > 1 : alignment_dir = op . join ( self . sequences_by_gene_dir , ref_gene . id ) if not op . exists ( alignment_dir ) : os . mkdir ( align... | For each gene in the base strain run a pairwise alignment for all orthologous gene sequences to it . |
29,117 | def get_atlas_per_gene_mutation_df ( self , gene_id ) : g = self . reference_gempro . genes . get_by_id ( gene_id ) single , fingerprint = g . protein . sequence_mutation_summary ( alignment_type = 'seqalign' ) structure_type_suffix = 'NA' appender = [ ] for k , strains in single . items ( ) : to_append = { } orig_res ... | Create a single data frame which summarizes a gene and its mutations . |
29,118 | def add_residues_highlight_to_nglview ( view , structure_resnums , chain , res_color = 'red' ) : chain = ssbio . utils . force_list ( chain ) if isinstance ( structure_resnums , list ) : structure_resnums = list ( set ( structure_resnums ) ) elif isinstance ( structure_resnums , int ) : structure_resnums = ssbio . util... | Add a residue number or numbers to an NGLWidget view object . |
29,119 | def download_kegg_gene_metadata ( gene_id , outdir = None , force_rerun = False ) : if not outdir : outdir = '' outfile = op . join ( outdir , '{}.kegg' . format ( custom_slugify ( gene_id ) ) ) if ssbio . utils . force_rerun ( flag = force_rerun , outfile = outfile ) : raw_text = bs_kegg . get ( "{}" . format ( gene_i... | Download the KEGG flatfile for a KEGG ID and return the path . |
29,120 | def parse_kegg_gene_metadata ( infile ) : metadata = defaultdict ( str ) with open ( infile ) as mf : kegg_parsed = bs_kegg . parse ( mf . read ( ) ) if 'DBLINKS' in kegg_parsed . keys ( ) : if 'UniProt' in kegg_parsed [ 'DBLINKS' ] : unis = str ( kegg_parsed [ 'DBLINKS' ] [ 'UniProt' ] ) . split ( ' ' ) if isinstance ... | Parse the KEGG flatfile and return a dictionary of metadata . |
29,121 | def map_kegg_all_genes ( organism_code , target_db ) : mapping = bs_kegg . conv ( target_db , organism_code ) new_mapping = { } for k , v in mapping . items ( ) : new_mapping [ k . replace ( organism_code + ':' , '' ) ] = str ( v . split ( ':' ) [ 1 ] ) return new_mapping | Map all of an organism s gene IDs to the target database . |
29,122 | def prep_folder ( self , seq ) : itasser_dir = op . join ( self . root_dir , self . id ) if not op . exists ( itasser_dir ) : os . makedirs ( itasser_dir ) tmp = { self . id : seq } fasta . write_fasta_file_from_dict ( indict = tmp , outname = 'seq' , outext = '.fasta' , outdir = itasser_dir ) return itasser_dir | Take in a sequence string and prepares the folder for the I - TASSER run . |
29,123 | def run_makeblastdb ( infile , dbtype , outdir = '' ) : og_dir , name , ext = utils . split_folder_and_path ( infile ) if not outdir : outdir = og_dir outfile_basename = op . join ( outdir , name ) if dbtype == 'nucl' : outext = [ '.nhr' , '.nin' , '.nsq' ] elif dbtype == 'prot' : outext = [ '.phr' , '.pin' , '.psq' ] ... | Make the BLAST database for a genome file . |
29,124 | def run_bidirectional_blast ( reference , other_genome , dbtype , outdir = '' ) : if dbtype == 'nucl' : command = 'blastn' elif dbtype == 'prot' : command = 'blastp' else : raise ValueError ( 'dbtype must be "nucl" or "prot"' ) r_folder , r_name , r_ext = utils . split_folder_and_path ( reference ) g_folder , g_name , ... | BLAST a genome against another and vice versa . |
29,125 | def print_run_bidirectional_blast ( reference , other_genome , dbtype , outdir ) : if dbtype == 'nucl' : command = 'blastn' elif dbtype == 'prot' : command = 'blastp' else : raise ValueError ( 'dbtype must be "nucl" or "prot"' ) r_folder , r_name , r_ext = utils . split_folder_and_path ( reference ) g_folder , g_name ,... | Write torque submission files for running bidirectional blast on a server and print execution command . |
29,126 | def write_pdb ( self , custom_name = '' , out_suffix = '' , out_dir = None , custom_selection = None , force_rerun = False ) : if not custom_selection : custom_selection = ModelSelection ( [ 0 ] ) if not out_dir or not custom_name : if not out_suffix : out_suffix = '_new' outfile = ssbio . utils . outfile_maker ( innam... | Write a new PDB file for the Structure s FIRST MODEL . |
29,127 | def _handle_builder_exception ( self , message , residue ) : message = "%s. Error when parsing residue %s:%s" % ( message , residue [ 'number' ] , residue [ 'name' ] ) raise PDBConstructionException ( message ) | Makes a PDB Construction Error a bit more verbose and informative |
29,128 | def _parse ( self ) : atom_counter = 0 structure_build = self . structure_builder residues = self . _extract_residues ( ) cur_model = None cur_chain = None structure_build . init_seg ( ' ' ) for r in residues : if cur_model != r [ 'model' ] : cur_model = r [ 'model' ] try : structure_build . init_model ( cur_model ) ex... | Parse atomic data of the XML file . |
29,129 | def _extract_residues ( self ) : r_list = self . handle . getElementsByTagName ( "response" ) r_data = { } for r in r_list : data = self . _parse_residue ( r ) res_id = ( data [ 'model' ] , data [ 'chain' ] , data [ 'number' ] ) if not r_data . has_key ( res_id ) : r_data [ res_id ] = data else : r_data [ res_id ] [ 'a... | WHAT IF puts terminal atoms in new residues at the end for some reason .. |
29,130 | def calculate_residue_counts_perstrain ( protein_pickle_path , outdir , pdbflex_keys_file , wt_pid_cutoff = None , force_rerun = False ) : from collections import defaultdict from ssbio . protein . sequence . seqprop import SeqProp from ssbio . protein . sequence . properties . residues import _aa_property_dict_one log... | Writes out a feather file for a PROTEIN counting amino acid occurences for ALL STRAINS along with SUBSEQUENCES |
29,131 | def filter_genes_and_strains ( self , remove_genes_not_in_reference_model = True , remove_strains_with_no_orthology = True , remove_strains_with_no_differences = False , custom_keep_strains = None , custom_keep_genes = None ) : if len ( self . df_orthology_matrix ) == 0 : raise RuntimeError ( 'Empty orthology matrix, p... | Filters the analysis by keeping a subset of strains or genes based on certain criteria . |
29,132 | def _write_strain_functional_genes ( self , strain_id , ref_functional_genes , orth_matrix , force_rerun = False ) : func_genes_path = op . join ( self . model_dir , '{}_funcgenes.json' . format ( strain_id ) ) if ssbio . utils . force_rerun ( flag = force_rerun , outfile = func_genes_path ) : gene_to_func = { k : True... | Create strain functional genes json file |
29,133 | def write_strain_functional_genes ( self , force_rerun = False ) : if len ( self . df_orthology_matrix ) == 0 : raise RuntimeError ( 'Empty orthology matrix, please calculate first!' ) ref_functional_genes = [ g . id for g in self . reference_gempro . functional_genes ] log . info ( 'Building strain specific models...'... | Wrapper function for _write_strain_functional_genes |
29,134 | def _build_strain_specific_model ( self , strain_id , ref_functional_genes , orth_matrix , force_rerun = False ) : gp_noseqs_path = op . join ( self . model_dir , '{}_gp.pckl' . format ( strain_id ) ) if ssbio . utils . force_rerun ( flag = force_rerun , outfile = gp_noseqs_path ) : logging . disable ( logging . WARNIN... | Create strain GEMPRO set functional genes |
29,135 | def build_strain_specific_models ( self , joblib = False , cores = 1 , force_rerun = False ) : if len ( self . df_orthology_matrix ) == 0 : raise RuntimeError ( 'Empty orthology matrix, please calculate first!' ) ref_functional_genes = [ g . id for g in self . reference_gempro . functional_genes ] log . info ( 'Buildin... | Wrapper function for _build_strain_specific_model |
29,136 | def _load_sequences_to_strain ( self , strain_id , force_rerun = False ) : gp_seqs_path = op . join ( self . model_dir , '{}_gp_withseqs.pckl' . format ( strain_id ) ) if ssbio . utils . force_rerun ( flag = force_rerun , outfile = gp_seqs_path ) : gp_noseqs = ssbio . io . load_pickle ( self . strain_infodict [ strain_... | Load strain GEMPRO with functional genes defined load sequences to it save as new GEMPRO |
29,137 | def load_sequences_to_strains ( self , joblib = False , cores = 1 , force_rerun = False ) : log . info ( 'Loading sequences to strain GEM-PROs...' ) if joblib : result = DictList ( Parallel ( n_jobs = cores ) ( delayed ( self . _load_sequences_to_strain ) ( s , force_rerun ) for s in self . strain_ids ) ) else : result... | Wrapper function for _load_sequences_to_strain |
29,138 | def _load_sequences_to_reference_gene ( self , g_id , force_rerun = False ) : protein_seqs_pickle_path = op . join ( self . sequences_by_gene_dir , '{}_protein_withseqs.pckl' . format ( g_id ) ) if ssbio . utils . force_rerun ( flag = force_rerun , outfile = protein_seqs_pickle_path ) : protein_pickle_path = self . gen... | Load orthologous strain sequences to reference Protein object save as new pickle |
29,139 | def load_sequences_to_reference ( self , sc = None , force_rerun = False ) : log . info ( 'Loading sequences to reference GEM-PRO...' ) from random import shuffle g_ids = [ g . id for g in self . reference_gempro . functional_genes ] shuffle ( g_ids ) def _load_sequences_to_reference_gene_sc ( g_id , outdir = self . se... | Wrapper for _load_sequences_to_reference_gene |
29,140 | def store_disorder ( self , sc = None , force_rerun = False ) : log . info ( 'Loading sequences to reference GEM-PRO...' ) from random import shuffle g_ids = [ g . id for g in self . reference_gempro . functional_genes ] shuffle ( g_ids ) def _store_disorder_sc ( g_id , outdir = self . sequences_by_gene_dir , g_to_pick... | Wrapper for _store_disorder |
29,141 | def _align_orthologous_gene_pairwise ( self , g_id , gapopen = 10 , gapextend = 0.5 , engine = 'needle' , parse = True , force_rerun = False ) : protein_seqs_aln_pickle_path = op . join ( self . sequences_by_gene_dir , '{}_protein_withseqs_dis_aln.pckl' . format ( g_id ) ) if ssbio . utils . force_rerun ( flag = force_... | Align orthologous strain sequences to representative Protein sequence save as new pickle |
29,142 | def align_orthologous_genes_pairwise ( self , sc = None , joblib = False , cores = 1 , gapopen = 10 , gapextend = 0.5 , engine = 'needle' , parse = True , force_rerun = False ) : log . info ( 'Aligning sequences to reference GEM-PRO...' ) from random import shuffle g_ids = [ g . id for g in self . reference_gempro . fu... | Wrapper for _align_orthologous_gene_pairwise |
29,143 | def cast_to_str ( obj ) : if isinstance ( obj , str ) : return obj if isinstance ( obj , Seq ) : return str ( obj ) if isinstance ( obj , SeqRecord ) : return str ( obj . seq ) else : raise ValueError ( 'Must provide a string, Seq, or SeqRecord object.' ) | Return a string representation of a Seq or SeqRecord . |
29,144 | def cast_to_seq ( obj , alphabet = IUPAC . extended_protein ) : if isinstance ( obj , Seq ) : return obj if isinstance ( obj , SeqRecord ) : return obj . seq if isinstance ( obj , str ) : obj = obj . upper ( ) return Seq ( obj , alphabet ) else : raise ValueError ( 'Must provide a string, Seq, or SeqRecord object.' ) | Return a Seq representation of a string or SeqRecord object . |
29,145 | def cast_to_seq_record ( obj , alphabet = IUPAC . extended_protein , id = "<unknown id>" , name = "<unknown name>" , description = "<unknown description>" , dbxrefs = None , features = None , annotations = None , letter_annotations = None ) : if isinstance ( obj , SeqRecord ) : return obj if isinstance ( obj , Seq ) : ... | Return a SeqRecord representation of a string or Seq object . |
29,146 | def write_fasta_file ( seq_records , outname , outdir = None , outext = '.faa' , force_rerun = False ) : if not outdir : outdir = '' outfile = ssbio . utils . outfile_maker ( inname = '' , outname = outname , outdir = outdir , outext = outext ) if ssbio . utils . force_rerun ( flag = force_rerun , outfile = outfile ) :... | Write a FASTA file for a SeqRecord or a list of SeqRecord objects . |
29,147 | def write_fasta_file_from_dict ( indict , outname , outdir = None , outext = '.faa' , force_rerun = False ) : if not outdir : outdir = '' outfile = ssbio . utils . outfile_maker ( inname = '' , outname = outname , outdir = outdir , outext = outext ) if ssbio . utils . force_rerun ( flag = force_rerun , outfile = outfil... | Write a FASTA file for a dictionary of IDs and their sequence strings . |
29,148 | def write_seq_as_temp_fasta ( seq ) : sr = ssbio . protein . sequence . utils . cast_to_seq_record ( seq , id = 'tempfasta' ) return write_fasta_file ( seq_records = sr , outname = 'temp' , outdir = tempfile . gettempdir ( ) , force_rerun = True ) | Write a sequence as a temporary FASTA file |
29,149 | def load_fasta_file ( filename ) : with open ( filename , "r" ) as handle : records = list ( SeqIO . parse ( handle , "fasta" ) ) return records | Load a FASTA file and return the sequences as a list of SeqRecords |
29,150 | def fasta_files_equal ( seq_file1 , seq_file2 ) : seq1 = SeqIO . read ( open ( seq_file1 ) , 'fasta' ) seq2 = SeqIO . read ( open ( seq_file2 ) , 'fasta' ) if str ( seq1 . seq ) == str ( seq2 . seq ) : return True else : return False | Check equality of a FASTA file to another FASTA file |
29,151 | def from_structure ( cls , original , filter_residues ) : P = cls ( original . id ) P . full_id = original . full_id for child in original . child_dict . values ( ) : copycat = deepcopy ( child ) P . add ( copycat ) remove_list = [ ] if filter_residues : for model in P : for chain in model : for residue in chain : if r... | Loads structure as a protein exposing protein - specific methods . |
29,152 | def get_aggregation_propensity ( self , seq , outdir , cutoff_v = 5 , cutoff_n = 5 , run_amylmuts = False ) : seq = ssbio . protein . sequence . utils . cast_to_str ( seq ) results = self . run_amylpred2 ( seq = seq , outdir = outdir , run_amylmuts = run_amylmuts ) agg_index , agg_conf = self . parse_for_consensus_aggr... | Run the AMYLPRED2 web server for a protein sequence and get the consensus result for aggregation propensity . |
29,153 | def run_amylpred2 ( self , seq , outdir , run_amylmuts = False ) : outdir_amylpred = op . join ( outdir , 'AMYLPRED2_results' ) if not op . exists ( outdir_amylpred ) : os . mkdir ( outdir_amylpred ) url = "http://aias.biol.uoa.gr/AMYLPRED2/login.php" cj = CookieJar ( ) opener = build_opener ( HTTPCookieProcessor ( cj ... | Run all methods on the AMYLPRED2 web server for an amino acid sequence and gather results . |
29,154 | def parse_method_results ( self , results_file , met ) : result = str ( open ( results_file ) . read ( ) ) ind_s = str . find ( result , 'HITS' ) ind_e = str . find ( result , '**NOTE' ) tmp = result [ ind_s + 10 : ind_e ] . strip ( " " ) hits_resid = [ ] method = None if ":" in tmp : method = tmp . split ( ":" ) [ 0 ]... | Parse the output of a AMYLPRED2 result file . |
29,155 | def _load_video ( video_filename ) : video_filename = str ( video_filename ) print ( "Loading " + video_filename ) if not os . path . isfile ( video_filename ) : raise Exception ( "File Not Found: %s" % video_filename ) capture = cv2 . VideoCapture ( video_filename ) frame_count = int ( capture . get ( cv2 . CAP_PROP_F... | Load a video into a numpy array |
29,156 | def get_capture_dimensions ( capture ) : width = int ( capture . get ( cv2 . CAP_PROP_FRAME_WIDTH ) ) height = int ( capture . get ( cv2 . CAP_PROP_FRAME_HEIGHT ) ) return width , height | Get the dimensions of a capture |
29,157 | def save_video ( video , fps , save_filename = 'media/output.avi' ) : print ( save_filename ) video = float_to_uint8 ( video ) fourcc = cv2 . VideoWriter_fourcc ( * 'MJPG' ) writer = cv2 . VideoWriter ( save_filename , fourcc , fps , ( video . shape [ 2 ] , video . shape [ 1 ] ) , 1 ) for x in range ( 0 , video . shape... | Save a video to disk |
29,158 | def show_frequencies ( vid_data , fps , bounds = None ) : averages = [ ] if bounds : for x in range ( 1 , vid_data . shape [ 0 ] - 1 ) : averages . append ( vid_data [ x , bounds [ 2 ] : bounds [ 3 ] , bounds [ 0 ] : bounds [ 1 ] , : ] . sum ( ) ) else : for x in range ( 1 , vid_data . shape [ 0 ] - 1 ) : averages . ap... | Graph the average value of the video as well as the frequency strength |
29,159 | def gaussian_video ( video , shrink_multiple ) : vid_data = None for x in range ( 0 , video . shape [ 0 ] ) : frame = video [ x ] gauss_copy = np . ndarray ( shape = frame . shape , dtype = "float" ) gauss_copy [ : ] = frame for i in range ( shrink_multiple ) : gauss_copy = cv2 . pyrDown ( gauss_copy ) if x == 0 : vid_... | Create a gaussian representation of a video |
29,160 | def combine_pyramid_and_save ( g_video , orig_video , enlarge_multiple , fps , save_filename = 'media/output.avi' ) : width , height = get_frame_dimensions ( orig_video [ 0 ] ) fourcc = cv2 . VideoWriter_fourcc ( * 'MJPG' ) print ( "Outputting to %s" % save_filename ) writer = cv2 . VideoWriter ( save_filename , fourcc... | Combine a gaussian video representation with the original and save to file |
29,161 | def price ( self , from_ = None , ** kwargs ) : if from_ : kwargs [ "from" ] = from_ uri = "%s/%s" % ( self . uri , "price" ) response , instance = self . request ( "GET" , uri , params = kwargs ) return instance | Check pricing for a new outbound message . An useful synonym for message command with dummy parameters set to true . |
29,162 | def refresh ( self ) : uri = "%s/%s" % ( self . uri , "refresh" ) response , instance = self . request ( "GET" , uri ) return response . ok | Refresh access token . Only non - expired tokens can be renewed . |
29,163 | def update ( self , ** kwargs ) : response , instance = self . request ( "PUT" , self . uri , data = kwargs ) return response . status == 201 | Update an current User via a PUT request . Returns True if success . |
29,164 | def send_invite ( self , ** kwargs ) : resp , _ = self . request ( "POST" , self . uri , data = kwargs ) return resp . status == 204 | Invite new subaccount . Returns True if success . |
29,165 | def by_phone ( self , phone , ** kwargs ) : chat_messages = ChatMessages ( self . base_uri , self . auth ) return self . get_subresource_instances ( uid = phone , instance = chat_messages , params = kwargs ) | Fetch messages from chat with specified phone number . |
29,166 | def get_credentials ( env = None ) : environ = env or os . environ try : username = environ [ "TEXTMAGIC_USERNAME" ] token = environ [ "TEXTMAGIC_AUTH_TOKEN" ] return username , token except KeyError : return None , None | Gets the TextMagic credentials from current environment |
29,167 | def put_contacts ( self , uid , ** kwargs ) : return self . update_subresource_instance ( uid , body = kwargs , subresource = None , slug = "contacts" ) | Assign contacts to the specified list . |
29,168 | def delete_contacts ( self , uid , ** kwargs ) : uri = "%s/%s/contacts" % ( self . uri , uid ) response , instance = self . request ( "DELETE" , uri , data = kwargs ) return response . status == 204 | Unassign contacts from the specified list . If contacts assign only to the specified list then delete permanently . Returns True if success . |
29,169 | def get_cert_file ( ) : try : current_path = os . path . realpath ( __file__ ) ca_cert_path = os . path . join ( current_path , ".." , ".." , ".." , "conf" , "cacert.pem" ) return os . path . abspath ( ca_cert_path ) except Exception : return None | Get the certificates file for https |
29,170 | def make_tm_request ( method , uri , ** kwargs ) : headers = kwargs . get ( "headers" , { } ) user_agent = "textmagic-python/%s (Python %s)" % ( __version__ , platform . python_version ( ) ) headers [ "User-agent" ] = user_agent headers [ "Accept-Charset" ] = "utf-8" if "Accept-Language" not in headers : headers [ "Acc... | Make a request to TextMagic REST APIv2 . |
29,171 | def update_instance ( self , uid , body ) : uri = "%s/%s" % ( self . uri , uid ) response , instance = self . request ( "PUT" , uri , data = body ) return self . load_instance ( instance ) | Update an Model via a PUT request |
29,172 | def delete_instance ( self , uid ) : uri = "%s/%s" % ( self . uri , uid ) response , instance = self . request ( "DELETE" , uri ) return response . status == 204 | Delete an ObjectModel via a DELETE request |
29,173 | def _get_buffer ( self , index ) : if not 0 <= index < self . count : raise IndexError ( ) size = struct . calcsize ( self . format ) buf = bytearray ( size + 1 ) buf [ 0 ] = self . first_register + size * index return buf | Shared bounds checking and buffer creation . |
29,174 | def _unzip_file ( self , src_path , dest_path , filename ) : self . logger . info ( "unzipping file..." ) unzip_path = os . path . join ( dest_path , filename ) utils . ensure_directory_exists ( unzip_path ) with zipfile . ZipFile ( src_path , "r" ) as z : z . extractall ( unzip_path ) return True | unzips file located at src_path into destination_path |
29,175 | def get_dataset_url ( self , tournament = 1 ) : query = arguments = { 'tournament' : tournament } url = self . raw_query ( query , arguments ) [ 'data' ] [ 'dataset' ] return url | Fetch url of the current dataset . |
29,176 | def raw_query ( self , query , variables = None , authorization = False ) : body = { 'query' : query , 'variables' : variables } headers = { 'Content-type' : 'application/json' , 'Accept' : 'application/json' } if authorization : if self . token : public_id , secret_key = self . token headers [ 'Authorization' ] = 'Tok... | Send a raw request to the Numerai s GraphQL API . |
29,177 | def get_staking_leaderboard ( self , round_num = 0 , tournament = 1 ) : msg = "getting stakes for tournament {} round {}" self . logger . info ( msg . format ( tournament , round_num ) ) query = arguments = { 'number' : round_num , 'tournament' : tournament } result = self . raw_query ( query , arguments ) [ 'data' ] [... | Retrieves the leaderboard of the staking competition for the given round . |
29,178 | def get_nmr_prize_pool ( self , round_num = 0 , tournament = 1 ) : tournaments = self . get_competitions ( tournament ) tournaments . sort ( key = lambda t : t [ 'number' ] ) if round_num == 0 : t = tournaments [ - 1 ] else : tournaments = [ t for t in tournaments if t [ 'number' ] == round_num ] if len ( tournaments )... | Get NMR prize pool for the given round and tournament . |
29,179 | def get_competitions ( self , tournament = 1 ) : self . logger . info ( "getting rounds..." ) query = arguments = { 'tournament' : tournament } result = self . raw_query ( query , arguments ) rounds = result [ 'data' ] [ 'rounds' ] for r in rounds : utils . replace ( r , "openTime" , utils . parse_datetime_string ) uti... | Retrieves information about all competitions |
29,180 | def get_current_round ( self , tournament = 1 ) : query = arguments = { 'tournament' : tournament } data = self . raw_query ( query , arguments ) [ 'data' ] [ 'rounds' ] [ 0 ] if data is None : return None round_num = data [ "number" ] return round_num | Get number of the current active round . |
29,181 | def get_tournaments ( self , only_active = True ) : query = data = self . raw_query ( query ) [ 'data' ] [ 'tournaments' ] if only_active : data = [ d for d in data if d [ 'active' ] ] return data | Get all tournaments |
29,182 | def get_submission_filenames ( self , tournament = None , round_num = None ) : query = data = self . raw_query ( query , authorization = True ) [ 'data' ] [ 'user' ] filenames = [ { "round_num" : item [ 'round' ] [ 'number' ] , "tournament" : item [ 'round' ] [ 'tournament' ] , "filename" : item [ 'filename' ] } for it... | Get filenames of the submission of the user . |
29,183 | def get_rankings ( self , limit = 50 , offset = 0 ) : query = arguments = { 'limit' : limit , 'offset' : offset } data = self . raw_query ( query , arguments ) [ 'data' ] [ 'rankings' ] for item in data : for p in [ "nmrBurned" , "nmrPaid" , "nmrStaked" , "usdEarned" ] : utils . replace ( item , p , utils . parse_float... | Get the overall ranking |
29,184 | def get_submission_ids ( self , tournament = 1 ) : query = arguments = { 'tournament' : tournament } data = self . raw_query ( query , arguments ) [ 'data' ] [ 'rounds' ] [ 0 ] if data is None : return None mapping = { item [ 'username' ] : item [ 'submissionId' ] for item in data [ 'leaderboard' ] } return mapping | Get dict with username - > submission_id mapping . |
29,185 | def get_user ( self ) : query = data = self . raw_query ( query , authorization = True ) [ 'data' ] [ 'user' ] utils . replace ( data , "insertedAt" , utils . parse_datetime_string ) utils . replace ( data , "availableUsd" , utils . parse_float_string ) utils . replace ( data , "availableNmr" , utils . parse_float_stri... | Get all information about you! |
29,186 | def get_payments ( self ) : query = data = self . raw_query ( query , authorization = True ) [ 'data' ] payments = data [ 'user' ] [ 'payments' ] for p in payments : utils . replace ( p [ 'round' ] , "openTime" , utils . parse_datetime_string ) utils . replace ( p [ 'round' ] , "resolveTime" , utils . parse_datetime_st... | Get all your payments . |
29,187 | def get_transactions ( self ) : query = txs = self . raw_query ( query , authorization = True ) [ 'data' ] [ 'user' ] for t in txs [ 'usdWithdrawals' ] : utils . replace ( t , "confirmTime" , utils . parse_datetime_string ) utils . replace ( t , "sendTime" , utils . parse_datetime_string ) utils . replace ( t , "usdAmo... | Get all your deposits and withdrawals . |
29,188 | def get_stakes ( self ) : query = data = self . raw_query ( query , authorization = True ) [ 'data' ] stakes = data [ 'user' ] [ 'stakeTxs' ] for s in stakes : utils . replace ( s , "insertedAt" , utils . parse_datetime_string ) utils . replace ( s , "soc" , utils . parse_float_string ) utils . replace ( s , "confidenc... | List all your stakes . |
29,189 | def submission_status ( self , submission_id = None ) : if submission_id is None : submission_id = self . submission_id if submission_id is None : raise ValueError ( 'You need to submit something first or provide\ a submission ID' ) query = variable = { 'submission_id' : submission_id } dat... | submission status of the last submission associated with the account . |
29,190 | def upload_predictions ( self , file_path , tournament = 1 ) : self . logger . info ( "uploading predictions..." ) auth_query = arguments = { 'filename' : os . path . basename ( file_path ) , 'tournament' : tournament } submission_resp = self . raw_query ( auth_query , arguments , authorization = True ) submission_auth... | Upload predictions from file . |
29,191 | def check_submission_successful ( self , submission_id = None ) : status = self . submission_status ( submission_id ) success = bool ( status [ "concordance" ] [ "value" ] ) return success | Check if the last submission passes submission criteria . |
29,192 | def tournament_number2name ( self , number ) : tournaments = self . get_tournaments ( ) d = { t [ 'tournament' ] : t [ 'name' ] for t in tournaments } return d . get ( number , None ) | Translate tournament number to tournament name . |
29,193 | def tournament_name2number ( self , name ) : tournaments = self . get_tournaments ( ) d = { t [ 'name' ] : t [ 'tournament' ] for t in tournaments } return d . get ( name , None ) | Translate tournament name to tournament number . |
29,194 | def staking_leaderboard ( round_num = 0 , tournament = 1 ) : click . echo ( prettify ( napi . get_staking_leaderboard ( tournament = tournament , round_num = round_num ) ) ) | Retrieves the staking competition leaderboard for the given round . |
29,195 | def rankings ( limit = 20 , offset = 0 ) : click . echo ( prettify ( napi . get_rankings ( limit = limit , offset = offset ) ) ) | Get the overall rankings . |
29,196 | def submission_filenames ( round_num = None , tournament = None ) : click . echo ( prettify ( napi . get_submission_filenames ( tournament , round_num ) ) ) | Get filenames of your submissions |
29,197 | def install_bootstrapped_files ( nb_path = None , server_config = True , DEBUG = False ) : install_path = None print ( 'Starting hide_code.js install...' ) current_dir = path . abspath ( path . dirname ( __file__ ) ) config_dirs = j_path . jupyter_config_path ( ) notebook_module_path = Utils . get_notebook_module_dir (... | Installs javascript and exporting server extensions in Jupyter notebook . |
29,198 | def ipynb_file_name ( params ) : global notebook_dir p = notebook_dir + [ param . replace ( '/' , '' ) for param in params if param is not None ] return path . join ( * p ) | Returns OS path to notebook based on route parameters . |
29,199 | def radiance2tb ( rad , wavelength ) : from pyspectral . blackbody import blackbody_rad2temp as rad2temp return rad2temp ( wavelength , rad ) | Get the Tb from the radiance using the Planck function |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.