idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
1,400
def make_timestamp ( el_time ) : # Calc hours hrs = el_time // 3600.0 # Calc minutes mins = ( el_time % 3600.0 ) // 60.0 # Calc seconds secs = el_time % 60.0 # Construct timestamp string stamp = "{0}h {1}m {2}s" . format ( int ( hrs ) , int ( mins ) , int ( secs ) ) # Return return stamp
Generate an hour - minutes - seconds timestamp from an interval in seconds .
101
15
1,401
def check_geom ( c1 , a1 , c2 , a2 , tol = _DEF . XYZ_COORD_MATCH_TOL ) : # Import(s) from . . const import atom_num import numpy as np from . . const import EnumCheckGeomMismatch as ECGM # Initialize return value to success condition match = True #** Check coords for suitable shape. Assume 1-D np.arrays. if not len ( ...
Check for consistency of two geometries and atom symbol lists
818
12
1,402
def template_subst ( template , subs , delims = ( '<' , '>' ) ) : # Store the template into the working variable subst_text = template # Iterate over subs and perform the .replace() calls for ( k , v ) in subs . items ( ) : subst_text = subst_text . replace ( delims [ 0 ] + k + delims [ 1 ] , v ) ## next tup # Return t...
Perform substitution of content into tagged string .
100
9
1,403
def assert_npfloatarray ( obj , varname , desc , exc , tc , errsrc ) : # Imports import numpy as np # Check for whether member or object is to be checked if varname is None : var = obj else : # Try to get the variable to be typechecked try : var = getattr ( obj , varname ) except AttributeError : raise exc ( tc , "Attr...
Assert a value is an |nparray| of NumPy floats .
285
16
1,404
def advance ( self ) : elem = next ( self . _iterable ) for deque in self . _deques : deque . append ( elem )
Advance the base iterator publish to constituent iterators .
35
11
1,405
def _advance_pattern_generators ( self , p ) : valid_generators = [ ] for g in p . generators : for trial in range ( self . max_trials ) : # Generate a new position and add generator if it's ok if np . alltrue ( [ self . __distance_valid ( g , v , p ) for v in valid_generators ] ) : valid_generators . append ( g ) brea...
Advance the parameters for each generator for this presentation .
154
11
1,406
def _advance_params ( self ) : for p in [ 'x' , 'y' , 'direction' ] : self . force_new_dynamic_value ( p ) self . last_time = self . time_fn ( )
Explicitly generate new values for these parameters only when appropriate .
53
13
1,407
def register ( self , settings_class = NoSwitcher , * simple_checks , * * conditions ) : if settings_class is NoSwitcher : def decorator ( cls ) : self . register ( cls , * simple_checks , * * conditions ) return cls return decorator available_checks = self . checks . keys ( ) for condition in conditions . keys ( ) : i...
Register a settings class with the switcher . Can be passed the settings class to register or be used as a decorator .
128
25
1,408
def _peek_buffer ( self , i = 0 ) : while len ( self . _buffer ) <= i : self . _buffer . append ( next ( self . _source ) ) return self . _buffer [ i ]
Get the next line without consuming it .
48
8
1,409
def _make_readline_peeker ( self ) : counter = itertools . count ( 0 ) def readline ( ) : try : return self . _peek_buffer ( next ( counter ) ) except StopIteration : return '' return readline
Make a readline - like function which peeks into the source .
55
14
1,410
def _add_node ( self , node , depth ) : self . _topmost_node . add_child ( node , bool ( depth [ 1 ] ) ) self . _stack . append ( ( depth , node ) )
Add a node to the graph and the stack .
48
10
1,411
def _load_data ( self , atom_syms , coords , bohrs = True ) : # Imports import numpy as np from . const import atom_num , PHYS from . error import XYZError # Gripe if already initialized if 'geoms' in dir ( self ) : raise XYZError ( XYZError . OVERWRITE , "Cannot overwrite contents of existing OpanXYZ" , "" ) ## end if...
Internal function for making XYZ object from explicit geom data .
529
13
1,412
def geom_iter ( self , g_nums ) : # Using the custom coded pack_tups to not have to care whether the # input is iterable from . utils import pack_tups vals = pack_tups ( g_nums ) for val in vals : yield self . geom_single ( val [ 0 ] )
Iterator over a subset of geometries .
76
9
1,413
def dist_single ( self , g_num , at_1 , at_2 ) : # Import used math library function(s) import numpy as np from scipy import linalg as spla from . utils import safe_cast as scast # The below errors are explicitly thrown since values are multiplied by # three when they are used as an index and thus give non-intuitive # ...
Distance between two atoms .
383
5
1,414
def dist_iter ( self , g_nums , ats_1 , ats_2 , invalid_error = False ) : # Imports import numpy as np from . utils import pack_tups # Print the function inputs if debug mode is on if _DEBUG : # pragma: no cover print ( "g_nums = {0}" . format ( g_nums ) ) print ( "ats_1 = {0}" . format ( ats_1 ) ) print ( "ats_2 = {0}...
Iterator over selected interatomic distances .
268
7
1,415
def angle_single ( self , g_num , at_1 , at_2 , at_3 ) : # Imports import numpy as np from . utils import safe_cast as scast from . utils . vector import vec_angle # The below errors are explicitly thrown since they are multiplied by # three when they are used as an index and thus give non-intuitive # errors in later c...
Spanning angle among three atoms .
702
8
1,416
def angle_iter ( self , g_nums , ats_1 , ats_2 , ats_3 , invalid_error = False ) : # Suitability of ats_n indices will be checked within the # self.angle_single() calls and thus no check is needed here. # Import the tuple-generating function from . utils import pack_tups # Print the function inputs if debug mode is on ...
Iterator over selected atomic angles .
323
6
1,417
def dihed_iter ( self , g_nums , ats_1 , ats_2 , ats_3 , ats_4 , invalid_error = False ) : # Suitability of ats_n indices will be checked within the # self.dihed_single() calls and thus no check is needed here. # Import the tuple-generating function from . utils import pack_tups # Print the function inputs if debug mod...
Iterator over selected dihedral angles .
337
7
1,418
def displ_single ( self , g_num , at_1 , at_2 ) : # Library imports import numpy as np from . utils import safe_cast as scast # The below errors are explicitly thrown since they are multiplied by # three when they are used as an index and thus give non-intuitive # errors. # Complain if at_1 is invalid if not ( - self ....
Displacement vector between two atoms .
428
8
1,419
def displ_iter ( self , g_nums , ats_1 , ats_2 , invalid_error = False ) : # Import the tuple-generating function from . utils import pack_tups # Print the function inputs if debug mode is on if _DEBUG : # pragma: no cover print ( "g_nums = {0}" . format ( g_nums ) ) print ( "ats_1 = {0}" . format ( ats_1 ) ) print ( "...
Iterator over indicated displacement vectors .
246
6
1,420
def _none_subst ( self , * args ) : # Imports import numpy as np # Initialize argument list return value, and as None not found arglist = [ a for a in args ] none_found = False # Check for None values none_vals = list ( map ( lambda e : isinstance ( e , type ( None ) ) , arglist ) ) # Error if more than one None; handl...
Helper function to insert full ranges for |None| for X_iter methods .
354
16
1,421
def guess_external_url ( local_host , port ) : if local_host in [ '0.0.0.0' , '::' ] : # The server is listening on all interfaces, but we have to pick one. # The system's FQDN should give us a hint. local_host = socket . getfqdn ( ) # https://github.com/vfaronov/turq/issues/9 match = IPV4_REVERSE_DNS . match ( local_h...
Return a URL that is most likely to route to local_host from outside .
333
16
1,422
def _check_column_lengths ( self ) : column_lengths_dict = { name : len ( xs ) for ( name , xs ) in self . columns_dict . items ( ) } unique_column_lengths = set ( column_lengths_dict . values ( ) ) if len ( unique_column_lengths ) != 1 : raise ValueError ( "Mismatch between lengths of columns: %s" % ( column_lengths_d...
Make sure columns are of the same length or else DataFrame construction will fail .
105
16
1,423
def new_from_files ( self , basepath , basename , repo , bohrs = False , software = _E_SW . ORCA , repo_clobber = False , * * kwargs ) : # Imports import os from os import path as osp from . . xyz import OpanXYZ as OX from . . grad import OrcaEngrad as OE from . . hess import OrcaHess as OH from . repo import OpanAnhar...
Initialize with data from files .
751
7
1,424
def remote_exception ( exc , tb ) : if type ( exc ) in exceptions : typ = exceptions [ type ( exc ) ] return typ ( exc , tb ) else : try : typ = type ( exc . __class__ . __name__ , ( RemoteException , type ( exc ) ) , { 'exception_type' : type ( exc ) } ) exceptions [ type ( exc ) ] = typ return typ ( exc , tb ) except...
Metaclass that wraps exception type in RemoteException
102
10
1,425
def reads_overlapping_variants ( variants , samfile , * * kwargs ) : chromosome_names = set ( samfile . references ) for variant in variants : # I imagine the conversation went like this: # A: "Hey, I have an awesome idea" # B: "What's up?" # A: "Let's make two nearly identical reference genomes" # B: "But...that sound...
Generates sequence of tuples each containing a variant paired with a list of AlleleRead objects .
250
21
1,426
def group_reads_by_allele ( allele_reads ) : allele_to_reads_dict = defaultdict ( list ) for allele_read in allele_reads : allele_to_reads_dict [ allele_read . allele ] . append ( allele_read ) return allele_to_reads_dict
Returns dictionary mapping each allele s nucleotide sequence to a list of supporting AlleleRead objects .
66
20
1,427
def from_locus_read ( cls , locus_read , n_ref ) : sequence = locus_read . sequence reference_positions = locus_read . reference_positions # positions of the nucleotides before and after the variant within # the read sequence read_pos_before = locus_read . base0_read_position_before_variant read_pos_after = locus_read ...
Given a single LocusRead object return either an AlleleRead or None
663
16
1,428
def most_common_nucleotides ( partitioned_read_sequences ) : counts , variant_column_indices = nucleotide_counts ( partitioned_read_sequences ) max_count_per_column = counts . max ( axis = 0 ) assert len ( max_count_per_column ) == counts . shape [ 1 ] max_nucleotide_index_per_column = np . argmax ( counts , axis = 0 )...
Find the most common nucleotide at each offset to the left and right of a variant .
207
18
1,429
def point_displ ( pt1 , pt2 ) : #Imports import numpy as np # Make iterable if not np . iterable ( pt1 ) : pt1 = np . float64 ( np . array ( [ pt1 ] ) ) else : pt1 = np . float64 ( np . array ( pt1 ) . squeeze ( ) ) ## end if if not np . iterable ( pt2 ) : pt2 = np . float64 ( np . array ( [ pt2 ] ) ) else : pt2 = np ....
Calculate the displacement vector between two n - D points .
168
13
1,430
def point_dist ( pt1 , pt2 ) : # Imports from scipy import linalg as spla dist = spla . norm ( point_displ ( pt1 , pt2 ) ) return dist
Calculate the Euclidean distance between two n - D points .
47
15
1,431
def point_rotate ( pt , ax , theta ) : # Imports import numpy as np # Ensure pt is reducible to 3-D vector. pt = make_nd_vec ( pt , nd = 3 , t = np . float64 , norm = False ) # Calculate the rotation rot_pt = np . dot ( mtx_rot ( ax , theta , reps = 1 ) , pt ) # Should be ready to return return rot_pt
Rotate a 3 - D point around a 3 - D axis through the origin .
100
17
1,432
def point_reflect ( pt , nv ) : # Imports import numpy as np from scipy import linalg as spla # Ensure pt is reducible to 3-D vector pt = make_nd_vec ( pt , nd = 3 , t = np . float64 , norm = False ) # Transform the point and return refl_pt = np . dot ( mtx_refl ( nv , reps = 1 ) , pt ) return refl_pt
Reflect a 3 - D point through a plane intersecting the origin .
103
15
1,433
def geom_reflect ( g , nv ) : # Imports import numpy as np # Force g to n-vector g = make_nd_vec ( g , nd = None , t = np . float64 , norm = False ) # Transform the geometry and return refl_g = np . dot ( mtx_refl ( nv , reps = ( g . shape [ 0 ] // 3 ) ) , g ) . reshape ( ( g . shape [ 0 ] , 1 ) ) return refl_g
Reflection symmetry operation .
113
5
1,434
def geom_rotate ( g , ax , theta ) : # Imports import numpy as np # Force g to n-vector g = make_nd_vec ( g , nd = None , t = np . float64 , norm = False ) # Perform rotation and return rot_g = np . dot ( mtx_rot ( ax , theta , reps = ( g . shape [ 0 ] // 3 ) ) , g ) . reshape ( ( g . shape [ 0 ] , 1 ) ) return rot_g
Rotation symmetry operation .
114
5
1,435
def symm_op ( g , ax , theta , do_refl ) : # Imports import numpy as np # Depend on lower functions' geometry vector coercion. Just # do the rotation and, if indicated, the reflection. gx = geom_rotate ( g , ax , theta ) if do_refl : gx = geom_reflect ( gx , ax ) ## end if # Should be good to go return gx
Perform general point symmetry operation on a geometry .
96
10
1,436
def geom_find_rotsymm ( g , atwts , ax , improp , nmax = _DEF . SYMM_MATCH_NMAX , tol = _DEF . SYMM_MATCH_TOL ) : # Imports import numpy as np # Vectorize the geometry g = make_nd_vec ( g , nd = None , t = np . float64 , norm = False ) # Ensure a 3-D axis vector ax = make_nd_vec ( ax , nd = 3 , t = np . float64 , norm ...
Identify highest - order symmetry for a geometry on a given axis .
279
14
1,437
def g_subset ( g , atwts , atwt , digits = _DEF . SYMM_ATWT_ROUND_DIGITS ) : # Imports import numpy as np # Ensure g and atwts are n-D vectors g = make_nd_vec ( g , nd = None , t = np . float64 , norm = False ) atwts = make_nd_vec ( atwts , nd = None , t = np . float64 , norm = False ) # Ensure dims match (should alrea...
Extract a subset of a geometry matching a desired atom .
309
12
1,438
def mtx_refl ( nv , reps = 1 ) : # Imports import numpy as np from scipy import linalg as spla from . . const import PRM # Ensure |nv| is large enough for confident directionality if spla . norm ( nv ) < PRM . ZERO_VEC_TOL : raise ValueError ( "Norm of 'nv' is too small." ) ## end if # Ensure nv is a normalized np.floa...
Generate block - diagonal reflection matrix about nv .
412
11
1,439
def mtx_rot ( ax , theta , reps = 1 ) : # Imports import numpy as np from scipy import linalg as spla from . . const import PRM # Ensure |ax| is large enough for confident directionality if spla . norm ( ax ) < PRM . ZERO_VEC_TOL : raise ValueError ( "Norm of 'ax' is too small." ) ## end if # Ensure ax is a normalized ...
Generate block - diagonal rotation matrix about ax .
504
10
1,440
def ff ( items , targets ) : bins = [ ( target , [ ] ) for target in targets ] skip = [ ] for item in items : for target , content in bins : if item <= ( target - sum ( content ) ) : content . append ( item ) break else : skip . append ( item ) return bins , skip
First - Fit
69
3
1,441
def ffd ( items , targets , * * kwargs ) : sizes = zip ( items , weight ( items , * * kwargs ) ) sizes = sorted ( sizes , key = operator . itemgetter ( 1 ) , reverse = True ) items = map ( operator . itemgetter ( 0 ) , sizes ) return ff ( items , targets )
First - Fit Decreasing
75
5
1,442
def mr ( items , targets , * * kwargs ) : bins = [ ( target , [ ] ) for target in targets ] skip = [ ] for item in items : capacities = [ target - sum ( content ) for target , content in bins ] weighted = weight ( capacities , * * kwargs ) ( target , content ) , capacity , _ = max ( zip ( bins , capacities , weighted )...
Max - Rest
121
3
1,443
def bf ( items , targets , * * kwargs ) : bins = [ ( target , [ ] ) for target in targets ] skip = [ ] for item in items : containers = [ ] capacities = [ ] for target , content in bins : capacity = target - sum ( content ) if item <= capacity : containers . append ( content ) capacities . append ( capacity - item ) if...
Best - Fit
140
3
1,444
def bfd ( items , targets , * * kwargs ) : sizes = zip ( items , weight ( items , * * kwargs ) ) sizes = sorted ( sizes , key = operator . itemgetter ( 1 ) , reverse = True ) items = map ( operator . itemgetter ( 0 ) , sizes ) return bf ( items , targets , * * kwargs )
Best - Fit Decreasing
82
5
1,445
def trim_sequences ( variant_sequence , reference_context ) : cdna_prefix = variant_sequence . prefix cdna_alt = variant_sequence . alt cdna_suffix = variant_sequence . suffix # if the transcript is on the reverse strand then we have to # take the sequence PREFIX|VARIANT|SUFFIX # and take the complement of XIFFUS|TNAIR...
A VariantSequence and ReferenceContext may contain a different number of nucleotides before the variant locus . Furthermore the VariantSequence is always expressed in terms of the positive strand against which it aligned but reference transcripts may have sequences from the negative strand of the genome . Take the reve...
494
88
1,446
def count_mismatches_before_variant ( reference_prefix , cdna_prefix ) : if len ( reference_prefix ) != len ( cdna_prefix ) : raise ValueError ( "Expected reference prefix '%s' to be same length as %s" % ( reference_prefix , cdna_prefix ) ) return sum ( xi != yi for ( xi , yi ) in zip ( reference_prefix , cdna_prefix )...
Computes the number of mismatching nucleotides between two cDNA sequences before a variant locus .
100
21
1,447
def count_mismatches_after_variant ( reference_suffix , cdna_suffix ) : len_diff = len ( cdna_suffix ) - len ( reference_suffix ) # if the reference is shorter than the read, the read runs into the intron - these count as # mismatches return sum ( xi != yi for ( xi , yi ) in zip ( reference_suffix , cdna_suffix ) ) + m...
Computes the number of mismatching nucleotides between two cDNA sequences after a variant locus .
108
21
1,448
def compute_offset_to_first_complete_codon ( offset_to_first_complete_reference_codon , n_trimmed_from_reference_sequence ) : if n_trimmed_from_reference_sequence <= offset_to_first_complete_reference_codon : return ( offset_to_first_complete_reference_codon - n_trimmed_from_reference_sequence ) else : n_nucleotides_tr...
Once we ve aligned the variant sequence to the ReferenceContext we need to transfer reading frame from the reference transcripts to the variant sequences .
168
26
1,449
def match_variant_sequence_to_reference_context ( variant_sequence , reference_context , min_transcript_prefix_length , max_transcript_mismatches , include_mismatches_after_variant = False , max_trimming_attempts = 2 ) : variant_sequence_in_reading_frame = None # if we can't get the variant sequence to match this refer...
Iteratively trim low - coverage subsequences of a variant sequence until it either matches the given reference context or there are too few nucleotides left in the variant sequence .
706
34
1,450
def _check_codons ( self ) : for stop_codon in self . stop_codons : if stop_codon in self . codon_table : if self . codon_table [ stop_codon ] != "*" : raise ValueError ( ( "Codon '%s' not found in stop_codons, but codon table " "indicates that it should be" ) % ( stop_codon , ) ) else : self . codon_table [ stop_codon...
If codon table is missing stop codons then add them .
282
13
1,451
def copy ( self , name , start_codons = None , stop_codons = None , codon_table = None , codon_table_changes = None ) : new_start_codons = ( self . start_codons . copy ( ) if start_codons is None else start_codons ) new_stop_codons = ( self . stop_codons . copy ( ) if stop_codons is None else stop_codons ) new_codon_ta...
Make copy of this GeneticCode object with optional replacement values for all fields .
202
15
1,452
def start ( self ) : self . running = True self . thread = threading . Thread ( target = self . _main_loop ) self . thread . start ( )
Start listening to changes
36
4
1,453
def subscribe ( self , field_names ) : available_controls = dict ( self . raildriver . get_controller_list ( ) ) . values ( ) for field in field_names : if field not in available_controls : raise ValueError ( 'Cannot subscribe to a missing controller {}' . format ( field ) ) self . subscribed_fields = field_names
Subscribe to given fields .
80
5
1,454
def set_matrix_dimensions ( self , bounds , xdensity , ydensity ) : self . bounds = bounds self . xdensity = xdensity self . ydensity = ydensity scs = SheetCoordinateSystem ( bounds , xdensity , ydensity ) for of in self . output_fns : if isinstance ( of , TransferFn ) : of . initialize ( SCS = scs , shape = scs . shap...
Change the dimensions of the matrix into which the pattern will be drawn . Users of this class should call this method rather than changing the bounds xdensity and ydensity parameters directly . Subclasses can override this method to update any internal data structures that may depend on the matrix dimensions .
93
55
1,455
def state_push ( self ) : for of in self . output_fns : if hasattr ( of , 'state_push' ) : of . state_push ( ) super ( PatternGenerator , self ) . state_push ( )
Save the state of the output functions to be restored with state_pop .
52
15
1,456
def state_pop ( self ) : for of in self . output_fns : if hasattr ( of , 'state_pop' ) : of . state_pop ( ) super ( PatternGenerator , self ) . state_pop ( )
Restore the state of the output functions saved by state_push .
52
14
1,457
def pil ( self , * * params_to_override ) : from PIL . Image import fromarray nchans = self . num_channels ( ) if nchans in [ 0 , 1 ] : mode , arr = None , self ( * * params_to_override ) arr = ( 255.0 / arr . max ( ) * ( arr - arr . min ( ) ) ) . astype ( np . uint8 ) elif nchans in [ 3 , 4 ] : mode = 'RGB' if nchans ...
Returns a PIL image for this pattern overriding parameters if provided .
192
13
1,458
def state_push ( self ) : super ( Composite , self ) . state_push ( ) for gen in self . generators : gen . state_push ( )
Push the state of all generators
34
6
1,459
def state_pop ( self ) : super ( Composite , self ) . state_pop ( ) for gen in self . generators : gen . state_pop ( )
Pop the state of all generators
34
6
1,460
def function ( self , p ) : generators = self . _advance_pattern_generators ( p ) assert hasattr ( p . operator , 'reduce' ) , repr ( p . operator ) + " does not support 'reduce'." # CEBALERT: mask gets applied by all PGs including the Composite itself # (leads to redundant calculations in current lissom_oo_or usage, b...
Constructs combined pattern out of the individual ones .
250
10
1,461
def compile_column ( name : str , data_type : str , nullable : bool ) -> str : null_str = 'NULL' if nullable else 'NOT NULL' return '{name} {data_type} {null},' . format ( name = name , data_type = data_type , null = null_str )
Create column definition statement .
73
5
1,462
def create ( self , no_data = False ) : if self . query : ddl_statement = self . compile_create_as ( ) else : ddl_statement = self . compile_create ( ) if no_data : ddl_statement += '\nWITH NO DATA' return ddl_statement , self . query_values
Declare materalized view .
74
7
1,463
def predicted_effects_for_variant ( variant , transcript_id_whitelist = None , only_coding_changes = True ) : effects = [ ] for transcript in variant . transcripts : if only_coding_changes and not transcript . complete : logger . info ( "Skipping transcript %s for variant %s because it's incomplete" , transcript . name...
For a given variant return its set of predicted effects . Optionally filter to transcripts where this variant results in a non - synonymous change to the protein sequence .
367
31
1,464
def reference_transcripts_for_variant ( variant , transcript_id_whitelist = None , only_coding_changes = True ) : predicted_effects = predicted_effects_for_variant ( variant = variant , transcript_id_whitelist = transcript_id_whitelist , only_coding_changes = only_coding_changes ) return [ effect . transcript for effec...
For a given variant find all the transcripts which overlap the variant and for which it has a predictable effect on the amino acid sequence of the protein .
93
29
1,465
def pileup_reads_at_position ( samfile , chromosome , base0_position ) : # TODO: I want to pass truncate=True, stepper="all" # but for some reason I get this error: # pileup() got an unexpected keyword argument 'truncate' # ...even though these options are listed in the docs for pysam 0.9.0 # for column in samfile . pi...
Returns a pileup column at the specified position . Unclear if a function like this is hiding somewhere in pysam API .
167
26
1,466
def locus_read_generator ( samfile , chromosome , base1_position_before_variant , base1_position_after_variant , use_duplicate_reads = USE_DUPLICATE_READS , use_secondary_alignments = USE_SECONDARY_ALIGNMENTS , min_mapping_quality = MIN_READ_MAPPING_QUALITY ) : logger . debug ( "Gathering reads at locus %s: %d-%d" , ch...
Generator that yields a sequence of ReadAtLocus records for reads which contain the positions before and after a variant . The actual work to figure out if what s between those positions matches a variant happens later in the variant_reads module .
444
48
1,467
def locus_reads_dataframe ( * args , * * kwargs ) : df_builder = DataFrameBuilder ( LocusRead , variant_columns = False , converters = { "reference_positions" : list_to_string , "quality_scores" : list_to_string , } ) for locus_read in locus_read_generator ( * args , * * kwargs ) : df_builder . add ( variant = None , e...
Traverse a BAM file to find all the reads overlapping a specified locus .
122
17
1,468
def copy_from_csv_sql ( qualified_name : str , delimiter = ',' , encoding = 'utf8' , null_str = '' , header = True , escape_str = '\\' , quote_char = '"' , force_not_null = None , force_null = None ) : options = [ ] options . append ( "DELIMITER '%s'" % delimiter ) options . append ( "NULL '%s'" % null_str ) if header ...
Generate copy from csv statement .
268
8
1,469
def sort_protein_sequences ( protein_sequences ) : return list ( sorted ( protein_sequences , key = ProteinSequence . ascending_sort_key , reverse = True ) )
Sort protein sequences in decreasing order of priority
41
8
1,470
def reads_generator_to_protein_sequences_generator ( variant_and_overlapping_reads_generator , transcript_id_whitelist = None , protein_sequence_length = PROTEIN_SEQUENCE_LENGTH , min_alt_rna_reads = MIN_ALT_RNA_READS , min_variant_sequence_coverage = MIN_VARIANT_SEQUENCE_COVERAGE , min_transcript_prefix_length = MIN_T...
Translates each coding variant in a collection to one or more Translation objects which are then aggregated into equivalent ProteinSequence objects .
867
27
1,471
def from_translation_key ( cls , translation_key , translations , overlapping_reads , ref_reads , alt_reads , alt_reads_supporting_protein_sequence , transcripts_overlapping_variant , transcripts_supporting_protein_sequence , gene ) : return cls ( amino_acids = translation_key . amino_acids , variant_aa_interval_start ...
Create a ProteinSequence object from a TranslationKey along with all the extra fields a ProteinSequence requires .
250
22
1,472
def make_delete_table ( table : Table , delete_prefix = 'delete_from__' ) -> Table : name = delete_prefix + table . name primary_key = table . primary_key key_names = set ( primary_key . column_names ) columns = [ column for column in table . columns if column . name in key_names ] table = Table ( name , columns , prim...
Table referencing a delete from using primary key join .
90
10
1,473
def trim_variant_fields ( location , ref , alt ) : if len ( alt ) > 0 and ref . startswith ( alt ) : # if alt is a prefix of the ref sequence then we actually have a # deletion like: # g.10 GTT > GT # which can be trimmed to # g.12 'T'>'' ref = ref [ len ( alt ) : ] location += len ( alt ) alt = "" if len ( ref ) > 0 a...
Trims common prefixes from the ref and alt sequences
199
11
1,474
def base0_interval_for_variant ( variant ) : base1_location , ref , alt = trim_variant ( variant ) return base0_interval_for_variant_fields ( base1_location = base1_location , ref = ref , alt = alt )
Inteval of interbase offsets of the affected reference positions for a particular variant .
63
16
1,475
def interbase_range_affected_by_variant_on_transcript ( variant , transcript ) : if variant . is_insertion : if transcript . strand == "+" : # base-1 position of an insertion is the genomic nucleotide # before any inserted mutant nucleotides, so the start offset # of the actual inserted nucleotides is one past that ref...
Convert from a variant s position in global genomic coordinates on the forward strand to an interval of interbase offsets on a particular transcript s mRNA .
354
29
1,476
def insert ( conn , qualified_name : str , column_names , records ) : query = create_insert_statement ( qualified_name , column_names ) with conn : with conn . cursor ( cursor_factory = NamedTupleCursor ) as cursor : for record in records : cursor . execute ( query , record )
Insert a collection of namedtuple records .
69
9
1,477
def insert_many ( conn , tablename , column_names , records , chunksize = 2500 ) : groups = chunks ( records , chunksize ) column_str = ',' . join ( column_names ) insert_template = 'INSERT INTO {table} ({columns}) VALUES {values}' . format ( table = tablename , columns = column_str , values = '{0}' ) with conn : with ...
Insert many records by chunking data into insert statements .
169
11
1,478
def upsert_records ( conn , records , upsert_statement ) : with conn : with conn . cursor ( ) as cursor : for record in records : cursor . execute ( upsert_statement , record )
Upsert records .
45
5
1,479
def delete_joined_table_sql ( qualified_name , removing_qualified_name , primary_key ) : condition_template = 't.{}=d.{}' where_clause = ' AND ' . join ( condition_template . format ( pkey , pkey ) for pkey in primary_key ) delete_statement = ( 'DELETE FROM {table} t' ' USING {delete_table} d' ' WHERE {where_clause}' )...
SQL statement for a joined delete from . Generate SQL statement for deleting the intersection of rows between both tables from table referenced by tablename .
138
29
1,480
def copy_from_csv ( conn , file , qualified_name : str , delimiter = ',' , encoding = 'utf8' , null_str = '' , header = True , escape_str = '\\' , quote_char = '"' , force_not_null = None , force_null = None ) : copy_sql = copy_from_csv_sql ( qualified_name , delimiter , encoding , null_str = null_str , header = header...
Copy file - like object to database table .
164
9
1,481
def get_user_tables ( conn ) : query_string = "select schemaname, relname from pg_stat_user_tables;" with conn . cursor ( ) as cursor : cursor . execute ( query_string ) tables = cursor . fetchall ( ) return tables
Retrieve all user tables .
60
6
1,482
def get_column_metadata ( conn , table : str , schema = 'public' ) : query = """\ SELECT attname as name, format_type(atttypid, atttypmod) AS data_type, NOT attnotnull AS nullable FROM pg_catalog.pg_attribute WHERE attrelid=%s::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum;""" qualified_name = compile_qu...
Returns column data following db . Column parameter specification .
130
10
1,483
def reflect_table ( conn , table_name , schema = 'public' ) : column_meta = list ( get_column_metadata ( conn , table_name , schema = schema ) ) primary_key_columns = list ( get_primary_keys ( conn , table_name , schema = schema ) ) columns = [ Column ( * * column_data ) for column_data in column_meta ] primary_key = P...
Reflect basic table attributes .
118
6
1,484
def reset ( db_name ) : conn = psycopg2 . connect ( database = 'postgres' ) db = Database ( db_name ) conn . autocommit = True with conn . cursor ( ) as cursor : cursor . execute ( db . drop_statement ( ) ) cursor . execute ( db . create_statement ( ) ) conn . close ( )
Reset database .
78
4
1,485
def install_extensions ( extensions , * * connection_parameters ) : from postpy . connections import connect conn = connect ( * * connection_parameters ) conn . autocommit = True for extension in extensions : install_extension ( conn , extension )
Install Postgres extension if available .
56
7
1,486
def update ( self , status ) : logging . info ( 'Executor sends status update {} for task {}' . format ( status . state , status . task_id ) ) return self . driver . sendStatusUpdate ( encode ( status ) )
Sends a status update to the framework scheduler .
51
11
1,487
def message ( self , data ) : logging . info ( 'Driver sends framework message {}' . format ( data ) ) return self . driver . sendFrameworkMessage ( data )
Sends a message to the framework scheduler .
37
10
1,488
def get_current_time ( self ) : hms = [ int ( self . get_current_controller_value ( i ) ) for i in range ( 406 , 409 ) ] return datetime . time ( * hms )
Get current time
49
3
1,489
def get_loco_name ( self ) : ret_str = self . dll . GetLocoName ( ) . decode ( ) if not ret_str : return return ret_str . split ( '.:.' )
Returns the Provider Product and Engine name .
48
8
1,490
def set_controller_value ( self , index_or_name , value ) : if not isinstance ( index_or_name , int ) : index = self . get_controller_index ( index_or_name ) else : index = index_or_name self . dll . SetControllerValue ( index , ctypes . c_float ( value ) )
Sets controller value
78
4
1,491
def stop ( self , failover = False ) : logging . info ( 'Stops Scheduler Driver' ) return self . driver . stop ( failover )
Stops the scheduler driver .
33
7
1,492
def request ( self , requests ) : logging . info ( 'Request resources from Mesos' ) return self . driver . requestResources ( map ( encode , requests ) )
Requests resources from Mesos .
35
7
1,493
def launch ( self , offer_id , tasks , filters = Filters ( ) ) : logging . info ( 'Launches tasks {}' . format ( tasks ) ) return self . driver . launchTasks ( encode ( offer_id ) , map ( encode , tasks ) , encode ( filters ) )
Launches the given set of tasks .
63
8
1,494
def kill ( self , task_id ) : logging . info ( 'Kills task {}' . format ( task_id ) ) return self . driver . killTask ( encode ( task_id ) )
Kills the specified task .
43
6
1,495
def reconcile ( self , statuses ) : logging . info ( 'Reconciles task statuses {}' . format ( statuses ) ) return self . driver . reconcileTasks ( map ( encode , statuses ) )
Allows the framework to query the status for non - terminal tasks .
47
13
1,496
def accept ( self , offer_ids , operations , filters = Filters ( ) ) : logging . info ( 'Accepts offers {}' . format ( offer_ids ) ) return self . driver . acceptOffers ( map ( encode , offer_ids ) , map ( encode , operations ) , encode ( filters ) )
Accepts the given offers and performs a sequence of operations on those accepted offers .
67
16
1,497
def acknowledge ( self , status ) : logging . info ( 'Acknowledges status update {}' . format ( status ) ) return self . driver . acknowledgeStatusUpdate ( encode ( status ) )
Acknowledges the status update .
39
6
1,498
def message ( self , executor_id , slave_id , message ) : logging . info ( 'Sends message `{}` to executor `{}` on slave `{}`' . format ( message , executor_id , slave_id ) ) return self . driver . sendFrameworkMessage ( encode ( executor_id ) , encode ( slave_id ) , message )
Sends a message from the framework to one of its executors .
85
14
1,499
def _connect_func ( builder , obj , signal_name , handler_name , connect_object , flags , cls ) : if connect_object is None : extra = ( ) else : extra = ( connect_object , ) # The handler name refers to an attribute on the template instance, # so ask GtkBuilder for the template instance template_inst = builder . get_ob...
Handles GtkBuilder signal connect events
251
8