idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
0
def _GetTimeValues ( self , number_of_seconds ) : number_of_seconds = int ( number_of_seconds ) number_of_minutes , seconds = divmod ( number_of_seconds , 60 ) number_of_hours , minutes = divmod ( number_of_minutes , 60 ) number_of_days , hours = divmod ( number_of_hours , 24 ) return number_of_days , hours , minutes , seconds
Determines time values .
1
def CopyToStatTimeTuple ( self ) : normalized_timestamp = self . _GetNormalizedTimestamp ( ) if normalized_timestamp is None : return None , None if self . _precision in ( definitions . PRECISION_1_NANOSECOND , definitions . PRECISION_100_NANOSECONDS , definitions . PRECISION_1_MICROSECOND , definitions . PRECISION_1_MILLISECOND , definitions . PRECISION_100_MILLISECONDS ) : remainder = int ( ( normalized_timestamp % 1 ) * self . _100NS_PER_SECOND ) return int ( normalized_timestamp ) , remainder return int ( normalized_timestamp ) , None
Copies the date time value to a stat timestamp tuple .
2
def CopyToDateTimeStringISO8601 ( self ) : date_time_string = self . CopyToDateTimeString ( ) if date_time_string : date_time_string = date_time_string . replace ( ' ' , 'T' ) date_time_string = '{0:s}Z' . format ( date_time_string ) return date_time_string
Copies the date time value to an ISO 8601 date and time string .
3
def GetPlasoTimestamp ( self ) : normalized_timestamp = self . _GetNormalizedTimestamp ( ) if normalized_timestamp is None : return None normalized_timestamp *= definitions . MICROSECONDS_PER_SECOND normalized_timestamp = normalized_timestamp . quantize ( 1 , rounding = decimal . ROUND_HALF_UP ) return int ( normalized_timestamp )
Retrieves a timestamp that is compatible with plaso .
4
def GetTimeOfDay ( self ) : normalized_timestamp = self . _GetNormalizedTimestamp ( ) if normalized_timestamp is None : return None , None , None _ , hours , minutes , seconds = self . _GetTimeValues ( normalized_timestamp ) return hours , minutes , seconds
Retrieves the time of day represented by the date and time values .
5
def CopyFromDateTimeString ( self , time_string ) : date_time_values = self . _CopyDateTimeFromString ( time_string ) year = date_time_values . get ( 'year' , 0 ) month = date_time_values . get ( 'month' , 0 ) day_of_month = date_time_values . get ( 'day_of_month' , 0 ) hours = date_time_values . get ( 'hours' , 0 ) minutes = date_time_values . get ( 'minutes' , 0 ) seconds = date_time_values . get ( 'seconds' , 0 ) self . _normalized_timestamp = None self . _number_of_seconds = self . _GetNumberOfSecondsFromElements ( year , month , day_of_month , hours , minutes , seconds ) self . _microseconds = date_time_values . get ( 'microseconds' , None ) self . is_local_time = False
Copies a fake timestamp from a date and time string .
6
def CopyToDateTimeString ( self ) : if self . _number_of_seconds is None : return None return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:01d}' . format ( self . year , self . month , self . day_of_month , self . hours , self . minutes , self . seconds , self . deciseconds )
Copies the RFC2579 date - time to a date and time string .
7
def _GetNumberOfSeconds ( self , fat_date_time ) : day_of_month = ( fat_date_time & 0x1f ) month = ( ( fat_date_time >> 5 ) & 0x0f ) year = ( fat_date_time >> 9 ) & 0x7f days_per_month = self . _GetDaysPerMonth ( year , month ) if day_of_month < 1 or day_of_month > days_per_month : raise ValueError ( 'Day of month value out of bounds.' ) number_of_days = self . _GetDayOfYear ( 1980 + year , month , day_of_month ) number_of_days -= 1 for past_year in range ( 0 , year ) : number_of_days += self . _GetNumberOfDaysInYear ( past_year ) fat_date_time >>= 16 seconds = ( fat_date_time & 0x1f ) * 2 minutes = ( fat_date_time >> 5 ) & 0x3f hours = ( fat_date_time >> 11 ) & 0x1f if hours not in range ( 0 , 24 ) : raise ValueError ( 'Hours value out of bounds.' ) if minutes not in range ( 0 , 60 ) : raise ValueError ( 'Minutes value out of bounds.' ) if seconds not in range ( 0 , 60 ) : raise ValueError ( 'Seconds value out of bounds.' ) number_of_seconds = ( ( ( hours * 60 ) + minutes ) * 60 ) + seconds number_of_seconds += number_of_days * definitions . SECONDS_PER_DAY return number_of_seconds
Retrieves the number of seconds from a FAT date time .
8
def CopyToDateTimeString ( self ) : if ( self . _timestamp is None or self . _timestamp < 0 or self . _timestamp > self . _UINT64_MAX ) : return None timestamp , remainder = divmod ( self . _timestamp , self . _100NS_PER_SECOND ) number_of_days , hours , minutes , seconds = self . _GetTimeValues ( timestamp ) year , month , day_of_month = self . _GetDateValuesWithEpoch ( number_of_days , self . _EPOCH ) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:07d}' . format ( year , month , day_of_month , hours , minutes , seconds , remainder )
Copies the FILETIME timestamp to a date and time string .
9
def CreatePrecisionHelper ( cls , precision ) : precision_helper_class = cls . _PRECISION_CLASSES . get ( precision , None ) if not precision_helper_class : raise ValueError ( 'Unsupported precision: {0!s}' . format ( precision ) ) return precision_helper_class
Creates a precision helper .
10
def CopyFromDateTimeString ( self , time_string ) : super ( APFSTime , self ) . _CopyFromDateTimeString ( time_string ) if ( self . _timestamp is None or self . _timestamp < self . _INT64_MIN or self . _timestamp > self . _INT64_MAX ) : raise ValueError ( 'Date time value not supported.' )
Copies a APFS timestamp from a date and time string .
11
def CopyToDateTimeString ( self ) : if ( self . _timestamp is None or self . _timestamp < self . _INT64_MIN or self . _timestamp > self . _INT64_MAX ) : return None return super ( APFSTime , self ) . _CopyToDateTimeString ( )
Copies the APFS timestamp to a date and time string .
12
def CopyToDateTimeString ( self ) : if self . _timestamp is None : return None number_of_days , hours , minutes , seconds = self . _GetTimeValues ( int ( self . _timestamp ) ) year , month , day_of_month = self . _GetDateValuesWithEpoch ( number_of_days , self . _EPOCH ) microseconds = int ( ( self . _timestamp % 1 ) * definitions . MICROSECONDS_PER_SECOND ) return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:06d}' . format ( year , month , day_of_month , hours , minutes , seconds , microseconds )
Copies the Cocoa timestamp to a date and time string .
13
def send_sms_message ( sms_message , backend = None , fail_silently = False ) : with get_sms_connection ( backend = backend , fail_silently = fail_silently ) as connection : result = connection . send_messages ( [ sms_message ] ) return result
Send an SMSMessage instance using a connection given by the specified backend .
14
def send_messages ( self , sms_messages ) : results = [ ] for message in sms_messages : try : assert message . connection is None except AssertionError : if not self . fail_silently : raise backend = self . backend fail_silently = self . fail_silently result = django_rq . enqueue ( self . _send , message , backend = backend , fail_silently = fail_silently ) results . append ( result ) return results
Receives a list of SMSMessage instances and returns a list of RQ Job instances .
15
def _CopyDateTimeFromStringISO8601 ( self , time_string ) : if not time_string : raise ValueError ( 'Invalid time string.' ) time_string_length = len ( time_string ) year , month , day_of_month = self . _CopyDateFromString ( time_string ) if time_string_length <= 10 : return { 'year' : year , 'month' : month , 'day_of_month' : day_of_month } if time_string [ 10 ] != 'T' : raise ValueError ( 'Invalid time string - missing as date and time separator.' ) hours , minutes , seconds , microseconds , time_zone_offset = ( self . _CopyTimeFromStringISO8601 ( time_string [ 11 : ] ) ) if time_zone_offset : year , month , day_of_month , hours , minutes = self . _AdjustForTimeZoneOffset ( year , month , day_of_month , hours , minutes , time_zone_offset ) date_time_values = { 'year' : year , 'month' : month , 'day_of_month' : day_of_month , 'hours' : hours , 'minutes' : minutes , 'seconds' : seconds } if microseconds is not None : date_time_values [ 'microseconds' ] = microseconds return date_time_values
Copies a date and time from an ISO 8601 date and time string .
16
def CopyFromDateTimeString ( self , time_string ) : date_time_values = self . _CopyDateTimeFromString ( time_string ) self . _CopyFromDateTimeValues ( date_time_values )
Copies time elements from a date and time string .
17
def CopyFromStringISO8601 ( self , time_string ) : date_time_values = self . _CopyDateTimeFromStringISO8601 ( time_string ) self . _CopyFromDateTimeValues ( date_time_values )
Copies time elements from an ISO 8601 date and time string .
18
def CopyFromDateTimeString ( self , time_string ) : date_time_values = self . _CopyDateTimeFromString ( time_string ) year = date_time_values . get ( 'year' , 0 ) month = date_time_values . get ( 'month' , 0 ) day_of_month = date_time_values . get ( 'day_of_month' , 0 ) hours = date_time_values . get ( 'hours' , 0 ) minutes = date_time_values . get ( 'minutes' , 0 ) seconds = date_time_values . get ( 'seconds' , 0 ) microseconds = date_time_values . get ( 'microseconds' , 0 ) milliseconds , _ = divmod ( microseconds , definitions . MICROSECONDS_PER_MILLISECOND ) if year < 1601 or year > 30827 : raise ValueError ( 'Unsupported year value: {0:d}.' . format ( year ) ) self . _normalized_timestamp = None self . _number_of_seconds = self . _GetNumberOfSecondsFromElements ( year , month , day_of_month , hours , minutes , seconds ) self . year = year self . month = month self . day_of_month = day_of_month self . day_of_week = None self . hours = hours self . minutes = minutes self . seconds = seconds self . milliseconds = milliseconds self . is_local_time = False
Copies a SYSTEMTIME structure from a date and time string .
19
def _prepare_template ( self , obj , needs_request = False ) : if self . instance_name is None and self . template_name is None : raise SearchFieldError ( "This field requires either its instance_name variable to be populated or an explicit template_name in order to load the correct template." ) if self . template_name is not None : template_names = self . template_name if not isinstance ( template_names , ( list , tuple ) ) : template_names = [ template_names ] else : template_names = [ 'search/indexes/%s/%s_%s.txt' % ( obj . _meta . app_label , obj . _meta . module_name , self . instance_name ) ] t = loader . select_template ( template_names ) ctx = { 'object' : obj } if needs_request : request = rf . get ( "/" ) request . session = { } ctx [ 'request' ] = request return t . render ( Context ( ctx ) )
This is a copy of CharField . prepare_template except that it adds a fake request to the context which is mainly needed to render CMS placeholders
20
def get_value ( self , context , obj , field_name ) : try : language = get_language ( ) value = self . get_translated_value ( obj , field_name , language ) if value : return value if self . FALLBACK : for lang , lang_name in settings . LANGUAGES : if lang == language : continue value = self . get_translated_value ( obj , field_name , lang ) if value : return value untranslated = getattr ( obj , field_name ) if self . _is_truthy ( untranslated ) : return untranslated else : return self . EMPTY_VALUE except Exception : if settings . TEMPLATE_DEBUG : raise return self . EMPTY_VALUE
gets the translated value of field name . If FALLBACK evaluates to True and the field has no translation for the current language it tries to find a fallback value using the languages defined in settings . LANGUAGES .
21
def customWalker ( node , space = '' ) : txt = '' try : txt = node . literal except : pass if txt is None or txt == '' : print ( '{}{}' . format ( space , node . t ) ) else : print ( '{}{}\t{}' . format ( space , node . t , txt ) ) cur = node . first_child if cur : while cur is not None : customWalker ( cur , space + ' ' ) cur = cur . nxt
A convenience function to ease debugging . It will print the node structure that s returned from CommonMark
22
def paragraph ( node ) : text = '' if node . string_content is not None : text = node . string_content o = nodes . paragraph ( '' , ' ' . join ( text ) ) o . line = node . sourcepos [ 0 ] [ 0 ] for n in MarkDown ( node ) : o . append ( n ) return o
Process a paragraph which includes all content under it
23
def reference ( node ) : o = nodes . reference ( ) o [ 'refuri' ] = node . destination if node . title : o [ 'name' ] = node . title for n in MarkDown ( node ) : o += n return o
A hyperlink . Note that alt text doesn t work since there s no apparent way to do that in docutils
24
def emphasis ( node ) : o = nodes . emphasis ( ) for n in MarkDown ( node ) : o += n return o
An italicized section
25
def strong ( node ) : o = nodes . strong ( ) for n in MarkDown ( node ) : o += n return o
A bolded section
26
def title ( node ) : return nodes . title ( node . first_child . literal , node . first_child . literal )
A title node . It has no children
27
def block_quote ( node ) : o = nodes . block_quote ( ) o . line = node . sourcepos [ 0 ] [ 0 ] for n in MarkDown ( node ) : o += n return o
A block quote
28
def image ( node ) : o = nodes . image ( uri = node . destination ) if node . first_child is not None : o [ 'alt' ] = node . first_child . literal return o
An image element
29
def listItem ( node ) : o = nodes . list_item ( ) for n in MarkDown ( node ) : o += n return o
An item in a list
30
def MarkDown ( node ) : cur = node . first_child output = [ ] while cur is not None : t = cur . t if t == 'paragraph' : output . append ( paragraph ( cur ) ) elif t == 'text' : output . append ( text ( cur ) ) elif t == 'softbreak' : output . append ( softbreak ( cur ) ) elif t == 'linebreak' : output . append ( hardbreak ( cur ) ) elif t == 'link' : output . append ( reference ( cur ) ) elif t == 'heading' : output . append ( title ( cur ) ) elif t == 'emph' : output . append ( emphasis ( cur ) ) elif t == 'strong' : output . append ( strong ( cur ) ) elif t == 'code' : output . append ( literal ( cur ) ) elif t == 'code_block' : output . append ( literal_block ( cur ) ) elif t == 'html_inline' or t == 'html_block' : output . append ( raw ( cur ) ) elif t == 'block_quote' : output . append ( block_quote ( cur ) ) elif t == 'thematic_break' : output . append ( transition ( cur ) ) elif t == 'image' : output . append ( image ( cur ) ) elif t == 'list' : output . append ( listNode ( cur ) ) elif t == 'item' : output . append ( listItem ( cur ) ) elif t == 'MDsection' : output . append ( section ( cur ) ) else : print ( 'Received unhandled type: {}. Full print of node:' . format ( t ) ) cur . pretty ( ) cur = cur . nxt return output
Returns a list of nodes containing CommonMark nodes converted to docutils nodes
31
def finalizeSection ( section ) : cur = section . first_child last = section . last_child if last is not None : last . nxt = None while cur is not None : cur . parent = section cur = cur . nxt
Correct the nxt and parent for each child
32
def nestSections ( block , level = 1 ) : cur = block . first_child if cur is not None : children = [ ] nest = False while cur is not None : if cur . t == 'heading' and cur . level == level : nest = True break cur = cur . nxt if not nest : return section = Node ( 'MDsection' , 0 ) section . parent = block cur = block . first_child while cur is not None : if cur . t == 'heading' and cur . level == level : if section . first_child is not None : finalizeSection ( section ) children . append ( section ) section = Node ( 'MDsection' , 0 ) nxt = cur . nxt if section . first_child is None : if cur . t == 'heading' and cur . level == level : section . append_child ( cur ) else : children . append ( cur ) else : section . append_child ( cur ) cur = nxt if section . first_child is not None : finalizeSection ( section ) children . append ( section ) block . first_child = None block . last_child = None nextLevel = level + 1 for child in children : if child . t == 'MDsection' : nestSections ( child , level = nextLevel ) if block . first_child is None : block . first_child = child else : block . last_child . nxt = child child . parent = block child . nxt = None child . prev = block . last_child block . last_child = child
Sections aren t handled by CommonMark at the moment . This function adds sections to a block of nodes . title nodes with an assigned level below level will be put in a child section . If there are no child nodes with titles of level level then nothing is done
33
def parseMarkDownBlock ( text ) : block = Parser ( ) . parse ( text ) nestSections ( block ) return MarkDown ( block )
Parses a block of text returning a list of docutils nodes
34
def renderList ( l , markDownHelp , settings = None ) : if len ( l ) == 0 : return [ ] if markDownHelp : from sphinxarg . markdown import parseMarkDownBlock return parseMarkDownBlock ( '\n\n' . join ( l ) + '\n' ) else : all_children = [ ] for element in l : if isinstance ( element , str ) : if settings is None : settings = OptionParser ( components = ( Parser , ) ) . get_default_values ( ) document = new_document ( None , settings ) Parser ( ) . parse ( element + '\n' , document ) all_children += document . children elif isinstance ( element , nodes . definition ) : all_children += element return all_children
Given a list of reStructuredText or MarkDown sections return a docutils node list
35
def print_action_groups ( data , nested_content , markDownHelp = False , settings = None ) : definitions = map_nested_definitions ( nested_content ) nodes_list = [ ] if 'action_groups' in data : for action_group in data [ 'action_groups' ] : section = nodes . section ( ids = [ action_group [ 'title' ] ] ) section += nodes . title ( action_group [ 'title' ] , action_group [ 'title' ] ) desc = [ ] if action_group [ 'description' ] : desc . append ( action_group [ 'description' ] ) subContent = [ ] if action_group [ 'title' ] in definitions : classifier , s , subContent = definitions [ action_group [ 'title' ] ] if classifier == '@replace' : desc = [ s ] elif classifier == '@after' : desc . append ( s ) elif classifier == '@before' : desc . insert ( 0 , s ) elif classifier == '@skip' : continue if len ( subContent ) > 0 : for k , v in map_nested_definitions ( subContent ) . items ( ) : definitions [ k ] = v for element in renderList ( desc , markDownHelp ) : section += element localDefinitions = definitions if len ( subContent ) > 0 : localDefinitions = { k : v for k , v in definitions . items ( ) } for k , v in map_nested_definitions ( subContent ) . items ( ) : localDefinitions [ k ] = v items = [ ] for entry in action_group [ 'options' ] : arg = [ ] if 'choices' in entry : arg . append ( 'Possible choices: {}\n' . format ( ", " . join ( [ str ( c ) for c in entry [ 'choices' ] ] ) ) ) if 'help' in entry : arg . append ( entry [ 'help' ] ) if entry [ 'default' ] is not None and entry [ 'default' ] not in [ '"==SUPPRESS=="' , '==SUPPRESS==' ] : if entry [ 'default' ] == '' : arg . append ( 'Default: ""' ) else : arg . append ( 'Default: {}' . format ( entry [ 'default' ] ) ) desc = arg term = ' ' . join ( entry [ 'name' ] ) if term in localDefinitions : classifier , s , subContent = localDefinitions [ term ] if classifier == '@replace' : desc = [ s ] elif classifier == '@after' : desc . append ( s ) elif classifier == '@before' : desc . insert ( 0 , s ) term = ', ' . join ( entry [ 'name' ] ) n = nodes . option_list_item ( '' , nodes . option_group ( '' , nodes . option_string ( text = term ) ) , nodes . description ( '' , * renderList ( desc , markDownHelp , settings ) ) ) items . append ( n ) section += nodes . option_list ( '' , * items ) nodes_list . append ( section ) return nodes_list
Process all action groups which are also include Options and Required arguments . A list of nodes is returned .
36
def ensureUniqueIDs ( items ) : s = set ( ) for item in items : for n in item . traverse ( descend = True , siblings = True , ascend = False ) : if isinstance ( n , nodes . section ) : ids = n [ 'ids' ] for idx , id in enumerate ( ids ) : if id not in s : s . add ( id ) else : i = 1 while "{}_repeat{}" . format ( id , i ) in s : i += 1 ids [ idx ] = "{}_repeat{}" . format ( id , i ) s . add ( ids [ idx ] ) n [ 'ids' ] = ids
If action groups are repeated then links in the table of contents will just go to the first of the repeats . This may not be desirable particularly in the case of subcommands where the option groups have different members . This function updates the title IDs by adding _repeatX where X is a number so that the links are then unique .
37
def select ( self , item ) : self . _on_unselect [ self . _selected ] ( ) self . selected ( ) . unfocus ( ) if isinstance ( item , int ) : self . _selected = item % len ( self ) else : self . _selected = self . items . index ( item ) self . selected ( ) . focus ( ) self . _on_select [ self . _selected ] ( )
Select an arbitrary item by possition or by reference .
38
def on_select ( self , item , action ) : if not isinstance ( item , int ) : item = self . items . index ( item ) self . _on_select [ item ] = action
Add an action to make when an object is selected . Only one action can be stored this way .
39
def on_unselect ( self , item , action ) : if not isinstance ( item , int ) : item = self . items . index ( item ) self . _on_unselect [ item ] = action
Add an action to make when an object is unfocused .
40
def add ( self , widget , condition = lambda : 42 ) : assert callable ( condition ) assert isinstance ( widget , BaseWidget ) self . _widgets . append ( ( widget , condition ) ) return widget
Add a widget to the widows .
41
def remove ( self , widget ) : for i , ( wid , _ ) in enumerate ( self . _widgets ) : if widget is wid : del self . _widgets [ i ] return True raise ValueError ( 'Widget not in list' )
Remove a widget from the window .
42
def update_on_event ( self , e ) : if e . type == QUIT : self . running = False elif e . type == KEYDOWN : if e . key == K_ESCAPE : self . running = False elif e . key == K_F4 and e . mod & KMOD_ALT : self . running = False elif e . type == VIDEORESIZE : self . SCREEN_SIZE = e . size self . screen = self . new_screen ( )
Process a single event .
43
def render ( self ) : self . screen . fill ( self . BACKGROUND_COLOR ) for wid , cond in self . _widgets : if cond ( ) : wid . render ( self . screen ) if self . BORDER_COLOR is not None : pygame . draw . rect ( self . screen , self . BORDER_COLOR , ( ( 0 , 0 ) , self . SCREEN_SIZE ) , 1 ) if self . SHOW_FPS : self . fps . render ( self . screen )
Render the screen . Here you must draw everything .
44
def update_screen ( self ) : self . clock . tick ( self . FPS ) pygame . display . update ( )
Refresh the screen . You don t need to override this except to update only small portins of the screen .
45
def new_screen ( self ) : os . environ [ 'SDL_VIDEO_CENTERED' ] = '1' pygame . display . set_caption ( self . NAME ) screen_s = self . SCREEN_SIZE video_options = self . VIDEO_OPTIONS if FULLSCREEN & self . VIDEO_OPTIONS : video_options ^= FULLSCREEN video_options |= NOFRAME screen_s = ( 0 , 0 ) screen = pygame . display . set_mode ( screen_s , video_options ) if FULLSCREEN & self . VIDEO_OPTIONS : self . SCREEN_SIZE = screen . get_size ( ) if not QUIT in self . EVENT_ALLOWED : self . EVENT_ALLOWED = list ( self . EVENT_ALLOWED ) self . EVENT_ALLOWED . append ( QUIT ) pygame . event . set_allowed ( self . EVENT_ALLOWED ) return screen
Makes a new screen with a size of SCREEN_SIZE and VIDEO_OPTION as flags . Sets the windows name to NAME .
46
def merge_rects ( rect1 , rect2 ) : r = pygame . Rect ( rect1 ) t = pygame . Rect ( rect2 ) right = max ( r . right , t . right ) bot = max ( r . bottom , t . bottom ) x = min ( t . x , r . x ) y = min ( t . y , r . y ) return pygame . Rect ( x , y , right - x , bot - y )
Return the smallest rect containning two rects
47
def normnorm ( self ) : n = self . norm ( ) return V2 ( - self . y / n , self . x / n )
Return a vecor noraml to this one with a norm of one
48
def line ( surf , start , end , color = BLACK , width = 1 , style = FLAT ) : width = round ( width , 1 ) if width == 1 : return gfxdraw . line ( surf , * start , * end , color ) start = V2 ( * start ) end = V2 ( * end ) line_vector = end - start half_side = line_vector . normnorm ( ) * width / 2 point1 = start + half_side point2 = start - half_side point3 = end - half_side point4 = end + half_side liste = [ ( point1 . x , point1 . y ) , ( point2 . x , point2 . y ) , ( point3 . x , point3 . y ) , ( point4 . x , point4 . y ) ] rect = polygon ( surf , liste , color ) if style == ROUNDED : _ = circle ( surf , start , width / 2 , color ) rect = merge_rects ( rect , _ ) _ = circle ( surf , end , width / 2 , color ) rect = merge_rects ( rect , _ ) return rect
Draws an antialiased line on the surface .
49
def circle ( surf , xy , r , color = BLACK ) : x , y = xy x = round ( x ) y = round ( y ) r = round ( r ) gfxdraw . filled_circle ( surf , x , y , r , color ) gfxdraw . aacircle ( surf , x , y , r , color ) r += 1 return pygame . Rect ( x - r , y - r , 2 * r , 2 * r )
Draw an antialiased filled circle on the given surface
50
def ring ( surf , xy , r , width , color ) : r2 = r - width x0 , y0 = xy x = r2 y = 0 err = 0 right = { } while x >= y : right [ x ] = y right [ y ] = x right [ - x ] = y right [ - y ] = x y += 1 if err <= 0 : err += 2 * y + 1 if err > 0 : x -= 1 err -= 2 * x + 1 def h_fill_the_circle ( surf , color , x , y , right ) : if - r2 <= y <= r2 : pygame . draw . line ( surf , color , ( x0 + right [ y ] , y0 + y ) , ( x0 + x , y0 + y ) ) pygame . draw . line ( surf , color , ( x0 - right [ y ] , y0 + y ) , ( x0 - x , y0 + y ) ) else : pygame . draw . line ( surf , color , ( x0 - x , y0 + y ) , ( x0 + x , y0 + y ) ) x = r y = 0 err = 0 while x >= y : h_fill_the_circle ( surf , color , x , y , right ) h_fill_the_circle ( surf , color , x , - y , right ) h_fill_the_circle ( surf , color , y , x , right ) h_fill_the_circle ( surf , color , y , - x , right ) y += 1 if err < 0 : err += 2 * y + 1 if err >= 0 : x -= 1 err -= 2 * x + 1 gfxdraw . aacircle ( surf , x0 , y0 , r , color ) gfxdraw . aacircle ( surf , x0 , y0 , r2 , color )
Draws a ring
51
def roundrect ( surface , rect , color , rounding = 5 , unit = PIXEL ) : if unit == PERCENT : rounding = int ( min ( rect . size ) / 2 * rounding / 100 ) rect = pygame . Rect ( rect ) color = pygame . Color ( * color ) alpha = color . a color . a = 0 pos = rect . topleft rect . topleft = 0 , 0 rectangle = pygame . Surface ( rect . size , SRCALPHA ) circle = pygame . Surface ( [ min ( rect . size ) * 3 ] * 2 , SRCALPHA ) pygame . draw . ellipse ( circle , ( 0 , 0 , 0 ) , circle . get_rect ( ) , 0 ) circle = pygame . transform . smoothscale ( circle , ( rounding , rounding ) ) rounding = rectangle . blit ( circle , ( 0 , 0 ) ) rounding . bottomright = rect . bottomright rectangle . blit ( circle , rounding ) rounding . topright = rect . topright rectangle . blit ( circle , rounding ) rounding . bottomleft = rect . bottomleft rectangle . blit ( circle , rounding ) rectangle . fill ( ( 0 , 0 , 0 ) , rect . inflate ( - rounding . w , 0 ) ) rectangle . fill ( ( 0 , 0 , 0 ) , rect . inflate ( 0 , - rounding . h ) ) rectangle . fill ( color , special_flags = BLEND_RGBA_MAX ) rectangle . fill ( ( 255 , 255 , 255 , alpha ) , special_flags = BLEND_RGBA_MIN ) return surface . blit ( rectangle , pos )
Draw an antialiased round rectangle on the surface .
52
def polygon ( surf , points , color ) : gfxdraw . aapolygon ( surf , points , color ) gfxdraw . filled_polygon ( surf , points , color ) x = min ( [ x for ( x , y ) in points ] ) y = min ( [ y for ( x , y ) in points ] ) xm = max ( [ x for ( x , y ) in points ] ) ym = max ( [ y for ( x , y ) in points ] ) return pygame . Rect ( x , y , xm - x , ym - y )
Draw an antialiased filled polygon on a surface
53
def _get_color ( self ) : if self . clicked and self . hovered : color = mix ( self . color , BLACK , 0.8 ) elif self . hovered and not self . flags & self . NO_HOVER : color = mix ( self . color , BLACK , 0.93 ) else : color = self . color self . text . bg_color = color return color
Return the color of the button depending on its state
54
def _front_delta ( self ) : if self . flags & self . NO_MOVE : return Separator ( 0 , 0 ) if self . clicked and self . hovered : delta = 2 elif self . hovered and not self . flags & self . NO_HOVER : delta = 0 else : delta = 0 return Separator ( delta , delta )
Return the offset of the colored part .
55
def update ( self , event_or_list ) : for e in super ( ) . update ( event_or_list ) : if e . type == MOUSEBUTTONDOWN : if e . pos in self : self . click ( ) else : self . release ( force_no_call = True ) elif e . type == MOUSEBUTTONUP : self . release ( force_no_call = e . pos not in self ) elif e . type == MOUSEMOTION : if e . pos in self : self . hovered = True else : self . hovered = False
Update the button with the events .
56
def render ( self , surf ) : pos , size = self . topleft , self . size if not self . flags & self . NO_SHADOW : if self . flags & self . NO_ROUNDING : pygame . draw . rect ( surf , LIGHT_GREY , ( pos + self . _bg_delta , size ) ) else : roundrect ( surf , ( pos + self . _bg_delta , size ) , LIGHT_GREY + ( 100 , ) , 5 ) if self . flags & self . NO_ROUNDING : pygame . draw . rect ( surf , self . _get_color ( ) , ( pos + self . _front_delta , size ) ) else : roundrect ( surf , ( pos + self . _front_delta , size ) , self . _get_color ( ) , 5 ) self . text . center = self . center + self . _front_delta self . text . render ( surf )
Render the button on a surface .
57
def render ( self , surf ) : if not self . flags & self . NO_SHADOW : circle ( surf , self . center + self . _bg_delta , self . width / 2 , LIGHT_GREY ) circle ( surf , self . center + self . _front_delta , self . width / 2 , self . _get_color ( ) ) self . text . center = self . center + self . _front_delta self . text . render ( surf )
Draw the button on the surface .
58
def render ( self , surf ) : if self . clicked : icon = self . icon_pressed else : icon = self . icon surf . blit ( icon , self )
Render the button
59
def set ( self , value ) : value = min ( self . max , max ( self . min , value ) ) self . _value = value start_new_thread ( self . func , ( self . get ( ) , ) )
Set the value of the bar . If the value is out of bound sets it to an extremum
60
def _start ( self ) : last_call = 42 while self . _focus : sleep ( 1 / 100 ) mouse = pygame . mouse . get_pos ( ) last_value = self . get ( ) self . value_px = mouse [ 0 ] if self . get ( ) == last_value : continue if last_call + self . interval / 1000 < time ( ) : last_call = time ( ) self . func ( self . get ( ) )
Starts checking if the SB is shifted
61
def value_px ( self ) : step = self . w / ( self . max - self . min ) return self . x + step * ( self . get ( ) - self . min )
The position in pixels of the cursor
62
def render ( self , display ) : bar_rect = pygame . Rect ( 0 , 0 , self . width , self . height // 3 ) bar_rect . center = self . center display . fill ( self . bg_color , bar_rect ) circle ( display , ( self . value_px , self . centery ) , self . height // 2 , self . color ) if self . show_val : self . text_val . render ( display )
Renders the bar on the display
63
def __update ( self ) : width , height = self . size super ( BaseWidget , self ) . __setattr__ ( "width" , width ) super ( BaseWidget , self ) . __setattr__ ( "height" , height ) super ( BaseWidget , self ) . __setattr__ ( self . anchor , self . pos )
This is called each time an attribute is asked to be sure every params are updated beceause of callbacks .
64
def activate ( specifier ) : try : for distro in require ( specifier ) : distro . activate ( ) except ( VersionConflict , DistributionNotFound ) : raise RuntimeError ( 'The installed version of pip is too old; peep ' 'requires ' + specifier )
Make a compatible version of pip importable . Raise a RuntimeError if we couldn t .
65
def path_and_line ( req ) : path , line = ( re . match ( r'-r (.*) \(line (\d+)\)$' , req . comes_from ) . groups ( ) ) return path , int ( line )
Return the path and line number of the file from which an InstallRequirement came .
66
def hashes_above ( path , line_number ) : def hash_lists ( path ) : hashes = [ ] with open ( path ) as file : for lineno , line in enumerate ( file , 1 ) : match = HASH_COMMENT_RE . match ( line ) if match : hashes . append ( match . groupdict ( ) [ 'hash' ] ) if not IGNORED_LINE_RE . match ( line ) : yield hashes hashes = [ ] elif PIP_COUNTS_COMMENTS : yield [ ] return next ( islice ( hash_lists ( path ) , line_number - 1 , None ) )
Yield hashes from contiguous comment lines before line line_number .
67
def hash_of_file ( path ) : with open ( path , 'rb' ) as archive : sha = sha256 ( ) while True : data = archive . read ( 2 ** 20 ) if not data : break sha . update ( data ) return encoded_hash ( sha )
Return the hash of a downloaded file .
68
def requirement_args ( argv , want_paths = False , want_other = False ) : was_r = False for arg in argv : if was_r : if want_paths : yield arg was_r = False elif arg in [ '-r' , '--requirement' ] : was_r = True else : if want_other : yield arg
Return an iterable of filtered arguments .
69
def peep_hash ( argv ) : parser = OptionParser ( usage = 'usage: %prog hash file [file ...]' , description = 'Print a peep hash line for one or more files: for ' 'example, "# sha256: ' 'oz42dZy6Gowxw8AelDtO4gRgTW_xPdooH484k7I5EOY".' ) _ , paths = parser . parse_args ( args = argv ) if paths : for path in paths : print ( '# sha256:' , hash_of_file ( path ) ) return ITS_FINE_ITS_FINE else : parser . print_usage ( ) return COMMAND_LINE_ERROR
Return the peep hash of one or more files returning a shell status code or raising a PipException .
70
def memoize ( func ) : @ wraps ( func ) def memoizer ( self ) : if not hasattr ( self , '_cache' ) : self . _cache = { } if func . __name__ not in self . _cache : self . _cache [ func . __name__ ] = func ( self ) return self . _cache [ func . __name__ ] return memoizer
Memoize a method that should return the same result every time on a given instance .
71
def package_finder ( argv ) : try : command = InstallCommand ( ) except TypeError : from pip . baseparser import create_main_parser command = InstallCommand ( create_main_parser ( ) ) options , _ = loads ( dumps ( command . parser ) ) . parse_args ( argv ) possible_options = [ 'find_links' , FORMAT_CONTROL_ARG , ( 'allow_all_prereleases' , 'pre' ) , 'process_dependency_links' ] kwargs = { } for option in possible_options : kw , attr = option if isinstance ( option , tuple ) else ( option , option ) value = getattr ( options , attr , MARKER ) if value is not MARKER : kwargs [ kw ] = value index_urls = [ options . index_url ] + options . extra_index_urls if options . no_index : index_urls = [ ] index_urls += getattr ( options , 'mirrors' , [ ] ) if hasattr ( command , '_build_session' ) : kwargs [ 'session' ] = command . _build_session ( options ) return PackageFinder ( index_urls = index_urls , ** kwargs )
Return a PackageFinder respecting command - line options .
72
def bucket ( things , key ) : ret = defaultdict ( list ) for thing in things : ret [ key ( thing ) ] . append ( thing ) return ret
Return a map of key - > list of things .
73
def first_every_last ( iterable , first , every , last ) : did_first = False for item in iterable : if not did_first : did_first = True first ( item ) every ( item ) if did_first : last ( item )
Execute something before the first item of iter something else for each item and a third thing after the last .
74
def downloaded_reqs_from_path ( path , argv ) : finder = package_finder ( argv ) return [ DownloadedReq ( req , argv , finder ) for req in _parse_requirements ( path , finder ) ]
Return a list of DownloadedReqs representing the requirements parsed out of a given requirements file .
75
def peep_install ( argv ) : output = [ ] out = output . append reqs = [ ] try : req_paths = list ( requirement_args ( argv , want_paths = True ) ) if not req_paths : out ( "You have to specify one or more requirements files with the -r option, because\n" "otherwise there's nowhere for peep to look up the hashes.\n" ) return COMMAND_LINE_ERROR reqs = list ( chain . from_iterable ( downloaded_reqs_from_path ( path , argv ) for path in req_paths ) ) buckets = bucket ( reqs , lambda r : r . __class__ ) if any ( buckets [ b ] for b in ERROR_CLASSES ) : out ( '\n' ) printers = ( lambda r : out ( r . head ( ) ) , lambda r : out ( r . error ( ) + '\n' ) , lambda r : out ( r . foot ( ) ) ) for c in ERROR_CLASSES : first_every_last ( buckets [ c ] , * printers ) if any ( buckets [ b ] for b in ERROR_CLASSES ) : out ( '-------------------------------\n' 'Not proceeding to installation.\n' ) return SOMETHING_WENT_WRONG else : for req in buckets [ InstallableReq ] : req . install ( ) first_every_last ( buckets [ SatisfiedReq ] , * printers ) return ITS_FINE_ITS_FINE except ( UnsupportedRequirementError , InstallationError , DownloadError ) as exc : out ( str ( exc ) ) return SOMETHING_WENT_WRONG finally : for req in reqs : req . dispose ( ) print ( '' . join ( output ) )
Perform the peep install subcommand returning a shell status code or raising a PipException .
76
def peep_port ( paths ) : if not paths : print ( 'Please specify one or more requirements files so I have ' 'something to port.\n' ) return COMMAND_LINE_ERROR comes_from = None for req in chain . from_iterable ( _parse_requirements ( path , package_finder ( argv ) ) for path in paths ) : req_path , req_line = path_and_line ( req ) hashes = [ hexlify ( urlsafe_b64decode ( ( hash + '=' ) . encode ( 'ascii' ) ) ) . decode ( 'ascii' ) for hash in hashes_above ( req_path , req_line ) ] if req_path != comes_from : print ( ) print ( '# from %s' % req_path ) print ( ) comes_from = req_path if not hashes : print ( req . req ) else : print ( '%s' % ( req . link if getattr ( req , 'link' , None ) else req . req ) , end = '' ) for hash in hashes : print ( ' \\' ) print ( ' --hash=sha256:%s' % hash , end = '' ) print ( )
Convert a peep requirements file to one compatble with pip - 8 hashing .
77
def main ( ) : commands = { 'hash' : peep_hash , 'install' : peep_install , 'port' : peep_port } try : if len ( argv ) >= 2 and argv [ 1 ] in commands : return commands [ argv [ 1 ] ] ( argv [ 2 : ] ) else : return pip . main ( ) except PipException as exc : return exc . error_code
Be the top - level entrypoint . Return a shell status code .
78
def _version ( self ) : def version_of_archive ( filename , package_name ) : for ext in ARCHIVE_EXTENSIONS : if filename . endswith ( ext ) : filename = filename [ : - len ( ext ) ] break if is_git_sha ( filename ) : filename = package_name + '-' + filename if not filename . lower ( ) . replace ( '_' , '-' ) . startswith ( package_name . lower ( ) ) : give_up ( filename , package_name ) return filename [ len ( package_name ) + 1 : ] def version_of_wheel ( filename , package_name ) : whl_package_name , version , _rest = filename . split ( '-' , 2 ) our_package_name = re . sub ( r'[^\w\d.]+' , '_' , package_name , re . UNICODE ) if whl_package_name != our_package_name : give_up ( filename , whl_package_name ) return version def give_up ( filename , package_name ) : raise RuntimeError ( "The archive '%s' didn't start with the package name " "'%s', so I couldn't figure out the version number. " "My bad; improve me." % ( filename , package_name ) ) get_version = ( version_of_wheel if self . _downloaded_filename ( ) . endswith ( '.whl' ) else version_of_archive ) return get_version ( self . _downloaded_filename ( ) , self . _project_name ( ) )
Deduce the version number of the downloaded package from its filename .
79
def _is_always_unsatisfied ( self ) : url = self . _url ( ) if url : filename = filename_from_url ( url ) if filename . endswith ( ARCHIVE_EXTENSIONS ) : filename , ext = splitext ( filename ) if is_git_sha ( filename ) : return True return False
Returns whether this requirement is always unsatisfied
80
def _download ( self , link ) : def opener ( is_https ) : if is_https : opener = build_opener ( HTTPSHandler ( ) ) for handler in opener . handlers : if isinstance ( handler , HTTPHandler ) : opener . handlers . remove ( handler ) else : opener = build_opener ( ) return opener def best_filename ( link , response ) : content_type = response . info ( ) . get ( 'content-type' , '' ) filename = link . filename content_disposition = response . info ( ) . get ( 'content-disposition' ) if content_disposition : type , params = cgi . parse_header ( content_disposition ) filename = params . get ( 'filename' ) or filename ext = splitext ( filename ) [ 1 ] if not ext : ext = mimetypes . guess_extension ( content_type ) if ext : filename += ext if not ext and link . url != response . geturl ( ) : ext = splitext ( response . geturl ( ) ) [ 1 ] if ext : filename += ext return filename def pipe_to_file ( response , path , size = 0 ) : def response_chunks ( chunk_size ) : while True : chunk = response . read ( chunk_size ) if not chunk : break yield chunk print ( 'Downloading %s%s...' % ( self . _req . req , ( ' (%sK)' % ( size / 1000 ) ) if size > 1000 else '' ) ) progress_indicator = ( DownloadProgressBar ( max = size ) . iter if size else DownloadProgressSpinner ( ) . iter ) with open ( path , 'wb' ) as file : for chunk in progress_indicator ( response_chunks ( 4096 ) , 4096 ) : file . write ( chunk ) url = link . url . split ( '#' , 1 ) [ 0 ] try : response = opener ( urlparse ( url ) . scheme != 'http' ) . open ( url ) except ( HTTPError , IOError ) as exc : raise DownloadError ( link , exc ) filename = best_filename ( link , response ) try : size = int ( response . headers [ 'content-length' ] ) except ( ValueError , KeyError , TypeError ) : size = 0 pipe_to_file ( response , join ( self . _temp_path , filename ) , size = size ) return filename
Download a file and return its name within my temp dir .
81
def _downloaded_filename ( self ) : link = self . _link ( ) or self . _finder . find_requirement ( self . _req , upgrade = False ) if link : lower_scheme = link . scheme . lower ( ) if lower_scheme == 'http' or lower_scheme == 'https' : file_path = self . _download ( link ) return basename ( file_path ) elif lower_scheme == 'file' : link_path = url_to_path ( link . url_without_fragment ) if isdir ( link_path ) : raise UnsupportedRequirementError ( "%s: %s is a directory. So that it can compute " "a hash, peep supports only filesystem paths which " "point to files" % ( self . _req , link . url_without_fragment ) ) else : copy ( link_path , self . _temp_path ) return basename ( link_path ) else : raise UnsupportedRequirementError ( "%s: The download link, %s, would not result in a file " "that can be hashed. Peep supports only == requirements, " "file:// URLs pointing to files (not folders), and " "http:// and https:// URLs pointing to tarballs, zips, " "etc." % ( self . _req , link . url ) ) else : raise UnsupportedRequirementError ( "%s: couldn't determine where to download this requirement from." % ( self . _req , ) )
Download the package s archive if necessary and return its filename .
82
def install ( self ) : other_args = list ( requirement_args ( self . _argv , want_other = True ) ) archive_path = join ( self . _temp_path , self . _downloaded_filename ( ) ) run_pip ( [ 'install' ] + other_args + [ '--no-deps' , '-U' , archive_path ] )
Install the package I represent without dependencies .
83
def _project_name ( self ) : name = getattr ( self . _req . req , 'project_name' , '' ) if name : return name name = getattr ( self . _req . req , 'name' , '' ) if name : return safe_name ( name ) raise ValueError ( 'Requirement has no project_name.' )
Return the inner Requirement s unsafe name .
84
def _class ( self ) : try : self . _project_name ( ) except ValueError : return MalformedReq if self . _is_satisfied ( ) : return SatisfiedReq if not self . _expected_hashes ( ) : return MissingReq if self . _actual_hash ( ) not in self . _expected_hashes ( ) : return MismatchedReq return InstallableReq
Return the class I should be spanning a continuum of goodness .
85
def __get_response ( self , uri , params = None , method = "get" , stream = False ) : if not hasattr ( self , "session" ) or not self . session : self . session = requests . Session ( ) if self . access_token : self . session . headers . update ( { 'Authorization' : 'Bearer {}' . format ( self . access_token ) } ) if params : params = { k : v for k , v in params . items ( ) if v is not None } kwargs = { "url" : uri , "verify" : True , "stream" : stream } kwargs [ "params" if method == "get" else "data" ] = params return getattr ( self . session , method ) ( ** kwargs )
Creates a response object with the given params and option
86
def __call ( self , uri , params = None , method = "get" ) : try : resp = self . __get_response ( uri , params , method , False ) rjson = resp . json ( ** self . json_options ) assert resp . ok except AssertionError : msg = "OCode-{}: {}" . format ( resp . status_code , rjson [ "message" ] ) raise BadRequest ( msg ) except Exception as e : msg = "Bad response: {}" . format ( e ) log . error ( msg , exc_info = True ) raise BadRequest ( msg ) else : return rjson
Only returns the response nor the status_code
87
def __call_stream ( self , uri , params = None , method = "get" ) : try : resp = self . __get_response ( uri , params , method , True ) assert resp . ok except AssertionError : raise BadRequest ( resp . status_code ) except Exception as e : log . error ( "Bad response: {}" . format ( e ) , exc_info = True ) else : return resp
Returns an stream response
88
def get_trades ( self , max_id = None , count = None , instrument = None , ids = None ) : url = "{0}/{1}/accounts/{2}/trades" . format ( self . domain , self . API_VERSION , self . account_id ) params = { "maxId" : int ( max_id ) if max_id and max_id > 0 else None , "count" : int ( count ) if count and count > 0 else None , "instrument" : instrument , "ids" : ',' . join ( ids ) if ids else None } try : return self . _Client__call ( uri = url , params = params , method = "get" ) except RequestException : return False except AssertionError : return False
Get a list of open trades
89
def update_trade ( self , trade_id , stop_loss = None , take_profit = None , trailing_stop = None ) : url = "{0}/{1}/accounts/{2}/trades/{3}" . format ( self . domain , self . API_VERSION , self . account_id , trade_id ) params = { "stopLoss" : stop_loss , "takeProfit" : take_profit , "trailingStop" : trailing_stop } try : return self . _Client__call ( uri = url , params = params , method = "patch" ) except RequestException : return False except AssertionError : return False raise NotImplementedError ( )
Modify an existing trade .
90
def request_transaction_history ( self ) : url = "{0}/{1}/accounts/{2}/alltransactions" . format ( self . domain , self . API_VERSION , self . account_id ) try : resp = self . __get_response ( url ) return resp . headers [ 'location' ] except RequestException : return False except AssertionError : return False
Request full account history .
91
def get_transaction_history ( self , max_wait = 5.0 ) : url = self . request_transaction_history ( ) if not url : return False ready = False start = time ( ) delay = 0.1 while not ready and delay : response = requests . head ( url ) ready = response . ok if not ready : sleep ( delay ) time_remaining = max_wait - time ( ) + start max_delay = max ( 0. , time_remaining - .1 ) delay = min ( delay * 2 , max_delay ) if not ready : return False response = requests . get ( url ) try : with ZipFile ( BytesIO ( response . content ) ) as container : files = container . namelist ( ) if not files : log . error ( 'Transaction ZIP has no files.' ) return False history = container . open ( files [ 0 ] ) raw = history . read ( ) . decode ( 'ascii' ) except BadZipfile : log . error ( 'Response is not a valid ZIP file' , exc_info = True ) return False return json . loads ( raw , ** self . json_options )
Download full account history .
92
def get_accounts ( self , username = None ) : url = "{0}/{1}/accounts" . format ( self . domain , self . API_VERSION ) params = { "username" : username } try : return self . _Client__call ( uri = url , params = params , method = "get" ) except RequestException : return False except AssertionError : return False
Get a list of accounts owned by the user .
93
def choose ( self ) : if not self . choosed : self . choosed = True self . pos = self . pos + Sep ( 5 , 0 )
Marks the item as the one the user is in .
94
def stop_choose ( self ) : if self . choosed : self . choosed = False self . pos = self . pos + Sep ( - 5 , 0 )
Marks the item as the one the user is not in .
95
def get_darker_color ( self ) : if bw_contrasted ( self . _true_color , 30 ) == WHITE : color = mix ( self . _true_color , WHITE , 0.9 ) else : color = mix ( self . _true_color , BLACK , 0.9 ) return color
The color of the clicked version of the MenuElement . Darker than the normal one .
96
def render ( self , screen ) : self . rect . render ( screen ) super ( MenuElement , self ) . render ( screen )
Renders the MenuElement
97
def px_to_pt ( self , px ) : if px < 200 : pt = self . PX_TO_PT [ px ] else : pt = int ( floor ( ( px - 1.21 ) / 1.332 ) ) return pt
Convert a size in pxel to a size in points .
98
def set_size ( self , pt = None , px = None ) : assert ( pt , px ) != ( None , None ) if pt is not None : self . __init__ ( pt , self . font_name ) else : self . __init__ ( self . px_to_pt ( px ) , self . font_name )
Set the size of the font in px or pt .
99
def text ( self ) : if callable ( self . _text ) : return str ( self . _text ( ) ) return str ( self . _text )
Return the string to render .

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
9
Add dataset card