idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
245,200
def decode ( self ) : buflen = len ( self . buffer ) tftpassert ( buflen >= 4 , "malformed ERR packet, too short" ) log . debug ( "Decoding ERR packet, length %s bytes" , buflen ) if buflen == 4 : log . debug ( "Allowing this affront to the RFC of a 4-byte packet" ) fmt = b"!HH" log . debug ( "Decoding ERR packet with ...
Decode self . buffer populating instance variables and return self .
249
13
245,201
def match_options ( self , options ) : for name in self . options : if name in options : if name == 'blksize' : # We can accept anything between the min and max values. size = int ( self . options [ name ] ) if size >= MIN_BLKSIZE and size <= MAX_BLKSIZE : log . debug ( "negotiated blksize of %d bytes" , size ) options...
This method takes a set of options and tries to match them with its own . It can accept some changes in those options from the server as part of a negotiation . Changed or unchanged it will return a dict of the options so that the session can update itself to the negotiated options .
183
56
245,202
def handleOACK ( self , pkt ) : if len ( pkt . options . keys ( ) ) > 0 : if pkt . match_options ( self . context . options ) : log . info ( "Successful negotiation of options" ) # Set options to OACK options self . context . options = pkt . options for key in self . context . options : log . info ( " %s = %s" % ( key ...
This method handles an OACK from the server syncing any accepted options .
149
15
245,203
def returnSupportedOptions ( self , options ) : # We support the options blksize and tsize right now. # FIXME - put this somewhere else? accepted_options = { } for option in options : if option == 'blksize' : # Make sure it's valid. if int ( options [ option ] ) > MAX_BLKSIZE : log . info ( "Client requested blksize gr...
This method takes a requested options list from a client and returns the ones that are supported .
255
18
245,204
def sendDAT ( self ) : finished = False blocknumber = self . context . next_block # Test hook if DELAY_BLOCK and DELAY_BLOCK == blocknumber : import time log . debug ( "Deliberately delaying 10 seconds..." ) time . sleep ( 10 ) dat = None blksize = self . context . getBlocksize ( ) buffer = self . context . fileobj . r...
This method sends the next DAT packet based on the data in the context . It returns a boolean indicating whether the transfer is finished .
267
27
245,205
def sendACK ( self , blocknumber = None ) : log . debug ( "In sendACK, passed blocknumber is %s" , blocknumber ) if blocknumber is None : blocknumber = self . context . next_block log . info ( "Sending ack to block %d" % blocknumber ) ackpkt = TftpPacketACK ( ) ackpkt . blocknumber = blocknumber self . context . sock ....
This method sends an ack packet to the block number specified . If none is specified it defaults to the next_block property in the parent context .
137
30
245,206
def sendError ( self , errorcode ) : log . debug ( "In sendError, being asked to send error %d" , errorcode ) errpkt = TftpPacketERR ( ) errpkt . errorcode = errorcode if self . context . tidport == None : log . debug ( "Error packet received outside session. Discarding" ) else : self . context . sock . sendto ( errpkt...
This method uses the socket passed and uses the errorcode to compose and send an error packet .
126
19
245,207
def sendOACK ( self ) : log . debug ( "In sendOACK with options %s" , self . context . options ) pkt = TftpPacketOACK ( ) pkt . options = self . context . options self . context . sock . sendto ( pkt . encode ( ) . buffer , ( self . context . host , self . context . tidport ) ) self . context . last_pkt = pkt
This method sends an OACK packet with the options from the current context .
95
15
245,208
def resendLast ( self ) : log . warning ( "Resending packet %s on sessions %s" % ( self . context . last_pkt , self ) ) self . context . metrics . resent_bytes += len ( self . context . last_pkt . buffer ) self . context . metrics . add_dup ( self . context . last_pkt ) sendto_port = self . context . tidport if not sen...
Resend the last sent packet due to a timeout .
206
11
245,209
def handleDat ( self , pkt ) : log . info ( "Handling DAT packet - block %d" % pkt . blocknumber ) log . debug ( "Expecting block %s" , self . context . next_block ) if pkt . blocknumber == self . context . next_block : log . debug ( "Good, received block %d in sequence" , pkt . blocknumber ) self . sendACK ( ) self . ...
This method handles a DAT packet during a client download or a server upload .
419
16
245,210
def serverInitial ( self , pkt , raddress , rport ) : options = pkt . options sendoack = False if not self . context . tidport : self . context . tidport = rport log . info ( "Setting tidport to %s" % rport ) log . debug ( "Setting default options, blksize" ) self . context . options = { 'blksize' : DEF_BLKSIZE } if op...
This method performs initial setup for a server context transfer put here to refactor code out of the TftpStateServerRecvRRQ and TftpStateServerRecvWRQ classes since their initial setup is identical . The method returns a boolean sendoack to indicate whether it is required to send an OACK to the client .
680
69
245,211
def handle ( self , pkt , raddress , rport ) : log . debug ( "In TftpStateServerRecvRRQ.handle" ) sendoack = self . serverInitial ( pkt , raddress , rport ) path = self . full_path log . info ( "Opening file %s for reading" % path ) if os . path . exists ( path ) : # Note: Open in binary mode for win32 portability, sin...
Handle an initial RRQ packet as a server .
564
10
245,212
def make_subdirs ( self ) : # Pull off everything below the root. subpath = self . full_path [ len ( self . context . root ) : ] log . debug ( "make_subdirs: subpath is %s" , subpath ) # Split on directory separators, but drop the last one, as it should # be the filename. dirs = subpath . split ( os . sep ) [ : - 1 ] l...
The purpose of this method is to if necessary create all of the subdirectories leading up to the file to the written .
178
25
245,213
def handle ( self , pkt , raddress , rport ) : log . debug ( "In TftpStateServerRecvWRQ.handle" ) sendoack = self . serverInitial ( pkt , raddress , rport ) path = self . full_path if self . context . upload_open : f = self . context . upload_open ( path , self . context ) if f is None : self . sendError ( TftpErrors ....
Handle an initial WRQ packet as a server .
387
10
245,214
def handle ( self , pkt , raddress , rport ) : if isinstance ( pkt , TftpPacketACK ) : log . debug ( "Received ACK for packet %d" % pkt . blocknumber ) # Is this an ack to the one we just sent? if self . context . next_block == pkt . blocknumber : if self . context . pending_complete : log . info ( "Received ACK to fin...
Handle a packet hopefully an ACK since we just sent a DAT .
356
15
245,215
def handle ( self , pkt , raddress , rport ) : if isinstance ( pkt , TftpPacketDAT ) : return self . handleDat ( pkt ) # Every other packet type is a problem. elif isinstance ( pkt , TftpPacketACK ) : # Umm, we ACK, you don't. self . sendError ( TftpErrors . IllegalTftpOp ) raise TftpException ( "Received ACK from peer...
Handle the packet in response to an ACK which should be a DAT .
264
16
245,216
def handle ( self , pkt , raddress , rport ) : if not self . context . tidport : self . context . tidport = rport log . info ( "Set remote port for session to %s" % rport ) # Now check the packet type and dispatch it properly. if isinstance ( pkt , TftpPacketOACK ) : log . info ( "Received OACK from server" ) try : sel...
Handle the packet in response to an RRQ to the server .
588
13
245,217
def stop ( self , now = False ) : if now : self . shutdown_immediately = True else : self . shutdown_gracefully = True
Stop the server gracefully . Do not take any new transfers but complete the existing ones . If force is True drop everything and stop . Note immediately will not interrupt the select loop it will happen when the server returns on ready data or a timeout . ie . SOCK_TIMEOUT
32
56
245,218
def _fetch ( url , ssl_verify = True ) : req = Request ( url ) if ssl_verify : page = urlopen ( req ) else : ctx = ssl . create_default_context ( ) ctx . check_hostname = False ctx . verify_mode = ssl . CERT_NONE page = urlopen ( req , context = ctx ) content = page . read ( ) . decode ( 'utf-8' ) page . close ( ) retu...
Helper funcation to fetch content from a given url .
110
11
245,219
def _dict ( content ) : if _has_pandas : data = _data_frame ( content ) . to_dict ( orient = 'records' ) else : response = loads ( content ) key = [ x for x in response . keys ( ) if x in c . response_data ] [ 0 ] data = response [ key ] return data
Helper funcation that converts text - based get response to a python dictionary for additional manipulation .
76
18
245,220
def _data_frame ( content ) : response = loads ( content ) key = [ x for x in response . keys ( ) if x in c . response_data ] [ 0 ] frame = DataFrame ( response [ key ] ) final_frame = _convert ( frame ) return final_frame
Helper funcation that converts text - based get response to a pandas dataframe for additional manipulation .
63
20
245,221
def _tab ( content ) : response = _data_frame ( content ) . to_csv ( index = False , sep = '\t' ) return response
Helper funcation that converts text - based get response to tab separated values for additional manipulation .
34
18
245,222
def _pipe ( content ) : response = _data_frame ( content ) . to_csv ( index = False , sep = '|' ) return response
Helper funcation that converts text - based get response to pipe separated values for additional manipulation .
33
18
245,223
def _get_request ( url_root , api_key , path , response_type , params , ssl_verify ) : url = _url_builder ( url_root , api_key , path , params ) content = _fetch ( url , ssl_verify ) response = _dispatch ( response_type ) ( content ) return response
Helper funcation that requests a get response from FRED .
77
12
245,224
def parse_atom_file ( filename : str ) -> AtomFeed : root = parse_xml ( filename ) . getroot ( ) return _parse_atom ( root )
Parse an Atom feed from a local XML file .
36
11
245,225
def parse_atom_bytes ( data : bytes ) -> AtomFeed : root = parse_xml ( BytesIO ( data ) ) . getroot ( ) return _parse_atom ( root )
Parse an Atom feed from a byte - string containing XML data .
41
14
245,226
def _get_link ( element : Element ) -> Optional [ str ] : link = get_text ( element , 'link' ) if link is not None : return link guid = get_child ( element , 'guid' ) if guid is not None and guid . attrib . get ( 'isPermaLink' ) == 'true' : return get_text ( element , 'guid' ) return None
Attempt to retrieve item link .
88
6
245,227
def parse_rss_file ( filename : str ) -> RSSChannel : root = parse_xml ( filename ) . getroot ( ) return _parse_rss ( root )
Parse an RSS feed from a local XML file .
36
11
245,228
def parse_rss_bytes ( data : bytes ) -> RSSChannel : root = parse_xml ( BytesIO ( data ) ) . getroot ( ) return _parse_rss ( root )
Parse an RSS feed from a byte - string containing XML data .
41
14
245,229
def parse_json_feed_file ( filename : str ) -> JSONFeed : with open ( filename ) as f : try : root = json . load ( f ) except json . decoder . JSONDecodeError : raise FeedJSONError ( 'Not a valid JSON document' ) return parse_json_feed ( root )
Parse a JSON feed from a local json file .
68
11
245,230
def parse_json_feed_bytes ( data : bytes ) -> JSONFeed : try : root = json . loads ( data ) except json . decoder . JSONDecodeError : raise FeedJSONError ( 'Not a valid JSON document' ) return parse_json_feed ( root )
Parse a JSON feed from a byte - string containing JSON data .
60
14
245,231
def parse_opml_file ( filename : str ) -> OPML : root = parse_xml ( filename ) . getroot ( ) return _parse_opml ( root )
Parse an OPML document from a local XML file .
38
12
245,232
def parse_opml_bytes ( data : bytes ) -> OPML : root = parse_xml ( BytesIO ( data ) ) . getroot ( ) return _parse_opml ( root )
Parse an OPML document from a byte - string containing XML data .
43
15
245,233
def get_feed_list ( opml_obj : OPML ) -> List [ str ] : rv = list ( ) def collect ( obj ) : for outline in obj . outlines : if outline . type == 'rss' and outline . xml_url : rv . append ( outline . xml_url ) if outline . outlines : collect ( outline ) collect ( opml_obj ) return rv
Walk an OPML document to extract the list of feed it contains .
85
14
245,234
def simple_parse_file ( filename : str ) -> Feed : pairs = ( ( rss . parse_rss_file , _adapt_rss_channel ) , ( atom . parse_atom_file , _adapt_atom_feed ) , ( json_feed . parse_json_feed_file , _adapt_json_feed ) ) return _simple_parse ( pairs , filename )
Parse an Atom RSS or JSON feed from a local file .
83
13
245,235
def simple_parse_bytes ( data : bytes ) -> Feed : pairs = ( ( rss . parse_rss_bytes , _adapt_rss_channel ) , ( atom . parse_atom_bytes , _adapt_atom_feed ) , ( json_feed . parse_json_feed_bytes , _adapt_json_feed ) ) return _simple_parse ( pairs , data )
Parse an Atom RSS or JSON feed from a byte - string containing data .
83
16
245,236
def get_shear_distance ( a ) : cx , cy , cz = a . cell if 'shear_dx' in a . info : assert abs ( cx [ 1 ] ) < 1e-12 , 'cx[1] = {0}' . format ( cx [ 1 ] ) assert abs ( cx [ 2 ] ) < 1e-12 , 'cx[2] = {0}' . format ( cx [ 2 ] ) assert abs ( cy [ 0 ] ) < 1e-12 , 'cx[0] = {0}' . format ( cy [ 0 ] ) assert abs ( cy [ 2 ] ) < 1...
Returns the distance a volume has moved during simple shear . Considers either Lees - Edwards boundary conditions or sheared cells .
389
26
245,237
def array_inverse ( A ) : A = np . ascontiguousarray ( A , dtype = float ) b = np . identity ( A . shape [ 2 ] , dtype = A . dtype ) n_eq = A . shape [ 1 ] n_rhs = A . shape [ 2 ] pivots = np . zeros ( n_eq , np . intc ) identity = np . eye ( n_eq ) def lapack_inverse ( a ) : b = np . copy ( identity ) pivots = np . ze...
Compute inverse for each matrix in a list of matrices . This is faster than calling numpy . linalg . inv for each matrix .
222
30
245,238
def get_delta_plus_epsilon ( nat , i_now , dr_now , dr_old ) : XIJ = get_XIJ ( nat , i_now , dr_now , dr_old ) YIJ = get_YIJ ( nat , i_now , dr_old ) YIJ_invert = array_inverse ( YIJ ) # Perform sum_k X_ik Y_jk^-1 epsilon = np . sum ( XIJ . reshape ( - 1 , 3 , 1 , 3 ) * YIJ_invert . reshape ( - 1 , 1 , 3 , 3 ) , axis =...
Calculate delta_ij + epsilon_ij i . e . the deformation gradient matrix
147
21
245,239
def get_D_square_min ( atoms_now , atoms_old , i_now , j_now , delta_plus_epsilon = None ) : nat = len ( atoms_now ) assert len ( atoms_now ) == len ( atoms_old ) pos_now = atoms_now . positions pos_old = atoms_old . positions # Compute current and old distance vectors. Note that current distance # vectors cannot be ta...
Calculate the D^2_min norm of Falk and Langer
430
15
245,240
def dhms ( secs ) : dhms = [ 0 , 0 , 0 , 0 ] dhms [ 0 ] = int ( secs // 86400 ) s = secs % 86400 dhms [ 1 ] = int ( s // 3600 ) s = secs % 3600 dhms [ 2 ] = int ( s // 60 ) s = secs % 60 dhms [ 3 ] = int ( s + .5 ) return dhms
return days hours minutes and seconds
97
6
245,241
def hms ( secs ) : hms = [ 0 , 0 , 0 ] hms [ 0 ] = int ( secs // 3600 ) s = secs % 3600 hms [ 1 ] = int ( s // 60 ) s = secs % 60 hms [ 2 ] = int ( s + .5 ) return hms
return hours minutes and seconds
73
5
245,242
def get_enclosing_orthorhombic_box ( cell ) : # Cell vectors cx , cy , cz = cell # The cell has eight corners, one is at the origin, three at cx, cy, cz # and the last ones are... c1 = cx + cy c2 = cx + cz c3 = cy + cz c4 = cx + cy + cz corners = np . array ( [ [ 0 , 0 , 0 ] , cx , cy , cz , c1 , c2 , c3 , c4 ] ) lower...
Return lower and upper bounds of the orthorhombic box that encloses the parallelepiped spanned by the three cell vectors of cell .
143
31
245,243
def stress_invariants ( s ) : s = np . asarray ( s ) if s . shape == ( 6 , ) : s = s . reshape ( 1 , - 1 ) elif s . shape == ( 3 , 3 ) : s = s . reshape ( 1 , - 1 , - 1 ) if len ( s . shape ) == 3 : s = np . transpose ( [ s [ : , 0 , 0 ] , s [ : , 1 , 1 ] , s [ : , 2 , 2 ] , ( s [ : , 0 , 1 ] + s [ : , 1 , 0 ] ) / 2 , ...
Receives a list of stress tensors and returns the three invariants . Return hydrostatic pressure octahedral shear stress and J3
439
29
245,244
def scanmeta ( f ) : print ( f ) if isinstance ( f , str ) : f = io . open ( f , mode = 'r' , encoding = 'latin-1' ) done = False l = f . readline ( ) s = None while l and s is None : i = l . find ( '!' ) if i >= 0 : l = l [ i + 1 : ] i = l . find ( '@meta' ) if i >= 0 : l = l [ i + 5 : ] i = l . find ( '@endmeta' ) if...
Scan file headers for
329
4
245,245
def mic ( dr , cell , pbc = None ) : # Check where distance larger than 1/2 cell. Particles have crossed # periodic boundaries then and need to be unwrapped. rec = np . linalg . inv ( cell ) if pbc is not None : rec *= np . array ( pbc , dtype = int ) . reshape ( 3 , 1 ) dri = np . round ( np . dot ( dr , rec ) ) # Unw...
Apply minimum image convention to an array of distance vectors .
111
11
245,246
def s_from_dhms ( time ) : dhms_s = { 's' : 1 , 'm' : 60 , 'h' : 3600 , 'd' : 86400 } time = time . lower ( ) word_list = re . findall ( '\d*[^\d]*' , time ) seconds = 0 for word in word_list : if word != '' : sec = 1 for t in list ( dhms_s . keys ( ) ) : nw = word . replace ( t , '' ) if nw != word : sec = dhms_s [ t ...
return seconds from dhms
167
5
245,247
def get_stress ( self , a ) : s = np . zeros ( 6 , dtype = float ) for c in self . calcs : s += c . get_stress ( a ) return s
Calculate stress tensor .
44
7
245,248
def set_atoms ( self , a ) : for c in self . calcs : if hasattr ( c , "set_atoms" ) : c . set_atoms ( a )
Assign an atoms object .
42
6
245,249
def rename_edges ( self , old_task_name , new_task_name , graph = None ) : if not graph : graph = self . graph for node , edges in graph . items ( ) : if node == old_task_name : graph [ new_task_name ] = copy ( edges ) del graph [ old_task_name ] else : if old_task_name in edges : edges . remove ( old_task_name ) edges...
Change references to a task in existing edges .
107
9
245,250
def predecessors ( self , node , graph = None ) : if graph is None : graph = self . graph return [ key for key in graph if node in graph [ key ] ]
Returns a list of all predecessors of the given node
37
10
245,251
def constant ( name , shape , value = 0 , dtype = tf . sg_floatx , summary = True , regularizer = None , trainable = True ) : shape = shape if isinstance ( shape , ( tuple , list ) ) else [ shape ] x = tf . get_variable ( name , shape , dtype = dtype , initializer = tf . constant_initializer ( value ) , regularizer = r...
r Creates a tensor variable of which initial values are value and shape is shape .
118
18
245,252
def sg_producer_func ( func ) : @ wraps ( func ) def wrapper ( * * kwargs ) : r"""Manages arguments of `tf.sg_opt`. Args: **kwargs: source: A source queue list to enqueue dtypes: Input data types of each tensor out_dtypes: Output data types of each tensor ( If None, same as dtypes ) capacity: Queue capacity. Default is...
r Decorates a function func as sg_producer_func .
568
16
245,253
def sg_transpose ( tensor , opt ) : assert opt . perm is not None , 'perm is mandatory' return tf . transpose ( tensor , opt . perm , name = opt . name )
r Permutes the dimensions according to opt . perm .
45
12
245,254
def sg_argmin ( tensor , opt ) : opt += tf . sg_opt ( axis = tensor . get_shape ( ) . ndims - 1 ) return tf . argmin ( tensor , opt . axis , opt . name )
r Returns the indices of the minimum values along the specified axis .
56
13
245,255
def sg_concat ( tensor , opt ) : assert opt . target is not None , 'target is mandatory.' opt += tf . sg_opt ( axis = tensor . get_shape ( ) . ndims - 1 ) target = opt . target if isinstance ( opt . target , ( tuple , list ) ) else [ opt . target ] return tf . concat ( [ tensor ] + target , opt . axis , name = opt . na...
r Concatenates tensors along a axis .
100
11
245,256
def sg_log ( tensor , opt ) : return tf . log ( tensor + tf . sg_eps , name = opt . name )
r Log transform a dense tensor
33
7
245,257
def sg_prod ( tensor , opt ) : return tf . reduce_prod ( tensor , axis = opt . axis , keep_dims = opt . keep_dims , name = opt . name )
r Computes the product of elements across axis of a tensor .
48
14
245,258
def sg_min ( tensor , opt ) : return tf . reduce_min ( tensor , axis = opt . axis , keep_dims = opt . keep_dims , name = opt . name )
r Computes the minimum of elements across axis of a tensor .
46
14
245,259
def sg_max ( tensor , opt ) : return tf . reduce_max ( tensor , axis = opt . axis , keep_dims = opt . keep_dims , name = opt . name )
r Computes the maximum of elements across axis of a tensor .
46
14
245,260
def sg_any ( tensor , opt ) : return tf . reduce_any ( tensor , axis = opt . axis , keep_dims = opt . keep_dims , name = opt . name )
r Computes the logical or of elements across axis of a tensor .
46
15
245,261
def sg_lookup ( tensor , opt ) : assert opt . emb is not None , 'emb is mandatory.' return tf . nn . embedding_lookup ( opt . emb , tensor , name = opt . name )
r Looks up the tensor which is the embedding matrix .
51
13
245,262
def sg_reverse_seq ( tensor , opt ) : # default sequence dimension opt += tf . sg_opt ( axis = 1 ) seq_len = tf . not_equal ( tensor , tf . zeros_like ( tensor ) ) . sg_int ( ) . sg_sum ( axis = opt . axis ) return tf . reverse_sequence ( tensor , seq_len , opt . axis , name = opt . name )
r Reverses variable length slices .
98
8
245,263
def sg_gpus ( ) : global _gpus if _gpus is None : local_device_protos = device_lib . list_local_devices ( ) _gpus = len ( [ x . name for x in local_device_protos if x . device_type == 'GPU' ] ) return max ( _gpus , 1 )
r Gets current available GPU nums
78
7
245,264
def sg_context ( * * kwargs ) : global _context # set options when enter context_now = tf . sg_opt ( kwargs ) _context += [ context_now ] # if named context if context_now . name : context_now . scope_name = context_now . name context_now . name = None with tf . variable_scope ( context_now . scope_name ) : yield else ...
r Context helper for computational graph building . Makes all elements within the with Block share the parameters .
107
19
245,265
def sg_get_context ( ) : global _context # merge current context res = tf . sg_opt ( ) for c in _context : res += c return res
r Get current context information
38
5
245,266
def sg_sugar_func ( func ) : @ wraps ( func ) def wrapper ( tensor , * * kwargs ) : # call sugar function out = func ( tensor , tf . sg_opt ( kwargs ) ) # save node info for reuse out . _sugar = tf . sg_opt ( func = func , arg = tf . sg_opt ( kwargs ) + sg_get_context ( ) , prev = tensor ) # inject reuse function out ....
r Decorates a function func so that it can be a sugar function . Sugar function can be used in a chainable manner .
133
27
245,267
def sg_reuse ( tensor , * * opt ) : opt = tf . sg_opt ( opt ) assert hasattr ( tensor , '_sugar' ) , 'cannot reuse this node.' assert opt . input is not None , 'input is mandatory.' # get all nodes in this graph nodes , prev = [ tensor ] , tensor . _sugar . prev while prev is not None : nodes = [ prev ] + nodes prev = ...
r Reconstruct computational graph of tensor so all the parameters can be reused and replace its input tensor with opt . input .
314
26
245,268
def sg_input ( shape = None , dtype = sg_floatx , name = None ) : if shape is None : return tf . placeholder ( dtype , shape = None , name = name ) else : if not isinstance ( shape , ( list , tuple ) ) : shape = [ shape ] return tf . placeholder ( dtype , shape = [ None ] + list ( shape ) , name = name )
r Creates a placeholder .
89
6
245,269
def sg_inject ( path , mod_name ) : # import module import sys if path not in list ( sys . path ) : sys . path . append ( path ) globals ( ) [ mod_name ] = importlib . import_module ( mod_name ) # find functions for func_name in dir ( globals ( ) [ mod_name ] ) : if isinstance ( globals ( ) [ mod_name ] . __dict__ . ge...
r Converts all functions in the given Python module to sugar functions so that they can be used in a chainable manner .
204
25
245,270
def sg_queue_context ( sess = None ) : # default session sess = tf . get_default_session ( ) if sess is None else sess # thread coordinator coord = tf . train . Coordinator ( ) try : # start queue thread threads = tf . train . start_queue_runners ( sess , coord ) yield finally : # stop queue thread coord . request_stop...
r Context helper for queue routines .
98
7
245,271
def sg_arg ( ) : if not tf . app . flags . FLAGS . __dict__ [ '__parsed' ] : tf . app . flags . FLAGS . _parse_flags ( ) return tf . sg_opt ( tf . app . flags . FLAGS . __dict__ [ '__flags' ] )
r Gets current command line options
76
6
245,272
def sg_arg_def ( * * kwargs ) : for k , v in kwargs . items ( ) : if type ( v ) is tuple or type ( v ) is list : v , c = v [ 0 ] , v [ 1 ] else : c = k if type ( v ) is str : tf . app . flags . DEFINE_string ( k , v , c ) elif type ( v ) is int : tf . app . flags . DEFINE_integer ( k , v , c ) elif type ( v ) is float ...
r Defines command line options
164
6
245,273
def sg_summary_loss ( tensor , prefix = 'losses' , name = None ) : # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name ( tensor ) if name is None else prefix + name # summary statistics _scalar ( name , tf . reduce_mean ( tensor ) ) _histogram ( name + '-h' , tensor )
r Register tensor to summary report as loss
94
9
245,274
def sg_summary_gradient ( tensor , gradient , prefix = None , name = None ) : # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name ( tensor ) if name is None else prefix + name # summary statistics # noinspection PyBroadException _scalar ( name + '/grad' , tf . reduce_m...
r Register tensor to summary report as gradient
113
9
245,275
def sg_summary_activation ( tensor , prefix = None , name = None ) : # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name ( tensor ) if name is None else prefix + name # summary statistics _scalar ( name + '/ratio' , tf . reduce_mean ( tf . cast ( tf . greater ( tensor ...
r Register tensor to summary report as activation
118
9
245,276
def sg_summary_param ( tensor , prefix = None , name = None ) : # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name ( tensor ) if name is None else prefix + name # summary statistics _scalar ( name + '/abs' , tf . reduce_mean ( tf . abs ( tensor ) ) ) _histogram ( name...
r Register tensor to summary report as parameters
106
9
245,277
def sg_summary_image ( tensor , prefix = None , name = None ) : # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name ( tensor ) if name is None else prefix + name # summary statistics if not tf . get_variable_scope ( ) . reuse : tf . summary . image ( name + '-im' , ten...
r Register tensor to summary report as image
90
9
245,278
def sg_summary_audio ( tensor , sample_rate = 16000 , prefix = None , name = None ) : # defaults prefix = '' if prefix is None else prefix + '/' # summary name name = prefix + _pretty_name ( tensor ) if name is None else prefix + name # summary statistics if not tf . get_variable_scope ( ) . reuse : tf . summary . audi...
r Register tensor to summary report as audio
101
9
245,279
def sg_train ( * * kwargs ) : opt = tf . sg_opt ( kwargs ) assert opt . loss is not None , 'loss is mandatory.' # default training options opt += tf . sg_opt ( optim = 'MaxProp' , lr = 0.001 , beta1 = 0.9 , beta2 = 0.99 , category = '' , ep_size = 100000 ) # get optimizer train_op = sg_optim ( opt . loss , optim = opt ...
r Trains the model .
246
6
245,280
def sg_restore ( sess , save_path , category = '' ) : # to list if not isinstance ( category , ( tuple , list ) ) : category = [ category ] # make variable list to load var_list = { } for cat in category : for t in tf . global_variables ( ) : if t . name . startswith ( cat ) : var_list [ t . name [ : - 2 ] ] = t # rest...
r Restores previously saved variables .
126
7
245,281
def sg_regularizer_loss ( scale = 1.0 ) : return scale * tf . reduce_mean ( tf . get_collection ( tf . GraphKeys . REGULARIZATION_LOSSES ) )
r Get regularizer losss
46
6
245,282
def sg_densenet_layer ( x , opt ) : assert opt . dim is not None , 'dim is mandatory.' assert opt . num is not None , 'num is mandatory.' # default stride opt += tf . sg_opt ( stride = 1 , act = 'relu' , trans = True ) # format convolutional layer name def cname ( index ) : return opt . name if opt . name is None else ...
r Applies basic architecture of densenet layer .
342
11
245,283
def deep_merge_dict ( a , b ) : if not isinstance ( a , dict ) : raise TypeError ( "a must be a dict, but found %s" % a . __class__ . __name__ ) if not isinstance ( b , dict ) : raise TypeError ( "b must be a dict, but found %s" % b . __class__ . __name__ ) _a = copy ( a ) _b = copy ( b ) for key_b , val_b in iteritems...
Deep merges dictionary b into dictionary a .
233
9
245,284
def copy_file_if_modified ( src_path , dest_path ) : # if the destination path is a directory, delete it completely - we assume here we are # writing a file to the filesystem if os . path . isdir ( dest_path ) : shutil . rmtree ( dest_path ) must_copy = False if not os . path . exists ( dest_path ) : must_copy = True e...
Only copies the file from the source path to the destination path if it doesn t exist yet or it has been modified . Intended to provide something of an optimisation when a project has large trees of assets .
203
42
245,285
def get_url_file_ext ( url ) : # get the last part of the path component filename = url . split ( '/' ) [ - 1 ] name , ext = os . path . splitext ( filename ) # handle case of files with leading dot if not ext and name and name [ 0 ] == '.' : ext = name return ext
Attempts to extract the file extension from the given URL .
75
11
245,286
def generate_quickstart ( project_path ) : ensure_path_exists ( project_path ) ensure_file_exists ( os . path . join ( project_path , "config.yml" ) , DEFAULT_CONFIG_CONTENT ) ensure_path_exists ( os . path . join ( project_path , 'models' ) ) ensure_path_exists ( os . path . join ( project_path , 'data' ) ) ensure_pat...
Generates all of the basic paths for a Statik project within the given project path . If the project path doesn t exist it will be created .
216
30
245,287
def get_project_config_file ( path , default_config_file_name ) : _path , _config_file_path = None , None path = os . path . abspath ( path ) if os . path . isdir ( path ) : _path = path # use the default config file _config_file_path = os . path . join ( _path , default_config_file_name ) logger . debug ( "Using defau...
Attempts to extract the project config file s absolute path from the given path . If the path is a directory it automatically assumes a config . yml file will be in that directory . If the path is to a . yml file it assumes that that is the root configuration file for the project .
179
59
245,288
def strip_el_text ( el , max_depth = 0 , cur_depth = 0 ) : # text in front of any child elements el_text = strip_str ( el . text if el . text is not None else "" ) if cur_depth < max_depth : for child in el : el_text += " " + strip_el_text ( child , max_depth = max_depth , cur_depth = cur_depth + 1 ) else : # add the l...
Recursively strips the plain text out of the given XML etree element up to the desired depth .
219
21
245,289
def find_first_file_with_ext ( base_paths , prefix , exts ) : for base_path in base_paths : for ext in exts : filename = os . path . join ( base_path , "%s%s" % ( prefix , ext ) ) if os . path . exists ( filename ) and os . path . isfile ( filename ) : logger . debug ( "Found first file with relevant extension: %s" , f...
Runs through the given list of file extensions and returns the first file with the given base path and extension combination that actually exists .
139
26
245,290
def find_duplicates_in_array ( array ) : duplicates = [ ] non_duplicates = [ ] if len ( array ) != len ( set ( array ) ) : for item in array : if item not in non_duplicates : non_duplicates . append ( item ) elif item in non_duplicates and item not in duplicates : duplicates . append ( item ) return duplicates
Runs through the array and returns the elements that contain more than one duplicate
92
15
245,291
def read_requirements ( filename ) : data = [ ] for line in read_file ( filename ) : line = line . strip ( ) if not line or line . startswith ( '#' ) : continue if '+' in line [ : 4 ] : repo_link , egg_name = line . split ( '#egg=' ) if not egg_name : raise ValueError ( 'Unknown requirement: {0}' . format ( line ) ) DE...
Parse a requirements file .
124
6
245,292
def find_additional_rels ( self , all_models ) : for model_name , model in iteritems ( all_models ) : if model_name != self . name : for field_name in model . field_names : field = model . fields [ field_name ] # if this field type references the current model if field . field_type == self . name and field . back_popul...
Attempts to scan for additional relationship fields for this model based on all of the other models structures and relationships .
235
21
245,293
def create_db ( self , models ) : # first create the table definitions self . tables = dict ( [ ( model_name , self . create_model_table ( model ) ) for model_name , model in iteritems ( models ) ] ) # now create the tables in memory logger . debug ( "Creating %d database table(s)..." , len ( self . tables ) ) try : se...
Creates the in - memory SQLite database from the model configuration .
140
14
245,294
def sort_models ( self ) : model_names = [ table . name for table in self . Base . metadata . sorted_tables if table . name in self . models ] logger . debug ( "Unsorted models: %s" , model_names ) model_count = len ( model_names ) swapped = True sort_round = 0 while swapped : sort_round += 1 logger . debug ( 'Sorting ...
Sorts the database models appropriately based on their relationships so that we load our data in the appropriate order .
269
21
245,295
def create_model_table ( self , model ) : try : return db_model_factory ( self . Base , model , self . models ) except Exception as exc : raise ModelError ( model . name , message = "failed to create in-memory table." , orig_exc = exc , context = self . error_context )
Creates the table for the given model .
71
9
245,296
def load_model_data ( self , path , model ) : if os . path . isdir ( path ) : # try find a model data collection if os . path . isfile ( os . path . join ( path , '_all.yml' ) ) : self . load_model_data_collection ( path , model ) self . load_model_data_from_files ( path , model ) self . session . commit ( )
Loads the data for the specified model from the given path .
95
13
245,297
def query ( self , query , additional_locals = None , safe_mode = False ) : logger . debug ( "Attempting to execute database query: %s" , query ) if safe_mode and not isinstance ( query , dict ) : raise SafetyViolationError ( context = self . error_context ) if isinstance ( query , dict ) : logger . debug ( "Executing ...
Executes the given SQLAlchemy query string .
217
10
245,298
def generate ( input_path , output_path = None , in_memory = False , safe_mode = False , error_context = None ) : project = StatikProject ( input_path , safe_mode = safe_mode , error_context = error_context ) return project . generate ( output_path = output_path , in_memory = in_memory )
Executes the Statik site generator using the given parameters .
79
12
245,299
def generate ( self , output_path = None , in_memory = False ) : result = dict ( ) if in_memory else 0 logger . info ( "Generating Statik build..." ) try : if output_path is None and not in_memory : raise InternalError ( "If project is not to be generated in-memory, an output path must be specified" ) self . error_cont...
Executes the Statik project generator .
603
8