text
stringlengths
81
112k
Add some raw html (possibly as a block) def raw(node): """ Add some raw html (possibly as a block) """ o = nodes.raw(node.literal, node.literal, format='html') if node.sourcepos is not None: o.line = node.sourcepos[0][0] for n in MarkDown(node): o += n return o
A title node. It has no children def title(node): """ A title node. It has no children """ return nodes.title(node.first_child.literal, node.first_child.literal)
A section in reStructuredText, which needs a title (the first child) This is a custom type def section(node): """ A section in reStructuredText, which needs a title (the first child) This is a custom type """ title = '' # All sections need an id if node.first_child is not None: if node.first_child.t == u'heading': title = node.first_child.first_child.literal o = nodes.section(ids=[title], names=[title]) for n in MarkDown(node): o += n return o
A block quote def block_quote(node): """ A block quote """ o = nodes.block_quote() o.line = node.sourcepos[0][0] for n in MarkDown(node): o += n return o
An image element The first child is the alt text. reStructuredText can't handle titles def image(node): """ An image element The first child is the alt text. reStructuredText can't handle titles """ o = nodes.image(uri=node.destination) if node.first_child is not None: o['alt'] = node.first_child.literal return o
An item in a list def listItem(node): """ An item in a list """ o = nodes.list_item() for n in MarkDown(node): o += n return o
A list (numbered or not) For numbered lists, the suffix is only rendered as . in html def listNode(node): """ A list (numbered or not) For numbered lists, the suffix is only rendered as . in html """ if node.list_data['type'] == u'bullet': o = nodes.bullet_list(bullet=node.list_data['bullet_char']) else: o = nodes.enumerated_list(suffix=node.list_data['delimiter'], enumtype='arabic', start=node.list_data['start']) for n in MarkDown(node): o += n return o
Returns a list of nodes, containing CommonMark nodes converted to docutils nodes def MarkDown(node): """ Returns a list of nodes, containing CommonMark nodes converted to docutils nodes """ cur = node.first_child # Go into each child, in turn 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
Correct the nxt and parent for each child def finalizeSection(section): """ Correct the nxt and parent for each child """ 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
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 def nestSections(block, level=1): """ 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 """ cur = block.first_child if cur is not None: children = [] # Do we need to do anything? 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: # Found a split point, flush the last section if needed if section.first_child is not None: finalizeSection(section) children.append(section) section = Node('MDsection', 0) nxt = cur.nxt # Avoid adding sections without titles at the start 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 there's only 1 child then don't bother 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: # Handle nesting if child.t == 'MDsection': nestSections(child, level=nextLevel) # Append 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
Parses a block of text, returning a list of docutils nodes >>> parseMarkdownBlock("Some\n====\n\nblock of text\n\nHeader\n======\n\nblah\n") [] def parseMarkDownBlock(text): """ Parses a block of text, returning a list of docutils nodes >>> parseMarkdownBlock("Some\n====\n\nblock of text\n\nHeader\n======\n\nblah\n") [] """ block = Parser().parse(text) # CommonMark can't nest sections, so do it manually nestSections(block) return MarkDown(block)
Given a list of reStructuredText or MarkDown sections, return a docutils node list def renderList(l, markDownHelp, settings=None): """ Given a list of reStructuredText or MarkDown sections, return a docutils node list """ 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
Process all 'action groups', which are also include 'Options' and 'Required arguments'. A list of nodes is returned. def print_action_groups(data, nested_content, markDownHelp=False, settings=None): """ Process all 'action groups', which are also include 'Options' and 'Required arguments'. A list of nodes is returned. """ definitions = map_nested_definitions(nested_content) nodes_list = [] if 'action_groups' in data: for action_group in data['action_groups']: # Every action group is comprised of a section, holding a title, the description, and the option group (members) 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']) # Replace/append/prepend content to the description according to nested content 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 # Render appropriately 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 = [] # Iterate over action group members for entry in action_group['options']: """ Members will include: default The default value. This may be ==SUPPRESS== name A list of option names (e.g., ['-h', '--help'] help The help message string There may also be a 'choices' member. """ # Build the help text 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'])) # Handle nested content, the term used in the dict has the comma removed for simplicity 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
Each subcommand is a dictionary with the following keys: ['usage', 'action_groups', 'bare_usage', 'name', 'help'] In essence, this is all tossed in a new section with the title 'name'. Apparently there can also be a 'description' entry. def print_subcommands(data, nested_content, markDownHelp=False, settings=None): """ Each subcommand is a dictionary with the following keys: ['usage', 'action_groups', 'bare_usage', 'name', 'help'] In essence, this is all tossed in a new section with the title 'name'. Apparently there can also be a 'description' entry. """ definitions = map_nested_definitions(nested_content) items = [] if 'children' in data: subCommands = nodes.section(ids=["Sub-commands:"]) subCommands += nodes.title('Sub-commands:', 'Sub-commands:') for child in data['children']: sec = nodes.section(ids=[child['name']]) sec += nodes.title(child['name'], child['name']) if 'description' in child and child['description']: desc = [child['description']] elif child['help']: desc = [child['help']] else: desc = ['Undocumented'] # Handle nested content subContent = [] if child['name'] in definitions: classifier, s, subContent = definitions[child['name']] if classifier == '@replace': desc = [s] elif classifier == '@after': desc.append(s) elif classifier == '@before': desc.insert(0, s) for element in renderList(desc, markDownHelp): sec += element sec += nodes.literal_block(text=child['bare_usage']) for x in print_action_groups(child, nested_content + subContent, markDownHelp, settings=settings): sec += x for x in print_subcommands(child, nested_content + subContent, markDownHelp, settings=settings): sec += x if 'epilog' in child and child['epilog']: for element in renderList([child['epilog']], markDownHelp): sec += element subCommands += sec items.append(subCommands) return items
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. def ensureUniqueIDs(items): """ 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. """ 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
Construct a typical man page consisting of the following elements: NAME (automatically generated, out of our control) SYNOPSIS DESCRIPTION OPTIONS FILES SEE ALSO BUGS def _construct_manpage_specific_structure(self, parser_info): """ Construct a typical man page consisting of the following elements: NAME (automatically generated, out of our control) SYNOPSIS DESCRIPTION OPTIONS FILES SEE ALSO BUGS """ items = [] # SYNOPSIS section synopsis_section = nodes.section( '', nodes.title(text='Synopsis'), nodes.literal_block(text=parser_info["bare_usage"]), ids=['synopsis-section']) items.append(synopsis_section) # DESCRIPTION section if 'nodescription' not in self.options: description_section = nodes.section( '', nodes.title(text='Description'), nodes.paragraph(text=parser_info.get( 'description', parser_info.get( 'help', "undocumented").capitalize())), ids=['description-section']) nested_parse_with_titles( self.state, self.content, description_section) items.append(description_section) if parser_info.get('epilog') and 'noepilog' not in self.options: # TODO: do whatever sphinx does to understand ReST inside # docstrings magically imported from other places. The nested # parse method invoked above seem to be able to do this but # I haven't found a way to do it for arbitrary text if description_section: description_section += nodes.paragraph( text=parser_info['epilog']) else: description_section = nodes.paragraph( text=parser_info['epilog']) items.append(description_section) # OPTIONS section options_section = nodes.section( '', nodes.title(text='Options'), ids=['options-section']) if 'args' in parser_info: options_section += nodes.paragraph() options_section += nodes.subtitle(text='Positional arguments:') options_section += self._format_positional_arguments(parser_info) for action_group in parser_info['action_groups']: if 'options' in parser_info: options_section += nodes.paragraph() options_section += nodes.subtitle(text=action_group['title']) options_section += self._format_optional_arguments(action_group) # NOTE: we cannot generate NAME ourselves. It is generated by # docutils.writers.manpage # TODO: items.append(files) # TODO: items.append(see also) # TODO: items.append(bugs) if len(options_section.children) > 1: items.append(options_section) if 'nosubcommands' not in self.options: # SUBCOMMANDS section (non-standard) subcommands_section = nodes.section( '', nodes.title(text='Sub-Commands'), ids=['subcommands-section']) if 'children' in parser_info: subcommands_section += self._format_subcommands(parser_info) if len(subcommands_section) > 1: items.append(subcommands_section) if os.getenv("INCLUDE_DEBUG_SECTION"): import json # DEBUG section (non-standard) debug_section = nodes.section( '', nodes.title(text="Argparse + Sphinx Debugging"), nodes.literal_block(text=json.dumps(parser_info, indent=' ')), ids=['debug-section']) items.append(debug_section) return items
Select an arbitrary item, by possition or by reference. def select(self, item): """Select an arbitrary item, by possition or by reference.""" 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]()
Add an action to make when an object is selected. Only one action can be stored this way. def on_select(self, item, action): """ Add an action to make when an object is selected. Only one action can be stored this way. """ if not isinstance(item, int): item = self.items.index(item) self._on_select[item] = action
Add an action to make when an object is unfocused. def on_unselect(self, item, action): """Add an action to make when an object is unfocused.""" if not isinstance(item, int): item = self.items.index(item) self._on_unselect[item] = action
Add a widget to the widows. The widget will auto render. You can use the function like that if you want to keep the widget accecible : self.my_widget = self.add(my_widget) def add(self, widget, condition=lambda: 42): """ Add a widget to the widows. The widget will auto render. You can use the function like that if you want to keep the widget accecible : self.my_widget = self.add(my_widget) """ assert callable(condition) assert isinstance(widget, BaseWidget) self._widgets.append((widget, condition)) return widget
Remove a widget from the window. def remove(self, widget): """Remove a widget from the window.""" for i, (wid, _) in enumerate(self._widgets): if widget is wid: del self._widgets[i] return True raise ValueError('Widget not in list')
Process a single event. def update_on_event(self, e): """Process a single event.""" 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: # Alt+F4 --> quits self.running = False elif e.type == VIDEORESIZE: self.SCREEN_SIZE = e.size self.screen = self.new_screen()
Get all events and process them by calling update_on_event() def update(self): """Get all events and process them by calling update_on_event()""" events = pygame.event.get() for e in events: self.update_on_event(e) for wid, cond in self._widgets: if cond(): wid.update(events)
Render the screen. Here you must draw everything. def render(self): """Render the screen. Here you must draw everything.""" 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)
Refresh the screen. You don't need to override this except to update only small portins of the screen. def update_screen(self): """Refresh the screen. You don't need to override this except to update only small portins of the screen.""" self.clock.tick(self.FPS) pygame.display.update()
The run loop. Returns self.destroy() def run(self): """The run loop. Returns self.destroy()""" while self.running: self.update() self.render() self.update_screen() return self.destroy()
Makes a new screen with a size of SCREEN_SIZE, and VIDEO_OPTION as flags. Sets the windows name to NAME. def new_screen(self): """Makes a new screen with a size of SCREEN_SIZE, and VIDEO_OPTION as flags. Sets the windows name to NAME.""" 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
Return the smallest rect containning two rects def merge_rects(rect1, rect2): """Return the smallest rect containning two rects""" 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 a vecor noraml to this one with a norm of one :return: V2 def normnorm(self): """ Return a vecor noraml to this one with a norm of one :return: V2 """ n = self.norm() return V2(-self.y / n, self.x / n)
Draws an antialiased line on the surface. def line(surf, start, end, color=BLACK, width=1, style=FLAT): """Draws an antialiased line on the surface.""" width = round(width, 1) if width == 1: # return pygame.draw.aaline(surf, color, start, end) 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 # noinspection PyUnresolvedReferences 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
Draw an antialiased filled circle on the given surface def circle(surf, xy, r, color=BLACK): """Draw an antialiased filled circle on the given surface""" 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)
Draws a ring def ring(surf, xy, r, width, color): """Draws a ring""" r2 = r - width x0, y0 = xy x = r2 y = 0 err = 0 # collect points of the inner circle 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)
Draw an antialiased round rectangle on the surface. surface : destination rect : rectangle color : rgb or rgba radius : 0 <= radius <= 1 :source: http://pygame.org/project-AAfilledRoundedRect-2349-.html def roundrect(surface, rect, color, rounding=5, unit=PIXEL): """ Draw an antialiased round rectangle on the surface. surface : destination rect : rectangle color : rgb or rgba radius : 0 <= radius <= 1 :source: http://pygame.org/project-AAfilledRoundedRect-2349-.html """ 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 filled polygon on a surface def polygon(surf, points, color): """Draw an antialiased filled polygon on a surface""" 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)
Call when the button is pressed. This start the callback function in a thread If :milis is given, will release the button after :milis miliseconds def click(self, force_no_call=False, milis=None): """ Call when the button is pressed. This start the callback function in a thread If :milis is given, will release the button after :milis miliseconds """ if self.clicked: return False if not force_no_call and self.flags & self.CALL_ON_PRESS: if self.flags & self.THREADED_CALL: start_new_thread(self.func, ()) else: self.func() super().click() if milis is not None: start_new_thread(self.release, (), {'milis': milis})
Return the color of the button, depending on its state def _get_color(self): """Return the color of the button, depending on its state""" if self.clicked and self.hovered: # the mouse is over the button 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 offset of the colored part. def _front_delta(self): """Return the offset of the colored part.""" if self.flags & self.NO_MOVE: return Separator(0, 0) if self.clicked and self.hovered: # the mouse is over the button delta = 2 elif self.hovered and not self.flags & self.NO_HOVER: delta = 0 else: delta = 0 return Separator(delta, delta)
Update the button with the events. def update(self, event_or_list): """Update the button with the events.""" 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
Render the button on a surface. def render(self, surf): """Render the button on a surface.""" 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)
Draw the button on the surface. def render(self, surf): """Draw the button on the surface.""" 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)
Returns an icon 80% more dark def get_darker_image(self): """Returns an icon 80% more dark""" icon_pressed = self.icon.copy() for x in range(self.w): for y in range(self.h): r, g, b, *_ = tuple(self.icon.get_at((x, y))) const = 0.8 r = int(const * r) g = int(const * g) b = int(const * b) icon_pressed.set_at((x, y), (r, g, b)) return icon_pressed
Render the button def render(self, surf): """Render the button""" if self.clicked: icon = self.icon_pressed else: icon = self.icon surf.blit(icon, self)
Set the value of the bar. If the value is out of bound, sets it to an extremum def set(self, value): """Set the value of the bar. If the value is out of bound, sets it to an extremum""" value = min(self.max, max(self.min, value)) self._value = value start_new_thread(self.func, (self.get(),))
Starts checking if the SB is shifted def _start(self): """Starts checking if the SB is shifted""" # TODO : make an update method instead last_call = 42 while self._focus: sleep(1 / 100) mouse = pygame.mouse.get_pos() last_value = self.get() self.value_px = mouse[0] # we do not need to do anything when it the same value if self.get() == last_value: continue if last_call + self.interval / 1000 < time(): last_call = time() self.func(self.get())
The position in pixels of the cursor def value_px(self): """The position in pixels of the cursor""" step = self.w / (self.max - self.min) return self.x + step * (self.get() - self.min)
Renders the bar on the display def render(self, display): """Renders the bar on the display""" # the bar bar_rect = pygame.Rect(0, 0, self.width, self.height // 3) bar_rect.center = self.center display.fill(self.bg_color, bar_rect) # the cursor circle(display, (self.value_px, self.centery), self.height // 2, self.color) # the value if self.show_val: self.text_val.render(display)
This is called each time an attribute is asked, to be sure every params are updated, beceause of callbacks. def __update(self): """ This is called each time an attribute is asked, to be sure every params are updated, beceause of callbacks. """ # I can not set the size attr because it is my property, so I set the width and height separately width, height = self.size super(BaseWidget, self).__setattr__("width", width) super(BaseWidget, self).__setattr__("height", height) super(BaseWidget, self).__setattr__(self.anchor, self.pos)
Make a compatible version of pip importable. Raise a RuntimeError if we couldn't. def activate(specifier): """Make a compatible version of pip importable. Raise a RuntimeError if we couldn't.""" try: for distro in require(specifier): distro.activate() except (VersionConflict, DistributionNotFound): raise RuntimeError('The installed version of pip is too old; peep ' 'requires ' + specifier)
Return the path and line number of the file from which an InstallRequirement came. def path_and_line(req): """Return the path and line number of the file from which an InstallRequirement came. """ path, line = (re.match(r'-r (.*) \(line (\d+)\)$', req.comes_from).groups()) return path, int(line)
Yield hashes from contiguous comment lines before line ``line_number``. def hashes_above(path, line_number): """Yield hashes from contiguous comment lines before line ``line_number``. """ def hash_lists(path): """Yield lists of hashes appearing between non-comment lines. The lists will be in order of appearance and, for each non-empty list, their place in the results will coincide with that of the line number of the corresponding result from `parse_requirements` (which changed in pip 7.0 to not count comments). """ hashes = [] with open(path) as file: for lineno, line in enumerate(file, 1): match = HASH_COMMENT_RE.match(line) if match: # Accumulate this hash. hashes.append(match.groupdict()['hash']) if not IGNORED_LINE_RE.match(line): yield hashes # Report hashes seen so far. hashes = [] elif PIP_COUNTS_COMMENTS: # Comment: count as normal req but have no hashes. yield [] return next(islice(hash_lists(path), line_number - 1, None))
Delegate to pip the given args (starting with the subcommand), and raise ``PipException`` if something goes wrong. def run_pip(initial_args): """Delegate to pip the given args (starting with the subcommand), and raise ``PipException`` if something goes wrong.""" status_code = pip.main(initial_args) # Clear out the registrations in the pip "logger" singleton. Otherwise, # loggers keep getting appended to it with every run. Pip assumes only one # command invocation will happen per interpreter lifetime. logger.consumers = [] if status_code: raise PipException(status_code)
Return the hash of a downloaded file. def hash_of_file(path): """Return the hash of a downloaded file.""" 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 an iterable of filtered arguments. :arg argv: Arguments, starting after the subcommand :arg want_paths: If True, the returned iterable includes the paths to any requirements files following a ``-r`` or ``--requirement`` option. :arg want_other: If True, the returned iterable includes the args that are not a requirement-file path or a ``-r`` or ``--requirement`` flag. def requirement_args(argv, want_paths=False, want_other=False): """Return an iterable of filtered arguments. :arg argv: Arguments, starting after the subcommand :arg want_paths: If True, the returned iterable includes the paths to any requirements files following a ``-r`` or ``--requirement`` option. :arg want_other: If True, the returned iterable includes the args that are not a requirement-file path or a ``-r`` or ``--requirement`` flag. """ was_r = False for arg in argv: # Allow for requirements files named "-r", don't freak out if there's a # trailing "-r", etc. 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 the peep hash of one or more files, returning a shell status code or raising a PipException. :arg argv: The commandline args, starting after the subcommand def peep_hash(argv): """Return the peep hash of one or more files, returning a shell status code or raising a PipException. :arg argv: The commandline args, starting after the subcommand """ 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
Memoize a method that should return the same result every time on a given instance. def memoize(func): """Memoize a method that should return the same result every time on a given instance. """ @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
Return a PackageFinder respecting command-line options. :arg argv: Everything after the subcommand def package_finder(argv): """Return a PackageFinder respecting command-line options. :arg argv: Everything after the subcommand """ # We instantiate an InstallCommand and then use some of its private # machinery--its arg parser--for our own purposes, like a virus. This # approach is portable across many pip versions, where more fine-grained # ones are not. Ignoring options that don't exist on the parser (for # instance, --use-wheel) gives us a straightforward method of backward # compatibility. try: command = InstallCommand() except TypeError: # This is likely pip 1.3.0's "__init__() takes exactly 2 arguments (1 # given)" error. In that version, InstallCommand takes a top=level # parser passed in from outside. from pip.baseparser import create_main_parser command = InstallCommand(create_main_parser()) # The downside is that it essentially ruins the InstallCommand class for # further use. Calling out to pip.main() within the same interpreter, for # example, would result in arguments parsed this time turning up there. # Thus, we deepcopy the arg parser so we don't trash its singletons. Of # course, deepcopy doesn't work on these objects, because they contain # uncopyable regex patterns, so we pickle and unpickle instead. Fun! options, _ = loads(dumps(command.parser)).parse_args(argv) # Carry over PackageFinder kwargs that have [about] the same names as # options attr names: 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 # Figure out index_urls: index_urls = [options.index_url] + options.extra_index_urls if options.no_index: index_urls = [] index_urls += getattr(options, 'mirrors', []) # If pip is new enough to have a PipSession, initialize one, since # PackageFinder requires it: if hasattr(command, '_build_session'): kwargs['session'] = command._build_session(options) return PackageFinder(index_urls=index_urls, **kwargs)
Return a map of key -> list of things. def bucket(things, key): """Return a map of key -> list of things.""" ret = defaultdict(list) for thing in things: ret[key(thing)].append(thing) return ret
Execute something before the first item of iter, something else for each item, and a third thing after the last. If there are no items in the iterable, don't execute anything. def first_every_last(iterable, first, every, last): """Execute something before the first item of iter, something else for each item, and a third thing after the last. If there are no items in the iterable, don't execute anything. """ did_first = False for item in iterable: if not did_first: did_first = True first(item) every(item) if did_first: last(item)
Return a list of DownloadedReqs representing the requirements parsed out of a given requirements file. :arg path: The path to the requirements file :arg argv: The commandline args, starting after the subcommand def downloaded_reqs_from_path(path, argv): """Return a list of DownloadedReqs representing the requirements parsed out of a given requirements file. :arg path: The path to the requirements file :arg argv: The commandline args, starting after the subcommand """ finder = package_finder(argv) return [DownloadedReq(req, argv, finder) for req in _parse_requirements(path, finder)]
Perform the ``peep install`` subcommand, returning a shell status code or raising a PipException. :arg argv: The commandline args, starting after the subcommand def peep_install(argv): """Perform the ``peep install`` subcommand, returning a shell status code or raising a PipException. :arg argv: The commandline args, starting after the subcommand """ 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 # We're a "peep install" command, and we have some requirement paths. reqs = list(chain.from_iterable( downloaded_reqs_from_path(path, argv) for path in req_paths)) buckets = bucket(reqs, lambda r: r.__class__) # Skip a line after pip's "Cleaning up..." so the important stuff # stands out: 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))
Convert a peep requirements file to one compatble with pip-8 hashing. Loses comments and tromps on URLs, so the result will need a little manual massaging, but the hard part--the hash conversion--is done for you. def peep_port(paths): """Convert a peep requirements file to one compatble with pip-8 hashing. Loses comments and tromps on URLs, so the result will need a little manual massaging, but the hard part--the hash conversion--is done for you. """ 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()
Be the top-level entrypoint. Return a shell status code. def main(): """Be the top-level entrypoint. Return a shell status code.""" 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: # Fall through to top-level pip main() for everything else: return pip.main() except PipException as exc: return exc.error_code
Deduce the version number of the downloaded package from its filename. def _version(self): """Deduce the version number of the downloaded package from its filename.""" # TODO: Can we delete this method and just print the line from the # reqs file verbatim instead? def version_of_archive(filename, package_name): # Since we know the project_name, we can strip that off the left, strip # any archive extensions off the right, and take the rest as the # version. for ext in ARCHIVE_EXTENSIONS: if filename.endswith(ext): filename = filename[:-len(ext)] break # Handle github sha tarball downloads. if is_git_sha(filename): filename = package_name + '-' + filename if not filename.lower().replace('_', '-').startswith(package_name.lower()): # TODO: Should we replace runs of [^a-zA-Z0-9.], not just _, with -? give_up(filename, package_name) return filename[len(package_name) + 1:] # Strip off '-' before version. def version_of_wheel(filename, package_name): # For Wheel files (http://legacy.python.org/dev/peps/pep-0427/#file- # name-convention) we know the format bits are '-' separated. whl_package_name, version, _rest = filename.split('-', 2) # Do the alteration to package_name from PEP 427: 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())
Returns whether this requirement is always unsatisfied This would happen in cases where we can't determine the version from the filename. def _is_always_unsatisfied(self): """Returns whether this requirement is always unsatisfied This would happen in cases where we can't determine the version from the filename. """ # If this is a github sha tarball, then it is always unsatisfied # because the url has a commit sha in it and not the version # number. 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
Download a file, and return its name within my temp dir. This does no verification of HTTPS certs, but our checking hashes makes that largely unimportant. It would be nice to be able to use the requests lib, which can verify certs, but it is guaranteed to be available only in pip >= 1.5. This also drops support for proxies and basic auth, though those could be added back in. def _download(self, link): """Download a file, and return its name within my temp dir. This does no verification of HTTPS certs, but our checking hashes makes that largely unimportant. It would be nice to be able to use the requests lib, which can verify certs, but it is guaranteed to be available only in pip >= 1.5. This also drops support for proxies and basic auth, though those could be added back in. """ # Based on pip 1.4.1's URLOpener but with cert verification removed def opener(is_https): if is_https: opener = build_opener(HTTPSHandler()) # Strip out HTTPHandler to prevent MITM spoof: for handler in opener.handlers: if isinstance(handler, HTTPHandler): opener.handlers.remove(handler) else: opener = build_opener() return opener # Descended from unpack_http_url() in pip 1.4.1 def best_filename(link, response): """Return the most informative possible filename for a download, ideally with a proper extension. """ content_type = response.info().get('content-type', '') filename = link.filename # fallback # Have a look at the Content-Disposition header for a better guess: content_disposition = response.info().get('content-disposition') if content_disposition: type, params = cgi.parse_header(content_disposition) # We use ``or`` here because we don't want to use an "empty" value # from the filename param: 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 # Descended from _download_url() in pip 1.4.1 def pipe_to_file(response, path, size=0): """Pull the data off an HTTP response, shove it in a new file, and show progress. :arg response: A file-like object to read from :arg path: The path of the new file :arg size: The expected size, in bytes, of the download. 0 for unknown or to suppress progress indication (as for cached downloads) """ 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 the package's archive if necessary, and return its filename. --no-deps is implied, as we have reimplemented the bits that would ordinarily do dependency resolution. def _downloaded_filename(self): """Download the package's archive if necessary, and return its filename. --no-deps is implied, as we have reimplemented the bits that would ordinarily do dependency resolution. """ # Peep doesn't support requirements that don't come down as a single # file, because it can't hash them. Thus, it doesn't support editable # requirements, because pip itself doesn't support editable # requirements except for "local projects or a VCS url". Nor does it # support VCS requirements yet, because we haven't yet come up with a # portable, deterministic way to hash them. In summary, all we support # is == requirements and tarballs/zips/etc. # TODO: Stop on reqs that are editable or aren't ==. # If the requirement isn't already specified as a URL, get a URL # from an index: link = self._link() or self._finder.find_requirement(self._req, upgrade=False) if link: lower_scheme = link.scheme.lower() # pip lower()s it for some reason. if lower_scheme == 'http' or lower_scheme == 'https': file_path = self._download(link) return basename(file_path) elif lower_scheme == 'file': # The following is inspired by pip's unpack_file_url(): 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,))
Install the package I represent, without dependencies. Obey typical pip-install options passed in on the command line. def install(self): """Install the package I represent, without dependencies. Obey typical pip-install options passed in on the command line. """ other_args = list(requirement_args(self._argv, want_other=True)) archive_path = join(self._temp_path, self._downloaded_filename()) # -U so it installs whether pip deems the requirement "satisfied" or # not. This is necessary for GitHub-sourced zips, which change without # their version numbers changing. run_pip(['install'] + other_args + ['--no-deps', '-U', archive_path])
Return the inner Requirement's "unsafe name". Raise ValueError if there is no name. def _project_name(self): """Return the inner Requirement's "unsafe name". Raise ValueError if there is no name. """ 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 class I should be, spanning a continuum of goodness. def _class(self): """Return the class I should be, spanning a continuum of goodness.""" 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
Logic extracted from: http://developer.oanda.com/rest-live/orders/#createNewOrder def check(self): """ Logic extracted from: http://developer.oanda.com/rest-live/orders/#createNewOrder """ for k in iter(self.__dict__.keys()): if k not in self.__allowed: raise TypeError("Parameter not allowed {}".format(k)) for k in self.__requiered: if k not in self.__dict__: raise TypeError("Requiered parameter not found {}".format(k)) if not isinstance(self.units, (int, float)): msg = "Unit must be either int or float, '{}'' found".format( type(self.units)) raise TypeError(msg) if self.side not in self.__side: msg = "Side must be in {1}, '{0}' found".format( self.side, self.__side) raise TypeError(msg) if self.type not in self.__type: msg = "Type must be in {1}, '{0}' found".format( self.type, self.__type) raise TypeError(msg) if not self.type == "market" and ( not hasattr(self, "expiry") or not hasattr(self, "price")): msg = "As type is {}, expiry and price must be provided".format( self.type) raise TypeError(msg) if hasattr(self, "expiry") and not isinstance(self.expiry, datetime): msg = "Expiry must be {1}, '{0}' found".format( type(self.expiry), datetime) raise TypeError(msg) if hasattr(self, "price"): try: Decimal(self.price) except InvalidOperation: msg = "Expiry must be int or float, '{0}' found".format( type(self.price)) raise TypeError(msg) return True
Main function def gui(): """Main function""" global SCREEN_SIZE # ####### # setup all objects # ####### os.environ['SDL_VIDEO_CENTERED'] = '1' screen = new_widow() pygame.display.set_caption('Client swag') pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN]) clock = pygame.time.Clock() # fps = FPSIndicator(clock) bound = Rectangle((0, 0), SCREEN_SIZE, BLUE, Rectangle.BORDER) login = InLineTextBox((5, 1), 200, MIDNIGHT_BLUE, anchor=TOPLEFT, default_text='Login: ') passw = InLinePassBox(login.topright + Sep(5, 0), 200, MIDNIGHT_BLUE, anchor=TOPLEFT, default_text='Password: ') def sup(): print('Signed up !') print('login:', login.text) print('pass:', passw.text) def sin(): print('Signed in !') print('login:', login.text) print('pass:', passw.text) style = Button.NO_ROUNDING | Button.NO_MOVE | Button.NO_SHADOW sign_up = Button(sup, passw.topright + Sep(5, 0), (100, passw.height), 'Sign Up', YELLOW, anchor=TOPLEFT, flags=style) sign_in = Button(sin, sign_up.topright, (100, passw.height), 'Sign In', GREEN, anchor=TOPLEFT, flags=style) focus = FocusSelector(login, passw, sign_up, sign_in) focus.select(0) while True: # ####### # Input loop # ####### mouse = pygame.mouse.get_pos() for e in pygame.event.get(): if e.type == QUIT: return 0 # quit elif e.type == KEYDOWN: # intercept special inputs if e.key == K_ESCAPE: return 0 # quit elif e.key == K_F4 and e.mod & KMOD_ALT: return 0 # quit elif e.key == K_TAB: if e.mod & KMOD_SHIFT: focus.prev() else: focus.next() elif e.key == K_RETURN: if focus.selected() in (sign_up, sign_in): print(focus.selected()) focus.selected().click(40) else: focus.next() else: # or give them to the selected box focus.selected().update(e) elif e.type == VIDEORESIZE: SCREEN_SIZE = e.size screen = new_widow() elif e.type == MOUSEBUTTONDOWN: if mouse in login: focus.select(login) elif mouse in passw: focus.select(passw) elif mouse in sign_up: sign_up.click() elif mouse in sign_in: sign_in.click() elif e.type == MOUSEBUTTONUP: sign_in.release() sign_up.release() # ####### # Draw all # ####### screen.fill(WHITE) # fps.render(screen) bound.render(screen) login.render(screen) passw.render(screen) line(screen, login.topright + Sep(2, 0), login.bottomright + Sep(2, 0), BLUE) sign_up.render(screen) sign_in.render(screen) pygame.display.update() clock.tick(FPS)
Main function def gui(): """Main function""" global SCREEN_SIZE # ####### # setup all objects # ####### os.environ['SDL_VIDEO_CENTERED'] = '1' # centers the windows screen = new_screen() pygame.display.set_caption('Empty project') pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN]) clock = pygame.time.Clock() fps = FPSIndicator(clock) while True: # ####### # Input loop # ####### # mouse = pygame.mouse.get_pos() for e in pygame.event.get(): if e.type == QUIT: return 0 elif e.type == KEYDOWN: if e.key == K_ESCAPE: return 0 if e.key == K_F4 and e.mod & KMOD_ALT: # Alt+F4 --> quits return 0 if e.type == VIDEORESIZE: SCREEN_SIZE = e.size screen = new_screen() # ####### # Draw all # ####### screen.fill(WHITE) fps.render(screen) pygame.display.update() clock.tick(FPS)
Creates a response object with the given params and option Parameters ---------- url : string The full URL to request. params: dict A list of parameters to send with the request. This will be sent as data for methods that accept a request body and will otherwise be sent as query parameters. method : str The HTTP method to use. stream : bool Whether to stream the response. Returns a requests.Response object. def __get_response(self, uri, params=None, method="get", stream=False): """Creates a response object with the given params and option Parameters ---------- url : string The full URL to request. params: dict A list of parameters to send with the request. This will be sent as data for methods that accept a request body and will otherwise be sent as query parameters. method : str The HTTP method to use. stream : bool Whether to stream the response. Returns a requests.Response object. """ 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)} ) # Remove empty params 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)
Only returns the response, nor the status_code def __call(self, uri, params=None, method="get"): """Only returns the response, nor the status_code """ 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
Returns an stream response def __call_stream(self, uri, params=None, method="get"): """Returns an stream response """ 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
See more: http://developer.oanda.com/rest-live/rates/#getInstrumentList def get_instruments(self): """ See more: http://developer.oanda.com/rest-live/rates/#getInstrumentList """ url = "{0}/{1}/instruments".format(self.domain, self.API_VERSION) params = {"accountId": self.account_id} try: response = self._Client__call(uri=url, params=params) assert len(response) > 0 return response except RequestException: return False except AssertionError: return False
See more: http://developer.oanda.com/rest-live/rates/#getCurrentPrices def get_prices(self, instruments, stream=True): """ See more: http://developer.oanda.com/rest-live/rates/#getCurrentPrices """ url = "{0}/{1}/prices".format( self.domain_stream if stream else self.domain, self.API_VERSION ) params = {"accountId": self.account_id, "instruments": instruments} call = {"uri": url, "params": params, "method": "get"} try: if stream: return self._Client__call_stream(**call) else: return self._Client__call(**call) except RequestException: return False except AssertionError: return False
See more: http://developer.oanda.com/rest-live/rates/#retrieveInstrumentHistory def get_instrument_history(self, instrument, candle_format="bidask", granularity='S5', count=500, daily_alignment=None, alignment_timezone=None, weekly_alignment="Monday", start=None, end=None): """ See more: http://developer.oanda.com/rest-live/rates/#retrieveInstrumentHistory """ url = "{0}/{1}/candles".format(self.domain, self.API_VERSION) params = { "accountId": self.account_id, "instrument": instrument, "candleFormat": candle_format, "granularity": granularity, "count": count, "dailyAlignment": daily_alignment, "alignmentTimezone": alignment_timezone, "weeklyAlignment": weekly_alignment, "start": start, "end": end, } try: return self._Client__call(uri=url, params=params, method="get") except RequestException: return False except AssertionError: return False
See more: http://developer.oanda.com/rest-live/orders/#getOrdersForAnAccount def get_orders(self, instrument=None, count=50): """ See more: http://developer.oanda.com/rest-live/orders/#getOrdersForAnAccount """ url = "{0}/{1}/accounts/{2}/orders".format( self.domain, self.API_VERSION, self.account_id ) params = {"instrument": instrument, "count": count} try: return self._Client__call(uri=url, params=params, method="get") except RequestException: return False except AssertionError: return False
See more: http://developer.oanda.com/rest-live/orders/#getInformationForAnOrder def get_order(self, order_id): """ See more: http://developer.oanda.com/rest-live/orders/#getInformationForAnOrder """ url = "{0}/{1}/accounts/{2}/orders/{3}".format( self.domain, self.API_VERSION, self.account_id, order_id ) try: return self._Client__call(uri=url, method="get") except RequestException: return False except AssertionError: return False
See more: http://developer.oanda.com/rest-live/orders/#createNewOrder def create_order(self, order): """ See more: http://developer.oanda.com/rest-live/orders/#createNewOrder """ url = "{0}/{1}/accounts/{2}/orders".format( self.domain, self.API_VERSION, self.account_id ) try: return self._Client__call( uri=url, params=order.__dict__, method="post" ) except RequestException: return False except AssertionError: return False
Get a list of open trades Parameters ---------- max_id : int The server will return trades with id less than or equal to this, in descending order (for pagination) count : int Maximum number of open trades to return. Default: 50 Max value: 500 instrument : str Retrieve open trades for a specific instrument only Default: all ids : list A list of trades to retrieve. Maximum number of ids: 50. No other parameter may be specified with the ids parameter. See more: http://developer.oanda.com/rest-live/trades/#getListOpenTrades def get_trades(self, max_id=None, count=None, instrument=None, ids=None): """ Get a list of open trades Parameters ---------- max_id : int The server will return trades with id less than or equal to this, in descending order (for pagination) count : int Maximum number of open trades to return. Default: 50 Max value: 500 instrument : str Retrieve open trades for a specific instrument only Default: all ids : list A list of trades to retrieve. Maximum number of ids: 50. No other parameter may be specified with the ids parameter. See more: http://developer.oanda.com/rest-live/trades/#getListOpenTrades """ 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
Modify an existing trade. Note: Only the specified parameters will be modified. All other parameters will remain unchanged. To remove an optional parameter, set its value to 0. Parameters ---------- trade_id : int The id of the trade to modify. stop_loss : number Stop Loss value. take_profit : number Take Profit value. trailing_stop : number Trailing Stop distance in pips, up to one decimal place See more: http://developer.oanda.com/rest-live/trades/#modifyExistingTrade def update_trade( self, trade_id, stop_loss=None, take_profit=None, trailing_stop=None ): """ Modify an existing trade. Note: Only the specified parameters will be modified. All other parameters will remain unchanged. To remove an optional parameter, set its value to 0. Parameters ---------- trade_id : int The id of the trade to modify. stop_loss : number Stop Loss value. take_profit : number Take Profit value. trailing_stop : number Trailing Stop distance in pips, up to one decimal place See more: http://developer.oanda.com/rest-live/trades/#modifyExistingTrade """ 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()
Request full account history. Submit a request for a full transaction history. A successfully accepted submission results in a response containing a URL in the Location header to a file that will be available once the request is served. Response for the URL will be HTTP 404 until the file is ready. Once served the URL will be valid for a certain amount of time. See more: http://developer.oanda.com/rest-live/transaction-history/#getFullAccountHistory http://developer.oanda.com/rest-live/transaction-history/#transactionTypes def request_transaction_history(self): """ Request full account history. Submit a request for a full transaction history. A successfully accepted submission results in a response containing a URL in the Location header to a file that will be available once the request is served. Response for the URL will be HTTP 404 until the file is ready. Once served the URL will be valid for a certain amount of time. See more: http://developer.oanda.com/rest-live/transaction-history/#getFullAccountHistory http://developer.oanda.com/rest-live/transaction-history/#transactionTypes """ 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
Download full account history. Uses request_transaction_history to get the transaction history URL, then polls the given URL until it's ready (or the max_wait time is reached) and provides the decoded response. Parameters ---------- max_wait : float The total maximum time to spend waiting for the file to be ready; if this is exceeded a failed response will be returned. This is not guaranteed to be strictly followed, as one last attempt will be made to check the file before giving up. See more: http://developer.oanda.com/rest-live/transaction-history/#getFullAccountHistory http://developer.oanda.com/rest-live/transaction-history/#transactionTypes def get_transaction_history(self, max_wait=5.0): """ Download full account history. Uses request_transaction_history to get the transaction history URL, then polls the given URL until it's ready (or the max_wait time is reached) and provides the decoded response. Parameters ---------- max_wait : float The total maximum time to spend waiting for the file to be ready; if this is exceeded a failed response will be returned. This is not guaranteed to be strictly followed, as one last attempt will be made to check the file before giving up. See more: http://developer.oanda.com/rest-live/transaction-history/#getFullAccountHistory http://developer.oanda.com/rest-live/transaction-history/#transactionTypes """ 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)
Create a new account. This call is only available on the sandbox system. Please create accounts on fxtrade.oanda.com on our production system. See more: http://developer.oanda.com/rest-sandbox/accounts/#-a-name-createtestaccount-a-create-a-test-account def create_account(self, currency=None): """ Create a new account. This call is only available on the sandbox system. Please create accounts on fxtrade.oanda.com on our production system. See more: http://developer.oanda.com/rest-sandbox/accounts/#-a-name-createtestaccount-a-create-a-test-account """ url = "{0}/{1}/accounts".format(self.domain, self.API_VERSION) params = {"currency": currency} try: return self._Client__call(uri=url, params=params, method="post") except RequestException: return False except AssertionError: return False
Get a list of accounts owned by the user. Parameters ---------- username : string The name of the user. Note: This is only required on the sandbox, on production systems your access token will identify you. See more: http://developer.oanda.com/rest-sandbox/accounts/#-a-name-getaccountsforuser-a-get-accounts-for-a-user def get_accounts(self, username=None): """ Get a list of accounts owned by the user. Parameters ---------- username : string The name of the user. Note: This is only required on the sandbox, on production systems your access token will identify you. See more: http://developer.oanda.com/rest-sandbox/accounts/#-a-name-getaccountsforuser-a-get-accounts-for-a-user """ 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
Marks the item as the one the user is in. def choose(self): """Marks the item as the one the user is in.""" if not self.choosed: self.choosed = True self.pos = self.pos + Sep(5, 0)
Marks the item as the one the user is not in. def stop_choose(self): """Marks the item as the one the user is not in.""" if self.choosed: self.choosed = False self.pos = self.pos + Sep(-5, 0)
The color of the clicked version of the MenuElement. Darker than the normal one. def get_darker_color(self): """The color of the clicked version of the MenuElement. Darker than the normal one.""" # we change a bit the color in one direction 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
Renders the MenuElement def render(self, screen): """Renders the MenuElement""" self.rect.render(screen) super(MenuElement, self).render(screen)
Main function def gui(): """Main function""" # ####### # setup all objects # ####### zones = [ALL] last_zones = [] COLORS.remove(WHITE) screen = pygame.display.set_mode(SCREEN_SIZE, DOUBLEBUF) pygame.display.set_caption('Bezier simulator') pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN]) points = [ (40, 40), (100, 400), (200, 100), (650, 420) ] bezier = Bezier((0, 0), SCREEN_SIZE, points, ORANGE, 8) points = [Point(p, 24, choice(COLORS)) for p in points] clock = pygame.time.Clock() fps = FPSIndicator(clock) dragging = None render = True while True: # ####### # Input loop # ####### mouse = pygame.mouse.get_pos() for e in pygame.event.get(): if e.type == QUIT: return 0 elif e.type == KEYDOWN: if e.key == K_ESCAPE: return 0 if e.key == K_F4 and e.mod & KMOD_ALT: return 0 elif e.type == MOUSEBUTTONDOWN: if e.button == 1: dragging = not dragging if e.button == 3: points.append(Point(mouse, 24, choice(COLORS))) bezier.points.append(V2(mouse)) render = True if dragging: mdist = 10000 the_p = None for i, p in enumerate(points): if p.dist_to(mouse) < mdist: mdist = p.dist_to(mouse) the_p = i render = points[the_p].pos != mouse points[the_p].pos = mouse bezier.points[the_p] = V2(mouse) # ####### # Draw all # ####### if render: render = False screen.fill(WHITE) bezier.render(screen) for p in points: p.render(screen) zones.append(ALL) _ = fps.render(screen) zones.append(_) pygame.display.update(zones + last_zones) last_zones = zones[:] zones.clear() clock.tick(FPS)
Main function def gui(): """Main function""" # ####### # setup all objects # ####### os.environ['SDL_VIDEO_CENTERED'] = '1' clock = pygame.time.Clock() screen = pygame.display.set_mode(SCREEN_SIZE, DOUBLEBUF | NOFRAME) pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN]) game = Morpion() run = True while run: # ####### # Input loop # ####### mouse = pygame.mouse.get_pos() for e in pygame.event.get(): if e.type == QUIT: run = False elif e.type == KEYDOWN: if e.key == K_ESCAPE: run = False if e.key == K_F4 and e.mod & KMOD_ALT: return 0 elif e.type == MOUSEBUTTONDOWN: if e.button == 1: if pos_from_mouse(mouse): if game.is_full() or game.is_won(): game = Morpion() continue x, y = pos_from_mouse(mouse) try: game.play(x, y) except IndexError: pass if pos_from_mouse(mouse): x, y = pos_from_mouse(mouse) game.hint(x, y) # ####### # Draw all # ####### screen.fill(WHITE) game.render(screen) pygame.display.update() clock.tick(FPS)
Convert a size in pxel to a size in points. def px_to_pt(self, px): """Convert a size in pxel to a size in points.""" if px < 200: pt = self.PX_TO_PT[px] else: pt = int(floor((px - 1.21) / 1.332)) return pt
Set the size of the font, in px or pt. The px method is a bit inacurate, there can be one or two px less, and max 4 for big numbers (like 503) but the size is never over-estimated. It makes almost the good value. def set_size(self, pt=None, px=None): """ Set the size of the font, in px or pt. The px method is a bit inacurate, there can be one or two px less, and max 4 for big numbers (like 503) but the size is never over-estimated. It makes almost the good value. """ 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)
Return the string to render. def text(self): """Return the string to render.""" if callable(self._text): return str(self._text()) return str(self._text)
Set the color to a new value (tuple). Renders the text if needed. def color(self, value): """Set the color to a new value (tuple). Renders the text if needed.""" if value != self.color: self._color = value self._render()
Sets the color to a new value (tuple). Renders the text if needed. def bg_color(self, value): """Sets the color to a new value (tuple). Renders the text if needed.""" if value != self.bg_color: self._bg_color = value self._render()
Set the font size to the desired size, in pt or px. def set_font_size(self, pt=None, px=None): """Set the font size to the desired size, in pt or px.""" self.font.set_size(pt, px) self._render()
Render the text. Avoid using this fonction too many time as it is slow as it is low to render text and blit it. def _render(self): """ Render the text. Avoid using this fonction too many time as it is slow as it is low to render text and blit it. """ self._last_text = self.text self._surface = self.font.render(self.text, True, self.color, self.bg_color) rect = self._surface.get_rect() self.size = rect.size