idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
13,600
def complete_credit_note ( self , credit_note_it , complete_dict ) : return self . _create_put_request ( resource = CREDIT_NOTES , billomat_id = credit_note_it , command = COMPLETE , send_data = complete_dict )
Completes an credit note
63
6
13,601
def credit_note_pdf ( self , credit_note_it ) : return self . _create_get_request ( resource = CREDIT_NOTES , billomat_id = credit_note_it , command = PDF )
Opens a pdf of a credit note
50
8
13,602
def upload_credit_note_signature ( self , credit_note_it , signature_dict ) : return self . _create_put_request ( resource = CREDIT_NOTES , billomat_id = credit_note_it , send_data = signature_dict , command = UPLOAD_SIGNATURE )
Uploads a signature for the credit note
70
8
13,603
def get_items_of_credit_note_per_page ( self , credit_note_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = CREDIT_NOTE_ITEMS , per_page = per_page , page = page , params = { 'credit_note_id' : credit_note_id } , )
Get items of credit note per page
87
7
13,604
def get_all_items_of_credit_note ( self , credit_note_id ) : return self . _iterate_through_pages ( get_function = self . get_items_of_credit_note_per_page , resource = CREDIT_NOTE_ITEMS , * * { 'credit_note_id' : credit_note_id } )
Get all items of credit note This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
81
35
13,605
def update_credit_note_item ( self , credit_note_item_id , credit_note_item_dict ) : return self . _create_put_request ( resource = CREDIT_NOTE_ITEMS , billomat_id = credit_note_item_id , send_data = credit_note_item_dict )
Updates a credit note item
74
6
13,606
def get_comments_of_credit_note_per_page ( self , credit_note_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = CREDIT_NOTE_COMMENTS , per_page = per_page , page = page , params = { 'credit_note_id' : credit_note_id } , )
Get comments of credit note per page
87
7
13,607
def get_all_comments_of_credit_note ( self , credit_note_id ) : return self . _iterate_through_pages ( get_function = self . get_comments_of_credit_note_per_page , resource = CREDIT_NOTE_COMMENTS , * * { 'credit_note_id' : credit_note_id } )
Get all comments of credit note This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
81
35
13,608
def update_credit_note_comment ( self , credit_note_comment_id , credit_note_comment_dict ) : return self . _create_put_request ( resource = CREDIT_NOTE_COMMENTS , billomat_id = credit_note_comment_id , send_data = credit_note_comment_dict )
Updates a credit note comment
74
6
13,609
def get_payments_of_credit_note_per_page ( self , credit_note_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = CREDIT_NOTE_PAYMENTS , per_page = per_page , page = page , params = { 'credit_note_id' : credit_note_id } , )
Get payments of credit note per page
89
7
13,610
def get_all_payments_of_credit_note ( self , credit_note_id ) : return self . _iterate_through_pages ( get_function = self . get_payments_of_credit_note_per_page , resource = CREDIT_NOTE_PAYMENTS , * * { 'credit_note_id' : credit_note_id } )
Get all payments of credit note This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
84
35
13,611
def get_tags_of_credit_note_per_page ( self , credit_note_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = CREDIT_NOTE_TAGS , per_page = per_page , page = page , params = { 'credit_note_id' : credit_note_id } , )
Get tags of credit note per page
87
7
13,612
def get_confirmations_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = CONFIRMATIONS , per_page = per_page , page = page , params = params )
Get confirmations per page
63
5
13,613
def get_all_confirmations ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( self . get_confirmations_per_page , resource = CONFIRMATIONS , * * { 'params' : params } )
Get all confirmations This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
64
33
13,614
def update_confirmation ( self , confirmation_id , confirmation_dict ) : return self . _create_put_request ( resource = CONFIRMATIONS , billomat_id = confirmation_id , send_data = confirmation_dict )
Updates a confirmation
52
4
13,615
def complete_confirmation ( self , confirmation_id , complete_dict ) : return self . _create_put_request ( resource = CONFIRMATIONS , billomat_id = confirmation_id , command = COMPLETE , send_data = complete_dict )
Completes an confirmation
57
5
13,616
def confirmation_pdf ( self , confirmation_id ) : return self . _create_get_request ( resource = CONFIRMATIONS , billomat_id = confirmation_id , command = PDF )
Opens a pdf of a confirmation
43
7
13,617
def cancel_confirmation ( self , confirmation_id ) : return self . _create_put_request ( resource = CONFIRMATIONS , billomat_id = confirmation_id , command = CANCEL , )
Cancelles an confirmation
47
6
13,618
def uncancel_confirmation ( self , confirmation_id ) : return self . _create_put_request ( resource = CONFIRMATIONS , billomat_id = confirmation_id , command = UNCANCEL , )
Uncancelles an confirmation
48
7
13,619
def mark_confirmation_as_clear ( self , confirmation_id ) : return self . _create_put_request ( resource = CONFIRMATIONS , billomat_id = confirmation_id , command = CLEAR , )
Mark confirmation as clear
50
4
13,620
def mark_confirmation_as_unclear ( self , confirmation_id ) : return self . _create_put_request ( resource = CONFIRMATIONS , billomat_id = confirmation_id , command = UNCLEAR , )
Mark confirmation as unclear
52
4
13,621
def get_items_of_confirmation_per_page ( self , confirmation_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = CONFIRMATION_ITEMS , per_page = per_page , page = page , params = { 'confirmation_id' : confirmation_id } , )
Get items of confirmation per page
81
6
13,622
def get_all_items_of_confirmation ( self , confirmation_id ) : return self . _iterate_through_pages ( get_function = self . get_items_of_confirmation_per_page , resource = CONFIRMATION_ITEMS , * * { 'confirmation_id' : confirmation_id } )
Get all items of confirmation This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
74
34
13,623
def update_confirmation_item ( self , confirmation_item_id , confirmation_item_dict ) : return self . _create_put_request ( resource = CONFIRMATION_ITEMS , billomat_id = confirmation_item_id , send_data = confirmation_item_dict )
Updates a confirmation item
65
5
13,624
def get_comments_of_confirmation_per_page ( self , confirmation_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = CONFIRMATION_COMMENTS , per_page = per_page , page = page , params = { 'confirmation_id' : confirmation_id } , )
Get comments of confirmation per page
81
6
13,625
def get_all_comments_of_confirmation ( self , confirmation_id ) : return self . _iterate_through_pages ( get_function = self . get_comments_of_confirmation_per_page , resource = CONFIRMATION_COMMENTS , * * { 'confirmation_id' : confirmation_id } )
Get all comments of confirmation This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
74
34
13,626
def update_confirmation_comment ( self , confirmation_comment_id , confirmation_comment_dict ) : return self . _create_put_request ( resource = CONFIRMATION_COMMENTS , billomat_id = confirmation_comment_id , send_data = confirmation_comment_dict )
Updates a confirmation comment
65
5
13,627
def get_tags_of_confirmation_per_page ( self , confirmation_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = CONFIRMATION_TAGS , per_page = per_page , page = page , params = { 'confirmation_id' : confirmation_id } , )
Get tags of confirmation per page
81
6
13,628
def get_all_tags_of_confirmation ( self , confirmation_id ) : return self . _iterate_through_pages ( get_function = self . get_tags_of_confirmation_per_page , resource = CONFIRMATION_TAGS , * * { 'confirmation_id' : confirmation_id } )
Get all tags of confirmation This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
74
34
13,629
def get_reminders_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = REMINDERS , per_page = per_page , page = page , params = params )
Get reminders per page
61
4
13,630
def get_all_reminders ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( self . get_reminders_per_page , resource = REMINDERS , * * { 'params' : params } )
Get all reminders This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
61
32
13,631
def update_reminder ( self , reminder_id , reminder_dict ) : return self . _create_put_request ( resource = REMINDERS , billomat_id = reminder_id , send_data = reminder_dict )
Updates a reminder
51
4
13,632
def complete_reminder ( self , reminder_id , complete_dict ) : return self . _create_put_request ( resource = REMINDERS , billomat_id = reminder_id , command = COMPLETE , send_data = complete_dict )
Completes a reminder
56
5
13,633
def reminder_pdf ( self , reminder_id ) : return self . _create_get_request ( resource = REMINDERS , billomat_id = reminder_id , command = PDF )
Opens a pdf of a reminder
42
7
13,634
def get_items_of_reminder_per_page ( self , reminder_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = REMINDER_ITEMS , per_page = per_page , page = page , params = { 'reminder_id' : reminder_id } , )
Get items of reminder per page
80
6
13,635
def get_all_items_of_reminder ( self , reminder_id ) : return self . _iterate_through_pages ( get_function = self . get_items_of_reminder_per_page , resource = REMINDER_ITEMS , * * { 'reminder_id' : reminder_id } )
Get all items of reminder This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
73
34
13,636
def update_reminder_item ( self , reminder_item_id , reminder_item_dict ) : return self . _create_put_request ( resource = REMINDER_ITEMS , billomat_id = reminder_item_id , send_data = reminder_item_dict )
Updates a reminder item
64
5
13,637
def get_tags_of_reminder_per_page ( self , reminder_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = REMINDER_TAGS , per_page = per_page , page = page , params = { 'reminder_id' : reminder_id } , )
Get tags of reminder per page
80
6
13,638
def get_all_tags_of_reminder ( self , reminder_id ) : return self . _iterate_through_pages ( get_function = self . get_tags_of_reminder_per_page , resource = REMINDER_TAGS , * * { 'reminder_id' : reminder_id } )
Get all tags of reminder This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
73
34
13,639
def get_delivery_notes_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = DELIVERY_NOTES , per_page = per_page , page = page , params = params )
Get delivery notes per page
66
5
13,640
def get_all_delivery_notes ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( self . get_delivery_notes_per_page , resource = DELIVERY_NOTES , * * { 'params' : params } )
Get all delivery notes This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
68
33
13,641
def update_delivery_note ( self , delivery_note_id , delivery_note_dict ) : return self . _create_put_request ( resource = DELIVERY_NOTES , billomat_id = delivery_note_id , send_data = delivery_note_dict )
Updates a delivery note
64
5
13,642
def complete_delivery_note ( self , delivery_note_id , complete_dict ) : return self . _create_put_request ( resource = DELIVERY_NOTES , billomat_id = delivery_note_id , command = COMPLETE , send_data = complete_dict )
Completes an delivery note
65
6
13,643
def delivery_note_pdf ( self , delivery_note_id ) : return self . _create_get_request ( resource = DELIVERY_NOTES , billomat_id = delivery_note_id , command = PDF )
Opens a pdf of a delivery note
51
8
13,644
def get_items_of_delivery_note_per_page ( self , delivery_note_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = DELIVERY_NOTE_ITEMS , per_page = per_page , page = page , params = { 'delivery_note_id' : delivery_note_id } , )
Get items of delivery note per page
90
7
13,645
def get_all_items_of_delivery_note ( self , delivery_note_id ) : return self . _iterate_through_pages ( get_function = self . get_items_of_delivery_note_per_page , resource = DELIVERY_NOTE_ITEMS , * * { 'delivery_note_id' : delivery_note_id } )
Get all items of delivery note This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
85
35
13,646
def update_delivery_note_item ( self , delivery_note_item_id , delivery_note_item_dict ) : return self . _create_put_request ( resource = DELIVERY_NOTE_ITEMS , billomat_id = delivery_note_item_id , send_data = delivery_note_item_dict )
Updates a delivery note item
76
6
13,647
def get_comments_of_delivery_note_per_page ( self , delivery_note_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = DELIVERY_NOTE_COMMENTS , per_page = per_page , page = page , params = { 'delivery_note_id' : delivery_note_id } , )
Get comments of delivery note per page
90
7
13,648
def get_all_comments_of_delivery_note ( self , delivery_note_id ) : return self . _iterate_through_pages ( get_function = self . get_comments_of_delivery_note_per_page , resource = DELIVERY_NOTE_COMMENTS , * * { 'delivery_note_id' : delivery_note_id } )
Get all comments of delivery note This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
85
35
13,649
def update_delivery_note_comment ( self , delivery_note_comment_id , delivery_note_comment_dict ) : return self . _create_put_request ( resource = DELIVERY_NOTE_COMMENTS , billomat_id = delivery_note_comment_id , send_data = delivery_note_comment_dict )
Updates a delivery note comment
76
6
13,650
def get_tags_of_delivery_note_per_page ( self , delivery_note_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = DELIVERY_NOTE_TAGS , per_page = per_page , page = page , params = { 'delivery_note_id' : delivery_note_id } , )
Get tags of delivery note per page
90
7
13,651
def get_all_tags_of_delivery_note ( self , delivery_note_id ) : return self . _iterate_through_pages ( get_function = self . get_tags_of_delivery_note_per_page , resource = DELIVERY_NOTE_TAGS , * * { 'delivery_note_id' : delivery_note_id } )
Get all tags of delivery note This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
85
35
13,652
def get_letters_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = LETTERS , per_page = per_page , page = page , params = params )
Get letters per page
60
4
13,653
def get_all_letters ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( self . get_letters_per_page , resource = LETTERS , * * { 'params' : params } )
Get all letters This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
59
32
13,654
def update_letter ( self , letter_id , letter_dict ) : return self . _create_put_request ( resource = LETTERS , billomat_id = letter_id , send_data = letter_dict )
Updates a letter
50
4
13,655
def get_comments_of_letter_per_page ( self , letter_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = LETTER_COMMENTS , per_page = per_page , page = page , params = { 'letter_id' : letter_id } , )
Get comments of letter per page
77
6
13,656
def get_all_comments_of_letter ( self , letter_id ) : return self . _iterate_through_pages ( get_function = self . get_comments_of_letter_per_page , resource = LETTER_COMMENTS , * * { 'letter_id' : letter_id } )
Get all comments of letter This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
69
34
13,657
def update_letter_comment ( self , letter_comment_id , letter_comment_dict ) : return self . _create_put_request ( resource = LETTER_COMMENTS , billomat_id = letter_comment_id , send_data = letter_comment_dict )
Updates a letter comment
62
5
13,658
def get_tags_of_letter_per_page ( self , letter_id , per_page = 1000 , page = 1 ) : return self . _get_resource_per_page ( resource = LETTER_TAGS , per_page = per_page , page = page , params = { 'letter_id' : letter_id } , )
Get tags of letter per page
77
6
13,659
def get_all_tags_of_letter ( self , letter_id ) : return self . _iterate_through_pages ( get_function = self . get_tags_of_letter_per_page , resource = LETTER_TAGS , * * { 'letter_id' : letter_id } )
Get all tags of letter This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
69
34
13,660
def get_email_templates_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = EMAIL_TEMPLATES , per_page = per_page , page = page , params = params )
Get e - mail templates per page
68
7
13,661
def get_email_templates ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( self . get_email_templates_per_page , resource = EMAIL_TEMPLATES , * * { 'params' : params } )
Get all e - mail templates This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
68
35
13,662
def update_email_template ( self , template_id , template_dict ) : return self . _create_put_request ( resource = EMAIL_TEMPLATES , billomat_id = template_id , send_data = template_dict )
Updates a emailtemplate
57
5
13,663
def get_templates_per_page ( self , per_page = 1000 , page = 1 , params = None ) : return self . _get_resource_per_page ( resource = TEMPLATES , per_page = per_page , page = page , params = params )
Get templates per page
62
4
13,664
def get_all_templates ( self , params = None ) : if not params : params = { } return self . _iterate_through_pages ( self . get_templates_per_page , resource = TEMPLATES , * * { 'params' : params } )
Get all templates This will iterate over all pages until it gets all elements . So if the rate limit exceeded it will throw an Exception and you will get nothing
62
32
13,665
def update_template ( self , template_id , template_dict ) : return self . _create_put_request ( resource = TEMPLATES , billomat_id = template_id , send_data = template_dict )
Updates a template
51
4
13,666
def reverse_translate ( protein_seq , template_dna = None , leading_seq = None , trailing_seq = None , forbidden_seqs = ( ) , include_stop = True , manufacturer = None ) : if manufacturer == 'gen9' : forbidden_seqs += gen9 . reserved_restriction_sites leading_seq = restriction_sites . get ( leading_seq , leading_seq or '' ) trailing_seq = restriction_sites . get ( trailing_seq , trailing_seq or '' ) codon_list = make_codon_list ( protein_seq , template_dna , include_stop ) sanitize_codon_list ( codon_list , forbidden_seqs ) dna_seq = leading_seq + '' . join ( codon_list ) + trailing_seq if manufacturer == 'gen9' : gen9 . apply_quality_control_checks ( dna_seq ) return dna_seq
Generate a well - behaved DNA sequence from the given protein sequence . If a template DNA sequence is specified the returned DNA sequence will be as similar to it as possible . Any given restriction sites will not be present in the sequence . And finally the given leading and trailing sequences will be appropriately concatenated .
205
61
13,667
def make_codon_list ( protein_seq , template_dna = None , include_stop = True ) : codon_list = [ ] if template_dna is None : template_dna = [ ] # Reverse translate each codon, preferring (in order): # 1. The codon with the most similarity to the template codon. # 2. The codon with the highest natural usage. for i , res in enumerate ( protein_seq . upper ( ) ) : try : template_codon = template_dna [ 3 * i : 3 * i + 3 ] except IndexError : template_codon = '---' # Already sorted by natural codon usage possible_codons = dna . ecoli_reverse_translate [ res ] # Sort by similarity. Note that this is a stable sort. possible_codons . sort ( key = lambda x : dna . num_mutations ( x , template_codon ) ) # Pick the best codon. codon_list . append ( possible_codons [ 0 ] ) # Make sure the sequence ends with a stop codon. last_codon = codon_list [ - 1 ] stop_codons = dna . ecoli_reverse_translate [ '.' ] if include_stop and last_codon not in stop_codons : codon_list . append ( stop_codons [ 0 ] ) return codon_list
Return a list of codons that would be translated to the given protein sequence . Codons are picked first to minimize the mutations relative to a template DNA sequence and second to prefer optimal codons .
310
39
13,668
def sanitize_codon_list ( codon_list , forbidden_seqs = ( ) ) : # Unit test missing for: # Homopolymer fixing for codon in codon_list : if len ( codon ) != 3 : raise ValueError ( "Codons must have exactly 3 bases: '{}'" . format ( codon ) ) # Compile a collection of all the sequences we don't want to appear in the # gene. This includes the given restriction sites and their reverse # complements, plus any homopolymers above a pre-defined length. bad_seqs = set ( ) bad_seqs . union ( restriction_sites . get ( seq , seq ) for seq in forbidden_seqs ) bad_seqs . union ( dna . reverse_complement ( seq ) for seq in bad_seqs ) bad_seqs . union ( base * ( gen9 . homopolymer_max_lengths [ base ] + 1 ) for base in dna . dna_bases ) bad_seqs = [ dna . dna_to_re ( bs ) for bs in bad_seqs ] # Remove every bad sequence from the gene by making silent mutations to the # codon list. num_corrections = 0 for bad_seq in bad_seqs : while remove_bad_sequence ( codon_list , bad_seq , bad_seqs ) : num_corrections += 1 return num_corrections
Make silent mutations to the given codon lists to remove any undesirable sequences that are present within it . Undesirable sequences include restriction sites which may be optionally specified as a second argument and homopolymers above a pre - defined length . The return value is the number of corrections made to the codon list .
315
62
13,669
def remove_bad_sequence ( codon_list , bad_seq , bad_seqs ) : gene_seq = '' . join ( codon_list ) problem = bad_seq . search ( gene_seq ) if not problem : return False bs_start_codon = problem . start ( ) // 3 bs_end_codon = problem . end ( ) // 3 for i in range ( bs_start_codon , bs_end_codon ) : problem_codon = codon_list [ i ] amino_acid = translate_dna ( problem_codon ) alternate_codons = [ codon for codon in dna . ecoli_reverse_translate [ amino_acid ] if codon != problem_codon ] for alternate_codon in alternate_codons : codon_list [ i ] = alternate_codon if problem_with_codon ( i , codon_list , bad_seqs ) : codon_list [ i ] = problem_codon else : return True raise RuntimeError ( "Could not remove bad sequence '{}' from gene." . format ( bs ) )
Make a silent mutation to the given codon list to remove the first instance of the given bad sequence found in the gene sequence . If the bad sequence isn t found nothing happens and the function returns false . Otherwise the function returns true . You can use these return values to easily write a loop totally purges the bad sequence from the codon list . Both the specific bad sequence in question and the list of all bad sequences are expected to be regular expressions .
252
91
13,670
def problem_with_codon ( codon_index , codon_list , bad_seqs ) : base_1 = 3 * codon_index base_3 = 3 * codon_index + 2 gene_seq = '' . join ( codon_list ) for bad_seq in bad_seqs : problem = bad_seq . search ( gene_seq ) if problem and problem . start ( ) < base_3 and problem . end ( ) > base_1 : return True return False
Return true if the given codon overlaps with a bad sequence .
108
14
13,671
def sequences_from_fasta ( path ) : from Bio import SeqIO return { x . description : x . seq for x in SeqIO . parse ( path , 'fasta' ) }
Extract multiple sequences from a FASTA file .
43
11
13,672
def write_sequences_to_fasta ( path , seqs ) : from Bio import SeqIO from Bio . Seq import Seq from Bio . SeqRecord import SeqRecord path = Path ( path ) records = [ ] for id , seq in seqs . items ( ) : record = SeqRecord ( Seq ( seq ) , id = id , description = '' ) records . append ( record ) SeqIO . write ( records , str ( path ) , 'fasta' )
Create a FASTA file listing the given sequences .
107
11
13,673
def write_sequences_to_xlsx ( path , seqs ) : from openpyxl import Workbook wb = Workbook ( ) ws = wb . active for row , id in enumerate ( seqs , 1 ) : ws . cell ( row , 1 ) . value = id ws . cell ( row , 2 ) . value = seqs [ id ] wb . save ( path )
Create a XLSX file listing the given sequences .
91
11
13,674
def add_node ( self , node ) : nodes = [ n for n in self . nodes ( ) if not isinstance ( n , Source ) ] num_agents = len ( nodes ) curr_generation = int ( ( num_agents - 1 ) / float ( self . generation_size ) ) node . generation = curr_generation if curr_generation == 0 : if self . initial_source : source = min ( self . nodes ( type = Source ) , key = attrgetter ( 'creation_time' ) ) source . connect ( whom = node ) source . transmit ( to_whom = node ) else : prev_agents = Node . query . filter_by ( failed = False , network_id = self . id , generation = ( curr_generation - 1 ) ) . all ( ) prev_fits = [ p . fitness for p in prev_agents ] prev_probs = [ ( f / ( 1.0 * sum ( prev_fits ) ) ) for f in prev_fits ] rnd = random . random ( ) temp = 0.0 for i , probability in enumerate ( prev_probs ) : temp += probability if temp > rnd : parent = prev_agents [ i ] break parent . connect ( whom = node ) parent . transmit ( to_whom = node )
Link the agent to a random member of the previous generation .
282
12
13,675
def add_node ( self , node ) : nodes = self . nodes ( ) # Start with a core of m0 fully-connected agents... if len ( nodes ) <= self . m0 : other_nodes = [ n for n in nodes if n . id != node . id ] for n in other_nodes : node . connect ( direction = "both" , whom = n ) # ...then add newcomers one by one with preferential attachment. else : for idx_newvector in xrange ( self . m ) : these_nodes = [ n for n in nodes if ( n . id != node . id and not n . is_connected ( direction = "either" , whom = node ) ) ] outdegrees = [ len ( n . vectors ( direction = "outgoing" ) ) for n in these_nodes ] # Select a member using preferential attachment ps = [ ( d / ( 1.0 * sum ( outdegrees ) ) ) for d in outdegrees ] rnd = random . random ( ) * sum ( ps ) cur = 0.0 for i , p in enumerate ( ps ) : cur += p if rnd < cur : vector_to = these_nodes [ i ] # Create vector from newcomer to selected member and back node . connect ( direction = "both" , whom = vector_to )
Add newcomers one by one using linear preferential attachment .
287
10
13,676
def docker_py_dict ( self ) : return { 'image' : self . image , 'command' : self . cmd , 'hostname' : self . hostname , 'user' : self . user , 'detach' : self . detach , 'stdin_open' : self . open_stdin , 'tty' : self . tty , 'ports' : self . exposed_ports , 'environment' : self . env , 'volumes' : self . volumes , 'network_disabled' : self . network_disabled , 'entrypoint' : self . entry_point , 'working_dir' : self . working_dir , 'domainname' : self . domain_name , 'labels' : self . labels }
Convert object to match valid docker - py properties .
160
11
13,677
def get_person_by_regid ( self , regid ) : if not self . valid_uwregid ( regid ) : raise InvalidRegID ( regid ) url = "{}/{}/full.json" . format ( PERSON_PREFIX , regid . upper ( ) ) response = DAO . getURL ( url , { "Accept" : "application/json" } ) if response . status != 200 : raise DataFailureException ( url , response . status , response . data ) return self . _person_from_json ( response . data )
Returns a restclients . Person object for the given regid . If the regid isn t found or if there is an error communicating with the PWS a DataFailureException will be thrown .
125
40
13,678
def get_person_by_netid ( self , netid ) : if not self . valid_uwnetid ( netid ) : raise InvalidNetID ( netid ) url = "{}/{}/full.json" . format ( PERSON_PREFIX , netid . lower ( ) ) response = DAO . getURL ( url , { "Accept" : "application/json" } ) if response . status != 200 : raise DataFailureException ( url , response . status , response . data ) return self . _person_from_json ( response . data )
Returns a restclients . Person object for the given netid . If the netid isn t found or if there is an error communicating with the PWS a DataFailureException will be thrown .
125
40
13,679
def get_person_by_employee_id ( self , employee_id ) : if not self . valid_employee_id ( employee_id ) : raise InvalidEmployeeID ( employee_id ) url = "{}.json?{}" . format ( PERSON_PREFIX , urlencode ( { "employee_id" : employee_id } ) ) response = DAO . getURL ( url , { "Accept" : "application/json" } ) if response . status != 200 : raise DataFailureException ( url , response . status , response . data ) # Search does not return a full person resource data = json . loads ( response . data ) if not len ( data [ "Persons" ] ) : raise DataFailureException ( url , 404 , "No person found" ) regid = data [ "Persons" ] [ 0 ] [ "PersonURI" ] [ "UWRegID" ] return self . get_person_by_regid ( regid )
Returns a restclients . Person object for the given employee id . If the employee id isn t found or if there is an error communicating with the PWS a DataFailureException will be thrown .
213
40
13,680
def get_person_by_student_number ( self , student_number ) : if not self . valid_student_number ( student_number ) : raise InvalidStudentNumber ( student_number ) url = "{}.json?{}" . format ( PERSON_PREFIX , urlencode ( { "student_number" : student_number } ) ) response = DAO . getURL ( url , { "Accept" : "application/json" } ) if response . status != 200 : raise DataFailureException ( url , response . status , response . data ) # Search does not return a full person resource data = json . loads ( response . data ) if not len ( data [ "Persons" ] ) : raise DataFailureException ( url , 404 , "No person found" ) regid = data [ "Persons" ] [ 0 ] [ "PersonURI" ] [ "UWRegID" ] return self . get_person_by_regid ( regid )
Returns a restclients . Person object for the given student number . If the student number isn t found or if there is an error communicating with the PWS a DataFailureException will be thrown .
209
40
13,681
def get_person_by_prox_rfid ( self , prox_rfid ) : if not self . valid_prox_rfid ( prox_rfid ) : raise InvalidProxRFID ( prox_rfid ) url = "{}.json?{}" . format ( CARD_PREFIX , urlencode ( { "prox_rfid" : prox_rfid } ) ) response = DAO . getURL ( url , { "Accept" : "application/json" } ) if response . status != 200 : raise DataFailureException ( url , response . status , response . data ) data = json . loads ( response . data ) if not len ( data [ "Cards" ] ) : raise DataFailureException ( url , 404 , "No card found" ) regid = data [ "Cards" ] [ 0 ] [ "RegID" ] return self . get_person_by_regid ( regid )
Returns a restclients . Person object for the given rfid . If the rfid isn t found or if there is an error communicating with the IdCard WS a DataFailureException will be thrown .
204
43
13,682
def get_entity_by_regid ( self , regid ) : if not self . valid_uwregid ( regid ) : raise InvalidRegID ( regid ) url = "{}/{}.json" . format ( ENTITY_PREFIX , regid . upper ( ) ) response = DAO . getURL ( url , { "Accept" : "application/json" } ) if response . status != 200 : raise DataFailureException ( url , response . status , response . data ) return self . _entity_from_json ( response . data )
Returns a restclients . Entity object for the given regid . If the regid isn t found or if there is an error communicating with the PWS a DataFailureException will be thrown .
123
40
13,683
def get_entity_by_netid ( self , netid ) : if not self . valid_uwnetid ( netid ) : raise InvalidNetID ( netid ) url = "{}/{}.json" . format ( ENTITY_PREFIX , netid . lower ( ) ) response = DAO . getURL ( url , { "Accept" : "application/json" } ) if response . status != 200 : raise DataFailureException ( url , response . status , response . data ) return self . _entity_from_json ( response . data )
Returns a restclients . Entity object for the given netid . If the netid isn t found or if there is an error communicating with the PWS a DataFailureException will be thrown .
123
40
13,684
def generate_identifier ( sender , instance , * * kwargs ) : identifier = Concept . create_identifier ( instance . query ) qs = Concept . objects . filter ( identifier = identifier , lang = instance . lang ) if instance . pk : qs = qs . exclude ( pk = instance . pk ) if qs . count ( ) > 0 : raise ValueError ( "Concept identifier conflict" ) instance . identifier = identifier
Generate and set identifier of concept before saving object to DB
97
12
13,685
def get_concept_item_mapping ( self , concepts = None , lang = None ) : if concepts is None : concepts = self . filter ( active = True ) if lang is not None : concepts = concepts . filter ( lang = lang ) if lang is None : languages = set ( [ concept . lang for concept in concepts ] ) if len ( languages ) > 1 : raise Exception ( 'Concepts has multiple languages' ) lang = list ( languages ) [ 0 ] item_lists = Item . objects . filter_all_reachable_leaves_many ( [ json . loads ( concept . query ) for concept in concepts ] , lang ) return dict ( zip ( [ c . pk for c in concepts ] , item_lists ) )
Get mapping of concepts to items belonging to concept .
158
10
13,686
def get_item_concept_mapping ( self , lang ) : concepts = self . filter ( active = True , lang = lang ) return group_keys_by_value_lists ( Concept . objects . get_concept_item_mapping ( concepts , lang ) )
Get mapping of items_ids to concepts containing these items
58
11
13,687
def get_concepts_to_recalculate ( self , users , lang , concepts = None ) : only_one_user = False if not isinstance ( users , list ) : only_one_user = True users = [ users ] mapping = self . get_item_concept_mapping ( lang ) current_user_stats = defaultdict ( lambda : { } ) user_stats_qs = UserStat . objects . filter ( user__in = users , stat = "answer_count" ) # we need only one type if concepts is not None : user_stats_qs = user_stats_qs . filter ( concept__in = concepts ) for user_stat in user_stats_qs : current_user_stats [ user_stat . user_id ] [ user_stat . concept_id ] = user_stat concepts_to_recalculate = defaultdict ( lambda : set ( ) ) for user , item , time in Answer . objects . filter ( user__in = users ) . values_list ( "user_id" , "item" ) . annotate ( Max ( "time" ) ) : if item not in mapping : # in reality this should by corner case, so it is efficient to not filter Answers continue # item is not in concept time_expiration_lower_bound = get_config ( 'proso_models' , 'knowledge_overview.time_shift_hours' , default = 4 ) time_expiration_factor = get_config ( 'proso_models' , 'knowledge_overview.time_expiration_factor' , default = 2 ) for concept in mapping [ item ] : if user in current_user_stats and concept in current_user_stats [ user ] and current_user_stats [ user ] [ concept ] . time > time : if not self . has_time_expired ( current_user_stats [ user ] [ concept ] . time , time , time_expiration_lower_bound , time_expiration_factor ) : continue # cache is up to date if concepts is None or concept in ( [ c . pk for c in concepts ] if type ( concepts [ 0 ] ) == Concept else Concept ) : concepts_to_recalculate [ user ] . add ( concept ) if only_one_user : return concepts_to_recalculate [ users [ 0 ] ] return concepts_to_recalculate
Get concept which have same changes and have to be recalculated
520
12
13,688
def recalculate_concepts ( self , concepts , lang = None ) : if len ( concepts ) == 0 : return if lang is None : items = Concept . objects . get_concept_item_mapping ( concepts = Concept . objects . filter ( pk__in = set ( flatten ( concepts . values ( ) ) ) ) ) else : items = Concept . objects . get_concept_item_mapping ( lang = lang ) environment = get_environment ( ) mastery_threshold = get_mastery_trashold ( ) for user , concepts in concepts . items ( ) : all_items = list ( set ( flatten ( [ items [ c ] for c in concepts ] ) ) ) answer_counts = environment . number_of_answers_more_items ( all_items , user ) correct_answer_counts = environment . number_of_correct_answers_more_items ( all_items , user ) predictions = dict ( list ( zip ( all_items , get_predictive_model ( ) . predict_more_items ( environment , user , all_items , time = get_time_for_knowledge_overview ( ) ) ) ) ) new_user_stats = [ ] stats_to_delete_condition = Q ( ) for concept in concepts : answer_aggregates = Answer . objects . filter ( user = user , item__in = items [ concept ] ) . aggregate ( time_spent = Sum ( "response_time" ) , sessions = Count ( "session" , True ) , time_first = Min ( "time" ) , time_last = Max ( "time" ) , ) stats = { "answer_count" : sum ( answer_counts [ i ] for i in items [ concept ] ) , "correct_answer_count" : sum ( correct_answer_counts [ i ] for i in items [ concept ] ) , "item_count" : len ( items [ concept ] ) , "practiced_items_count" : sum ( [ answer_counts [ i ] > 0 for i in items [ concept ] ] ) , "mastered_items_count" : sum ( [ predictions [ i ] >= mastery_threshold for i in items [ concept ] ] ) , "prediction" : sum ( [ predictions [ i ] for i in items [ concept ] ] ) / len ( items [ concept ] ) , "time_spent" : answer_aggregates [ "time_spent" ] / 1000 , "session_count" : answer_aggregates [ "sessions" ] , "time_first" : answer_aggregates [ "time_first" ] . timestamp ( ) , "time_last" : answer_aggregates [ "time_last" ] . timestamp ( ) , } stats_to_delete_condition |= Q ( user = user , concept = concept ) for stat_name , value in stats . items ( ) : new_user_stats . append ( UserStat ( user_id = user , concept_id = concept , stat = stat_name , value = value ) ) self . filter ( stats_to_delete_condition ) . delete ( ) self . bulk_create ( new_user_stats )
Recalculated given concepts for given users
702
8
13,689
def get_user_stats ( self , users , lang = None , concepts = None , since = None , recalculate = True ) : only_one_user = False if not isinstance ( users , list ) : users = [ users ] only_one_user = True if recalculate : if lang is None : raise ValueError ( 'Recalculation without lang is not supported.' ) time_start = time_lib ( ) concepts_to_recalculate = Concept . objects . get_concepts_to_recalculate ( users , lang , concepts ) LOGGER . debug ( "user_stats - getting identifying concepts to recalculate: %ss" , ( time_lib ( ) - time_start ) ) time_start = time_lib ( ) self . recalculate_concepts ( concepts_to_recalculate , lang ) LOGGER . debug ( "user_stats - recalculating concepts: %ss" , ( time_lib ( ) - time_start ) ) qs = self . prepare_related ( ) . filter ( user__in = users , concept__active = True ) if concepts is not None : qs = qs . filter ( concept__in = concepts ) if lang is not None : qs = qs . filter ( concept__lang = lang ) if since is not None : qs = qs . filter ( time__gte = since ) data = defaultdict ( lambda : defaultdict ( lambda : { } ) ) for user_stat in qs : data [ user_stat . user_id ] [ user_stat . concept . identifier ] [ user_stat . stat ] = user_stat . value if only_one_user : return data [ users [ 0 ] . pk if type ( users [ 0 ] ) == User else users [ 0 ] ] return data
Finds all UserStats of given concepts and users . Recompute UserStats if necessary
395
18
13,690
def locked_execute ( self , sql , parameters = None , cursorClass = DictCursor , quiet = False ) : return self . execute ( sql , parameters , cursorClass , quiet = quiet , locked = True )
We are lock - happy here but SQL performance is not currently an issue daemon - side .
46
18
13,691
def execute ( self , sql , parameters = None , cursorClass = DictCursor , quiet = False , locked = False , do_commit = True ) : i = 0 errcode = 0 caughte = None cursor = None if sql . find ( ";" ) != - 1 or sql . find ( "\\G" ) != - 1 : # Catches some injections raise Exception ( "The SQL command '%s' contains a semi-colon or \\G. This is a potential SQL injection." % sql ) while i < self . numTries : i += 1 try : assert ( not ( self . connection ) or not ( self . connection . open ) ) self . _get_connection ( cursorClass ) cursor = self . connection . cursor ( ) if locked : cursor . execute ( self . lockstring ) self . locked = True if parameters : errcode = cursor . execute ( sql , parameters ) else : errcode = cursor . execute ( sql ) self . lastrowid = int ( cursor . lastrowid ) if do_commit and self . isInnoDB : self . connection . commit ( ) results = cursor . fetchall ( ) if locked : cursor . execute ( self . unlockstring ) self . locked = False cursor . close ( ) self . _close_connection ( ) return results except MySQLdb . OperationalError , e : if cursor : if self . locked : cursor . execute ( self . unlockstring ) self . locked = False cursor . close ( ) self . _close_connection ( ) caughte = str ( e ) errcode = e [ 0 ] continue except Exception , e : if cursor : if self . locked : cursor . execute ( self . unlockstring ) self . locked = False cursor . close ( ) self . _close_connection ( ) caughte = str ( e ) traceback . print_exc ( ) break sleep ( 0.2 ) if not quiet : sys . stderr . write ( "\nSQL execution error in query %s at %s:" % ( sql , datetime . now ( ) . strftime ( "%Y-%m-%d %H:%M:%S" ) ) ) sys . stderr . write ( "\nErrorcode/Error: %d - '%s'.\n" % ( errcode , str ( caughte ) ) ) sys . stderr . flush ( ) raise MySQLdb . OperationalError ( caughte )
Execute SQL query . This uses DictCursor by default .
523
14
13,692
def insertDict ( self , tblname , d , fields = None ) : if fields == None : fields = sorted ( d . keys ( ) ) values = None try : SQL = 'INSERT INTO %s (%s) VALUES (%s)' % ( tblname , join ( fields , ", " ) , join ( [ '%s' for x in range ( len ( fields ) ) ] , ',' ) ) values = tuple ( [ d [ k ] for k in fields ] ) self . locked_execute ( SQL , parameters = values ) except Exception , e : if SQL and values : sys . stderr . write ( "\nSQL execution error in query '%s' %% %s at %s:" % ( SQL , values , datetime . now ( ) . strftime ( "%Y-%m-%d %H:%M:%S" ) ) ) sys . stderr . write ( "\nError: '%s'.\n" % ( str ( e ) ) ) sys . stderr . flush ( ) raise Exception ( "Error occurred during database insertion: '%s'." % str ( e ) )
Simple function for inserting a dictionary whose keys match the fieldnames of tblname .
246
17
13,693
def callproc ( self , procname , parameters = ( ) , cursorClass = DictCursor , quiet = False ) : i = 0 errcode = 0 caughte = None while i < self . numTries : i += 1 try : cursor = self . connection . cursor ( cursorClass ) if type ( parameters ) != type ( ( ) ) : parameters = ( parameters , ) errcode = cursor . callproc ( procname , parameters ) results = cursor . fetchall ( ) self . lastrowid = int ( cursor . lastrowid ) cursor . close ( ) return results except MySQLdb . OperationalError , e : errcode = e [ 0 ] self . connection . ping ( ) caughte = e continue except : traceback . print_exc ( ) break if not quiet : sys . stderr . write ( "\nSQL execution error call stored procedure %s at %s:" % ( procname , datetime . now ( ) . strftime ( "%Y-%m-%d %H:%M:%S" ) ) ) sys . stderr . write ( "\nErrorcode/Error: %d - '%s'.\n" % ( errcode , str ( caughte ) ) ) sys . stderr . flush ( ) raise MySQLdb . OperationalError ( caughte )
Calls a MySQL stored procedure procname . This uses DictCursor by default .
289
18
13,694
def execQuery ( self , sql , parameters = None , cursorClass = MySQLdb . cursors . Cursor , InnoDB = False ) : i = 0 errcode = 0 caughte = None while i < self . numTries : i += 1 try : cursor = self . connection . cursor ( cursorClass ) if parameters : errcode = cursor . execute ( sql , parameters ) else : errcode = cursor . execute ( sql ) if InnoDB : self . connection . commit ( ) results = cursor . fetchall ( ) self . lastrowid = int ( cursor . lastrowid ) cursor . close ( ) return results except MySQLdb . OperationalError , e : errcode = e [ 0 ] # errcodes of 2006 or 2013 usually indicate a dropped connection # errcode 1100 is an error with table locking print ( e ) self . connection . ping ( True ) caughte = e continue except : traceback . print_exc ( ) break sys . stderr . write ( "\nSQL execution error in query at %s:" % datetime . now ( ) . strftime ( "%Y-%m-%d %H:%M:%S" ) ) sys . stderr . write ( "\n %s." % sql ) sys . stderr . flush ( ) sys . stderr . write ( "\nErrorcode: '%s'.\n" % ( str ( caughte ) ) ) sys . stderr . flush ( ) raise MySQLdb . OperationalError ( caughte )
Execute SQL query .
333
5
13,695
def _getFieldsInDB ( self , tablename ) : SQL = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME="%s"' % tablename array_data = self . execQuery ( SQL ) return [ x [ 0 ] for x in array_data ]
get all the fields from a specific table
69
8
13,696
def _is_ascii_stl ( first_bytes ) : is_ascii = False if 'solid' in first_bytes . decode ( "utf-8" ) . lower ( ) : is_ascii = True return is_ascii
Determine if this is an ASCII based data stream simply by checking the bytes for the word solid .
58
21
13,697
def _is_binary_stl ( data ) : is_bin = False start_byte = 0 end_byte = 80 _ = data [ start_byte : end_byte ] # header data start_byte = end_byte end_byte += 4 facet_count = struct . unpack ( 'I' , data [ start_byte : end_byte ] ) [ 0 ] if facet_count > 0 : is_bin = True return is_bin
Determine if this is a binary file through unpacking the first value after the 80th character and testing whether this value is greater than zero . This indicates the number of facets in the file . Could possibly extend this to check that the remaining number of bytes is divisible by 50 .
97
58
13,698
def process_bind_param ( self , obj , dialect ) : value = obj or { } if isinstance ( obj , flask_cloudy . Object ) : value = { } for k in self . DEFAULT_KEYS : value [ k ] = getattr ( obj , k ) return super ( self . __class__ , self ) . process_bind_param ( value , dialect )
Get a flask_cloudy . Object and save it as a dict
83
14
13,699
def create_tasks ( task_coro , addrs , * args , flatten = True , * * kwargs ) : tasks = [ ] for agent_addr in addrs : task = asyncio . ensure_future ( task_coro ( agent_addr , * args , * * kwargs ) ) tasks . append ( task ) return wait_tasks ( tasks , flatten )
Create and schedule a set of asynchronous tasks .
86
9