idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
6,100
def secure_randint ( min_value , max_value , system_random = None ) : if not system_random : system_random = random . SystemRandom ( ) return system_random . randint ( min_value , max_value )
Return a random integer N such that a < = N < = b .
53
15
6,101
def _merge_maps ( m1 , m2 ) : return type ( m1 ) ( chain ( m1 . items ( ) , m2 . items ( ) ) )
merge two Mapping objects keeping the type of the first mapping
38
13
6,102
def basic_auth ( credentials ) : encoded = b64encode ( ':' . join ( credentials ) . encode ( 'ascii' ) ) . decode ( ) return header_adder ( { 'Authorization' : 'Basic ' + encoded } )
Create an HTTP basic authentication callable
54
7
6,103
def with_headers ( self , headers ) : return self . replace ( headers = _merge_maps ( self . headers , headers ) )
Create a new request with added headers
30
7
6,104
def with_params ( self , params ) : return self . replace ( params = _merge_maps ( self . params , params ) )
Create a new request with added query parameters
30
8
6,105
def _get_bit ( self , n , hash_bytes ) : if hash_bytes [ n // 8 ] >> int ( 8 - ( ( n % 8 ) + 1 ) ) & 1 == 1 : return True return False
Determines if the n - th bit of passed bytes is 1 or 0 .
48
17
6,106
def _generate_matrix ( self , hash_bytes ) : # Since the identicon needs to be symmetric, we'll need to work on half # the columns (rounded-up), and reflect where necessary. half_columns = self . columns // 2 + self . columns % 2 cells = self . rows * half_columns # Initialise the matrix (list of rows) that will be ret...
Generates matrix that describes which blocks should be coloured .
255
11
6,107
def _generate_image ( self , matrix , width , height , padding , foreground , background , image_format ) : # Set-up a new image object, setting the background to provided value. image = Image . new ( "RGBA" , ( width + padding [ 2 ] + padding [ 3 ] , height + padding [ 0 ] + padding [ 1 ] ) , background ) # Set-up a d...
Generates an identicon image in requested image format out of the passed block matrix with the requested width height padding foreground colour background colour and image format .
401
30
6,108
def _generate_ascii ( self , matrix , foreground , background ) : return "\n" . join ( [ "" . join ( [ foreground if cell else background for cell in row ] ) for row in matrix ] )
Generates an identicon image in the ASCII format . The image will just output the matrix used to generate the identicon .
48
25
6,109
def local_timezone ( value ) : if hasattr ( value , "tzinfo" ) and value . tzinfo is None : return value . replace ( tzinfo = dateutil . tz . tzlocal ( ) ) return value
Add the local timezone to value to make it aware .
52
12
6,110
def dumps ( data , * * kwargs ) : def _encoder ( value ) : if isinstance ( value , datetime . datetime ) : return value . isoformat ( ) if hasattr ( value , "_data" ) : return value . _data raise TypeError ( 'Could not encode %r' % value ) return json . dumps ( data , default = _encoder , * * kwargs )
Convert a PPMP entity to JSON . Additional arguments are the same as accepted by json . dumps .
89
22
6,111
def setup_lilypond ( path_to_lilypond_folder = "default" ) : options = { "win32" : setup_lilypond_windows , "darwin" : setup_lilypond_osx } if platform . startswith ( "linux" ) : setup_lilypond_linux ( ) else : options [ platform ] ( path_to_lilypond_folder )
Optional helper method which works out the platform and calls the relevant setup method
96
14
6,112
def setup_lilypond_windows ( path = "default" ) : default = "C:/Program Files (x86)/LilyPond/usr/bin" path_variable = os . environ [ 'PATH' ] . split ( ";" ) if path == "default" : path_variable . append ( default ) else : path_variable . append ( path ) os . environ [ 'PATH' ] = ";" . join ( path_variable )
Optional helper method which does the environment setup for lilypond in windows . If you ve ran this method you do not need and should not provide a lyscript when you instantiate this class . As this method is static you can run this method before you set up the LilypondRenderer instance .
100
64
6,113
def recursive_dict_to_dict ( rdict ) : d = { } for ( k , v ) in rdict . items ( ) : if isinstance ( v , defaultdict ) : d [ k ] = recursive_dict_to_dict ( v ) else : d [ k ] = v return d
Convert a recursive dict to a plain ol dict .
66
11
6,114
def scrub_dict ( d ) : if type ( d ) is dict : return dict ( ( k , scrub_dict ( v ) ) for k , v in d . iteritems ( ) if v and scrub_dict ( v ) ) elif type ( d ) is list : return [ scrub_dict ( v ) for v in d if v and scrub_dict ( v ) ] else : return d
Recursively inspect a dictionary and remove all empty values including empty strings lists and dictionaries .
85
19
6,115
def _to_json_type ( obj , classkey = None ) : if isinstance ( obj , dict ) : data = { } for ( k , v ) in obj . items ( ) : data [ k ] = _to_json_type ( v , classkey ) return data elif hasattr ( obj , "_ast" ) : return _to_json_type ( obj . _ast ( ) ) elif hasattr ( obj , "__iter__" ) : return [ _to_json_type ( v , clas...
Recursively convert the object instance into a valid JSON type .
232
13
6,116
def to_dict ( obj ) : d = _to_json_type ( obj ) if isinstance ( d , dict ) : return scrub_dict ( d ) else : raise ValueError ( "The value provided must be an object." )
Convert an instance of an object into a dict .
51
11
6,117
def print_exc_plus ( stream = sys . stdout ) : # code of this mothod is mainly from <Python Cookbook> write = stream . write # assert the mothod exists flush = stream . flush tp , value , tb = sys . exc_info ( ) while tb . tb_next : tb = tb . tb_next stack = list ( ) f = tb . tb_frame while f : stack . append ( f ) f =...
print normal traceback information with some local arg values
330
10
6,118
def format_single_space_only ( text ) : return " " . join ( [ word for word in text . strip ( ) . split ( " " ) if len ( word ) >= 1 ] )
Revise consecutive empty space to single space .
43
9
6,119
def format_title ( text ) : text = text . strip ( ) # if empty string, return "" if len ( text ) == 0 : return text else : text = text . lower ( ) # lower all char # Change to in single space format words = [ word for word in text . strip ( ) . split ( " " ) if len ( word ) >= 1 ] # Capitalize all words except function...
Capitalize first letter for each words except function words .
183
11
6,120
def format_person_name ( text ) : text = text . strip ( ) if len ( text ) == 0 : # if empty string, return it return text else : text = text . lower ( ) # lower all char # delete redundant empty space words = [ word for word in text . strip ( ) . split ( " " ) if len ( word ) >= 1 ] words = [ word [ 0 ] . upper ( ) + w...
Capitalize first letter for each part of the name .
108
11
6,121
def dump ( self , path ) : try : with open ( path , "wb" ) as f : f . write ( self . __str__ ( ) . encode ( "utf-8" ) ) except : pass with open ( path , "wb" ) as f : pickle . dump ( self . __data__ , f )
dump DictTree data to json files .
71
9
6,122
def load ( cls , path ) : try : with open ( path , "rb" ) as f : return cls ( __data__ = json . loads ( f . read ( ) . decode ( "utf-8" ) ) ) except : pass with open ( path , "rb" ) as f : return cls ( __data__ = pickle . load ( f ) )
load DictTree from json files .
82
8
6,123
def values ( self ) : for key , value in self . __data__ . items ( ) : if key not in ( META , KEY ) : yield DictTree ( __data__ = value )
Iterate values .
43
4
6,124
def keys_at ( self , depth , counter = 1 ) : if depth < 1 : yield ROOT else : if counter == depth : for key in self . keys ( ) : yield key else : counter += 1 for dict_tree in self . values ( ) : for key in dict_tree . keys_at ( depth , counter ) : yield key
Iterate keys at specified depth .
74
7
6,125
def values_at ( self , depth ) : if depth < 1 : yield self else : for dict_tree in self . values ( ) : for value in dict_tree . values_at ( depth - 1 ) : yield value
Iterate values at specified depth .
48
7
6,126
def items_at ( self , depth ) : if depth < 1 : yield ROOT , self elif depth == 1 : for key , value in self . items ( ) : yield key , value else : for dict_tree in self . values ( ) : for key , value in dict_tree . items_at ( depth - 1 ) : yield key , value
Iterate items at specified depth .
76
7
6,127
def stats ( self , result = None , counter = 0 ) : if result is None : result = dict ( ) if counter == 0 : if len ( self ) : result [ 0 ] = { "depth" : 0 , "leaf" : 0 , "root" : 1 } else : result [ 0 ] = { "depth" : 0 , "leaf" : 1 , "root" : 0 } counter += 1 if len ( self ) : result . setdefault ( counter , { "depth" :...
Display the node stats info on specific depth in this dict .
253
12
6,128
async def put ( self , data , * , pri = None , ttl = None , ttr = None , delay = None ) : opts = { } if pri is not None : opts [ 'pri' ] = pri if ttl is not None : opts [ 'ttl' ] = ttl if ttr is not None : opts [ 'ttr' ] = ttr if delay is not None : opts [ 'delay' ] = delay args = ( data , opts ) res = await self . con...
Puts data to the queue and returns a newly created Task
143
12
6,129
async def take ( self , timeout = None ) : args = None if timeout is not None : args = ( timeout , ) res = await self . conn . call ( self . __funcs [ 'take' ] , args ) if len ( res . body ) > 0 : return self . _create_task ( res . body ) return None
Takes task from the queue waiting the timeout if specified
73
11
6,130
async def peek ( self , task_id ) : args = ( task_id , ) res = await self . conn . call ( self . __funcs [ 'peek' ] , args ) return self . _create_task ( res . body )
Get task without changing its state
55
6
6,131
async def kick ( self , count ) : args = ( count , ) res = await self . conn . call ( self . __funcs [ 'kick' ] , args ) if self . conn . version < ( 1 , 7 ) : return res . body [ 0 ] [ 0 ] return res . body [ 0 ]
Kick count tasks from queue
68
5
6,132
def _parse_content ( response ) : if response . status_code != 200 : raise ApiError ( f'unknown error: {response.content.decode()}' ) result = json . loads ( response . content ) if not result [ 'ok' ] : raise ApiError ( f'{result["error"]}: {result.get("detail")}' ) return result
parse the response body as JSON raise on errors
83
9
6,133
def paginated_retrieval ( methodname , itemtype ) : return compose ( reusable , basic_interaction , map_yield ( partial ( _params_as_get , methodname ) ) , )
decorator factory for retrieval queries from query params
45
10
6,134
def json_post ( methodname , rtype , key ) : return compose ( reusable , map_return ( registry ( rtype ) , itemgetter ( key ) ) , basic_interaction , map_yield ( partial ( _json_as_post , methodname ) ) , oneyield , )
decorator factory for json POST queries
66
8
6,135
def _read_config ( cfg_file ) : config = ConfigParser ( ) # maintain case of options config . optionxform = lambda option : option if not os . path . exists ( cfg_file ) : # Create an empty config config . add_section ( _MAIN_SECTION_NAME ) config . add_section ( _ENVIRONMENT_SECTION_NAME ) else : config . read ( cfg_f...
Return a ConfigParser object populated from the settings . cfg file .
98
14
6,136
def _write_config ( config , cfg_file ) : directory = os . path . dirname ( cfg_file ) if not os . path . exists ( directory ) : os . makedirs ( directory ) with open ( cfg_file , "w+" ) as output_file : config . write ( output_file )
Write a config object to the settings . cfg file .
73
12
6,137
def get_environment ( ) : section = _ENVIRONMENT_SECTION_NAME # Read system sys_cfg = _read_config ( _SYSTEM_CONFIG_FILE ) sys_env = dict ( sys_cfg . items ( section ) ) if sys_cfg . has_section ( section ) else { } # Read user usr_cfg = _read_config ( _USER_CONFIG_FILE ) usr_env = dict ( usr_cfg . items ( section ) ) ...
Return all environment values from the config files . Values stored in the user configuration file will take precedence over values stored in the system configuration file .
158
28
6,138
def set_environment ( environment , system = False ) : config_filename = _SYSTEM_CONFIG_FILE if system is True else _USER_CONFIG_FILE config = _read_config ( config_filename ) section = _ENVIRONMENT_SECTION_NAME for key in environment . keys ( ) : config . set ( section , key , environment [ key ] ) _write_config ( con...
Set engine environment values in the config file .
93
9
6,139
def remove_environment ( environment_var_name , system = False ) : config_filename = _SYSTEM_CONFIG_FILE if system is True else _USER_CONFIG_FILE config = _read_config ( config_filename ) section = _ENVIRONMENT_SECTION_NAME config . remove_option ( section , environment_var_name ) _write_config ( config , config_filena...
Remove the specified environment setting from the appropriate config file .
89
11
6,140
def get ( property_name ) : config = _read_config ( _USER_CONFIG_FILE ) section = _MAIN_SECTION_NAME try : property_value = config . get ( section , property_name ) except ( NoOptionError , NoSectionError ) as error : # Try the system config file try : config = _read_config ( _SYSTEM_CONFIG_FILE ) property_value = conf...
Returns the value of the specified configuration property . Property values stored in the user configuration file take precedence over values stored in the system configuration file .
125
28
6,141
def set ( property_name , value , system = False ) : config_filename = _SYSTEM_CONFIG_FILE if system is True else _USER_CONFIG_FILE config = _read_config ( config_filename ) section = _MAIN_SECTION_NAME config . set ( section , property_name , value ) _write_config ( config , config_filename )
Sets the configuration property to the specified value .
82
10
6,142
def register ( self , id , name , address , port = None , tags = None , check = None ) : service = { } service [ 'ID' ] = id service [ 'Name' ] = name service [ 'Address' ] = address if port : service [ 'Port' ] = int ( port ) if tags : service [ 'Tags' ] = tags if check : service [ 'Check' ] = check r = requests . put...
Register a new service with the local consul agent
136
10
6,143
def deregister ( self , id ) : r = requests . put ( '{}/{}' . format ( self . url_deregister , id ) ) if r . status_code != 200 : raise consulDeregistrationError ( 'PUT returned {}' . format ( r . status_code ) ) return r
Deregister a service with the local consul agent
72
12
6,144
def info ( self , name ) : r = requests . get ( '{}/{}' . format ( self . url_service , name ) ) return r . json ( )
Info about a given service
39
5
6,145
def star ( self ) -> snug . Query [ bool ] : req = snug . PUT ( BASE + f'/user/starred/{self.owner}/{self.name}' ) return ( yield req ) . status_code == 204
star this repo
53
3
6,146
def device_message ( device , code , ts = None , origin = None , type = None , severity = None , title = None , description = None , hint = None , * * metaData ) : # pylint: disable=redefined-builtin, too-many-arguments if ts is None : ts = local_now ( ) payload = MessagePayload ( device = device ) payload . messages ....
This quickly builds a time - stamped message . If ts is None the current time is used .
135
19
6,147
def _dump ( obj , abspath , serializer_type , dumper_func = None , compress = True , overwrite = False , verbose = False , * * kwargs ) : _check_serializer_type ( serializer_type ) if not inspect . isfunction ( dumper_func ) : raise TypeError ( "dumper_func has to be a function take object as input " "and return binary...
Dump object to file .
302
6
6,148
def _load ( abspath , serializer_type , loader_func = None , decompress = True , verbose = False , * * kwargs ) : _check_serializer_type ( serializer_type ) if not inspect . isfunction ( loader_func ) : raise TypeError ( "loader_func has to be a function take binary as input " "and return an object!" ) prt_console ( "\...
load object from file .
257
5
6,149
def _get_response ( self , method , endpoint , data = None ) : url = urljoin ( IVONA_REGION_ENDPOINTS [ self . region ] , endpoint ) response = getattr ( self . session , method ) ( url , json = data , ) if 'x-amzn-ErrorType' in response . headers : raise IvonaAPIException ( response . headers [ 'x-amzn-ErrorType' ] ) ...
Helper method for wrapping API requests mainly for catching errors in one place .
135
14
6,150
def get_available_voices ( self , language = None , gender = None ) : endpoint = 'ListVoices' data = dict ( ) if language : data . update ( { 'Voice' : { 'Language' : language } } ) if gender : data . update ( { 'Voice' : { 'Gender' : gender } } ) print ( data ) response = self . _get_response ( 'get' , endpoint , data...
Returns a list of available voices via ListVoices endpoint
106
11
6,151
def text_to_speech ( self , text , file , voice_name = None , language = None ) : endpoint = 'CreateSpeech' data = { 'Input' : { 'Data' : text , } , 'OutputFormat' : { 'Codec' : self . codec . upper ( ) , } , 'Parameters' : { 'Rate' : self . rate , 'Volume' : self . volume , 'SentenceBreak' : self . sentence_break , 'P...
Saves given text synthesized audio file via CreateSpeech endpoint
172
13
6,152
def create_client_with_auto_poll ( api_key , poll_interval_seconds = 60 , max_init_wait_time_seconds = 5 , on_configuration_changed_callback = None , config_cache_class = None , base_url = None ) : if api_key is None : raise ConfigCatClientException ( 'API Key is required.' ) if poll_interval_seconds < 1 : poll_interva...
Create an instance of ConfigCatClient and setup Auto Poll mode with custom options
171
15
6,153
def create_client_with_lazy_load ( api_key , cache_time_to_live_seconds = 60 , config_cache_class = None , base_url = None ) : if api_key is None : raise ConfigCatClientException ( 'API Key is required.' ) if cache_time_to_live_seconds < 1 : cache_time_to_live_seconds = 1 return ConfigCatClient ( api_key , 0 , 0 , None...
Create an instance of ConfigCatClient and setup Lazy Load mode with custom options
122
16
6,154
def create_client_with_manual_poll ( api_key , config_cache_class = None , base_url = None ) : if api_key is None : raise ConfigCatClientException ( 'API Key is required.' ) return ConfigCatClient ( api_key , 0 , 0 , None , 0 , config_cache_class , base_url )
Create an instance of ConfigCatClient and setup Manual Poll mode with custom options
78
15
6,155
def basic_query ( returns ) : return compose ( reusable , map_send ( parse_request ) , map_yield ( prepare_params , snug . prefix_adder ( API_PREFIX ) ) , map_return ( loads ( returns ) ) , oneyield , )
decorator factory for NS queries
60
7
6,156
def departures ( station : str ) -> snug . Query [ t . List [ Departure ] ] : return snug . GET ( 'avt' , params = { 'station' : station } )
departures for a station
42
6
6,157
def journey_options ( origin : str , destination : str , via : t . Optional [ str ] = None , before : t . Optional [ int ] = None , after : t . Optional [ int ] = None , time : t . Optional [ datetime ] = None , hsl : t . Optional [ bool ] = None , year_card : t . Optional [ bool ] = None ) -> ( snug . Query [ t . List...
journey recommendations from an origin to a destination station
179
10
6,158
def rand_str ( length , allowed = CHARSET_ALPHA_DIGITS ) : res = list ( ) for _ in range ( length ) : res . append ( random . choice ( allowed ) ) return "" . join ( res )
Generate fixed - length random string from your allowed character pool .
53
13
6,159
def rand_hexstr ( length , lower = True ) : if lower : return rand_str ( length , allowed = CHARSET_HEXSTR_LOWER ) else : return rand_str ( length , allowed = CHARSET_HEXSTR_UPPER )
Gererate fixed - length random hexstring usually for md5 .
58
14
6,160
def rand_alphastr ( length , lower = True , upper = True ) : if lower is True and upper is True : return rand_str ( length , allowed = string . ascii_letters ) if lower is True and upper is False : return rand_str ( length , allowed = string . ascii_lowercase ) if lower is False and upper is True : return rand_str ( le...
Generate fixed - length random alpha only string .
103
10
6,161
def rand_article ( num_p = ( 4 , 10 ) , num_s = ( 2 , 15 ) , num_w = ( 5 , 40 ) ) : article = list ( ) for _ in range ( random . randint ( * num_p ) ) : p = list ( ) for _ in range ( random . randint ( * num_s ) ) : s = list ( ) for _ in range ( random . randint ( * num_w ) ) : s . append ( rand_str ( random . randint ...
Random article text .
165
4
6,162
def _resolve_dep ( self , key ) : if key in self . future_values_key_dep : # there are some dependencies that can be resoled dep_list = self . future_values_key_dep [ key ] del self . future_values_key_dep [ key ] # remove dependencies also_finish = [ ] # iterate over the dependencies that can now be resoled for dep in...
this method resolves dependencies for the given key . call the method afther the item key was added to the list of avalable items
154
26
6,163
def _get_all_refs ( self , dep , handled_refs = None ) : if handled_refs is None : handled_refs = [ dep ] else : if dep in handled_refs : return [ ] res = [ ] if dep in self . future_values_key_item : res . extend ( self . future_values_key_item [ dep ] [ "dependencies" ] . values ( ) ) add = [ ] for h_d in res : add ....
get al list of all dependencies for the given item dep
143
11
6,164
def parse ( response ) : if response . status_code == 400 : try : msg = json . loads ( response . content ) [ 'message' ] except ( KeyError , ValueError ) : msg = '' raise ApiError ( msg ) return response
check for errors
53
3
6,165
def create ( cls , host = 'localhost' , port = 14999 , auto_reconnect = True , loop = None , protocol_class = AVR , update_callback = None ) : assert port >= 0 , 'Invalid port value: %r' % ( port ) conn = cls ( ) conn . host = host conn . port = port conn . _loop = loop or asyncio . get_event_loop ( ) conn . _retry_int...
Initiate a connection to a specific device .
234
10
6,166
def close ( self ) : self . log . warning ( 'Closing connection to AVR' ) self . _closing = True if self . protocol . transport : self . protocol . transport . close ( )
Close the AVR device connection and don t try to reconnect .
44
13
6,167
def _compress_obj ( obj , level ) : return zlib . compress ( pickle . dumps ( obj , protocol = 2 ) , level )
Compress object to bytes .
32
6
6,168
def compress ( obj , level = 6 , return_type = "bytes" ) : if isinstance ( obj , binary_type ) : b = _compress_bytes ( obj , level ) elif isinstance ( obj , string_types ) : b = _compress_str ( obj , level ) else : b = _compress_obj ( obj , level ) if return_type == "bytes" : return b elif return_type == "str" : return...
Compress anything to bytes or string .
144
8
6,169
def decompress ( obj , return_type = "bytes" ) : if isinstance ( obj , binary_type ) : b = zlib . decompress ( obj ) elif isinstance ( obj , string_types ) : b = zlib . decompress ( base64 . b64decode ( obj . encode ( "utf-8" ) ) ) else : raise TypeError ( "input cannot be anything other than str and bytes!" ) if retur...
De - compress it to it s original .
172
9
6,170
def build_signature_template ( key_id , algorithm , headers ) : param_map = { 'keyId' : key_id , 'algorithm' : algorithm , 'signature' : '%s' } if headers : headers = [ h . lower ( ) for h in headers ] param_map [ 'headers' ] = ' ' . join ( headers ) kv = map ( '{0[0]}="{0[1]}"' . format , param_map . items ( ) ) kv_st...
Build the Signature template for use with the Authorization header .
145
11
6,171
def train ( self , data , key_id , key_lat , key_lng , clear_old = True ) : engine , t_point = self . engine , self . t_point if clear_old : try : t_point . drop ( engine ) except : pass t_point . create ( engine ) table_data = list ( ) for record in data : id = key_id ( record ) lat = key_lat ( record ) lng = key_lng ...
Feed data into database .
199
5
6,172
def find_n_nearest ( self , lat , lng , n = 5 , radius = None ) : engine , t_point = self . engine , self . t_point if radius : # Use a simple box filter to minimize candidates # Define latitude longitude boundary dist_btwn_lat_deg = 69.172 dist_btwn_lon_deg = cos ( lat ) * 69.172 lat_degr_rad = abs ( radius * 1.05 / d...
Find n nearest point within certain distance from a point .
373
11
6,173
def sample ( self , k ) : def new_get_iterators ( ) : tweet_parser = smappdragon . TweetParser ( ) it = iter ( self . get_collection_iterators ( ) ) sample = list ( itertools . islice ( it , k ) ) random . shuffle ( sample ) for i , item in enumerate ( it , start = k + 1 ) : j = random . randrange ( i ) if j < k : samp...
this method is especially troublesome i do not reccommend making any changes to it you may notice it uplicates code fro smappdragon there is no way around this as far as i can tell it really might screw up a lot of stuff stip tweets has been purposely omitted as it isnt supported in pysmap
219
64
6,174
def merge_networks ( output_file = "merged_network.txt" , * files ) : contacts = dict ( ) for network_file in files : with open ( network_file ) as network_file_handle : for line in network_file_handle : id_a , id_b , n_contacts = line . split ( "\t" ) pair = sorted ( ( id_a , id_b ) ) try : contacts [ pair ] += n_cont...
Merge networks into a larger network .
207
8
6,175
def merge_chunk_data ( output_file = "merged_idx_contig_hit_size_cov.txt" , * files ) : chunks = dict ( ) for chunk_file in files : with open ( chunk_file ) as chunk_file_handle : for line in chunk_file_handle : chunk_id , chunk_name , hit , size , cov = line . split ( "\t" ) try : chunks [ chunk_id ] [ "hit" ] += hit ...
Merge chunk data from different networks
302
7
6,176
def alignment_to_reads ( sam_merged , output_dir , parameters = DEFAULT_PARAMETERS , save_memory = True , * bin_fasta ) : # Just in case file objects are sent as input def get_file_string ( file_thing ) : try : file_string = file_thing . name except AttributeError : file_string = str ( file_thing ) return file_string #...
Generate reads from ambiguous alignment file
787
7
6,177
def ResetHandler ( self , name ) : if name in self . tags : if len ( self . tags ) > 1 : key = len ( self . tags ) - 2 self . handler = None while key >= 0 : if self . tags [ key ] in self . structure : self . handler = self . structure [ self . tags [ key ] ] break key -= 1 else : self . handler = None
Method which assigns handler to the tag encountered before the current or else sets it to None
84
17
6,178
def get_cluster ( self , label ) : for cluster in self . _clusters : if label == cluster [ 'label' ] : return self . _get_connection ( cluster ) raise AttributeError ( 'No such cluster %s.' % label )
Returns a connection to a mongo - clusters .
55
10
6,179
def _validate_config ( config ) : if not isinstance ( config , list ) : raise TypeError ( 'Config must be a list' ) for config_dict in config : if not isinstance ( config_dict , dict ) : raise TypeError ( 'Config must be a list of dictionaries' ) label = config_dict . keys ( ) [ 0 ] cfg = config_dict [ label ] if not i...
Validate that the provided configurtion is valid .
444
11
6,180
def _parse_configs ( self , config ) : for config_dict in config : label = config_dict . keys ( ) [ 0 ] cfg = config_dict [ label ] # Transform dbpath to something digestable by regexp. dbpath = cfg [ 'dbpath' ] pattern = self . _parse_dbpath ( dbpath ) read_preference = cfg . get ( 'read_preference' , 'primary' ) . up...
Builds a dict with information to connect to Clusters .
238
12
6,181
def _parse_dbpath ( dbpath ) : if isinstance ( dbpath , list ) : # Support dbpath param as an array. dbpath = '|' . join ( dbpath ) # Append $ (end of string) so that twit will not match twitter! if not dbpath . endswith ( '$' ) : dbpath = '(%s)$' % dbpath return dbpath
Converts the dbpath to a regexp pattern .
89
11
6,182
def _get_read_preference ( read_preference ) : read_preference = getattr ( pymongo . ReadPreference , read_preference , None ) if read_preference is None : raise ValueError ( 'Invalid read preference: %s' % read_preference ) return read_preference
Converts read_preference from string to pymongo . ReadPreference value .
69
18
6,183
def set_timeout ( self , network_timeout ) : # Do nothing if attempting to set the same timeout twice. if network_timeout == self . _network_timeout : return self . _network_timeout = network_timeout self . _disconnect ( )
Set the timeout for existing and future Clients .
54
10
6,184
def _disconnect ( self ) : for cluster in self . _clusters : if 'connection' in cluster : connection = cluster . pop ( 'connection' ) connection . close ( ) # Remove all attributes that are database names so that next time # when they are accessed, __getattr__ will be called and will create # new Clients for dbname in ...
Disconnect from all MongoDB Clients .
105
9
6,185
def _get_connection ( self , cluster ) : # w=1 because: # http://stackoverflow.com/questions/14798552/is-mongodb-2-x-write-concern-w-1-truly-equals-to-safe-true if 'connection' not in cluster : cluster [ 'connection' ] = self . _connection_class ( socketTimeoutMS = self . _network_timeout , w = 1 , j = self . j , * * c...
Return a connection to a Cluster .
122
7
6,186
def _match_dbname ( self , dbname ) : for config in self . _clusters : if re . match ( config [ 'pattern' ] , dbname ) : return config raise Exception ( 'No such database %s.' % dbname )
Map a database name to the Cluster that holds the database .
54
12
6,187
def try_ntime ( max_try , func , * args , * * kwargs ) : if max_try < 1 : raise ValueError for i in range ( max_try ) : try : return func ( * args , * * kwargs ) except Exception as e : last_exception = e raise last_exception
Try execute a function n times until no exception raised or tried max_try times .
72
17
6,188
def highlightjs_javascript ( jquery = None ) : javascript = '' # See if we have to include jQuery if jquery is None : jquery = get_highlightjs_setting ( 'include_jquery' , False ) if jquery : url = highlightjs_jquery_url ( ) if url : javascript += '<script src="{url}"></script>' . format ( url = url ) url = highlightjs...
Return HTML for highlightjs JavaScript .
141
7
6,189
def repo ( name : str , owner : str ) -> snug . Query [ dict ] : return json . loads ( ( yield f'/repos/{owner}/{name}' ) . content )
a repository lookup by owner and name
43
7
6,190
def repo ( name : str , owner : str ) -> snug . Query [ dict ] : request = snug . GET ( f'https://api.github.com/repos/{owner}/{name}' ) response = yield request return json . loads ( response . content )
a repo lookup by owner and name
60
7
6,191
def follow ( name : str ) -> snug . Query [ bool ] : request = snug . PUT ( f'https://api.github.com/user/following/{name}' ) response = yield request return response . status_code == 204
follow another user
54
3
6,192
def taskinfo ( self ) : task_input = { 'taskName' : 'QueryTask' , 'inputParameters' : { "Task_Name" : self . _name } } info = taskengine . execute ( task_input , self . _engine , cwd = self . _cwd ) task_def = info [ 'outputParameters' ] [ 'DEFINITION' ] task_def [ 'name' ] = str ( task_def . pop ( 'NAME' ) ) task_def ...
Retrieve the Task Information
874
5
6,193
def despeckle_simple ( B , th2 = 2 ) : A = np . copy ( B ) n1 = A . shape [ 0 ] dist = { u : np . diag ( A , u ) for u in range ( n1 ) } medians , stds = { } , { } for u in dist : medians [ u ] = np . median ( dist [ u ] ) stds [ u ] = np . std ( dist [ u ] ) for nw , j in itertools . product ( range ( n1 ) , range ( n...
Single - chromosome despeckling
236
7
6,194
def bin_sparse ( M , subsampling_factor = 3 ) : try : from scipy . sparse import coo_matrix except ImportError as e : print ( str ( e ) ) print ( "I am peforming dense binning by default." ) return bin_dense ( M . todense ( ) ) N = M . tocoo ( ) n , m = N . shape row , col , data = N . row , N . col , N . data # Divide...
Perform the bin_dense procedure for sparse matrices . Remaining rows and cols are lumped with the rest at the end .
266
29
6,195
def bin_matrix ( M , subsampling_factor = 3 ) : try : from scipy . sparse import issparse if issparse ( M ) : return bin_sparse ( M , subsampling_factor = subsampling_factor ) else : raise ImportError except ImportError : return bin_dense ( M , subsampling_factor = subsampling_factor )
Bin either sparse or dense matrices .
84
9
6,196
def bin_annotation ( annotation = None , subsampling_factor = 3 ) : if annotation is None : annotation = np . array ( [ ] ) n = len ( annotation ) binned_positions = [ annotation [ i ] for i in range ( n ) if i % subsampling_factor == 0 ] if len ( binned_positions ) == 0 : binned_positions . append ( 0 ) return np . ar...
Perform binning on genome annotations such as contig information or bin positions .
101
16
6,197
def build_pyramid ( M , subsampling_factor = 3 ) : subs = int ( subsampling_factor ) if subs < 1 : raise ValueError ( "Subsampling factor needs to be an integer greater than 1." ) N = [ M ] while min ( N [ - 1 ] . shape ) > 1 : N . append ( bin_matrix ( N [ - 1 ] , subsampling_factor = subs ) ) return N
Iterate over a given number of times on matrix M so as to compute smaller and smaller matrices with bin_dense .
96
26
6,198
def bin_exact_kb_dense ( M , positions , length = 10 ) : unit = 10 ** 3 ul = unit * length units = positions / ul n = len ( positions ) idx = [ i for i in range ( n - 1 ) if np . ceil ( units [ i ] ) < np . ceil ( units [ i + 1 ] ) ] m = len ( idx ) - 1 N = np . zeros ( ( m , m ) ) remainders = [ 0 ] + [ np . abs ( uni...
Perform the kb - binning procedure with total bin lengths being exactly set to that of the specified input . Fragments overlapping two potential bins will be split and related contact counts will be divided according to overlap proportions in each bin .
234
46
6,199
def bin_kb_sparse ( M , positions , length = 10 ) : try : from scipy . sparse import coo_matrix except ImportError as e : print ( str ( e ) ) print ( "I am peforming dense normalization by default." ) return bin_kb_dense ( M . todense ( ) , positions = positions ) r = M . tocoo ( ) unit = 10 ** 3 ul = unit * length uni...
Perform the exact kb - binning procedure on a sparse matrix .
228
14