idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
12,200 | def estimategaps ( args ) : p = OptionParser ( estimategaps . __doc__ ) p . add_option ( "--minsize" , default = 100 , type = "int" , help = "Minimum gap size" ) p . add_option ( "--maxsize" , default = 500000 , type = "int" , help = "Maximum gap size" ) p . add_option ( "--links" , default = 10 , type = "int" , help =... | %prog estimategaps input . bed |
12,201 | def merge ( args ) : p = OptionParser ( merge . __doc__ ) p . add_option ( "-w" , "--weightsfile" , default = "weights.txt" , help = "Write weights to file" ) p . set_outfile ( "out.bed" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) maps = args outfile = opts . outf... | %prog merge map1 map2 map3 ... |
12,202 | def mergebed ( args ) : p = OptionParser ( mergebed . __doc__ ) p . add_option ( "-w" , "--weightsfile" , default = "weights.txt" , help = "Write weights to file" ) p . set_outfile ( "out.bed" ) opts , args = p . parse_args ( args ) if len ( args ) < 1 : sys . exit ( not p . print_help ( ) ) maps = args outfile = opts ... | %prog mergebed map1 . bed map2 . bed map3 . bed ... |
12,203 | def summary ( args ) : p = OptionParser ( summary . __doc__ ) p . set_table ( sep = "|" , align = True ) p . set_outfile ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) inputbed , scaffolds = args pf = inputbed . rsplit ( "." , 1 ) [ 0 ] mapbed = pf + ".bed" chr_ag... | %prog summary input . bed scaffolds . fasta |
12,204 | def build ( args ) : p = OptionParser ( build . __doc__ ) p . add_option ( "--cleanup" , default = False , action = "store_true" , help = "Clean up bulky FASTA files, useful for plotting" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) inputbed , scaffolds = args pf ... | %prog build input . bed scaffolds . fasta |
12,205 | def plotall ( xargs ) : p = OptionParser ( plotall . __doc__ ) add_allmaps_plot_options ( p ) opts , args , iopts = p . set_image_options ( xargs , figsize = "10x6" ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) inputbed , = args pf = inputbed . rsplit ( "." , 1 ) [ 0 ] agpfile = pf + ".chr.agp" agp = A... | %prog plotall input . bed |
12,206 | def get_orientation ( self , si , sj ) : if not si or not sj : return 0 a = lms ( si + sj ) b = lms ( sj + si ) c = lms ( si + sj [ : : - 1 ] ) d = lms ( sj [ : : - 1 ] + si ) return max ( a , b ) [ 0 ] - max ( c , d ) [ 0 ] | si sj are two number series . To compute whether these two series have same orientation or not . We combine them in the two orientation configurations and compute length of the longest monotonic series . |
12,207 | def fix_tour ( self , tour ) : scaffolds , oos = zip ( * tour ) keep = set ( ) for mlg in self . linkage_groups : lg = mlg . lg for s , o in tour : i = scaffolds . index ( s ) L = [ self . get_series ( lg , x , xo ) for x , xo in tour [ : i ] ] U = [ self . get_series ( lg , x , xo ) for x , xo in tour [ i + 1 : ] ] L ... | Test each scaffold if dropping does not decrease LMS . |
12,208 | def fix_orientation ( self , tour ) : orientations = dict ( tour ) scaffold_oo = defaultdict ( list ) scaffolds , oos = zip ( * tour ) for mlg in self . linkage_groups : lg = mlg . lg mapname = mlg . mapname for s , o in tour : i = scaffolds . index ( s ) L = [ self . get_series ( lg , x , xo ) for x , xo in tour [ : i... | Test each scaffold if flipping will increass longest monotonic chain length . |
12,209 | def spin ( self ) : for x in self . spinchars : self . string = self . msg + "...\t" + x + "\r" self . out . write ( self . string . encode ( 'utf-8' ) ) self . out . flush ( ) time . sleep ( self . waittime ) | Perform a single spin |
12,210 | def make_sequence ( seq , name = "S" ) : return [ "{}_{}_{}" . format ( name , i , x ) for i , x in enumerate ( seq ) ] | Make unique nodes for sequence graph . |
12,211 | def sequence_to_graph ( G , seq , color = 'black' ) : for x in seq : if x . endswith ( "_1" ) : G . node ( x , color = color , width = "0.1" , shape = "circle" , label = "" ) else : G . node ( x , color = color ) for a , b in pairwise ( seq ) : G . edge ( a , b , color = color ) | Automatically construct graph given a sequence of characters . |
12,212 | def zip_sequences ( G , allseqs , color = "white" ) : for s in zip ( * allseqs ) : groups = defaultdict ( list ) for x in s : part = x . split ( '_' , 1 ) [ 1 ] groups [ part ] . append ( x ) for part , g in groups . items ( ) : with G . subgraph ( name = "cluster_" + part ) as c : for x in g : c . node ( x ) c . attr ... | Fuse certain nodes together if they contain same data except for the sequence name . |
12,213 | def gallery ( args ) : from jcvi . apps . base import iglob from jcvi . utils . iter import grouper p = OptionParser ( gallery . __doc__ ) p . add_option ( "--columns" , default = 3 , type = "int" , help = "How many cells per row" ) p . add_option ( "--width" , default = 200 , type = "int" , help = "Image width" ) opts... | %prog gallery folder link_prefix |
12,214 | def links ( args ) : p = OptionParser ( links . __doc__ ) p . add_option ( "--img" , default = False , action = "store_true" , help = "Extract <img> tags [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) url , = args img = opts . img htmlfile = dow... | %prog links url |
12,215 | def unescape ( s , unicode_action = "replace" ) : import HTMLParser hp = HTMLParser . HTMLParser ( ) s = hp . unescape ( s ) s = s . encode ( 'ascii' , unicode_action ) s = s . replace ( "\n" , "" ) . strip ( ) return s | Unescape HTML strings and convert & ; etc . |
12,216 | def table ( args ) : import csv p = OptionParser ( table . __doc__ ) p . set_sep ( sep = "," ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) htmlfile , = args page = open ( htmlfile ) . read ( ) soup = BeautifulSoup ( page ) for i , tabl in enumerate ( soup . findAll... | %prog table page . html |
12,217 | def blast ( args ) : p = OptionParser ( blast . __doc__ ) p . add_option ( "--dist" , default = 100 , type = "int" , help = "Merge adjacent HSPs separated by [default: %default]" ) p . add_option ( "--db" , help = "Use a different database rather than UniVec_Core" ) opts , args = p . parse_args ( args ) if len ( args )... | %prog blast fastafile |
12,218 | def check_exists ( filename , oappend = False ) : if op . exists ( filename ) : if oappend : return oappend logging . error ( "`{0}` found, overwrite (Y/N)?" . format ( filename ) ) overwrite = ( raw_input ( ) == 'Y' ) else : overwrite = True return overwrite | Avoid overwriting some files accidentally . |
12,219 | def must_open ( filename , mode = "r" , checkexists = False , skipcheck = False , oappend = False ) : if isinstance ( filename , list ) : assert "r" in mode if filename [ 0 ] . endswith ( ( ".gz" , ".bz2" ) ) : filename = " " . join ( filename ) else : import fileinput return fileinput . input ( filename ) if filename ... | Accepts filename and returns filehandle . |
12,220 | def read_block ( handle , signal ) : signal_len = len ( signal ) it = ( x [ 1 ] for x in groupby ( handle , key = lambda row : row . strip ( ) [ : signal_len ] == signal ) ) found_signal = False for header in it : header = list ( header ) for h in header [ : - 1 ] : h = h . strip ( ) if h [ : signal_len ] != signal : c... | Useful for reading block - like file formats for example FASTA or OBO file such file usually startswith some signal and in - between the signals are a record |
12,221 | def get_number ( s , cast = int ) : import string d = "" . join ( x for x in str ( s ) if x in string . digits ) return cast ( d ) | Try to get a number out of a string and cast it . |
12,222 | def seqids ( args ) : p = OptionParser ( seqids . __doc__ ) p . add_option ( "--pad0" , default = 0 , help = "How many zeros to pad" ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) prefix , start , end = args pad0 = opts . pad0 start , end = int ( start ) , int ( end... | %prog seqids prefix start end |
12,223 | def pairwise ( args ) : from itertools import combinations p = OptionParser ( pairwise . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) idsfile , = args ids = SetFile ( idsfile ) ids = sorted ( ids ) fw = open ( idsfile + ".pairs" , "w" ) for a , b in combin... | %prog pairwise ids |
12,224 | def truncate ( args ) : p = OptionParser ( truncate . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) number , filename = args number = int ( number ) count = 0 f = open ( filename , "r+b" ) f . seek ( 0 , os . SEEK_END ) while f . tell ( ) > 0 : f . seek ( -... | %prog truncate linecount filename |
12,225 | def flatten ( args ) : from six . moves import zip_longest p = OptionParser ( flatten . __doc__ ) p . set_sep ( sep = "," ) p . add_option ( "--zipflatten" , default = None , dest = "zipsep" , help = "Specify if columns of the file should be zipped before" + " flattening. If so, specify delimiter separating column elem... | %prog flatten filename > ids |
12,226 | def reorder ( args ) : import csv p = OptionParser ( reorder . __doc__ ) p . set_sep ( ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) tabfile , order = args sep = opts . sep order = [ int ( x ) - 1 for x in order . split ( "," ) ] reader = csv . reader ( must_open (... | %prog reorder tabfile 1 2 4 3 > newtabfile |
12,227 | def split ( args ) : p = OptionParser ( split . __doc__ ) mode_choices = ( "batch" , "cycle" , "optimal" ) p . add_option ( "--all" , default = False , action = "store_true" , help = "split all records [default: %default]" ) p . add_option ( "--mode" , default = "optimal" , choices = mode_choices , help = "Mode when sp... | %prog split file outdir N |
12,228 | def setop ( args ) : from jcvi . utils . natsort import natsorted p = OptionParser ( setop . __doc__ ) p . add_option ( "--column" , default = 0 , type = "int" , help = "The column to extract, 0-based, -1 to disable [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p .... | %prog setop fileA & fileB > newfile |
12,229 | def _batch_iterator ( self , N = 1 ) : batch_size = math . ceil ( self . num_records / float ( N ) ) handle = self . _open ( self . filename ) while True : batch = list ( islice ( handle , batch_size ) ) if not batch : break yield batch | Returns N lists of records . |
12,230 | def extract ( args ) : p = OptionParser ( extract . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) idsfile , sizesfile = args sizes = Sizes ( sizesfile ) . mapping fp = open ( idsfile ) for row in fp : name = row . strip ( ) size = sizes [ name ] print ( "\t... | %prog extract idsfile sizesfile |
12,231 | def _reversedict ( d ) : return dict ( list ( zip ( list ( d . values ( ) ) , list ( d . keys ( ) ) ) ) ) | Internal helper for generating reverse mappings ; given a dictionary returns a new dictionary with keys and values swapped . |
12,232 | def _percent_to_integer ( percent ) : num = float ( percent . split ( '%' ) [ 0 ] ) / 100.0 * 255 e = num - math . floor ( num ) return e < 0.5 and int ( math . floor ( num ) ) or int ( math . ceil ( num ) ) | Internal helper for converting a percentage value to an integer between 0 and 255 inclusive . |
12,233 | def closest_color ( requested_color ) : logging . disable ( logging . DEBUG ) colors = [ ] for key , name in css3_hex_to_names . items ( ) : diff = color_diff ( hex_to_rgb ( key ) , requested_color ) colors . append ( ( diff , name ) ) logging . disable ( logging . NOTSET ) min_diff , min_color = min ( colors ) return ... | Find closest color name for the request RGB tuple . |
12,234 | def offdiag ( args ) : p = OptionParser ( offdiag . __doc__ ) p . set_beds ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) anchorsfile , = args qbed , sbed , qorder , sorder , is_self = check_beds ( anchorsfile , p , opts ) fp = open ( anchorsfile ) pf = "-" . join... | %prog offdiag diploid . napus . 1x1 . lifted . anchors |
12,235 | def diff ( args ) : from jcvi . utils . cbook import SummaryStats p = OptionParser ( diff . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) simplefile , = args fp = open ( simplefile ) data = [ x . split ( ) for x in fp ] spans = [ ] for block_id , ab in grou... | %prog diff simplefile |
12,236 | def estimate_size ( accns , bed , order , conservative = True ) : accns = [ order [ x ] for x in accns ] ii , bb = zip ( * accns ) mini , maxi = min ( ii ) , max ( ii ) if not conservative : mini -= 1 maxi += 1 minb = bed [ mini ] maxb = bed [ maxi ] assert minb . seqid == maxb . seqid distmode = "ss" if conservative e... | Estimate the bp length for the deletion tracks indicated by the gene accns . True different levels of estimates vary on conservativeness . |
12,237 | def merge ( args ) : from jcvi . formats . base import DictFile p = OptionParser ( merge . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 3 : sys . exit ( not p . print_help ( ) ) quartets , registry , lost = args qq = DictFile ( registry , keypos = 1 , valuepos = 3 ) lost = DictFile ( lost , keypos... | %prog merge protein - quartets registry LOST |
12,238 | def gffselect ( args ) : from jcvi . formats . bed import intersectBed_wao p = OptionParser ( gffselect . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) gmapped , expected , idsfile , tag = args data = get_tags ( idsfile ) completeness = dict ( ( a . replace... | %prog gffselect gmaplocation . bed expectedlocation . bed translated . ids tag |
12,239 | def gaps ( args ) : from jcvi . formats . base import DictFile from jcvi . apps . base import popen from jcvi . utils . cbook import percentage p = OptionParser ( gaps . __doc__ ) p . add_option ( "--bdist" , default = 0 , type = "int" , help = "Base pair distance [default: %default]" ) opts , args = p . parse_args ( a... | %prog gaps idsfile fractionationfile gapsbed |
12,240 | def genestatus ( args ) : p = OptionParser ( genestatus . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) idsfile , = args data = get_tags ( idsfile ) key = lambda x : x [ 0 ] . split ( "." ) [ 0 ] for gene , cc in groupby ( data , key = key ) : cc = list ( c... | %prog genestatus diploid . gff3 . exon . ids |
12,241 | def validate ( args ) : from jcvi . formats . bed import intersectBed_wao p = OptionParser ( validate . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : sys . exit ( not p . print_help ( ) ) fractionation , cdsbed = args fp = open ( fractionation ) sbed = "S.bed" fw = open ( sbed , "w" ) for row i... | %prog validate diploid . napus . fractionation cds . bed |
12,242 | def longest ( args ) : from jcvi . formats . fasta import Fasta , SeqIO from jcvi . formats . sizes import Sizes p = OptionParser ( longest . __doc__ ) p . add_option ( "--prefix" , default = "pasa" , help = "Replace asmbl_ with prefix [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 2 : ... | %prog longest pasa . fasta output . subclusters . out |
12,243 | def ids ( args ) : p = OptionParser ( ids . __doc__ ) p . add_option ( "--prefix" , type = "int" , help = "Find rep id for prefix of len [default: %default]" ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) clstrfile , = args cf = ClstrFile ( clstrfile ) prefix = opts... | %prog ids cdhit . clstr |
12,244 | def summary ( args ) : from jcvi . graphics . histogram import loghistogram p = OptionParser ( summary . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) clstrfile , = args cf = ClstrFile ( clstrfile ) data = list ( cf . iter_sizes ( ) ) loghistogram ( data , ... | %prog summary cdhit . clstr |
12,245 | def deduplicate ( args ) : p = OptionParser ( deduplicate . __doc__ ) p . set_align ( pctid = 96 , pctcov = 0 ) p . add_option ( "--fast" , default = False , action = "store_true" , help = "Place sequence in the first cluster" ) p . add_option ( "--consensus" , default = False , action = "store_true" , help = "Compute ... | %prog deduplicate fastafile |
12,246 | def extract_blocks ( ubi ) : blocks = { } ubi . file . seek ( ubi . file . start_offset ) peb_count = 0 cur_offset = 0 bad_blocks = [ ] for i in range ( ubi . file . start_offset , ubi . file . end_offset , ubi . file . block_size ) : try : buf = ubi . file . read ( ubi . file . block_size ) except Exception as e : if ... | Get a list of UBI block objects from file |
12,247 | def by_image_seq ( blocks , image_seq ) : return list ( filter ( lambda block : blocks [ block ] . ec_hdr . image_seq == image_seq , blocks ) ) | Filter blocks to return only those associated with the provided image_seq number . |
12,248 | def by_vol_id ( blocks , slist = None ) : vol_blocks = { } for i in blocks : if slist and i not in slist : continue elif not blocks [ i ] . is_valid : continue if blocks [ i ] . vid_hdr . vol_id not in vol_blocks : vol_blocks [ blocks [ i ] . vid_hdr . vol_id ] = [ ] vol_blocks [ blocks [ i ] . vid_hdr . vol_id ] . app... | Sort blocks by volume id |
12,249 | def by_type ( blocks , slist = None ) : layout = [ ] data = [ ] int_vol = [ ] unknown = [ ] for i in blocks : if slist and i not in slist : continue if blocks [ i ] . is_vtbl and blocks [ i ] . is_valid : layout . append ( i ) elif blocks [ i ] . is_internal_vol and blocks [ i ] . is_valid : int_vol . append ( i ) elif... | Sort blocks into layout internal volume data or unknown |
12,250 | def get_newest ( blocks , layout_blocks ) : layout_temp = list ( layout_blocks ) for i in range ( 0 , len ( layout_temp ) ) : for k in range ( 0 , len ( layout_blocks ) ) : if blocks [ layout_temp [ i ] ] . ec_hdr . image_seq != blocks [ layout_blocks [ k ] ] . ec_hdr . image_seq : continue if blocks [ layout_temp [ i ... | Filter out old layout blocks from list |
12,251 | def group_pairs ( blocks , layout_blocks_list ) : image_dict = { } for block_id in layout_blocks_list : image_seq = blocks [ block_id ] . ec_hdr . image_seq if image_seq not in image_dict : image_dict [ image_seq ] = [ block_id ] else : image_dict [ image_seq ] . append ( block_id ) log ( group_pairs , 'Layout blocks f... | Sort a list of layout blocks into pairs |
12,252 | def associate_blocks ( blocks , layout_pairs , start_peb_num ) : seq_blocks = [ ] for layout_pair in layout_pairs : seq_blocks = sort . by_image_seq ( blocks , blocks [ layout_pair [ 0 ] ] . ec_hdr . image_seq ) layout_pair . append ( seq_blocks ) return layout_pairs | Group block indexes with appropriate layout pairs |
12,253 | def get_volumes ( blocks , layout_info ) : volumes = { } vol_blocks_lists = sort . by_vol_id ( blocks , layout_info [ 2 ] ) for vol_rec in blocks [ layout_info [ 0 ] ] . vtbl_recs : vol_name = vol_rec . name . strip ( b'\x00' ) . decode ( 'utf-8' ) if vol_rec . rec_index not in vol_blocks_lists : vol_blocks_lists [ vol... | Get a list of UBI volume objects from list of blocks |
12,254 | def parse_key ( key ) : hkey , lkey = struct . unpack ( '<II' , key [ 0 : UBIFS_SK_LEN ] ) ino_num = hkey & UBIFS_S_KEY_HASH_MASK key_type = lkey >> UBIFS_S_KEY_BLOCK_BITS khash = lkey return { 'type' : key_type , 'ino_num' : ino_num , 'khash' : khash } | Parse node key |
12,255 | def decompress ( ctype , unc_len , data ) : if ctype == UBIFS_COMPR_LZO : try : return lzo . decompress ( b'' . join ( ( b'\xf0' , struct . pack ( '>I' , unc_len ) , data ) ) ) except Exception as e : error ( decompress , 'Warn' , 'LZO Error: %s' % e ) elif ctype == UBIFS_COMPR_ZLIB : try : return zlib . decompress ( d... | Decompress data . |
12,256 | def guess_leb_size ( path ) : f = open ( path , 'rb' ) f . seek ( 0 , 2 ) file_size = f . tell ( ) + 1 f . seek ( 0 ) block_size = None for _ in range ( 0 , file_size , FILE_CHUNK_SZ ) : buf = f . read ( FILE_CHUNK_SZ ) for m in re . finditer ( UBIFS_NODE_MAGIC , buf ) : start = m . start ( ) chdr = nodes . common_hdr ... | Get LEB size from superblock |
12,257 | def guess_peb_size ( path ) : file_offset = 0 offsets = [ ] f = open ( path , 'rb' ) f . seek ( 0 , 2 ) file_size = f . tell ( ) + 1 f . seek ( 0 ) for _ in range ( 0 , file_size , FILE_CHUNK_SZ ) : buf = f . read ( FILE_CHUNK_SZ ) for m in re . finditer ( UBI_EC_HDR_MAGIC , buf ) : start = m . start ( ) if not file_of... | Determine the most likely block size |
12,258 | def convert_to_int ( value ) : if not value : return None if isinstance ( value , str ) : value = value . strip ( ' px' ) try : return int ( value ) except ( TypeError , ValueError ) : return None | Attempts to convert a specified value to an integer |
12,259 | def parse_oembed_data ( oembed_data , data ) : data . update ( { 'oembed' : oembed_data , } ) _type = oembed_data . get ( 'type' ) provider_name = oembed_data . get ( 'provider_name' ) if not _type : return data if oembed_data . get ( 'title' ) : data . update ( { 'title' : oembed_data . get ( 'title' ) , } ) if _type ... | Parse OEmbed resposne data to inject into lassie s response dict . |
12,260 | def _filter_meta_data ( self , source , soup , data , url = None ) : meta = FILTER_MAPS [ 'meta' ] [ source ] meta_map = meta [ 'map' ] html = soup . find_all ( 'meta' , { meta [ 'key' ] : meta [ 'pattern' ] } ) image = { } video = { } for line in html : prop = line . get ( meta [ 'key' ] ) value = line . get ( 'conten... | This method filters the web page content for meta tags that match patterns given in the FILTER_MAPS |
12,261 | def _filter_link_tag_data ( self , source , soup , data , url ) : link = FILTER_MAPS [ 'link' ] [ source ] html = soup . find_all ( 'link' , { link [ 'key' ] : link [ 'pattern' ] } ) if link [ 'type' ] == 'url' : for line in html : data [ 'url' ] = line . get ( 'href' ) else : for line in html : data [ 'images' ] . app... | This method filters the web page content for link tags that match patterns given in the FILTER_MAPS |
12,262 | def _find_all_images ( self , soup , data , url ) : all_images = soup . find_all ( 'img' ) for image in all_images : item = normalize_image_data ( image , url ) data [ 'images' ] . append ( item ) | This method finds all images in the web page content |
12,263 | def decode_mail_header ( value , default_charset = 'us-ascii' ) : try : headers = decode_header ( value ) except email . errors . HeaderParseError : return str_decode ( str_encode ( value , default_charset , 'replace' ) , default_charset ) else : for index , ( text , charset ) in enumerate ( headers ) : logger . debug ... | Decode a header value into a unicode string . |
12,264 | def get_mail_addresses ( message , header_name ) : headers = [ h for h in message . get_all ( header_name , [ ] ) ] addresses = email . utils . getaddresses ( headers ) for index , ( address_name , address_email ) in enumerate ( addresses ) : addresses [ index ] = { 'name' : decode_mail_header ( address_name ) , 'email... | Retrieve all email addresses from one message header . |
12,265 | def generate ( self , state ) : if self . count >= random . randint ( DharmaConst . VARIABLE_MIN , DharmaConst . VARIABLE_MAX ) : return "%s%d" % ( self . var , random . randint ( 1 , self . count ) ) var = random . choice ( self ) prefix = self . eval ( var [ 0 ] , state ) suffix = self . eval ( var [ 1 ] , state ) se... | Return a random variable if any otherwise create a new default variable . |
12,266 | def process_settings ( self , settings ) : logging . debug ( "Using configuration from: %s" , settings . name ) exec ( compile ( settings . read ( ) , settings . name , 'exec' ) , globals ( ) , locals ( ) ) | A lazy way of feeding Dharma with configuration settings . |
12,267 | def parse_xrefs ( self , token ) : out , end = [ ] , 0 token = token . replace ( "\\n" , "\n" ) for m in re . finditer ( self . xref_registry , token , re . VERBOSE | re . DOTALL ) : if m . start ( 0 ) > end : out . append ( String ( token [ end : m . start ( 0 ) ] , self . current_obj ) ) end = m . end ( 0 ) if m . gr... | Search token for + value + and !variable! style references . Be careful to not xref a new variable . |
12,268 | def calculate_leaf_paths ( self ) : reverse_xref = { } leaves = set ( ) for v in self . value . values ( ) : if v . leaf : leaves . add ( v ) for xref in v . value_xref : reverse_xref . setdefault ( xref , [ ] ) . append ( v . ident ) for leaf in leaves : self . calculate_leaf_path ( leaf , reverse_xref ) | Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves . |
12,269 | def generate_content ( self ) : if not self . variance : logging . error ( "%s: No variance information %s" , self . id ( ) , self . variance ) sys . exit ( - 1 ) for var in self . variable . values ( ) : var . clear ( ) variances = [ ] for _ in range ( random . randint ( DharmaConst . VARIANCE_MIN , DharmaConst . VARI... | Generates a test case as a string . |
12,270 | def process_grammars ( self , grammars ) : for path in self . default_grammars : grammars . insert ( 0 , open ( os . path . relpath ( os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , os . path . normcase ( path ) ) ) ) ) for fo in grammars : logging . debug ( "Processing grammar content of ... | Process provided grammars by parsing them into Python objects . |
12,271 | def set_preferences ( request , dashboard_id ) : try : preferences = DashboardPreferences . objects . get ( user = request . user , dashboard_id = dashboard_id ) except DashboardPreferences . DoesNotExist : preferences = None if request . method == "POST" : form = DashboardPreferencesForm ( user = request . user , dash... | This view serves and validates a preferences form . |
12,272 | def admin_tools_render_menu ( context , menu = None ) : if menu is None : menu = get_admin_menu ( context ) menu . init_with_context ( context ) has_bookmark_item = False bookmark = None if len ( [ c for c in menu . children if isinstance ( c , items . Bookmarks ) ] ) > 0 : has_bookmark_item = True url = context [ 'req... | Template tag that renders the menu it takes an optional Menu instance as unique argument if not given the menu will be retrieved with the get_admin_menu function . |
12,273 | def admin_tools_render_menu_item ( context , item , index = None ) : item . init_with_context ( context ) context . update ( { 'template' : item . template , 'item' : item , 'index' : index , 'selected' : item . is_selected ( context [ 'request' ] ) , 'admin_url' : reverse ( '%s:index' % get_admin_site_name ( context )... | Template tag that renders a given menu item it takes a MenuItem instance as unique parameter . |
12,274 | def admin_tools_render_menu_css ( context , menu = None ) : if menu is None : menu = get_admin_menu ( context ) context . update ( { 'template' : 'admin_tools/menu/css.html' , 'css_files' : menu . Media . css , } ) return context | Template tag that renders the menu css files it takes an optional Menu instance as unique argument if not given the menu will be retrieved with the get_admin_menu function . |
12,275 | def render_theming_css ( ) : css = getattr ( settings , 'ADMIN_TOOLS_THEMING_CSS' , False ) if not css : css = '/' . join ( [ 'admin_tools' , 'css' , 'theming.css' ] ) return mark_safe ( '<link rel="stylesheet" type="text/css" media="screen" href="%s" />' % staticfiles_storage . url ( css ) ) | Template tag that renders the needed css files for the theming app . |
12,276 | def add_bookmark ( request ) : if request . method == "POST" : form = BookmarkForm ( user = request . user , data = request . POST ) if form . is_valid ( ) : bookmark = form . save ( ) if not request . is_ajax ( ) : messages . success ( request , 'Bookmark added' ) if request . POST . get ( 'next' ) : return HttpRespon... | This view serves and validates a bookmark form . If requested via ajax it also returns the drop bookmark form to replace the add bookmark form . |
12,277 | def remove_bookmark ( request , id ) : bookmark = get_object_or_404 ( Bookmark , id = id , user = request . user ) if request . method == "POST" : bookmark . delete ( ) if not request . is_ajax ( ) : messages . success ( request , 'Bookmark removed' ) if request . POST . get ( 'next' ) : return HttpResponseRedirect ( r... | This view deletes a bookmark . If requested via ajax it also returns the add bookmark form to replace the drop bookmark form . |
12,278 | def autodiscover ( blacklist = [ ] ) : import imp from django . conf import settings try : from importlib import import_module except ImportError : from django . utils . importlib import import_module blacklist . append ( 'admin_tools.dashboard' ) blacklist . append ( 'admin_tools.menu' ) blacklist . append ( 'admin_to... | Automagically discover custom dashboards and menus for installed apps . Optionally you can pass a blacklist of apps that you don t want to provide their own app index dashboard . |
12,279 | def render_css_classes ( self ) : ret = [ 'dashboard-module' ] if not self . enabled : ret . append ( 'disabled' ) if self . draggable : ret . append ( 'draggable' ) if self . collapsible : ret . append ( 'collapsible' ) if self . deletable : ret . append ( 'deletable' ) ret += self . css_classes return ' ' . join ( re... | Return a string containing the css classes for the module . |
12,280 | def is_empty ( self ) : if super ( Group , self ) . is_empty ( ) : return True for child in self . children : if not child . is_empty ( ) : return False return True | A group of modules is considered empty if it has no children or if all its children are empty . |
12,281 | def get_app_index_dashboard ( context ) : app = context [ 'app_list' ] [ 0 ] model_list = [ ] app_label = None app_title = app [ 'name' ] admin_site = get_admin_site ( context = context ) for model , model_admin in admin_site . _registry . items ( ) : if app [ 'app_label' ] == model . _meta . app_label : split = model ... | Returns the admin dashboard defined by the user or the default one . |
12,282 | def get_app_model_classes ( self ) : models = [ ] for m in self . models : mod , cls = m . rsplit ( '.' , 1 ) mod = import_module ( mod ) models . append ( getattr ( mod , cls ) ) return models | Helper method that returns a list of model classes for the current app . |
12,283 | def get_app_content_types ( self ) : from django . contrib . contenttypes . models import ContentType return [ ContentType . objects . get_for_model ( c ) for c in self . get_app_model_classes ( ) ] | Return a list of all content_types for this app . |
12,284 | def admin_tools_render_dashboard_module ( context , module ) : module . init_with_context ( context ) context . update ( { 'template' : module . template , 'module' : module , 'admin_url' : reverse ( '%s:index' % get_admin_site_name ( context ) ) , } ) return context | Template tag that renders a given dashboard module it takes a DashboardModule instance as first parameter . |
12,285 | def is_selected ( self , request ) : current_url = request . get_full_path ( ) return self . url == current_url or len ( [ c for c in self . children if c . is_selected ( request ) ] ) > 0 | Helper method that returns True if the menu item is active . A menu item is considered as active if it s URL or one of its descendants URL is equals to the current URL . |
12,286 | def uniquify ( value , seen_values ) : id = 1 new_value = value while new_value in seen_values : new_value = "%s%s" % ( value , id ) id += 1 seen_values . add ( new_value ) return new_value | Adds value to seen_values set and ensures it is unique |
12,287 | def default_create_thread ( callback ) : thread = threading . Thread ( None , callback ) thread . daemon = True thread . start ( ) return thread | Default thread creation - used to create threads when the client doesn t want to provide their own thread creation . |
12,288 | def parse_headers ( lines , offset = 0 ) : headers = { } for header_line in lines [ offset : ] : header_match = HEADER_LINE_RE . match ( header_line ) if header_match : key = header_match . group ( 'key' ) key = re . sub ( r'\\.' , _unescape_header , key ) if key not in headers : value = header_match . group ( 'value' ... | Parse the headers in a STOMP response |
12,289 | def parse_frame ( frame ) : f = Frame ( ) if frame == b'\x0a' : f . cmd = 'heartbeat' return f mat = PREAMBLE_END_RE . search ( frame ) if mat : preamble_end = mat . start ( ) body_start = mat . end ( ) else : preamble_end = len ( frame ) body_start = preamble_end preamble = decode ( frame [ 0 : preamble_end ] ) preamb... | Parse a STOMP frame into a Frame object . |
12,290 | def merge_headers ( header_map_list ) : headers = { } for header_map in header_map_list : if header_map : headers . update ( header_map ) return headers | Helper function for combining multiple header maps into one . |
12,291 | def calculate_heartbeats ( shb , chb ) : ( sx , sy ) = shb ( cx , cy ) = chb x = 0 y = 0 if cx != 0 and sy != '0' : x = max ( cx , int ( sy ) ) if cy != 0 and sx != '0' : y = max ( cy , int ( sx ) ) return x , y | Given a heartbeat string from the server and a heartbeat tuple from the client calculate what the actual heartbeat settings should be . |
12,292 | def convert_frame ( frame , body_encoding = None ) : lines = [ ] body = None if frame . body : if body_encoding : body = encode ( frame . body , body_encoding ) else : body = encode ( frame . body ) if HDR_CONTENT_LENGTH in frame . headers : frame . headers [ HDR_CONTENT_LENGTH ] = len ( body ) if frame . cmd : lines .... | Convert a frame to a list of lines separated by newlines . |
12,293 | def on_send ( self , frame ) : if frame . cmd == CMD_CONNECT or frame . cmd == CMD_STOMP : if self . heartbeats != ( 0 , 0 ) : frame . headers [ HDR_HEARTBEAT ] = '%s,%s' % self . heartbeats if self . next_outbound_heartbeat is not None : self . next_outbound_heartbeat = monotonic ( ) + self . send_sleep | Add the heartbeat header to the frame when connecting and bump next outbound heartbeat timestamp . |
12,294 | def on_receipt ( self , headers , body ) : if 'receipt-id' in headers and headers [ 'receipt-id' ] == self . receipt : with self . receipt_condition : self . received = True self . receipt_condition . notify ( ) | If the receipt id can be found in the headers then notify the waiting thread . |
12,295 | def wait_on_receipt ( self ) : with self . receipt_condition : while not self . received : self . receipt_condition . wait ( ) self . received = False | Wait until we receive a message receipt . |
12,296 | def send_frame ( self , cmd , headers = None , body = '' ) : frame = utils . Frame ( cmd , headers , body ) self . transport . transmit ( frame ) | Encode and send a stomp frame through the underlying transport . |
12,297 | def abort ( self , transaction , headers = None , ** keyword_headers ) : assert transaction is not None , "'transaction' is required" headers = utils . merge_headers ( [ headers , keyword_headers ] ) headers [ HDR_TRANSACTION ] = transaction self . send_frame ( CMD_ABORT , headers ) | Abort a transaction . |
12,298 | def ack ( self , id , transaction = None , receipt = None ) : assert id is not None , "'id' is required" headers = { HDR_MESSAGE_ID : id } if transaction : headers [ HDR_TRANSACTION ] = transaction if receipt : headers [ HDR_RECEIPT ] = receipt self . send_frame ( CMD_ACK , headers ) | Acknowledge consumption of a message by id . |
12,299 | def commit ( self , transaction = None , headers = None , ** keyword_headers ) : assert transaction is not None , "'transaction' is required" headers = utils . merge_headers ( [ headers , keyword_headers ] ) headers [ HDR_TRANSACTION ] = transaction self . send_frame ( CMD_COMMIT , headers ) | Commit a transaction . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.