idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
60,000
def from_sequence ( cls , sequence , phos_3_prime = False ) : strand1 = NucleicAcidStrand ( sequence , phos_3_prime = phos_3_prime ) duplex = cls ( strand1 ) return duplex
Creates a DNA duplex from a nucleotide sequence .
60,001
def from_start_and_end ( cls , start , end , sequence , phos_3_prime = False ) : strand1 = NucleicAcidStrand . from_start_and_end ( start , end , sequence , phos_3_prime = phos_3_prime ) duplex = cls ( strand1 ) return duplex
Creates a DNA duplex from a start and end point .
60,002
def generate_complementary_strand ( strand1 ) : rise_adjust = ( strand1 . rise_per_nucleotide * strand1 . axis . unit_tangent ) * 2 strand2 = NucleicAcidStrand . from_start_and_end ( strand1 . helix_end - rise_adjust , strand1 . helix_start - rise_adjust , generate_antisense_sequence ( strand1 . base_sequence ) , phos_...
Takes a SingleStrandHelix and creates the antisense strand .
60,003
def total_accessibility ( in_rsa , path = True ) : if path : with open ( in_rsa , 'r' ) as inf : rsa = inf . read ( ) else : rsa = in_rsa [ : ] all_atoms , side_chains , main_chain , non_polar , polar = [ float ( x ) for x in rsa . splitlines ( ) [ - 1 ] . split ( ) [ 1 : ] ] return all_atoms , side_chains , main_chain...
Parses rsa file for the total surface accessibility data .
60,004
def get_aa_code ( aa_letter ) : aa_code = None if aa_letter != 'X' : for key , val in standard_amino_acids . items ( ) : if key == aa_letter : aa_code = val return aa_code
Get three - letter aa code if possible . If not return None .
60,005
def get_aa_letter ( aa_code ) : aa_letter = 'X' for key , val in standard_amino_acids . items ( ) : if val == aa_code : aa_letter = key return aa_letter
Get one - letter version of aa_code if possible . If not return X .
60,006
def get_aa_info ( code ) : letter = 'X' url_string = 'http://www.ebi.ac.uk/pdbe-srv/pdbechem/chemicalCompound/show/{0}' . format ( code ) r = requests . get ( url_string ) if not r . ok : raise IOError ( "Could not get to url {0}" . format ( url_string ) ) description = r . text . split ( '<h3>Molecule name' ) [ 1 ] . ...
Get dictionary of information relating to a new amino acid code not currently in the database .
60,007
def add_amino_acid_to_json ( code , description , letter = 'X' , modified = None , force_add = False ) : if ( not force_add ) and code in amino_acids_dict . keys ( ) : raise IOError ( "{0} is already in the amino_acids dictionary, with values: {1}" . format ( code , amino_acids_dict [ code ] ) ) add_code = code add_cod...
Add an amino acid to the amino_acids . json file used to populate the amino_acid table .
60,008
def from_polymers ( cls , polymers ) : n = len ( polymers ) instance = cls ( n = n , auto_build = False ) instance . major_radii = [ x . major_radius for x in polymers ] instance . major_pitches = [ x . major_pitch for x in polymers ] instance . major_handedness = [ x . major_handedness for x in polymers ] instance . a...
Creates a CoiledCoil from a list of HelicalHelices .
60,009
def from_parameters ( cls , n , aa = 28 , major_radius = None , major_pitch = None , phi_c_alpha = 26.42 , minor_helix_type = 'alpha' , auto_build = True ) : instance = cls ( n = n , auto_build = False ) instance . aas = [ aa ] * n instance . phi_c_alphas = [ phi_c_alpha ] * n instance . minor_helix_types = [ minor_hel...
Creates a CoiledCoil from defined super - helical parameters .
60,010
def tropocollagen ( cls , aa = 28 , major_radius = 5.0 , major_pitch = 85.0 , auto_build = True ) : instance = cls . from_parameters ( n = 3 , aa = aa , major_radius = major_radius , major_pitch = major_pitch , phi_c_alpha = 0.0 , minor_helix_type = 'collagen' , auto_build = False ) instance . major_handedness = [ 'r' ...
Creates a model of a collagen triple helix .
60,011
def build ( self ) : monomers = [ HelicalHelix ( major_pitch = self . major_pitches [ i ] , major_radius = self . major_radii [ i ] , major_handedness = self . major_handedness [ i ] , aa = self . aas [ i ] , minor_helix_type = self . minor_helix_types [ i ] , orientation = self . orientations [ i ] , phi_c_alpha = sel...
Builds a model of a coiled coil protein using input parameters .
60,012
def find_max_rad_npnp ( self ) : max_rad = 0 max_npnp = 0 for res , atoms in self . items ( ) : if res != 'KEY' : for atom , ff_params in self [ res ] . items ( ) : if max_rad < ff_params [ 1 ] : max_rad = ff_params [ 1 ] if max_npnp < ff_params [ 4 ] : max_npnp = ff_params [ 4 ] return max_rad , max_npnp
Finds the maximum radius and npnp in the force field .
60,013
def parameter_struct_dict ( self ) : if self . _parameter_struct_dict is None : self . _parameter_struct_dict = self . _make_ff_params_dict ( ) elif self . auto_update_f_params : new_hash = hash ( tuple ( [ tuple ( item ) for sublist in self . values ( ) for item in sublist . values ( ) ] ) ) if self . _old_hash != new...
Dictionary containing PyAtomData structs for the force field .
60,014
def run_reduce ( input_file , path = True ) : if path : input_path = Path ( input_file ) if not input_path . exists ( ) : print ( 'No file found at' , path ) return None , None else : pathf = tempfile . NamedTemporaryFile ( ) encoded_input = input_file . encode ( ) pathf . write ( encoded_input ) pathf . seek ( 0 ) fil...
Runs reduce on a pdb or mmol file at the specified path .
60,015
def reduce_output_path ( path = None , pdb_name = None ) : if not path : if not pdb_name : raise NameError ( "Cannot save an output for a temporary file without a PDB" "code specified" ) pdb_name = pdb_name . lower ( ) output_path = Path ( global_settings [ 'structural_database' ] [ 'path' ] , pdb_name [ 1 : 3 ] . lowe...
Defines location of Reduce output files relative to input files .
60,016
def output_reduce ( input_file , path = True , pdb_name = None , force = False ) : if path : output_path = reduce_output_path ( path = input_file ) else : output_path = reduce_output_path ( pdb_name = pdb_name ) if output_path . exists ( ) and not force : return output_path reduce_mmol , reduce_message = run_reduce ( i...
Runs Reduce on a pdb or mmol file and creates a new file with the output .
60,017
def output_reduce_list ( path_list , force = False ) : output_paths = [ ] for path in path_list : output_path = output_reduce ( path , force = force ) if output_path : output_paths . append ( output_path ) return output_paths
Generates structure file with protons from a list of structure files .
60,018
def assembly_plus_protons ( input_file , path = True , pdb_name = None , save_output = False , force_save = False ) : from ampal . pdb_parser import convert_pdb_to_ampal if path : input_path = Path ( input_file ) if not pdb_name : pdb_name = input_path . stem [ : 4 ] reduced_path = reduce_output_path ( path = input_pat...
Returns an Assembly with protons added by Reduce .
60,019
def from_start_and_end ( cls , start , end , aa = None , helix_type = 'alpha' ) : start = numpy . array ( start ) end = numpy . array ( end ) if aa is None : rise_per_residue = _helix_parameters [ helix_type ] [ 1 ] aa = int ( ( numpy . linalg . norm ( end - start ) / rise_per_residue ) + 1 ) instance = cls ( aa = aa ,...
Creates a Helix between start and end .
60,020
def build ( self ) : ang_per_res = ( 2 * numpy . pi ) / self . residues_per_turn atom_offsets = _atom_offsets [ self . helix_type ] if self . handedness == 'l' : handedness = - 1 else : handedness = 1 atom_labels = [ 'N' , 'CA' , 'C' , 'O' ] if all ( [ x in atom_offsets . keys ( ) for x in atom_labels ] ) : res_label =...
Build straight helix along z - axis starting with CA1 on x - axis
60,021
def from_start_and_end ( cls , start , end , aa = None , major_pitch = 225.8 , major_radius = 5.07 , major_handedness = 'l' , minor_helix_type = 'alpha' , orientation = 1 , phi_c_alpha = 0.0 , minor_repeat = None ) : start = numpy . array ( start ) end = numpy . array ( end ) if aa is None : minor_rise_per_residue = _h...
Creates a HelicalHelix between a start and end point .
60,022
def curve ( self ) : return HelicalCurve . pitch_and_radius ( self . major_pitch , self . major_radius , handedness = self . major_handedness )
Curve of the super helix .
60,023
def curve_primitive ( self ) : curve = self . curve curve . axis_start = self . helix_start curve . axis_end = self . helix_end coords = curve . get_coords ( n_points = ( self . num_monomers + 1 ) , spacing = self . minor_rise_per_residue ) if self . orientation == - 1 : coords . reverse ( ) return Primitive . from_coo...
Primitive of the super - helical curve .
60,024
def major_rise_per_monomer ( self ) : return numpy . cos ( numpy . deg2rad ( self . curve . alpha ) ) * self . minor_rise_per_residue
Rise along super - helical axis per monomer .
60,025
def minor_residues_per_turn ( self , minor_repeat = None ) : if minor_repeat is None : minor_rpt = _helix_parameters [ self . minor_helix_type ] [ 0 ] else : precession = self . curve . t_from_arc_length ( minor_repeat * self . minor_rise_per_residue ) if self . orientation == - 1 : precession = - precession if self . ...
Calculates the number of residues per turn of the minor helix .
60,026
def build ( self ) : helical_helix = Polypeptide ( ) primitive_coords = self . curve_primitive . coordinates helices = [ Helix . from_start_and_end ( start = primitive_coords [ i ] , end = primitive_coords [ i + 1 ] , helix_type = self . minor_helix_type , aa = 1 ) for i in range ( len ( primitive_coords ) - 1 ) ] resi...
Builds the HelicalHelix .
60,027
def rotate_monomers ( self , angle , radians = False ) : if radians : angle = numpy . rad2deg ( angle ) for i in range ( len ( self . primitive ) - 1 ) : axis = self . primitive [ i + 1 ] [ 'CA' ] - self . primitive [ i ] [ 'CA' ] point = self . primitive [ i ] [ 'CA' ] . _vector self [ i ] . rotate ( angle = angle , a...
Rotates each Residue in the Polypeptide .
60,028
def side_chain_centres ( assembly , masses = False ) : if masses : elts = set ( [ x . element for x in assembly . get_atoms ( ) ] ) masses_dict = { e : element_data [ e ] [ 'atomic mass' ] for e in elts } pseudo_monomers = [ ] for chain in assembly : if isinstance ( chain , Polypeptide ) : centres = OrderedDict ( ) for...
PseudoGroup containing side_chain centres of each Residue in each Polypeptide in Assembly .
60,029
def cluster_helices ( helices , cluster_distance = 12.0 ) : condensed_distance_matrix = [ ] for h1 , h2 in itertools . combinations ( helices , 2 ) : md = minimal_distance_between_lines ( h1 [ 0 ] [ 'CA' ] . _vector , h1 [ - 1 ] [ 'CA' ] . _vector , h2 [ 0 ] [ 'CA' ] . _vector , h2 [ - 1 ] [ 'CA' ] . _vector , segments...
Clusters helices according to the minimum distance between the line segments representing their backbone .
60,030
def find_kihs ( assembly , hole_size = 4 , cutoff = 7.0 ) : pseudo_group = side_chain_centres ( assembly = assembly , masses = False ) pairs = itertools . permutations ( pseudo_group , 2 ) kihs = [ ] for pp_1 , pp_2 in pairs : for r in pp_1 : close_atoms = pp_2 . is_within ( cutoff , r ) if len ( close_atoms ) < hole_s...
KnobIntoHoles between residues of different chains in assembly .
60,031
def find_contiguous_packing_segments ( polypeptide , residues , max_dist = 10.0 ) : segments = Assembly ( assembly_id = polypeptide . ampal_parent . id ) residues_in_polypeptide = list ( sorted ( residues . intersection ( set ( polypeptide . get_monomers ( ) ) ) , key = lambda x : int ( x . id ) ) ) if not residues_in_...
Assembly containing segments of polypeptide divided according to separation of contiguous residues .
60,032
def gen_reference_primitive ( polypeptide , start , end ) : prim = polypeptide . primitive q = find_foot ( a = start , b = end , p = prim . coordinates [ 0 ] ) ax = Axis ( start = q , end = end ) if not is_acute ( polypeptide_vector ( polypeptide ) , ax . unit_tangent ) : ax = Axis ( start = end , end = q ) arc_length ...
Generates a reference Primitive for a Polypeptide given start and end coordinates .
60,033
def from_helices ( cls , assembly , cutoff = 7.0 , min_helix_length = 8 ) : cutoff = float ( cutoff ) helices = Assembly ( [ x for x in assembly . helices if len ( x ) >= min_helix_length ] ) if len ( helices ) <= 1 : return None helices . relabel_polymers ( [ x . ampal_parent . id for x in helices ] ) for i , h in enu...
Generate KnobGroup from the helices in the assembly - classic socket functionality .
60,034
def knob_subgroup ( self , cutoff = 7.0 ) : if cutoff > self . cutoff : raise ValueError ( "cutoff supplied ({0}) cannot be greater than self.cutoff ({1})" . format ( cutoff , self . cutoff ) ) return KnobGroup ( monomers = [ x for x in self . get_monomers ( ) if x . max_kh_distance <= cutoff ] , ampal_parent = self . ...
KnobGroup where all KnobsIntoHoles have max_kh_distance < = cutoff .
60,035
def graph ( self ) : g = networkx . MultiDiGraph ( ) edge_list = [ ( x . knob_helix , x . hole_helix , x . id , { 'kih' : x } ) for x in self . get_monomers ( ) ] g . add_edges_from ( edge_list ) return g
Returns MultiDiGraph from kihs . Nodes are helices and edges are kihs .
60,036
def filter_graph ( g , cutoff = 7.0 , min_kihs = 2 ) : edge_list = [ e for e in g . edges ( keys = True , data = True ) if e [ 3 ] [ 'kih' ] . max_kh_distance <= cutoff ] if min_kihs > 0 : c = Counter ( [ ( e [ 0 ] , e [ 1 ] ) for e in edge_list ] ) node_list = set ( list ( itertools . chain . from_iterable ( [ k for k...
Get subgraph formed from edges that have max_kh_distance < cutoff .
60,037
def get_coiledcoil_region ( self , cc_number = 0 , cutoff = 7.0 , min_kihs = 2 ) : g = self . filter_graph ( self . graph , cutoff = cutoff , min_kihs = min_kihs ) ccs = sorted ( networkx . connected_component_subgraphs ( g , copy = True ) , key = lambda x : len ( x . nodes ( ) ) , reverse = True ) cc = ccs [ cc_number...
Assembly containing only assigned regions ( i . e . regions with contiguous KnobsIntoHoles .
60,038
def daisy_chain_graph ( self ) : g = networkx . DiGraph ( ) for x in self . get_monomers ( ) : for h in x . hole : g . add_edge ( x . knob , h ) return g
Directed graph with edges from knob residue to each hole residue for each KnobIntoHole in self .
60,039
def knob_end ( self ) : side_chain_atoms = self . knob_residue . side_chain if not side_chain_atoms : return self . knob_residue [ 'CA' ] distances = [ distance ( self . knob_residue [ 'CB' ] , x ) for x in side_chain_atoms ] max_d = max ( distances ) knob_end_atoms = [ atom for atom , d in zip ( side_chain_atoms , dis...
Coordinates of the end of the knob residue ( atom in side - chain furthest from CB atom . Returns CA coordinates for GLY .
60,040
def max_knob_end_distance ( self ) : return max ( [ distance ( self . knob_end , h ) for h in self . hole ] )
Maximum distance between knob_end and each of the hole side - chain centres .
60,041
def base_install ( ) : scwrl = { } print ( '{BOLD}{HEADER}Generating configuration files for ISAMBARD.{END_C}\n' 'All required input can use tab completion for paths.\n' '{BOLD}Setting up SCWRL 4.0 (Recommended){END_C}' . format ( ** text_colours ) ) scwrl_path = get_user_path ( 'Please provide a path to your SCWRL exe...
Generates configuration setting for required functionality of ISAMBARD .
60,042
def optional_install ( ) : print ( '{BOLD}Setting up Reduce (optional){END_C}' . format ( ** text_colours ) ) reduce = { } reduce_path = get_user_path ( 'Please provide a path to your reduce executable.' , required = False ) reduce [ 'path' ] = str ( reduce_path ) reduce [ 'folder' ] = str ( reduce_path . parent ) if r...
Generates configuration settings for optional functionality of ISAMBARD .
60,043
def pdb ( self ) : pdb_str = write_pdb ( [ self ] , ' ' if not self . tags [ 'chain_id' ] else self . tags [ 'chain_id' ] ) return pdb_str
Generates a PDB string for the PseudoMonomer .
60,044
def from_coordinates ( cls , coordinates ) : prim = cls ( ) for coord in coordinates : pm = PseudoMonomer ( ampal_parent = prim ) pa = PseudoAtom ( coord , ampal_parent = pm ) pm . atoms = OrderedDict ( [ ( 'CA' , pa ) ] ) prim . append ( pm ) prim . relabel_all ( ) return prim
Creates a Primitive from a list of coordinates .
60,045
def rise_per_residue ( self ) : rprs = [ distance ( self [ i ] [ 'CA' ] , self [ i + 1 ] [ 'CA' ] ) for i in range ( len ( self ) - 1 ) ] rprs . append ( None ) return rprs
The rise per residue at each point on the Primitive .
60,046
def sequence ( self ) : seq = [ x . mol_code for x in self . _monomers ] return ' ' . join ( seq )
Returns the sequence of the Polynucleotide as a string .
60,047
def run_dssp ( pdb , path = True , outfile = None ) : if not path : if type ( pdb ) == str : pdb = pdb . encode ( ) try : temp_pdb = tempfile . NamedTemporaryFile ( delete = False ) temp_pdb . write ( pdb ) temp_pdb . seek ( 0 ) dssp_out = subprocess . check_output ( [ global_settings [ 'dssp' ] [ 'path' ] , temp_pdb ....
Uses DSSP to find helices and extracts helices from a pdb file or string .
60,048
def extract_solvent_accessibility_dssp ( in_dssp , path = True ) : if path : with open ( in_dssp , 'r' ) as inf : dssp_out = inf . read ( ) else : dssp_out = in_dssp [ : ] dssp_residues = [ ] go = False for line in dssp_out . splitlines ( ) : if go : try : res_num = int ( line [ 5 : 10 ] . strip ( ) ) chain = line [ 10...
Uses DSSP to extract solvent accessibilty information on every residue .
60,049
def extract_helices_dssp ( in_pdb ) : from ampal . pdb_parser import split_pdb_lines dssp_out = subprocess . check_output ( [ global_settings [ 'dssp' ] [ 'path' ] , in_pdb ] ) helix = 0 helices = [ ] h_on = False for line in dssp_out . splitlines ( ) : dssp_line = line . split ( ) try : if dssp_line [ 4 ] == 'H' : if ...
Uses DSSP to find alpha - helices and extracts helices from a pdb file .
60,050
def extract_pp_helices ( in_pdb ) : t_phi = - 75.0 t_phi_d = 29.0 t_psi = 145.0 t_psi_d = 29.0 pph_dssp = subprocess . check_output ( [ global_settings [ 'dssp' ] [ 'path' ] , in_pdb ] ) dssp_residues = [ ] go = False for line in pph_dssp . splitlines ( ) : if go : res_num = int ( line [ : 5 ] . strip ( ) ) chain = lin...
Uses DSSP to find polyproline helices in a pdb file .
60,051
def main ( ) : args = get_args ( ) tr = TestRail ( project_dict [ args . project ] ) project = tr . project ( project_dict [ args . project ] ) new_run = tr . run ( ) new_run . name = "Creating a new Run through the API" new_run . project = project new_run . include_all = True run = tr . add ( new_run ) print ( "Create...
This will offer a step by step guide to create a new run in TestRail update tests in the run with results and close the run
60,052
def memory ( ) : mem_info = { } if platform . linux_distribution ( ) [ 0 ] : with open ( '/proc/meminfo' ) as file : c = 0 for line in file : lst = line . split ( ) if str ( lst [ 0 ] ) == 'MemTotal:' : mem_info [ 'total' ] = int ( lst [ 1 ] ) elif str ( lst [ 0 ] ) in ( 'MemFree:' , 'Buffers:' , 'Cached:' ) : c += int...
Determine the machine s memory specifications .
60,053
def get_chunk_size ( N , n ) : mem_free = memory ( ) [ 'free' ] if mem_free > 60000000 : chunks_size = int ( ( ( mem_free - 10000000 ) * 1000 ) / ( 4 * n * N ) ) return chunks_size elif mem_free > 40000000 : chunks_size = int ( ( ( mem_free - 7000000 ) * 1000 ) / ( 4 * n * N ) ) return chunks_size elif mem_free > 14000...
Given a dimension of size N determine the number of rows or columns that can fit into memory .
60,054
def all_floating_ips ( self ) : if self . api_version == 2 : json = self . request ( '/floating_ips' ) return json [ 'floating_ips' ] else : raise DoError ( v2_api_required_str )
Lists all of the Floating IPs available on the account .
60,055
def new_floating_ip ( self , ** kwargs ) : droplet_id = kwargs . get ( 'droplet_id' ) region = kwargs . get ( 'region' ) if self . api_version == 2 : if droplet_id is not None and region is not None : raise DoError ( 'Only one of droplet_id and region is required to create a Floating IP. ' 'Set one of the variables and...
Creates a Floating IP and assigns it to a Droplet or reserves it to a region .
60,056
def destroy_floating_ip ( self , ip_addr ) : if self . api_version == 2 : self . request ( '/floating_ips/' + ip_addr , method = 'DELETE' ) else : raise DoError ( v2_api_required_str )
Deletes a Floating IP and removes it from the account .
60,057
def assign_floating_ip ( self , ip_addr , droplet_id ) : if self . api_version == 2 : params = { 'type' : 'assign' , 'droplet_id' : droplet_id } json = self . request ( '/floating_ips/' + ip_addr + '/actions' , params = params , method = 'POST' ) return json [ 'action' ] else : raise DoError ( v2_api_required_str )
Assigns a Floating IP to a Droplet .
60,058
def unassign_floating_ip ( self , ip_addr ) : if self . api_version == 2 : params = { 'type' : 'unassign' } json = self . request ( '/floating_ips/' + ip_addr + '/actions' , params = params , method = 'POST' ) return json [ 'action' ] else : raise DoError ( v2_api_required_str )
Unassign a Floating IP from a Droplet . The Floating IP will be reserved in the region but not assigned to a Droplet .
60,059
def list_floating_ip_actions ( self , ip_addr ) : if self . api_version == 2 : json = self . request ( '/floating_ips/' + ip_addr + '/actions' ) return json [ 'actions' ] else : raise DoError ( v2_api_required_str )
Retrieve a list of all actions that have been executed on a Floating IP .
60,060
def get_floating_ip_action ( self , ip_addr , action_id ) : if self . api_version == 2 : json = self . request ( '/floating_ips/' + ip_addr + '/actions/' + action_id ) return json [ 'action' ] else : raise DoError ( v2_api_required_str )
Retrieve the status of a Floating IP action .
60,061
def raw_sign ( message , secret ) : digest = hmac . new ( secret , message , hashlib . sha256 ) . digest ( ) return base64 . b64encode ( digest )
Sign a message .
60,062
def get_signature_from_signature_string ( self , signature ) : match = self . SIGNATURE_RE . search ( signature ) if not match : return None return match . group ( 1 )
Return the signature from the signature header or None .
60,063
def get_headers_from_signature ( self , signature ) : match = self . SIGNATURE_HEADERS_RE . search ( signature ) if not match : return [ 'date' ] headers_string = match . group ( 1 ) return headers_string . split ( )
Returns a list of headers fields to sign .
60,064
def header_canonical ( self , header_name ) : header_name = header_name . lower ( ) if header_name == 'content-type' : return 'CONTENT-TYPE' elif header_name == 'content-length' : return 'CONTENT-LENGTH' return 'HTTP_%s' % header_name . replace ( '-' , '_' ) . upper ( )
Translate HTTP headers to Django header names .
60,065
def build_dict_to_sign ( self , request , signature_headers ) : d = { } for header in signature_headers : if header == '(request-target)' : continue d [ header ] = request . META . get ( self . header_canonical ( header ) ) return d
Build a dict with headers and values used in the signature .
60,066
def build_signature ( self , user_api_key , user_secret , request ) : path = request . get_full_path ( ) sent_signature = request . META . get ( self . header_canonical ( 'Authorization' ) ) signature_headers = self . get_headers_from_signature ( sent_signature ) unsigned = self . build_dict_to_sign ( request , signatu...
Return the signature for the request .
60,067
def camel_to_snake_case ( string ) : s = _1 . sub ( r'\1_\2' , string ) return _2 . sub ( r'\1_\2' , s ) . lower ( )
Converts string presented in camel case to snake case .
60,068
def url_assembler ( query_string , no_redirect = 0 , no_html = 0 , skip_disambig = 0 ) : params = [ ( 'q' , query_string . encode ( "utf-8" ) ) , ( 'format' , 'json' ) ] if no_redirect : params . append ( ( 'no_redirect' , 1 ) ) if no_html : params . append ( ( 'no_html' , 1 ) ) if skip_disambig : params . append ( ( '...
Assembler of parameters for building request query .
60,069
def query ( query_string , secure = False , container = 'namedtuple' , verbose = False , user_agent = api . USER_AGENT , no_redirect = False , no_html = False , skip_disambig = False ) : if container not in Hook . containers : raise exc . DuckDuckArgumentError ( "Argument 'container' must be one of the values: " "{0}" ...
Generates and sends a query to DuckDuckGo API .
60,070
def create ( type_dict , * type_parameters ) : assert len ( type_parameters ) == 1 klazz = TypeFactory . new ( type_dict , * type_parameters [ 0 ] ) assert isclass ( klazz ) assert issubclass ( klazz , Object ) return TypeMetaclass ( '%sList' % klazz . __name__ , ( ListContainer , ) , { 'TYPE' : klazz } )
Construct a List containing type klazz .
60,071
def load_file ( filename ) : "Runs the given scent.py file." mod_name = '.' . join ( os . path . basename ( filename ) . split ( '.' ) [ : - 1 ] ) mod_path = os . path . dirname ( filename ) if mod_name in sys . modules : del sys . modules [ mod_name ] if mod_path not in set ( sys . modules . keys ( ) ) : sys . path . ...
Runs the given scent . py file .
60,072
def new ( type_dict , type_factory , * type_parameters ) : type_tuple = ( type_factory , ) + type_parameters if type_tuple not in type_dict : factory = TypeFactory . get_factory ( type_factory ) reified_type = factory . create ( type_dict , * type_parameters ) type_dict [ type_tuple ] = reified_type return type_dict [ ...
Create a fully reified type from a type schema .
60,073
def wrap ( sig ) : if isclass ( sig ) and issubclass ( sig , Object ) : return TypeSignature ( sig ) elif isinstance ( sig , TypeSignature ) : return sig
Convert a Python class into a type signature .
60,074
def trigger_modified ( self , filepath ) : mod_time = self . _get_modified_time ( filepath ) if mod_time > self . _watched_files . get ( filepath , 0 ) : self . _trigger ( 'modified' , filepath ) self . _watched_files [ filepath ] = mod_time
Triggers modified event if the given filepath mod time is newer .
60,075
def trigger_created ( self , filepath ) : if os . path . exists ( filepath ) : self . _trigger ( 'created' , filepath )
Triggers created event if file exists .
60,076
def trigger_deleted ( self , filepath ) : if not os . path . exists ( filepath ) : self . _trigger ( 'deleted' , filepath )
Triggers deleted event if the flie doesn t exist .
60,077
def log ( self , * message ) : if self . _logger is None : return s = " " . join ( [ str ( m ) for m in message ] ) self . _logger . write ( s + '\n' ) self . _logger . flush ( )
Logs a messate to a defined io stream if available .
60,078
def in_repo ( self , filepath ) : filepath = set ( filepath . replace ( '\\' , '/' ) . split ( '/' ) ) for p in ( '.git' , '.hg' , '.svn' , '.cvs' , '.bzr' ) : if p in filepath : return True return False
This excludes repository directories because they cause some exceptions occationally .
60,079
def _modify_event ( self , event_name , method , func ) : if event_name not in self . ALL_EVENTS : raise TypeError ( ( 'event_name ("%s") can only be one of the ' 'following: %s' ) % ( event_name , repr ( self . ALL_EVENTS ) ) ) if not isinstance ( func , collections . Callable ) : raise TypeError ( ( 'func must be cal...
Wrapper to call a list s method from one of the events
60,080
def _watch_file ( self , filepath , trigger_event = True ) : is_new = filepath not in self . _watched_files if trigger_event : if is_new : self . trigger_created ( filepath ) else : self . trigger_modified ( filepath ) try : self . _watched_files [ filepath ] = self . _get_modified_time ( filepath ) except OSError : re...
Adds the file s modified time into its internal watchlist .
60,081
def _unwatch_file ( self , filepath , trigger_event = True ) : if filepath not in self . _watched_files : return if trigger_event : self . trigger_deleted ( filepath ) del self . _watched_files [ filepath ]
Removes the file from the internal watchlist if exists .
60,082
def _is_modified ( self , filepath ) : if self . _is_new ( filepath ) : return False mtime = self . _get_modified_time ( filepath ) return self . _watched_files [ filepath ] < mtime
Returns True if the file has been modified since last seen . Will return False if the file has not been seen before .
60,083
def loop ( self , sleep_time = 1 , callback = None ) : self . log ( "No supported libraries found: using polling-method." ) self . _running = True self . trigger_init ( ) self . _scan ( trigger = False ) if self . _warn : print ( ) while self . _running : self . _scan ( ) if isinstance ( callback , collections . Callab...
Goes into a blocking IO loop . If polling is used the sleep_time is the interval in seconds between polls .
60,084
def run ( sniffer_instance = None , wait_time = 0.5 , clear = True , args = ( ) , debug = False ) : if sniffer_instance is None : sniffer_instance = ScentSniffer ( ) if debug : scanner = Scanner ( sniffer_instance . watch_paths , scent = sniffer_instance . scent , logger = sys . stdout ) else : scanner = Scanner ( snif...
Runs the auto tester loop . Internally the runner instanciates the sniffer_cls and scanner class .
60,085
def main ( sniffer_instance = None , test_args = ( ) , progname = sys . argv [ 0 ] , args = sys . argv [ 1 : ] ) : parser = OptionParser ( version = "%prog " + __version__ ) parser . add_option ( '-w' , '--wait' , dest = "wait_time" , metavar = "TIME" , default = 0.5 , type = "float" , help = "Wait time, in seconds, be...
Runs the program . This is used when you want to run this program standalone .
60,086
def set_up ( self , test_args = ( ) , clear = True , debug = False ) : self . test_args = test_args self . debug , self . clear = debug , clear
Sets properties right before calling run .
60,087
def observe_scanner ( self , scanner ) : scanner . observe ( scanner . ALL_EVENTS , self . absorb_args ( self . modules . restore ) ) if self . clear : scanner . observe ( scanner . ALL_EVENTS , self . absorb_args ( self . clear_on_run ) ) scanner . observe ( scanner . ALL_EVENTS , self . absorb_args ( self . _run ) ) ...
Hooks into multiple events of a scanner .
60,088
def clear_on_run ( self , prefix = "Running Tests:" ) : if platform . system ( ) == 'Windows' : os . system ( 'cls' ) else : os . system ( 'clear' ) if prefix : print ( prefix )
Clears console before running the tests .
60,089
def run ( self ) : try : import nose arguments = [ sys . argv [ 0 ] ] + list ( self . test_args ) return nose . run ( argv = arguments ) except ImportError : print ( ) print ( "*** Nose library missing. Please install it. ***" ) print ( ) raise
Runs the unit test framework . Can be overridden to run anything . Returns True on passing and False on failure .
60,090
def run ( self ) : if not self . scent or len ( self . scent . runners ) == 0 : print ( "Did not find 'scent.py', running nose:" ) return super ( ScentSniffer , self ) . run ( ) else : print ( "Using scent:" ) arguments = [ sys . argv [ 0 ] ] + list ( self . test_args ) return self . scent . run ( arguments ) return Tr...
Runs the CWD s scent file .
60,091
def copy ( self ) : self_copy = self . dup ( ) self_copy . _scopes = copy . copy ( self . _scopes ) return self_copy
Return a copy of this object .
60,092
def bind ( self , * args , ** kw ) : new_self = self . copy ( ) new_scopes = Object . translate_to_scopes ( * args , ** kw ) new_self . _scopes = tuple ( reversed ( new_scopes ) ) + new_self . _scopes return new_self
Bind environment variables into this object s scope .
60,093
def check ( self ) : try : si , uninterp = self . interpolate ( ) except ( Object . CoercionError , MustacheParser . Uninterpolatable ) as e : return TypeCheck ( False , "Unable to interpolate: %s" % e ) return self . checker ( si )
Type check this object .
60,094
def restore ( self ) : sys = set ( self . _sys_modules . keys ( ) ) for mod_name in sys . difference ( self . _saved_modules ) : del self . _sys_modules [ mod_name ]
Unloads all modules that weren t loaded when save_modules was called .
60,095
def join ( cls , splits , * namables ) : isplits = [ ] unbound = [ ] for ref in splits : if isinstance ( ref , Ref ) : resolved = False for namable in namables : try : value = namable . find ( ref ) resolved = True break except Namable . Error : continue if resolved : isplits . append ( value ) else : isplits . append ...
Interpolate strings .
60,096
def outitem ( title , elems , indent = 4 ) : out ( title ) max_key_len = max ( len ( key ) for key , _ in elems ) + 1 for key , val in elems : key_spaced = ( '%s:' % key ) . ljust ( max_key_len ) out ( '%s%s %s' % ( indent * ' ' , key_spaced , val ) ) out ( )
Output formatted as list item .
60,097
def profile_dir ( name ) : if name : possible_path = Path ( name ) if possible_path . exists ( ) : return possible_path profiles = list ( read_profiles ( ) ) try : if name : profile = next ( p for p in profiles if p . name == name ) else : profile = next ( p for p in profiles if p . default ) except StopIteration : rai...
Return path to FF profile for a given profile name or path .
60,098
def formatter ( name , default = False ) : def decorator ( func ) : func . _output_format = dict ( name = name , default = default ) return func return decorator
Decorate a Feature method to register it as an output formatter .
60,099
def load_sqlite ( self , db , query = None , table = None , cls = None , column_map = None ) : if column_map is None : column_map = { } db_path = self . profile_path ( db , must_exist = True ) def obj_factory ( cursor , row ) : dict_ = { } for idx , col in enumerate ( cursor . description ) : new_name = column_map . ge...
Load data from sqlite db and return as list of specified objects .