sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def _CopyFromDateTimeValues(self, date_time_values):
"""Copies time elements from date and time values.
Args:
date_time_values (dict[str, int]): date and time values, such as year,
month, day of month, hours, minutes, seconds, microseconds.
"""
year = date_time_values.get('year', 0)
... | Copies time elements from date and time values.
Args:
date_time_values (dict[str, int]): date and time values, such as year,
month, day of month, hours, minutes, seconds, microseconds. | entailment |
def _CopyTimeFromStringISO8601(self, time_string):
"""Copies a time from an ISO 8601 date and time string.
Args:
time_string (str): time value formatted as:
hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6... | Copies a time from an ISO 8601 date and time string.
Args:
time_string (str): time value formatted as:
hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The faction of second and
time zone off... | entailment |
def CopyFromDateTimeString(self, time_string):
"""Copies time elements from a date and time string.
Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be ... | Copies time elements from a date and time string.
Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The time of day, seconds
... | entailment |
def CopyFromStringISO8601(self, time_string):
"""Copies time elements from an ISO 8601 date and time string.
Currently not supported:
* Duration notation: "P..."
* Week notation "2016-W33"
* Date with week number notation "2016-W33-3"
* Date without year notation "--08-17"
* Ordinal date no... | Copies time elements from an ISO 8601 date and time string.
Currently not supported:
* Duration notation: "P..."
* Week notation "2016-W33"
* Date with week number notation "2016-W33-3"
* Date without year notation "--08-17"
* Ordinal date notation "2016-230"
Args:
time_string (str):... | entailment |
def CopyFromStringTuple(self, time_elements_tuple):
"""Copies time elements from string-based time elements tuple.
Args:
time_elements_tuple (Optional[tuple[str, str, str, str, str, str]]):
time elements, contains year, month, day of month, hours, minutes and
seconds.
Raises:
... | Copies time elements from string-based time elements tuple.
Args:
time_elements_tuple (Optional[tuple[str, str, str, str, str, str]]):
time elements, contains year, month, day of month, hours, minutes and
seconds.
Raises:
ValueError: if the time elements tuple is invalid. | entailment |
def CopyToDateTimeString(self):
"""Copies the time elements to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or None
if time elements are missing.
"""
if self._number_of_seconds is None:
return None
return '{0:04d}-{1:02d}-{2:02... | Copies the time elements to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or None
if time elements are missing. | entailment |
def _CopyFromDateTimeValues(self, date_time_values):
"""Copies time elements from date and time values.
Args:
date_time_values (dict[str, int]): date and time values, such as year,
month, day of month, hours, minutes, seconds, microseconds.
Raises:
ValueError: if no helper can be cr... | Copies time elements from date and time values.
Args:
date_time_values (dict[str, int]): date and time values, such as year,
month, day of month, hours, minutes, seconds, microseconds.
Raises:
ValueError: if no helper can be created for the current precision. | entailment |
def CopyFromStringTuple(self, time_elements_tuple):
"""Copies time elements from string-based time elements tuple.
Args:
time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]):
time elements, contains year, month, day of month, hours, minutes,
seconds and fraction of... | Copies time elements from string-based time elements tuple.
Args:
time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]):
time elements, contains year, month, day of month, hours, minutes,
seconds and fraction of seconds.
Raises:
ValueError: if the time elemen... | entailment |
def CopyToDateTimeString(self):
"""Copies the time elements to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or
"YYYY-MM-DD hh:mm:ss.######" or None if time elements are missing.
Raises:
ValueError: if the precision value is unsupported... | Copies the time elements to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or
"YYYY-MM-DD hh:mm:ss.######" or None if time elements are missing.
Raises:
ValueError: if the precision value is unsupported. | entailment |
def CopyFromStringTuple(self, time_elements_tuple):
"""Copies time elements from string-based time elements tuple.
Args:
time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]):
time elements, contains year, month, day of month, hours, minutes,
seconds and millisecond... | Copies time elements from string-based time elements tuple.
Args:
time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]):
time elements, contains year, month, day of month, hours, minutes,
seconds and milliseconds.
Raises:
ValueError: if the time elements tupl... | entailment |
def CopyFromStringTuple(self, time_elements_tuple):
"""Copies time elements from string-based time elements tuple.
Args:
time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]):
time elements, contains year, month, day of month, hours, minutes,
seconds and microsecond... | Copies time elements from string-based time elements tuple.
Args:
time_elements_tuple (Optional[tuple[str, str, str, str, str, str, str]]):
time elements, contains year, month, day of month, hours, minutes,
seconds and microseconds.
Raises:
ValueError: if the time elements tupl... | entailment |
def _GetNormalizedTimestamp(self):
"""Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cann... | Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cannot be
determined. | entailment |
def CopyFromDateTimeString(self, time_string):
"""Copies a SYSTEMTIME structure from a date and time string.
Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fractio... | Copies a SYSTEMTIME structure from a date and time string.
Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The time of day, second... | entailment |
def send_messages(self, messages):
"""Redirect messages to the dummy outbox"""
msg_count = 0
for message in messages: # .message() triggers header validation
message.message()
msg_count += 1
mail.outbox.extend(messages)
return msg_count | Redirect messages to the dummy outbox | entailment |
def _prepare_template(self, obj, needs_request=False):
"""
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
"""
if self.instance_name is None and self.template_name is None:
... | 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 | entailment |
def get_value(self, context, obj, field_name):
"""
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`.
"""
... | 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`. | entailment |
def customWalker(node, space=''):
"""
A convenience function to ease debugging. It will print the node structure that's returned from CommonMark
The usage would be something like:
>>> content = Parser().parse('Some big text block\n===================\n\nwith content\n')
>>> customWalker(content)
... | A convenience function to ease debugging. It will print the node structure that's returned from CommonMark
The usage would be something like:
>>> content = Parser().parse('Some big text block\n===================\n\nwith content\n')
>>> customWalker(content)
document
heading
text S... | entailment |
def paragraph(node):
"""
Process a paragraph, which includes all content under it
"""
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)
r... | Process a paragraph, which includes all content under it | entailment |
def reference(node):
"""
A hyperlink. Note that alt text doesn't work, since there's no apparent way to do that in docutils
"""
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 | entailment |
def emphasis(node):
"""
An italicized section
"""
o = nodes.emphasis()
for n in MarkDown(node):
o += n
return o | An italicized section | entailment |
def strong(node):
"""
A bolded section
"""
o = nodes.strong()
for n in MarkDown(node):
o += n
return o | A bolded section | entailment |
def literal(node):
"""
Inline code
"""
rendered = []
try:
if node.info is not None:
l = Lexer(node.literal, node.info, tokennames="long")
for _ in l:
rendered.append(node.inline(classes=_[0], text=_[1]))
except:
pass
classes = ['code']... | Inline code | entailment |
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 | Add some raw html (possibly as a block) | entailment |
def title(node):
"""
A title node. It has no children
"""
return nodes.title(node.first_child.literal, node.first_child.literal) | A title node. It has no children | entailment |
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... | A section in reStructuredText, which needs a title (the first child)
This is a custom type | entailment |
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 | A block quote | entailment |
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 image element
The first child is the alt text. reStructuredText can't handle titles | entailment |
def listItem(node):
"""
An item in a list
"""
o = nodes.list_item()
for n in MarkDown(node):
o += n
return o | An item in a list | entailment |
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']... | A list (numbered or not)
For numbered lists, the suffix is only rendered as . in html | entailment |
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))
... | Returns a list of nodes, containing CommonMark nodes converted to docutils nodes | entailment |
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 | Correct the nxt and parent for each child | entailment |
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... | 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 | entailment |
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)
... | Parses a block of text, returning a list of docutils nodes
>>> parseMarkdownBlock("Some\n====\n\nblock of text\n\nHeader\n======\n\nblah\n")
[] | entailment |
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) + '... | Given a list of reStructuredText or MarkDown sections, return a docutils node list | entailment |
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_group... | Process all 'action groups', which are also include 'Options' and 'Required
arguments'. A list of nodes is returned. | entailment |
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 ... | 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. | entailment |
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 addin... | 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 t... | entailment |
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
... | Construct a typical man page consisting of the following elements:
NAME (automatically generated, out of our control)
SYNOPSIS
DESCRIPTION
OPTIONS
FILES
SEE ALSO
BUGS | entailment |
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)
... | Select an arbitrary item, by possition or by reference. | entailment |
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 selected.
Only one action can be stored this way. | entailment |
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 an action to make when an object is unfocused. | entailment |
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... | 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) | entailment |
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') | Remove a widget from the window. | entailment |
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
... | Process a single event. | entailment |
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) | Get all events and process them by calling update_on_event() | entailment |
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, s... | Render the screen. Here you must draw everything. | entailment |
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() | Refresh the screen. You don't need to override this except to update only small portins of the screen. | entailment |
def run(self):
"""The run loop. Returns self.destroy()"""
while self.running:
self.update()
self.render()
self.update_screen()
return self.destroy() | The run loop. Returns self.destroy() | entailment |
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
... | Makes a new screen with a size of SCREEN_SIZE, and VIDEO_OPTION as flags. Sets the windows name to NAME. | entailment |
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 the smallest rect containning two rects | entailment |
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) | Return a vecor noraml to this one with a norm of one
:return: V2 | entailment |
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)... | Draws an antialiased line on the surface. | entailment |
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 ... | Draw an antialiased filled circle on the given surface | entailment |
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 er... | Draws a ring | entailment |
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 u... | 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 | entailment |
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 ... | Draw an antialiased filled polygon on a surface | entailment |
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 an... | 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 | entailment |
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... | Return the color of the button, depending on its state | entailment |
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:
... | Return the offset of the colored part. | entailment |
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)
... | Update the button with the events. | entailment |
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:
... | Render the button on a surface. | entailment |
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.c... | Draw the button on the surface. | entailment |
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)
... | Returns an icon 80% more dark | entailment |
def render(self, surf):
"""Render the button"""
if self.clicked:
icon = self.icon_pressed
else:
icon = self.icon
surf.blit(icon, self) | Render the button | entailment |
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(),)) | Set the value of the bar. If the value is out of bound, sets it to an extremum | entailment |
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]
... | Starts checking if the SB is shifted | entailment |
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) | The position in pixels of the cursor | entailment |
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), s... | Renders the bar on the display | entailment |
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(BaseW... | This is called each time an attribute is asked, to be sure every params are updated, beceause of callbacks. | entailment |
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 ol... | Make a compatible version of pip importable. Raise a RuntimeError if we
couldn't. | entailment |
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) | Return the path and line number of the file from which an
InstallRequirement came. | entailment |
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... | Yield hashes from contiguous comment lines before line ``line_number``. | entailment |
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... | Delegate to pip the given args (starting with the subcommand), and raise
``PipException`` if something goes wrong. | entailment |
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 the hash of a downloaded file. | entailment |
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`` optio... | 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 arg... | entailment |
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... | 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 | entailment |
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__] = f... | Memoize a method that should return the same result every time on a
given instance. | entailment |
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 a... | Return a PackageFinder respecting command-line options.
:arg argv: Everything after the subcommand | entailment |
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 | Return a map of key -> list of things. | entailment |
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_... | 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. | entailment |
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 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 | entailment |
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,... | Perform the ``peep install`` subcommand, returning a shell status code
or raising a PipException.
:arg argv: The commandline args, starting after the subcommand | entailment |
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 ... | 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. | entailment |
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:
... | Be the top-level entrypoint. Return a shell status code. | entailment |
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, ... | Deduce the version number of the downloaded package from its filename. | entailment |
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 co... | Returns whether this requirement is always unsatisfied
This would happen in cases where we can't determine the version
from the filename. | entailment |
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 b... | 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... | entailment |
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 ... | 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. | entailment |
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())
... | Install the package I represent, without dependencies.
Obey typical pip-install options passed in on the command line. | entailment |
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 the inner Requirement's "unsafe name".
Raise ValueError if there is no name. | entailment |
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():
re... | Return the class I should be, spanning a continuum of goodness. | entailment |
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.__r... | Logic extracted from:
http://developer.oanda.com/rest-live/orders/#createNewOrder | entailment |
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(... | Main function | entailment |
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])
... | Main function | entailment |
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 ... | 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 ... | entailment |
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:
... | Only returns the response, nor the status_code | entailment |
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... | Returns an stream response | entailment |
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__c... | See more:
http://developer.oanda.com/rest-live/rates/#getInstrumentList | entailment |
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 =... | See more:
http://developer.oanda.com/rest-live/rates/#getCurrentPrices | entailment |
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 | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.