idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
225,900
def column_coordinates ( self , X ) : utils . validation . check_is_fitted ( self , 'V_' ) _ , _ , _ , col_names = util . make_labels_and_names ( X ) if isinstance ( X , pd . SparseDataFrame ) : X = X . to_coo ( ) elif isinstance ( X , pd . DataFrame ) : X = X . to_numpy ( ) if self . copy : X = X . copy ( ) # Transpose and make sure the rows sum up to 1 if isinstance ( X , np . ndarray ) : X = X . T / X . T . sum ( axis = 1 ) [ : , None ] else : X = X . T / X . T . sum ( axis = 1 ) return pd . DataFrame ( data = X @ sparse . diags ( self . row_masses_ . to_numpy ( ) ** - 0.5 ) @ self . U_ , index = col_names )
The column principal coordinates .
225
5
225,901
def plot_coordinates ( self , X , ax = None , figsize = ( 6 , 6 ) , x_component = 0 , y_component = 1 , show_row_labels = True , show_col_labels = True , * * kwargs ) : utils . validation . check_is_fitted ( self , 's_' ) if ax is None : fig , ax = plt . subplots ( figsize = figsize ) # Add style ax = plot . stylize_axis ( ax ) # Get labels and names row_label , row_names , col_label , col_names = util . make_labels_and_names ( X ) # Plot row principal coordinates row_coords = self . row_coordinates ( X ) ax . scatter ( row_coords [ x_component ] , row_coords [ y_component ] , * * kwargs , label = row_label ) # Plot column principal coordinates col_coords = self . column_coordinates ( X ) ax . scatter ( col_coords [ x_component ] , col_coords [ y_component ] , * * kwargs , label = col_label ) # Add row labels if show_row_labels : x = row_coords [ x_component ] y = row_coords [ y_component ] for i , label in enumerate ( row_names ) : ax . annotate ( label , ( x [ i ] , y [ i ] ) ) # Add column labels if show_col_labels : x = col_coords [ x_component ] y = col_coords [ y_component ] for i , label in enumerate ( col_names ) : ax . annotate ( label , ( x [ i ] , y [ i ] ) ) # Legend ax . legend ( ) # Text ax . set_title ( 'Principal coordinates' ) ei = self . explained_inertia_ ax . set_xlabel ( 'Component {} ({:.2f}% inertia)' . format ( x_component , 100 * ei [ x_component ] ) ) ax . set_ylabel ( 'Component {} ({:.2f}% inertia)' . format ( y_component , 100 * ei [ y_component ] ) ) return ax
Plot the principal coordinates .
498
5
225,902
def plot_coordinates ( self , X , ax = None , figsize = ( 6 , 6 ) , x_component = 0 , y_component = 1 , show_row_points = True , row_points_size = 10 , show_row_labels = False , show_column_points = True , column_points_size = 30 , show_column_labels = False , legend_n_cols = 1 ) : utils . validation . check_is_fitted ( self , 'total_inertia_' ) if ax is None : fig , ax = plt . subplots ( figsize = figsize ) # Add style ax = plot . stylize_axis ( ax ) # Plot row principal coordinates if show_row_points or show_row_labels : row_coords = self . row_coordinates ( X ) if show_row_points : ax . scatter ( row_coords . iloc [ : , x_component ] , row_coords . iloc [ : , y_component ] , s = row_points_size , label = None , color = plot . GRAY [ 'dark' ] , alpha = 0.6 ) if show_row_labels : for _ , row in row_coords . iterrows ( ) : ax . annotate ( row . name , ( row [ x_component ] , row [ y_component ] ) ) # Plot column principal coordinates if show_column_points or show_column_labels : col_coords = self . column_coordinates ( X ) x = col_coords [ x_component ] y = col_coords [ y_component ] prefixes = col_coords . index . str . split ( '_' ) . map ( lambda x : x [ 0 ] ) for prefix in prefixes . unique ( ) : mask = prefixes == prefix if show_column_points : ax . scatter ( x [ mask ] , y [ mask ] , s = column_points_size , label = prefix ) if show_column_labels : for i , label in enumerate ( col_coords [ mask ] . index ) : ax . annotate ( label , ( x [ mask ] [ i ] , y [ mask ] [ i ] ) ) ax . legend ( ncol = legend_n_cols ) # Text ax . set_title ( 'Row and column principal coordinates' ) ei = self . explained_inertia_ ax . set_xlabel ( 'Component {} ({:.2f}% inertia)' . format ( x_component , 100 * ei [ x_component ] ) ) ax . set_ylabel ( 'Component {} ({:.2f}% inertia)' . format ( y_component , 100 * ei [ y_component ] ) ) return ax
Plot row and column principal coordinates .
607
7
225,903
def compute_svd ( X , n_components , n_iter , random_state , engine ) : # Determine what SVD engine to use if engine == 'auto' : engine = 'sklearn' # Compute the SVD if engine == 'fbpca' : if FBPCA_INSTALLED : U , s , V = fbpca . pca ( X , k = n_components , n_iter = n_iter ) else : raise ValueError ( 'fbpca is not installed; please install it if you want to use it' ) elif engine == 'sklearn' : U , s , V = extmath . randomized_svd ( X , n_components = n_components , n_iter = n_iter , random_state = random_state ) else : raise ValueError ( "engine has to be one of ('auto', 'fbpca', 'sklearn')" ) U , V = extmath . svd_flip ( U , V ) return U , s , V
Computes an SVD with k components .
226
9
225,904
def row_standard_coordinates ( self , X ) : utils . validation . check_is_fitted ( self , 's_' ) return self . row_coordinates ( X ) . div ( self . eigenvalues_ , axis = 'columns' )
Returns the row standard coordinates .
58
6
225,905
def row_cosine_similarities ( self , X ) : utils . validation . check_is_fitted ( self , 's_' ) squared_coordinates = np . square ( self . row_coordinates ( X ) ) total_squares = squared_coordinates . sum ( axis = 'columns' ) return squared_coordinates . div ( total_squares , axis = 'rows' )
Returns the cosine similarities between the rows and their principal components .
89
13
225,906
def column_correlations ( self , X ) : utils . validation . check_is_fitted ( self , 's_' ) # Convert numpy array to pandas DataFrame if isinstance ( X , np . ndarray ) : X = pd . DataFrame ( X ) row_pc = self . row_coordinates ( X ) return pd . DataFrame ( { component : { feature : row_pc [ component ] . corr ( X [ feature ] ) for feature in X . columns } for component in row_pc . columns } )
Returns the column correlations with each principal component .
120
9
225,907
def build_ellipse ( X , Y ) : x_mean = np . mean ( X ) y_mean = np . mean ( Y ) cov_matrix = np . cov ( np . vstack ( ( X , Y ) ) ) U , s , V = linalg . svd ( cov_matrix , full_matrices = False ) chi_95 = np . sqrt ( 4.61 ) # 90% quantile of the chi-square distribution width = np . sqrt ( cov_matrix [ 0 ] [ 0 ] ) * chi_95 * 2 height = np . sqrt ( cov_matrix [ 1 ] [ 1 ] ) * chi_95 * 2 eigenvector = V . T [ 0 ] angle = np . arctan ( eigenvector [ 1 ] / eigenvector [ 0 ] ) return x_mean , y_mean , width , height , angle
Construct ellipse coordinates from two arrays of numbers .
196
11
225,908
def set_start_time ( self , start_time ) : start_time = start_time or dt . time ( ) if isinstance ( start_time , dt . time ) : # ensure that we operate with time self . start_time = dt . time ( start_time . hour , start_time . minute ) else : self . start_time = dt . time ( start_time . time ( ) . hour , start_time . time ( ) . minute )
set the start time . when start time is set drop down list will start from start time and duration will be displayed in brackets
105
25
225,909
def extract_time ( match ) : hour = int ( match . group ( 'hour' ) ) minute = int ( match . group ( 'minute' ) ) return dt . time ( hour , minute )
extract time from a time_re match .
44
10
225,910
def default_logger ( name ) : # https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial logger = logging . getLogger ( name ) # this is a basic handler, with output to stderr logger_handler = logging . StreamHandler ( ) formatter = logging . Formatter ( '%(name)s - %(levelname)s - %(message)s' ) logger_handler . setFormatter ( formatter ) logger . addHandler ( logger_handler ) return logger
Return a toplevel logger .
120
7
225,911
def serialized ( self , prepend_date = True ) : name = self . serialized_name ( ) datetime = self . serialized_time ( prepend_date ) return "%s %s" % ( datetime , name )
Return a string fully representing the fact .
52
8
225,912
def _with_rotation ( self , w , h ) : res_w = abs ( w * math . cos ( self . rotation ) + h * math . sin ( self . rotation ) ) res_h = abs ( h * math . cos ( self . rotation ) + w * math . sin ( self . rotation ) ) return res_w , res_h
calculate the actual dimensions after rotation
78
8
225,913
def queue_resize ( self ) : self . _children_resize_queued = True parent = getattr ( self , "parent" , None ) if parent and isinstance ( parent , graphics . Sprite ) and hasattr ( parent , "queue_resize" ) : parent . queue_resize ( )
request the element to re - check it s child sprite sizes
68
12
225,914
def get_min_size ( self ) : if self . visible == False : return 0 , 0 else : return ( ( self . min_width or 0 ) + self . horizontal_padding + self . margin_left + self . margin_right , ( self . min_height or 0 ) + self . vertical_padding + self . margin_top + self . margin_bottom )
returns size required by the widget
81
7
225,915
def insert ( self , index = 0 , * widgets ) : for widget in widgets : self . _add ( widget , index ) index += 1 # as we are moving forwards self . _sort ( )
insert widget in the sprites list at the given index . by default will prepend .
42
17
225,916
def insert_before ( self , target ) : if not target . parent : return target . parent . insert ( target . parent . sprites . index ( target ) , self )
insert this widget into the targets parent before the target
36
10
225,917
def insert_after ( self , target ) : if not target . parent : return target . parent . insert ( target . parent . sprites . index ( target ) + 1 , self )
insert this widget into the targets parent container after the target
38
11
225,918
def width ( self ) : alloc_w = self . alloc_w if self . parent and isinstance ( self . parent , graphics . Scene ) : alloc_w = self . parent . width def res ( scene , event ) : if self . parent : self . queue_resize ( ) else : scene . disconnect ( self . _scene_resize_handler ) self . _scene_resize_handler = None if not self . _scene_resize_handler : # TODO - disconnect on reparenting self . _scene_resize_handler = self . parent . connect ( "on-resize" , res ) min_width = ( self . min_width or 0 ) + self . margin_left + self . margin_right w = alloc_w if alloc_w is not None and self . fill else min_width w = max ( w or 0 , self . get_min_size ( ) [ 0 ] ) return w - self . margin_left - self . margin_right
width in pixels
215
3
225,919
def height ( self ) : alloc_h = self . alloc_h if self . parent and isinstance ( self . parent , graphics . Scene ) : alloc_h = self . parent . height min_height = ( self . min_height or 0 ) + self . margin_top + self . margin_bottom h = alloc_h if alloc_h is not None and self . fill else min_height h = max ( h or 0 , self . get_min_size ( ) [ 1 ] ) return h - self . margin_top - self . margin_bottom
height in pixels
121
3
225,920
def enabled ( self ) : enabled = self . _enabled if not enabled : return False if self . parent and isinstance ( self . parent , Widget ) : if self . parent . enabled == False : return False return True
whether the user is allowed to interact with the widget . Item is enabled only if all it s parent elements are
47
22
225,921
def resize_children ( self ) : width = self . width - self . horizontal_padding height = self . height - self . vertical_padding for sprite , props in ( get_props ( sprite ) for sprite in self . sprites if sprite . visible ) : sprite . alloc_w = width sprite . alloc_h = height w , h = getattr ( sprite , "width" , 0 ) , getattr ( sprite , "height" , 0 ) if hasattr ( sprite , "get_height_for_width_size" ) : w2 , h2 = sprite . get_height_for_width_size ( ) w , h = max ( w , w2 ) , max ( h , h2 ) w = w * sprite . scale_x + props [ "margin_left" ] + props [ "margin_right" ] h = h * sprite . scale_y + props [ "margin_top" ] + props [ "margin_bottom" ] sprite . x = self . padding_left + props [ "margin_left" ] + ( max ( sprite . alloc_w * sprite . scale_x , w ) - w ) * getattr ( sprite , "x_align" , 0 ) sprite . y = self . padding_top + props [ "margin_top" ] + ( max ( sprite . alloc_h * sprite . scale_y , h ) - h ) * getattr ( sprite , "y_align" , 0 ) self . __dict__ [ '_children_resize_queued' ] = False
default container alignment is to pile stuff just up respecting only padding margin and element s alignment properties
332
18
225,922
def check_hamster ( self ) : try : # can't use the client because then we end up in a dbus loop # as this is initiated in storage todays_facts = self . storage . _Storage__get_todays_facts ( ) self . check_user ( todays_facts ) except Exception as e : logger . error ( "Error while refreshing: %s" % e ) finally : # we want to go on no matter what, so in case of any error we find out about it sooner return True
refresh hamster every x secs - load today check last activity etc .
112
16
225,923
def check_user ( self , todays_facts ) : interval = self . conf_notify_interval if interval <= 0 or interval >= 121 : return now = dt . datetime . now ( ) message = None last_activity = todays_facts [ - 1 ] if todays_facts else None # update duration of current task if last_activity and not last_activity [ 'end_time' ] : delta = now - last_activity [ 'start_time' ] duration = delta . seconds / 60 if duration and duration % interval == 0 : message = _ ( "Working on %s" ) % last_activity [ 'name' ] self . notify_user ( message ) elif self . conf_notify_on_idle : #if we have no last activity, let's just calculate duration from 00:00 if ( now . minute + now . hour * 60 ) % interval == 0 : self . notify_user ( _ ( "No activity" ) )
check if we need to notify user perhaps
210
8
225,924
def stop_tracking ( self , end_time ) : facts = self . __get_todays_facts ( ) if facts and not facts [ - 1 ] [ 'end_time' ] : self . __touch_fact ( facts [ - 1 ] , end_time ) self . facts_changed ( )
Stops tracking the current activity
67
6
225,925
def remove_fact ( self , fact_id ) : self . start_transaction ( ) fact = self . __get_fact ( fact_id ) if fact : self . __remove_fact ( fact_id ) self . facts_changed ( ) self . end_transaction ( )
Remove fact from storage by it s ID
62
8
225,926
def load_ui_file ( name ) : ui = gtk . Builder ( ) ui . add_from_file ( os . path . join ( runtime . data_dir , name ) ) return ui
loads interface from the glade file ; sorts out the path business
46
13
225,927
def _fix_key ( self , key ) : if not key . startswith ( self . GCONF_DIR ) : return self . GCONF_DIR + key else : return key
Appends the GCONF_PREFIX to the key if needed
42
15
225,928
def _key_changed ( self , client , cnxn_id , entry , data = None ) : key = self . _fix_key ( entry . key ) [ len ( self . GCONF_DIR ) : ] value = self . _get_value ( entry . value , self . DEFAULTS [ key ] ) self . emit ( 'conf-changed' , key , value )
Callback when a gconf key changes
86
7
225,929
def _get_value ( self , value , default ) : vtype = type ( default ) if vtype is bool : return value . get_bool ( ) elif vtype is str : return value . get_string ( ) elif vtype is int : return value . get_int ( ) elif vtype in ( list , tuple ) : l = [ ] for i in value . get_list ( ) : l . append ( i . get_string ( ) ) return l return None
calls appropriate gconf function by the default value
106
10
225,930
def get ( self , key , default = None ) : #function arguments override defaults if default is None : default = self . DEFAULTS . get ( key , None ) vtype = type ( default ) #we now have a valid key and type if default is None : logger . warn ( "Unknown key: %s, must specify default value" % key ) return None if vtype not in self . VALID_KEY_TYPES : logger . warn ( "Invalid key type: %s" % vtype ) return None #for gconf refer to the full key path key = self . _fix_key ( key ) if key not in self . _notifications : self . _client . notify_add ( key , self . _key_changed , None ) self . _notifications . append ( key ) value = self . _client . get ( key ) if value is None : self . set ( key , default ) return default value = self . _get_value ( value , default ) if value is not None : return value logger . warn ( "Unknown gconf key: %s" % key ) return None
Returns the value of the key or the default value if the key is not yet in gconf
238
19
225,931
def set ( self , key , value ) : logger . debug ( "Settings %s -> %s" % ( key , value ) ) if key in self . DEFAULTS : vtype = type ( self . DEFAULTS [ key ] ) else : vtype = type ( value ) if vtype not in self . VALID_KEY_TYPES : logger . warn ( "Invalid key type: %s" % vtype ) return False #for gconf refer to the full key path key = self . _fix_key ( key ) if vtype is bool : self . _client . set_bool ( key , value ) elif vtype is str : self . _client . set_string ( key , value ) elif vtype is int : self . _client . set_int ( key , value ) elif vtype in ( list , tuple ) : #Save every value as a string strvalues = [ str ( i ) for i in value ] #self._client.set_list(key, gconf.VALUE_STRING, strvalues) return True
Sets the key value in gconf and connects adds a signal which is fired if the key changes
230
20
225,932
def day_start ( self ) : day_start_minutes = self . get ( "day_start_minutes" ) hours , minutes = divmod ( day_start_minutes , 60 ) return dt . time ( hours , minutes )
Start of the hamster day .
54
7
225,933
def localized_fact ( self ) : fact = Fact ( self . activity . get_text ( ) ) if fact . start_time : fact . date = self . date else : fact . start_time = dt . datetime . now ( ) return fact
Make sure fact has the correct start_time .
55
10
225,934
def set_row_positions ( self ) : self . row_positions = [ i * self . row_height for i in range ( len ( self . rows ) ) ] self . set_size_request ( 0 , self . row_positions [ - 1 ] + self . row_height if self . row_positions else 0 )
creates a list of row positions for simpler manipulation
75
10
225,935
def from_dbus_fact ( fact ) : return Fact ( fact [ 4 ] , start_time = dt . datetime . utcfromtimestamp ( fact [ 1 ] ) , end_time = dt . datetime . utcfromtimestamp ( fact [ 2 ] ) if fact [ 2 ] else None , description = fact [ 3 ] , activity_id = fact [ 5 ] , category = fact [ 6 ] , tags = fact [ 7 ] , date = dt . datetime . utcfromtimestamp ( fact [ 8 ] ) . date ( ) , id = fact [ 0 ] )
unpack the struct into a proper dict
131
8
225,936
def get_tags ( self , only_autocomplete = False ) : return self . _to_dict ( ( 'id' , 'name' , 'autocomplete' ) , self . conn . GetTags ( only_autocomplete ) )
returns list of all tags . by default only those that have been set for autocomplete
54
19
225,937
def stop_tracking ( self , end_time = None ) : end_time = timegm ( ( end_time or dt . datetime . now ( ) ) . timetuple ( ) ) return self . conn . StopTracking ( end_time )
Stop tracking current activity . end_time can be passed in if the activity should have other end time than the current moment
55
24
225,938
def get_category_activities ( self , category_id = None ) : category_id = category_id or - 1 return self . _to_dict ( ( 'id' , 'name' , 'category_id' , 'category' ) , self . conn . GetCategoryActivities ( category_id ) )
Return activities for category . If category is not specified will return activities that have no category
69
17
225,939
def get_activity_by_name ( self , activity , category_id = None , resurrect = True ) : category_id = category_id or 0 return self . conn . GetActivityByName ( activity , category_id , resurrect )
returns activity dict by name and optionally filtering by category . if activity is found but is marked as deleted it will be resurrected unless told otherwise in the resurrect param
51
32
225,940
def bus_inspector ( self , bus , message ) : # We only care about stuff on this interface. We did filter # for it above, but even so we still hear from ourselves # (hamster messages). if message . get_interface ( ) != self . screensaver_uri : return True member = message . get_member ( ) if member in ( "SessionIdleChanged" , "ActiveChanged" ) : logger . debug ( "%s -> %s" % ( member , message . get_args_list ( ) ) ) idle_state = message . get_args_list ( ) [ 0 ] if idle_state : self . idle_from = dt . datetime . now ( ) # from gnome screensaver 2.24 to 2.28 they have switched # configuration keys and signal types. # luckily we can determine key by signal type if member == "SessionIdleChanged" : delay_key = "/apps/gnome-screensaver/idle_delay" else : delay_key = "/desktop/gnome/session/idle_delay" client = gconf . Client . get_default ( ) self . timeout_minutes = client . get_int ( delay_key ) else : self . screen_locked = False self . idle_from = None if member == "ActiveChanged" : # ActiveChanged comes before SessionIdleChanged signal # as a workaround for pre 2.26, we will wait a second - maybe # SessionIdleChanged signal kicks in def dispatch_active_changed ( idle_state ) : if not self . idle_was_there : self . emit ( 'idle-changed' , idle_state ) self . idle_was_there = False gobject . timeout_add_seconds ( 1 , dispatch_active_changed , idle_state ) else : # dispatch idle status change to interested parties self . idle_was_there = True self . emit ( 'idle-changed' , idle_state ) elif member == "Lock" : # in case of lock, lock signal will be sent first, followed by # ActiveChanged and SessionIdle signals logger . debug ( "Screen Lock Requested" ) self . screen_locked = True return
Inspect the bus for screensaver messages of interest
470
10
225,941
def C_ ( ctx , s ) : translated = gettext . gettext ( '%s\x04%s' % ( ctx , s ) ) if '\x04' in translated : # no translation found, return input string return s return translated
Provide qualified translatable strings via context . Taken from gnome - games .
56
16
225,942
def clean ( bld ) : try : proj = Environment . Environment ( Options . lockfile ) except IOError : raise Utils . WafError ( 'Nothing to clean (project not configured)' ) bld . load_dirs ( proj [ SRCDIR ] , proj [ BLDDIR ] ) bld . load_envs ( ) bld . is_install = 0 bld . add_subdirs ( [ os . path . split ( Utils . g_module . root_path ) [ 0 ] ] ) try : bld . clean ( ) finally : bld . save ( )
removes the build files
132
5
225,943
def install ( bld ) : bld = check_configured ( bld ) Options . commands [ 'install' ] = True Options . commands [ 'uninstall' ] = False Options . is_install = True bld . is_install = INSTALL build_impl ( bld ) bld . install ( )
installs the build files
68
5
225,944
def uninstall ( bld ) : Options . commands [ 'install' ] = False Options . commands [ 'uninstall' ] = True Options . is_install = True bld . is_install = UNINSTALL try : def runnable_status ( self ) : return SKIP_ME setattr ( Task . Task , 'runnable_status_back' , Task . Task . runnable_status ) setattr ( Task . Task , 'runnable_status' , runnable_status ) build_impl ( bld ) bld . install ( ) finally : setattr ( Task . Task , 'runnable_status' , Task . Task . runnable_status_back )
removes the installed files
152
5
225,945
def distclean ( ctx = None ) : global commands lst = os . listdir ( '.' ) for f in lst : if f == Options . lockfile : try : proj = Environment . Environment ( f ) except : Logs . warn ( 'could not read %r' % f ) continue try : shutil . rmtree ( proj [ BLDDIR ] ) except IOError : pass except OSError , e : if e . errno != errno . ENOENT : Logs . warn ( 'project %r cannot be removed' % proj [ BLDDIR ] ) try : os . remove ( f ) except OSError , e : if e . errno != errno . ENOENT : Logs . warn ( 'file %r cannot be removed' % f ) if not commands and f . startswith ( '.waf' ) : shutil . rmtree ( f , ignore_errors = True )
removes the build directory
207
5
225,946
def dist ( appname = '' , version = '' ) : import tarfile if not appname : appname = Utils . g_module . APPNAME if not version : version = Utils . g_module . VERSION tmp_folder = appname + '-' + version if g_gz in [ 'gz' , 'bz2' ] : arch_name = tmp_folder + '.tar.' + g_gz else : arch_name = tmp_folder + '.' + 'zip' try : shutil . rmtree ( tmp_folder ) except ( OSError , IOError ) : pass try : os . remove ( arch_name ) except ( OSError , IOError ) : pass blddir = getattr ( Utils . g_module , BLDDIR , None ) if not blddir : blddir = getattr ( Utils . g_module , 'out' , None ) copytree ( '.' , tmp_folder , blddir ) dist_hook = getattr ( Utils . g_module , 'dist_hook' , None ) if dist_hook : back = os . getcwd ( ) os . chdir ( tmp_folder ) try : dist_hook ( ) finally : os . chdir ( back ) if g_gz in [ 'gz' , 'bz2' ] : tar = tarfile . open ( arch_name , 'w:' + g_gz ) tar . add ( tmp_folder ) tar . close ( ) else : Utils . zip_folder ( tmp_folder , arch_name , tmp_folder ) try : from hashlib import sha1 as sha except ImportError : from sha import sha try : digest = " (sha=%r)" % sha ( Utils . readf ( arch_name ) ) . hexdigest ( ) except : digest = '' info ( 'New archive created: %s%s' % ( arch_name , digest ) ) if os . path . exists ( tmp_folder ) : shutil . rmtree ( tmp_folder ) return arch_name
makes a tarball for redistributing the sources
453
10
225,947
def show ( self , start_date , end_date ) : # title in the report file name vars = { "title" : _ ( "Time track" ) , "start" : start_date . strftime ( "%x" ) . replace ( "/" , "." ) , "end" : end_date . strftime ( "%x" ) . replace ( "/" , "." ) } if start_date != end_date : filename = "%(title)s, %(start)s - %(end)s.html" % vars else : filename = "%(title)s, %(start)s.html" % vars self . dialog . set_current_name ( filename ) response = self . dialog . run ( ) if response != gtk . ResponseType . OK : self . emit ( "report-chooser-closed" ) self . dialog . destroy ( ) self . dialog = None else : self . on_save_button_clicked ( )
setting suggested name to something readable replace backslashes with dots so the name is valid in linux
213
19
225,948
def kill_tweens ( self , obj = None ) : if obj is not None : try : del self . current_tweens [ obj ] except : pass else : self . current_tweens = collections . defaultdict ( set )
Stop tweening an object without completing the motion or firing the on_complete
53
15
225,949
def remove_tween ( self , tween ) : if tween . target in self . current_tweens and tween in self . current_tweens [ tween . target ] : self . current_tweens [ tween . target ] . remove ( tween ) if not self . current_tweens [ tween . target ] : del self . current_tweens [ tween . target ]
remove given tween without completing the motion or firing the on_complete
92
14
225,950
def finish ( self ) : for obj in self . current_tweens : for tween in self . current_tweens [ obj ] : tween . finish ( ) self . current_tweens = { }
jump the the last frame of all tweens
48
9
225,951
def update ( self , delta_seconds ) : for obj in tuple ( self . current_tweens ) : for tween in tuple ( self . current_tweens [ obj ] ) : done = tween . update ( delta_seconds ) if done : self . current_tweens [ obj ] . remove ( tween ) if tween . on_complete : tween . on_complete ( tween . target ) if not self . current_tweens [ obj ] : del self . current_tweens [ obj ] return self . current_tweens
update tweeners . delta_seconds is time in seconds since last frame
124
14
225,952
def update ( self , ptime ) : delta = self . delta + ptime total_duration = self . delay + self . duration if delta > total_duration : delta = total_duration if delta < self . delay : pass elif delta == total_duration : for key , tweenable in self . tweenables : setattr ( self . target , key , tweenable . target_value ) else : fraction = self . ease ( ( delta - self . delay ) / ( total_duration - self . delay ) ) for key , tweenable in self . tweenables : res = tweenable . update ( fraction ) if isinstance ( res , float ) and self . round : res = int ( res ) setattr ( self . target , key , res ) if delta == total_duration or len ( self . tweenables ) == 0 : self . complete = True self . delta = delta if self . on_update : self . on_update ( self . target ) return self . complete
Update tween with the time since the last frame
210
10
225,953
def set_items ( self , items ) : res = [ ] max_value = max ( sum ( ( rec [ 1 ] for rec in items ) ) , 1 ) for key , val in items : res . append ( ( key , val , val * 1.0 / max_value ) ) self . _items = res
expects a list of key value to work with
69
10
225,954
def set_values ( self , values ) : self . values = values self . height = len ( self . values ) * 14 self . _max = max ( rec [ 1 ] for rec in values ) if values else dt . timedelta ( 0 )
expects a list of 2 - tuples
54
9
225,955
def datetime_to_hamsterday ( civil_date_time ) : # work around cyclic imports from hamster . lib . configuration import conf if civil_date_time . time ( ) < conf . day_start : # early morning, between midnight and day_start # => the hamster day is the previous civil day hamster_date_time = civil_date_time - dt . timedelta ( days = 1 ) else : hamster_date_time = civil_date_time # return only the date return hamster_date_time . date ( )
Return the hamster day corresponding to a given civil datetime .
123
13
225,956
def hamsterday_time_to_datetime ( hamsterday , time ) : # work around cyclic imports from hamster . lib . configuration import conf if time < conf . day_start : # early morning, between midnight and day_start # => the hamster day is the previous civil day civil_date = hamsterday + dt . timedelta ( days = 1 ) else : civil_date = hamsterday return dt . datetime . combine ( civil_date , time )
Return the civil datetime corresponding to a given hamster day and time .
106
15
225,957
def format_duration ( minutes , human = True ) : if isinstance ( minutes , dt . timedelta ) : minutes = duration_minutes ( minutes ) if not minutes : if human : return "" else : return "00:00" if minutes < 0 : # format_duration did not work for negative values anyway # return a warning return "NEGATIVE" hours = minutes / 60 minutes = minutes % 60 formatted_duration = "" if human : if minutes % 60 == 0 : # duration in round hours formatted_duration += ( "%dh" ) % ( hours ) elif hours == 0 : # duration less than hour formatted_duration += ( "%dmin" ) % ( minutes % 60.0 ) else : # x hours, y minutes formatted_duration += ( "%dh %dmin" ) % ( hours , minutes % 60 ) else : formatted_duration += "%02d:%02d" % ( hours , minutes ) return formatted_duration
formats duration in a human readable format . accepts either minutes or timedelta
201
15
225,958
def duration_minutes ( duration ) : if isinstance ( duration , list ) : res = dt . timedelta ( ) for entry in duration : res += entry return duration_minutes ( res ) elif isinstance ( duration , dt . timedelta ) : return duration . total_seconds ( ) / 60 else : return duration
returns minutes from duration otherwise we keep bashing in same math
71
12
225,959
def locale_first_weekday ( ) : first_weekday = 6 #by default settle on monday try : process = os . popen ( "locale first_weekday week-1stday" ) week_offset , week_start = process . read ( ) . split ( '\n' ) [ : 2 ] process . close ( ) week_start = dt . date ( * time . strptime ( week_start , "%Y%m%d" ) [ : 3 ] ) week_offset = dt . timedelta ( int ( week_offset ) - 1 ) beginning = week_start + week_offset first_weekday = int ( beginning . strftime ( "%w" ) ) except : logger . warn ( "WARNING - Failed to get first weekday from locale" ) return first_weekday
figure if week starts on monday or sunday
177
10
225,960
def totals ( iter , keyfunc , sumfunc ) : data = sorted ( iter , key = keyfunc ) res = { } for k , group in groupby ( data , keyfunc ) : res [ k ] = sum ( [ sumfunc ( entry ) for entry in group ] ) return res
groups items by field described in keyfunc and counts totals using value from sumfunc
62
16
225,961
def dateDict ( date , prefix = "" ) : res = { } res [ prefix + "a" ] = date . strftime ( "%a" ) res [ prefix + "A" ] = date . strftime ( "%A" ) res [ prefix + "b" ] = date . strftime ( "%b" ) res [ prefix + "B" ] = date . strftime ( "%B" ) res [ prefix + "c" ] = date . strftime ( "%c" ) res [ prefix + "d" ] = date . strftime ( "%d" ) res [ prefix + "H" ] = date . strftime ( "%H" ) res [ prefix + "I" ] = date . strftime ( "%I" ) res [ prefix + "j" ] = date . strftime ( "%j" ) res [ prefix + "m" ] = date . strftime ( "%m" ) res [ prefix + "M" ] = date . strftime ( "%M" ) res [ prefix + "p" ] = date . strftime ( "%p" ) res [ prefix + "S" ] = date . strftime ( "%S" ) res [ prefix + "U" ] = date . strftime ( "%U" ) res [ prefix + "w" ] = date . strftime ( "%w" ) res [ prefix + "W" ] = date . strftime ( "%W" ) res [ prefix + "x" ] = date . strftime ( "%x" ) res [ prefix + "X" ] = date . strftime ( "%X" ) res [ prefix + "y" ] = date . strftime ( "%y" ) res [ prefix + "Y" ] = date . strftime ( "%Y" ) res [ prefix + "Z" ] = date . strftime ( "%Z" ) for i , value in res . items ( ) : res [ i ] = locale_to_utf8 ( value ) return res
converts date into dictionary having prefix for all the keys
421
11
225,962
def __get_tag_ids ( self , tags ) : db_tags = self . fetchall ( "select * from tags where name in (%s)" % "," . join ( [ "?" ] * len ( tags ) ) , tags ) # bit of magic here - using sqlites bind variables changes = False # check if any of tags needs resurrection set_complete = [ str ( tag [ "id" ] ) for tag in db_tags if tag [ "autocomplete" ] == "false" ] if set_complete : changes = True self . execute ( "update tags set autocomplete='true' where id in (%s)" % ", " . join ( set_complete ) ) found_tags = [ tag [ "name" ] for tag in db_tags ] add = set ( tags ) - set ( found_tags ) if add : statement = "insert into tags(name) values(?)" self . execute ( [ statement ] * len ( add ) , [ ( tag , ) for tag in add ] ) return self . __get_tag_ids ( tags ) [ 0 ] , True # all done, recurse else : return db_tags , changes
look up tags by their name . create if not found
249
11
225,963
def __get_activity_by_name ( self , name , category_id = None , resurrect = True ) : if category_id : query = """ SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category FROM activities a LEFT JOIN categories b ON category_id = b.id WHERE lower(a.name) = lower(?) AND category_id = ? ORDER BY a.deleted, a.id desc LIMIT 1 """ res = self . fetchone ( query , ( self . _unsorted_localized , name , category_id ) ) else : query = """ SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category FROM activities a LEFT JOIN categories b ON category_id = b.id WHERE lower(a.name) = lower(?) ORDER BY a.deleted, a.id desc LIMIT 1 """ res = self . fetchone ( query , ( self . _unsorted_localized , name , ) ) if res : keys = ( 'id' , 'name' , 'deleted' , 'category' ) res = dict ( [ ( key , res [ key ] ) for key in keys ] ) res [ 'deleted' ] = res [ 'deleted' ] or False # if the activity was marked as deleted, resurrect on first call # and put in the unsorted category if res [ 'deleted' ] and resurrect : update = """ UPDATE activities SET deleted = null, category_id = -1 WHERE id = ? """ self . execute ( update , ( res [ 'id' ] , ) ) return res return None
get most recent preferably not deleted activity by it s name
359
11
225,964
def __get_category_id ( self , name ) : query = """ SELECT id from categories WHERE lower(name) = lower(?) ORDER BY id desc LIMIT 1 """ res = self . fetchone ( query , ( name , ) ) if res : return res [ 'id' ] return None
returns category by it s name
63
7
225,965
def __group_tags ( self , facts ) : if not facts : return facts #be it None or whatever grouped_facts = [ ] for fact_id , fact_tags in itertools . groupby ( facts , lambda f : f [ "id" ] ) : fact_tags = list ( fact_tags ) # first one is as good as the last one grouped_fact = fact_tags [ 0 ] # we need dict so we can modify it (sqlite.Row is read only) # in python 2.5, sqlite does not have keys() yet, so we hardcode them (yay!) keys = [ "id" , "start_time" , "end_time" , "description" , "name" , "activity_id" , "category" , "tag" ] grouped_fact = dict ( [ ( key , grouped_fact [ key ] ) for key in keys ] ) grouped_fact [ "tags" ] = [ ft [ "tag" ] for ft in fact_tags if ft [ "tag" ] ] grouped_facts . append ( grouped_fact ) return grouped_facts
put the fact back together and move all the unique tags to an array
239
14
225,966
def __squeeze_in ( self , start_time ) : # we are checking if our start time is in the middle of anything # or maybe there is something after us - so we know to adjust end time # in the latter case go only few hours ahead. everything else is madness, heh query = """ SELECT a.*, b.name FROM facts a LEFT JOIN activities b on b.id = a.activity_id WHERE ((start_time < ? and end_time > ?) OR (start_time > ? and start_time < ? and end_time is null) OR (start_time > ? and start_time < ?)) ORDER BY start_time LIMIT 1 """ fact = self . fetchone ( query , ( start_time , start_time , start_time - dt . timedelta ( hours = 12 ) , start_time , start_time , start_time + dt . timedelta ( hours = 12 ) ) ) end_time = None if fact : if start_time > fact [ "start_time" ] : #we are in middle of a fact - truncate it to our start self . execute ( "UPDATE facts SET end_time=? WHERE id=?" , ( start_time , fact [ "id" ] ) ) else : #otherwise we have found a task that is after us end_time = fact [ "start_time" ] return end_time
tries to put task in the given date if there are conflicts we will only truncate the ongoing task and replace it s end part with our activity
303
30
225,967
def __get_activities ( self , search ) : query = """ SELECT a.name AS name, b.name AS category FROM activities a LEFT JOIN categories b ON coalesce(b.id, -1) = a.category_id LEFT JOIN facts f ON a.id = f.activity_id WHERE deleted IS NULL AND a.search_name LIKE ? ESCAPE '\\' GROUP BY a.id ORDER BY max(f.start_time) DESC, lower(a.name) LIMIT 50 """ search = search . lower ( ) search = search . replace ( '\\' , '\\\\' ) . replace ( '%' , '\\%' ) . replace ( '_' , '\\_' ) activities = self . fetchall ( query , ( '%s%%' % search , ) ) return activities
returns list of activities for autocomplete activity names converted to lowercase
181
15
225,968
def __remove_activity ( self , id ) : query = "select count(*) as count from facts where activity_id = ?" bound_facts = self . fetchone ( query , ( id , ) ) [ 'count' ] if bound_facts > 0 : self . execute ( "UPDATE activities SET deleted = 1 WHERE id = ?" , ( id , ) ) else : self . execute ( "delete from activities where id = ?" , ( id , ) )
check if we have any facts with this activity and behave accordingly if there are facts - sets activity to deleted = True else just remove it
100
27
225,969
def __remove_category ( self , id ) : affected_query = """ SELECT id FROM facts WHERE activity_id in (SELECT id FROM activities where category_id=?) """ affected_ids = [ res [ 0 ] for res in self . fetchall ( affected_query , ( id , ) ) ] update = "update activities set category_id = -1 where category_id = ?" self . execute ( update , ( id , ) ) self . execute ( "delete from categories where id = ?" , ( id , ) ) self . __remove_index ( affected_ids )
move all activities to unsorted and remove category
124
9
225,970
def __remove_index ( self , ids ) : if not ids : return ids = "," . join ( ( str ( id ) for id in ids ) ) self . execute ( "DELETE FROM fact_index where id in (%s)" % ids )
remove affected ids from the index
60
7
225,971
def execute ( self , statement , params = ( ) ) : con = self . __con or self . connection cur = self . __cur or con . cursor ( ) if isinstance ( statement , list ) == False : # we expect to receive instructions in list statement = [ statement ] params = [ params ] for state , param in zip ( statement , params ) : logger . debug ( "%s %s" % ( state , param ) ) cur . execute ( state , param ) if not self . __con : con . commit ( ) cur . close ( ) self . register_modification ( )
execute sql statement . optionally you can give multiple statements to save on cursor creation and closure
125
17
225,972
def run_fixtures ( self ) : self . start_transaction ( ) version = self . fetchone ( "SELECT version FROM version" ) [ "version" ] current_version = 9 if version < 8 : # working around sqlite's utf-f case sensitivity (bug 624438) # more info: http://www.gsak.net/help/hs23820.htm self . execute ( "ALTER TABLE activities ADD COLUMN search_name varchar2" ) activities = self . fetchall ( "select * from activities" ) statement = "update activities set search_name = ? where id = ?" for activity in activities : self . execute ( statement , ( activity [ 'name' ] . lower ( ) , activity [ 'id' ] ) ) # same for categories self . execute ( "ALTER TABLE categories ADD COLUMN search_name varchar2" ) categories = self . fetchall ( "select * from categories" ) statement = "update categories set search_name = ? where id = ?" for category in categories : self . execute ( statement , ( category [ 'name' ] . lower ( ) , category [ 'id' ] ) ) if version < 9 : # adding full text search self . execute ( """CREATE VIRTUAL TABLE fact_index USING fts3(id, name, category, description, tag)""" ) # at the happy end, update version number if version < current_version : #lock down current version self . execute ( "UPDATE version SET version = %d" % current_version ) print ( "updated database from version %d to %d" % ( version , current_version ) ) self . end_transaction ( )
upgrade DB to hamster version
365
7
225,973
def current_fact_index ( self ) : facts_ids = [ fact . id for fact in self . facts ] return facts_ids . index ( self . current_fact . id )
Current fact index in the self . facts list .
40
10
225,974
def chain ( * steps ) : if not steps : return def on_done ( sprite = None ) : chain ( * steps [ 2 : ] ) obj , params = steps [ : 2 ] if len ( steps ) > 2 : params [ 'on_complete' ] = on_done if callable ( obj ) : obj ( * * params ) else : obj . animate ( * * params )
chains the given list of functions and object animations into a callback string .
83
14
225,975
def full_pixels ( space , data , gap_pixels = 1 ) : available = space - ( len ( data ) - 1 ) * gap_pixels # 8 recs 7 gaps res = [ ] for i , val in enumerate ( data ) : # convert data to 0..1 scale so we deal with fractions data_sum = sum ( data [ i : ] ) norm = val * 1.0 / data_sum w = max ( int ( round ( available * norm ) ) , 1 ) res . append ( w ) available -= w return res
returns the given data distributed in the space ensuring it s full pixels and with the given gap . this will result in minor sub - pixel inaccuracies . XXX - figure out where to place these guys as they are quite useful
119
45
225,976
def gdk ( self , color ) : c = self . parse ( color ) return gdk . Color . from_floats ( c )
returns gdk . Color object of the given color
30
11
225,977
def contrast ( self , color , step ) : hls = colorsys . rgb_to_hls ( * self . rgb ( color ) ) if self . is_light ( color ) : return colorsys . hls_to_rgb ( hls [ 0 ] , hls [ 1 ] - step , hls [ 2 ] ) else : return colorsys . hls_to_rgb ( hls [ 0 ] , hls [ 1 ] + step , hls [ 2 ] )
if color is dark will return a lighter one otherwise darker
107
11
225,978
def mix ( self , ca , cb , xb ) : r = ( 1 - xb ) * ca . red + xb * cb . red g = ( 1 - xb ) * ca . green + xb * cb . green b = ( 1 - xb ) * ca . blue + xb * cb . blue a = ( 1 - xb ) * ca . alpha + xb * cb . alpha return gdk . RGBA ( red = r , green = g , blue = b , alpha = a )
Mix colors .
117
3
225,979
def set_line_style ( self , width = None , dash = None , dash_offset = 0 ) : if width is not None : self . _add_instruction ( "set_line_width" , width ) if dash is not None : self . _add_instruction ( "set_dash" , dash , dash_offset )
change width and dash of a line
74
7
225,980
def _set_color ( self , context , r , g , b , a ) : if a < 1 : context . set_source_rgba ( r , g , b , a ) else : context . set_source_rgb ( r , g , b )
the alpha has to changed based on the parent so that happens at the time of drawing
58
17
225,981
def arc ( self , x , y , radius , start_angle , end_angle ) : self . _add_instruction ( "arc" , x , y , radius , start_angle , end_angle )
draw arc going counter - clockwise from start_angle to end_angle
46
15
225,982
def ellipse ( self , x , y , width , height , edges = None ) : # the automatic edge case is somewhat arbitrary steps = edges or max ( ( 32 , width , height ) ) / 2 angle = 0 step = math . pi * 2 / steps points = [ ] while angle < math . pi * 2 : points . append ( ( width / 2.0 * math . cos ( angle ) , height / 2.0 * math . sin ( angle ) ) ) angle += step min_x = min ( ( point [ 0 ] for point in points ) ) min_y = min ( ( point [ 1 ] for point in points ) ) self . move_to ( points [ 0 ] [ 0 ] - min_x + x , points [ 0 ] [ 1 ] - min_y + y ) for p_x , p_y in points : self . line_to ( p_x - min_x + x , p_y - min_y + y ) self . line_to ( points [ 0 ] [ 0 ] - min_x + x , points [ 0 ] [ 1 ] - min_y + y )
draw perfect ellipse opposed to squashed circle . works also for equilateral polygons
243
18
225,983
def arc_negative ( self , x , y , radius , start_angle , end_angle ) : self . _add_instruction ( "arc_negative" , x , y , radius , start_angle , end_angle )
draw arc going clockwise from start_angle to end_angle
50
13
225,984
def rectangle ( self , x , y , width , height , corner_radius = 0 ) : if corner_radius <= 0 : self . _add_instruction ( "rectangle" , x , y , width , height ) return # convert into 4 border and make sure that w + h are larger than 2 * corner_radius if isinstance ( corner_radius , ( int , float ) ) : corner_radius = [ corner_radius ] * 4 corner_radius = [ min ( r , min ( width , height ) / 2 ) for r in corner_radius ] x2 , y2 = x + width , y + height self . _rounded_rectangle ( x , y , x2 , y2 , corner_radius )
draw a rectangle . if corner_radius is specified will draw rounded corners . corner_radius can be either a number or a tuple of four items to specify individually each corner starting from top - left and going clockwise
155
43
225,985
def fill_area ( self , x , y , width , height , color , opacity = 1 ) : self . save_context ( ) self . rectangle ( x , y , width , height ) self . _add_instruction ( "clip" ) self . rectangle ( x , y , width , height ) self . fill ( color , opacity ) self . restore_context ( )
fill rectangular area with specified color
80
6
225,986
def fill_stroke ( self , fill = None , stroke = None , opacity = 1 , line_width = None ) : if line_width : self . set_line_style ( line_width ) if fill and stroke : self . fill_preserve ( fill , opacity ) elif fill : self . fill ( fill , opacity ) if stroke : self . stroke ( stroke )
fill and stroke the drawn area in one go
80
9
225,987
def create_layout ( self , size = None ) : if not self . context : # TODO - this is rather sloppy as far as exception goes # should explain better raise Exception ( "Can not create layout without existing context!" ) layout = pangocairo . create_layout ( self . context ) font_desc = pango . FontDescription ( _font_desc ) if size : font_desc . set_absolute_size ( size * pango . SCALE ) layout . set_font_description ( font_desc ) return layout
utility function to create layout with the default font . Size and alignment parameters are shortcuts to according functions of the pango . Layout
113
26
225,988
def show_label ( self , text , size = None , color = None , font_desc = None ) : font_desc = pango . FontDescription ( font_desc or _font_desc ) if color : self . set_color ( color ) if size : font_desc . set_absolute_size ( size * pango . SCALE ) self . show_layout ( text , font_desc )
display text . unless font_desc is provided will use system s default font
87
15
225,989
def _draw ( self , context , opacity ) : # if we have been moved around, we should update bounds fresh_draw = len ( self . __new_instructions or [ ] ) > 0 if fresh_draw : #new stuff! self . paths = [ ] self . __instruction_cache = self . __new_instructions self . __new_instructions = [ ] else : if not self . __instruction_cache : return for instruction , args in self . __instruction_cache : if fresh_draw : if instruction in ( "new_path" , "stroke" , "fill" , "clip" ) : self . paths . append ( ( instruction , "path" , context . copy_path ( ) ) ) elif instruction in ( "save" , "restore" , "translate" , "scale" , "rotate" ) : self . paths . append ( ( instruction , "transform" , args ) ) if instruction == "set_color" : self . _set_color ( context , args [ 0 ] , args [ 1 ] , args [ 2 ] , args [ 3 ] * opacity ) elif instruction == "show_layout" : self . _show_layout ( context , * args ) elif opacity < 1 and instruction == "paint" : context . paint_with_alpha ( opacity ) else : getattr ( context , instruction ) ( * args )
draw accumulated instructions in context
304
5
225,990
def find ( self , id ) : for sprite in self . sprites : if sprite . id == id : return sprite for sprite in self . sprites : found = sprite . find ( id ) if found : return found
breadth - first sprite search by ID
44
8
225,991
def traverse ( self , attr_name = None , attr_value = None ) : for sprite in self . sprites : if ( attr_name is None ) or ( attr_value is None and hasattr ( sprite , attr_name ) ) or ( attr_value is not None and getattr ( sprite , attr_name , None ) == attr_value ) : yield sprite for child in sprite . traverse ( attr_name , attr_value ) : yield child
traverse the whole sprite tree and return child sprites which have the attribute and it s set to the specified value . If falue is None will return all sprites that have the attribute
107
36
225,992
def log ( self , * lines ) : if getattr ( self , "debug" , False ) : print ( dt . datetime . now ( ) . time ( ) , end = ' ' ) for line in lines : print ( line , end = ' ' ) print ( )
will print out the lines in console if debug is enabled for the specific sprite
60
15
225,993
def _add ( self , sprite , index = None ) : if sprite == self : raise Exception ( "trying to add sprite to itself" ) if sprite . parent : sprite . x , sprite . y = self . from_scene_coords ( * sprite . to_scene_coords ( ) ) sprite . parent . remove_child ( sprite ) if index is not None : self . sprites . insert ( index , sprite ) else : self . sprites . append ( sprite ) sprite . parent = self
add one sprite at a time . used by add_child . split them up so that it would be possible specify the index externally
106
26
225,994
def _sort ( self ) : self . __dict__ [ '_z_ordered_sprites' ] = sorted ( self . sprites , key = lambda sprite : sprite . z_order )
sort sprites by z_order
41
6
225,995
def add_child ( self , * sprites ) : for sprite in sprites : self . _add ( sprite ) self . _sort ( ) self . redraw ( )
Add child sprite . Child will be nested within parent
35
10
225,996
def all_child_sprites ( self ) : for sprite in self . sprites : for child_sprite in sprite . all_child_sprites ( ) : yield child_sprite yield sprite
returns all child and grandchild sprites in a flat list
42
12
225,997
def disconnect_child ( self , sprite , * handlers ) : handlers = handlers or self . _child_handlers . get ( sprite , [ ] ) for handler in list ( handlers ) : if sprite . handler_is_connected ( handler ) : sprite . disconnect ( handler ) if handler in self . _child_handlers . get ( sprite , [ ] ) : self . _child_handlers [ sprite ] . remove ( handler ) if not self . _child_handlers [ sprite ] : del self . _child_handlers [ sprite ]
disconnects from child event . if handler is not specified will disconnect from all the child sprite events
116
20
225,998
def _get_mouse_cursor ( self ) : if self . mouse_cursor is not None : return self . mouse_cursor elif self . interactive and self . draggable : return gdk . CursorType . FLEUR elif self . interactive : return gdk . CursorType . HAND2
Determine mouse cursor . By default look for self . mouse_cursor is defined and take that . Otherwise use gdk . CursorType . FLEUR for draggable sprites and gdk . CursorType . HAND2 for interactive sprites . Defaults to scenes cursor .
70
60
225,999
def bring_to_front ( self ) : if not self . parent : return self . z_order = self . parent . _z_ordered_sprites [ - 1 ] . z_order + 1
adjusts sprite s z - order so that the sprite is on top of it s siblings
44
18