_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q51800 | HkAVR.power_off | train | def power_off(self):
"""Turn off receiver"""
try:
self.send_command("POWER_OFF")
self._power = POWER_OFF
self._state = STATE_OFF
return True
except requests.exceptions.RequestException:
_LOGGER.error("Connection error: power off command... | python | {
"resource": ""
} |
q51801 | Game2048.icon | train | def icon(cls, size):
"""Returns an icon to use for the game."""
tile = pygame.Surface((size, size))
tile.fill((237, 194, 46))
label = load_font(cls.BOLD_NAME, int(size / 3.2)).render(cls.NAME, True, (249, 246, 242))
width, height = label.get_size()
tile.blit(label, ((size... | python | {
"resource": ""
} |
q51802 | Game2048._make_tile | train | def _make_tile(self, value, background, text):
"""Renders a tile, according to its value, and background and foreground colours."""
tile = pygame.Surface((self.cell_width, self.cell_height), pygame.SRCALPHA)
pygame.draw.rect(tile, background, (0, 0, self.cell_width, self.cell_height))
# ... | python | {
"resource": ""
} |
q51803 | Game2048._create_default_tiles | train | def _create_default_tiles(self):
"""Create all default tiles, as defined above."""
for value, background, text in self.DEFAULT_TILES:
self.tiles[value] = self._make_tile(value, background, text) | python | {
"resource": ""
} |
q51804 | Game2048._draw_button | train | def _draw_button(self, overlay, text, location):
"""Draws a button on the won and lost overlays, and return its hitbox."""
label = self.button_font.render(text, True, (119, 110, 101))
w, h = label.get_size()
# Let the callback calculate the location based on
# the width and heigh... | python | {
"resource": ""
} |
q51805 | Game2048._is_in_keep_going | train | def _is_in_keep_going(self, x, y):
"""Checks if the mouse is in the keep going button, and if the won overlay is shown."""
x1, y1, x2, y2 = self._keep_going
return self.won == 1 and x1 <= x < x2 and y1 <= y < y2 | python | {
"resource": ""
} |
q51806 | Game2048._is_in_try_again | train | def _is_in_try_again(self, x, y):
"""Checks if the game is to be restarted."""
if self.won == 1:
# Checks if in try button on won screen.
x1, y1, x2, y2 = self._won_try_again
return x1 <= x < x2 and y1 <= y < y2
elif self.lost:
# Checks if in try b... | python | {
"resource": ""
} |
q51807 | Game2048._is_in_restart | train | def _is_in_restart(self, x, y):
"""Checks if the game is to be restarted by request."""
x1, y1, x2, y2 = self._new_game
return x1 <= x < x2 and y1 <= y < y2 | python | {
"resource": ""
} |
q51808 | Game2048._make_title | train | def _make_title(self):
"""Draw the header section."""
# Draw the game title.
title = pygame.Surface((self.game_width, self.origin[1]), pygame.SRCALPHA)
title.fill((0, 0, 0, 0))
label = self.font.render(self.NAME, True, (119, 110, 101))
title.blit(label, (self.BORDER, (90 ... | python | {
"resource": ""
} |
q51809 | Game2048.free_cells | train | def free_cells(self):
"""Returns a list of empty cells."""
return [(x, y)
for x in range(self.COUNT_X)
for y in range(self.COUNT_Y)
if not self.grid[y][x]] | python | {
"resource": ""
} |
q51810 | Game2048._can_cell_be_merged | train | def _can_cell_be_merged(self, x, y):
"""Checks if a cell can be merged, when the """
value = self.grid[y][x]
if y > 0 and self.grid[y - 1][x] == value: # Cell above
return True
if y < self.COUNT_Y - 1 and self.grid[y + 1][x] == value: # Cell below
return True
... | python | {
"resource": ""
} |
q51811 | Game2048.has_free_moves | train | def has_free_moves(self):
"""Returns whether a move is possible, when there are no free cells."""
return any(self._can_cell_be_merged(x, y)
for x in range(self.COUNT_X)
for y in range(self.COUNT_Y)) | python | {
"resource": ""
} |
q51812 | Game2048.get_tile_location | train | def get_tile_location(self, x, y):
"""Get the screen coordinate for the top-left corner of a tile."""
x1, y1 = self.origin
x1 += self.BORDER + (self.BORDER + self.cell_width) * x
y1 += self.BORDER + (self.BORDER + self.cell_height) * y
return x1, y1 | python | {
"resource": ""
} |
q51813 | Game2048.draw_grid | train | def draw_grid(self):
"""Draws the grid and tiles."""
self.screen.fill((0xbb, 0xad, 0xa0), self.origin + (self.game_width, self.game_height))
for y, row in enumerate(self.grid):
for x, cell in enumerate(row):
self.screen.blit(self.tiles[cell], self.get_tile_location(x,... | python | {
"resource": ""
} |
q51814 | Game2048._draw_score_box | train | def _draw_score_box(self, label, score, position, size):
x1, y1 = position
width, height = size
"""Draw a score box, whether current or best."""
pygame.draw.rect(self.screen, (187, 173, 160), (x1, y1, width, height))
w, h = label.get_size()
self.screen.blit(label, (x1 + ... | python | {
"resource": ""
} |
q51815 | Game2048.draw_scores | train | def draw_scores(self):
"""Draw the current and best score"""
x1, y1 = self.WIDTH - self.BORDER - 200 - 2 * self.BORDER, self.BORDER
width, height = 100, 60
self.screen.fill((255, 255, 255), (x1, 0, self.WIDTH - x1, height + y1))
self._draw_score_box(self.score_label, self.score, ... | python | {
"resource": ""
} |
q51816 | Game2048._scale_tile | train | def _scale_tile(self, value, width, height):
"""Return the prescaled tile if already exists, otherwise scale and store it."""
try:
return self._scale_cache[value, width, height]
except KeyError:
tile = pygame.transform.smoothscale(self.tiles[value], (width, height))
... | python | {
"resource": ""
} |
q51817 | Game2048._center_tile | train | def _center_tile(self, position, size):
x, y = position
w, h = size
"""Calculate the centre of a tile given the top-left corner and the size of the image."""
return x + (self.cell_width - w) / 2, y + (self.cell_height - h) / 2 | python | {
"resource": ""
} |
q51818 | Game2048.animate | train | def animate(self, animation, static, score, best, appear):
"""Handle animation."""
# Create a surface of static parts in the animation.
surface = pygame.Surface((self.game_width, self.game_height), 0)
surface.fill(self.BACKGROUND)
# Draw all static tiles.
for y in range... | python | {
"resource": ""
} |
q51819 | Game2048._spawn_new | train | def _spawn_new(self, count=1):
"""Spawn some new tiles."""
free = self.free_cells()
for x, y in random.sample(free, min(count, len(free))):
self.grid[y][x] = random.randint(0, 10) and 2 or 4 | python | {
"resource": ""
} |
q51820 | pattern_to_regex | train | def pattern_to_regex(pattern: str) -> str:
""" convert url patten to regex """
if pattern and pattern[-1] == "*":
pattern = pattern[:-1]
end = ""
else:
end = "$"
for metac in META_CHARS:
pattern = pattern.replace(metac, "\\" + metac)
return "^" + VARS_PT.sub(regex_re... | python | {
"resource": ""
} |
q51821 | detect_converters | train | def detect_converters(pattern: str,
converter_dict: Dict[str, Callable],
default: Callable = str):
""" detect pairs of varname and converter from pattern"""
converters = {}
for matched in VARS_PT.finditer(pattern):
matchdict = matched.groupdict()
v... | python | {
"resource": ""
} |
q51822 | MatchResult.new_named_args | train | def new_named_args(self, cur_named_args: Dict[str, Any]) -> Dict[str, Any]:
""" create new named args updating current name args"""
named_args = cur_named_args.copy()
named_args.update(self.matchdict)
return named_args | python | {
"resource": ""
} |
q51823 | MatchResult.split_path_info | train | def split_path_info(self, path_info: str) -> Tuple[str, str]:
""" split path_info to new script_name and new path_info"""
return path_info[:self.matchlength], path_info[self.matchlength:] | python | {
"resource": ""
} |
q51824 | URITemplate.match | train | def match(self, path_info: str) -> MatchResult:
""" parse path_info and detect urlvars of url pattern """
matched = self.regex.match(path_info)
if matched is None:
return None
matchlength = len(matched.group(0))
matchdict = matched.groupdict()
try:
... | python | {
"resource": ""
} |
q51825 | URITemplate.convert_values | train | def convert_values(self, matchdict: Dict[str, str]) -> Dict[str, Any]:
""" convert values of ``matchdict``
with converter this object has."""
converted = {}
for varname, value in matchdict.items():
converter = self.converters[varname]
converted[varname] = convert... | python | {
"resource": ""
} |
q51826 | URITemplate.substitute | train | def substitute(self, values: Dict[str, Any]) -> str:
""" generate url with url template"""
return self.template.substitute(values) | python | {
"resource": ""
} |
q51827 | AttributeList.merge | train | def merge(cls, first, second):
"""
Return an AttributeList that is the result of merging first with second.
"""
merged = AttributeList([], None)
assert (isinstance(first, AttributeList))
assert (isinstance(second, AttributeList))
merged._contents = first._content... | python | {
"resource": ""
} |
q51828 | AttributeList.get_attribute | train | def get_attribute(self, reference):
"""
Return the attribute that matches the reference. Raise an error if
the attribute cannot be found, or if there is more then one match.
"""
prefix, _, name = reference.rpartition('.')
match = None
for attribute in self._conte... | python | {
"resource": ""
} |
q51829 | AttributeList.extend | train | def extend(self, attributes, prefix):
"""
Add the attributes with the specified prefix to the end of the attribute
list.
"""
self._contents += [Attribute(attr, prefix) for attr in attributes] | python | {
"resource": ""
} |
q51830 | AttributeList.trim | train | def trim(self, restriction_list):
"""
Trim and reorder the attributes to the specifications in a restriction
list.
"""
replacement = []
for reference in restriction_list:
replacement.append(self.get_attribute(reference))
if self.has_duplicates(replace... | python | {
"resource": ""
} |
q51831 | BaseHandler.dispatch | train | def dispatch(self):
"""Wraps the dispatch method to add session support."""
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response) | python | {
"resource": ""
} |
q51832 | DispatchBase.register_app | train | def register_app(self, name: str, app: Callable = None) -> Callable:
""" register dispatchable wsgi application"""
if app is None:
def dec(app):
""" inner decorator for register app """
assert app is not None
self.register_app(name, app)
... | python | {
"resource": ""
} |
q51833 | DispatchBase.on_view_not_found | train | def on_view_not_found(
self,
environ: Dict[str, Any],
start_response: Callable) -> Iterable[bytes]: # pragma: nocover
""" called when view is not found"""
raise NotImplementedError() | python | {
"resource": ""
} |
q51834 | EntityDefinitionParser.parse_definition | train | def parse_definition(self, definition):
"""
Parse the basic structure of both provided and requested entities
:param definition: string encoding an entity
:return: tuple of entity type, alias and attributes
"""
type = definition[0]
alias = None
attributes... | python | {
"resource": ""
} |
q51835 | receive_oaiharvest_job | train | def receive_oaiharvest_job(request, records, name, **kwargs):
"""Receive a list of harvested OAI-PMH records and schedule crawls."""
spider = kwargs.get('spider')
workflow = kwargs.get('workflow')
if not spider or not workflow:
return
files_created, _ = write_to_dir(
records,
... | python | {
"resource": ""
} |
q51836 | MixinBase.parent | train | def parent(self):
""" Cache a instance of self parent class.
:return object: instance of self.Meta.parent class
"""
if not self._meta.parent:
return None
if not self.__parent__:
self.__parent__ = self._meta.parent()
return self.__parent__ | python | {
"resource": ""
} |
q51837 | get_database_size | train | def get_database_size(db_user, db_name, localhost=False):
"""
Returns the total size for the given database role and name.
:param db_user: String representing the database role.
:param db_name: String representing the database name.
"""
localhost_part = ''
if localhost:
localhost_p... | python | {
"resource": ""
} |
q51838 | Basecamp.people_per_project | train | def people_per_project(self, project_id, company_id):
"""
This will return all of the people in the given company that can
access the given project.
"""
path = '/projects/%u/contacts/people/%u' % (project_id, company_id)
return self._request(path) | python | {
"resource": ""
} |
q51839 | Basecamp.create_message | train | def create_message(self, project_id, category_id, title, body,
extended_body, use_textile=False, private=False, notify=None,
attachments=None):
"""
Creates a new message, optionally sending notifications to a selected
list of people. Note that you can also upload files using this... | python | {
"resource": ""
} |
q51840 | Basecamp.comments | train | def comments(self, message_id):
"""
Return the list of comments associated with the specified message.
"""
path = '/msg/comments/%u' % message_id
req = ET.Element('request')
return self._request(path, req) | python | {
"resource": ""
} |
q51841 | Basecamp.create_comment | train | def create_comment(self, post_id, body):
"""
Create a new comment, associating it with a specific message.
"""
path = '/msg/create_comment'
req = ET.Element('request')
comment = ET.SubElement(req, 'comment')
ET.SubElement(comment, 'post-id').text = str(int(post_id... | python | {
"resource": ""
} |
q51842 | Basecamp.update_comment | train | def update_comment(self, comment_id, body):
"""
Update a specific comment. This can be used to edit the content of an
existing comment.
"""
path = '/msg/update_comment'
req = ET.Element('request')
ET.SubElement(req, 'comment_id').text = str(int(comment_id))
... | python | {
"resource": ""
} |
q51843 | Basecamp.create_todo_list | train | def create_todo_list(self, project_id, milestone_id=None, private=None,
tracked=False, name=None, description=None, template_id=None):
"""
This will create a new, empty list. You can create the list
explicitly, or by giving it a list template id to base the new list
off of.
... | python | {
"resource": ""
} |
q51844 | Basecamp.update_todo_list | train | def update_todo_list(self, list_id, name, description, milestone_id=None,
private=None, tracked=None):
"""
With this call you can alter the metadata for a list.
"""
path = '/todos/update_list/%u' % list_id
req = ET.Element('request')
list_ = ET.SubElement('list')
... | python | {
"resource": ""
} |
q51845 | Basecamp.create_todo_item | train | def create_todo_item(self, list_id, content, party_id=None, notify=False):
"""
This call lets you add an item to an existing list. The item is added
to the bottom of the list. If a person is responsible for the item,
give their id as the party_id value. If a company is responsible,
... | python | {
"resource": ""
} |
q51846 | Basecamp.update_todo_item | train | def update_todo_item(self, item_id, content, party_id=None, notify=False):
"""
Modifies an existing item. The values work much like the "create item"
operation, so you should refer to that for a more detailed explanation.
"""
path = '/todos/update_item/%u' % item_id
req =... | python | {
"resource": ""
} |
q51847 | Basecamp.move_todo_item | train | def move_todo_item(self, item_id, to):
"""
Changes the position of an item within its parent list. It does not
currently support reparenting an item. Position 1 is at the top of the
list. Moving an item beyond the end of the list puts it at the bottom
of the list.
"""
... | python | {
"resource": ""
} |
q51848 | Basecamp.list_milestones | train | def list_milestones(self, project_id, find=None):
"""
This lets you query the list of milestones for a project. You can
either return all milestones, or only those that are late, completed,
or upcoming.
"""
path = '/projects/%u/milestones/list' % project_id
req = ... | python | {
"resource": ""
} |
q51849 | Basecamp.create_milestones | train | def create_milestones(self, project_id, milestones):
"""
With this function you can create multiple milestones in a single
request. See the "create" function for a description of the individual
fields in the milestone.
"""
path = '/projects/%u/milestones/create' % project... | python | {
"resource": ""
} |
q51850 | Basecamp.update_milestone | train | def update_milestone(self, milestone_id, title, deadline, party_id, notify,
move_upcoming_milestones=None,
move_upcoming_milestones_off_weekends=None):
"""
Modifies a single milestone. You can use this to shift the deadline of
a single milestone, and optionally shift the deadline... | python | {
"resource": ""
} |
q51851 | key_swap | train | def key_swap(
d,
cls,
marshal
):
""" Swap the keys in a dictionary
Args:
d: dict, The dict to swap keys in
cls: class, If the class has a staticly defined
_marshal_key_swap and/or _unmarshal_key_swap dict,
the keys will... | python | {
"resource": ""
} |
q51852 | Logger.debug | train | def debug(self, message, *args, **kwargs):
"""Log debug event.
Compatible with logging.debug signature.
"""
self.system.debug(message, *args, **kwargs) | python | {
"resource": ""
} |
q51853 | Logger.info | train | def info(self, message, *args, **kwargs):
"""Log info event.
Compatible with logging.info signature.
"""
self.system.info(message, *args, **kwargs) | python | {
"resource": ""
} |
q51854 | Logger.warning | train | def warning(self, message, *args, **kwargs):
"""Log warning event.
Compatible with logging.warning signature.
"""
self.system.warning(message, *args, **kwargs) | python | {
"resource": ""
} |
q51855 | Logger.error | train | def error(self, message, *args, **kwargs):
"""Log error event.
Compatible with logging.error signature.
"""
self.system.error(message, *args, **kwargs) | python | {
"resource": ""
} |
q51856 | Logger.exception | train | def exception(self, message, *args, **kwargs):
"""Log exception event.
Compatible with logging.exception signature.
"""
self.system.exception(message, *args, **kwargs) | python | {
"resource": ""
} |
q51857 | Logger.critical | train | def critical(self, message, *args, **kwargs):
"""Log critical event.
Compatible with logging.critical signature.
"""
self.system.critical(message, *args, **kwargs) | python | {
"resource": ""
} |
q51858 | AuthUrls.sign_out | train | def sign_out(self, redirect_url=None):
"""Returns a signed URL to disassociate the ouath2 user from the session."""
config = config_lib.get_config()
key = self.handler.app.config['webapp2_extras.sessions']['secret_key']
if redirect_url is None:
redirect_url = self.handler.request.url
user_id =... | python | {
"resource": ""
} |
q51859 | DocumentField.wrap | train | def wrap(self, value):
''' Validate ``value`` and then use the document's class to wrap the
value'''
self.validate_wrap(value)
return self.type.wrap(value) | python | {
"resource": ""
} |
q51860 | DocumentField.unwrap | train | def unwrap(self, value, fields=None, session=None):
''' Validate ``value`` and then use the document's class to unwrap the
value'''
self.validate_unwrap(value, fields=fields, session=session)
return self.type.unwrap(value, fields=fields, session=session) | python | {
"resource": ""
} |
q51861 | DocumentField.validate_wrap | train | def validate_wrap(self, value):
''' Checks that ``value`` is an instance of ``DocumentField.type``.
if it is, then validation on its fields has already been done and
no further validation is needed.
'''
if not isinstance(value, self.type):
self._fail_validatio... | python | {
"resource": ""
} |
q51862 | build_re_pattern_from_intervals | train | def build_re_pattern_from_intervals(intervals: IntervalListType) -> BuiltInReType:
"""
Convert intervals to regular expression pattern.
:param intervals: Unicode codepoint intervals.
"""
inner = [f'{chr(lb)}-{chr(ub)}' for lb, ub in intervals]
joined_inner = ''.join(inner)
pattern = f'[{jo... | python | {
"resource": ""
} |
q51863 | compute_author_match_score | train | def compute_author_match_score(x_authors, y_authors):
"""Return the matching score of 2 given lists of authors.
Args:
x_authors (list(dict)): first schema-compliant list of authors.
y_authors (list(dict)): second schema-compliant list of authors.
Returns:
float: matching score of a... | python | {
"resource": ""
} |
q51864 | compute_jaccard_index | train | def compute_jaccard_index(x_set, y_set):
"""Return the Jaccard similarity coefficient of 2 given sets.
Args:
x_set (set): first set.
y_set (set): second set.
Returns:
float: Jaccard similarity coefficient.
"""
if not x_set or not y_set:
return 0.0
intersection... | python | {
"resource": ""
} |
q51865 | info | train | def info(*messages):
"""
Prints the current GloTK module and a `message`.
Taken from biolite
"""
sys.stderr.write("%s.%s: " % get_caller_info())
sys.stderr.write(' '.join(map(str, messages)))
sys.stderr.write('\n') | python | {
"resource": ""
} |
q51866 | dir_is_glotk | train | def dir_is_glotk(path):
"""check that the current directory is a glotk project folder"""
test_set = set(["gloTK_info", "gloTK_assemblies",
"gloTK_configs", "gloTK_reads",
"gloTK_fastqc", "gloTK_kmer",
"gloTK_reports"])
#http://stackoverflow.com/que... | python | {
"resource": ""
} |
q51867 | get_caller_info | train | def get_caller_info(depth=2, trace=False):
"""
Uses the inspect module to determine the name of the calling function and
its module.
Returns a 2-tuple with the module name and the function name.
From Biolite package
"""
try:
frame = inspect.stack()[depth]
except:
die("c... | python | {
"resource": ""
} |
q51868 | die | train | def die(*messages):
"""
Prints the current BioLite module and an error `message`, then aborts.
"""
sys.stderr.write("%s.%s: " % get_caller_info(trace=True))
sys.stderr.write(' '.join(map(str, messages)))
sys.stderr.write('\n')
sys.exit(1) | python | {
"resource": ""
} |
q51869 | BasicWorkflow.result | train | def result(self, input_sequence: str, config: Optional[BasicConfig] = None) -> Any:
"""
Execute the workflow.
:param input_sequence: The input sequence.
"""
# Step 1.
sequential_labelers = [
sl_cls(input_sequence, config) for sl_cls in self.sequential_lab... | python | {
"resource": ""
} |
q51870 | calc_checksum | train | def calc_checksum(sentence):
"""Calculate a NMEA 0183 checksum for the given sentence.
NMEA checksums are a simple XOR of all the characters in the sentence
between the leading "$" symbol, and the "*" checksum separator.
Args:
sentence (str): NMEA 0183 formatted sentence
"""
if sentenc... | python | {
"resource": ""
} |
q51871 | parse_latitude | train | def parse_latitude(latitude, hemisphere):
"""Parse a NMEA-formatted latitude pair.
Args:
latitude (str): Latitude in DDMM.MMMM
hemisphere (str): North or South
Returns:
float: Decimal representation of latitude
"""
latitude = int(latitude[:2]) + float(latitude[2:]) / 60
... | python | {
"resource": ""
} |
q51872 | parse_longitude | train | def parse_longitude(longitude, hemisphere):
"""Parse a NMEA-formatted longitude pair.
Args:
longitude (str): Longitude in DDDMM.MMMM
hemisphere (str): East or West
Returns:
float: Decimal representation of longitude
"""
longitude = int(longitude[:3]) + float(longitude[3:]) ... | python | {
"resource": ""
} |
q51873 | Fix.parse_elements | train | def parse_elements(elements):
"""Parse essential fix's data elements.
Args:
elements (list): Data values for fix
Returns:
Fix: Fix object representing data
"""
if not len(elements) in (14, 15):
raise ValueError('Invalid GGA fix data')
... | python | {
"resource": ""
} |
q51874 | Waypoint.parse_elements | train | def parse_elements(elements):
"""Parse waypoint data elements.
Args:
elements (list): Data values for fix
Returns:
nmea.Waypoint: Object representing data
"""
if not len(elements) == 5:
raise ValueError('Invalid WPL waypoint data')
# ... | python | {
"resource": ""
} |
q51875 | Locations.import_locations | train | def import_locations(self, gpsdata_file, checksum=True):
r"""Import GPS NMEA-formatted data files.
``import_locations()`` returns a list of `Fix` objects representing the
fix sentences found in the GPS data.
It expects data files in NMEA 0183 format, as specified in `the
offici... | python | {
"resource": ""
} |
q51876 | get_platform | train | def get_platform():
"""Detect and instantiate an instance of the underlying platform"""
# Detect
platform_str = platform.system()
print 'Platform detected: {}'.format(platform_str)
# Instantiate
if platform_str == 'Windows':
return WindowsPlatform()
elif platform_str == 'Linux':
return LinuxPlatform()
else:... | python | {
"resource": ""
} |
q51877 | Change.length | train | def length(self):
"""The number of elements changed.
:rtype: int
.. code:: python
assert change.length == len(change.indices)
assert change.length == len(change.elements)
"""
span = self._stop - self._start
length, modulo = divmod(span, self._st... | python | {
"resource": ""
} |
q51878 | ObservableList._notify_add | train | def _notify_add(self, slice_):
"""Notify about an AddChange."""
change = AddChange(self, slice_)
self.notify_observers(change) | python | {
"resource": ""
} |
q51879 | ObservableList._notify_add_at | train | def _notify_add_at(self, index, length=1):
"""Notify about an AddChange at a caertain index and length."""
slice_ = self._slice_at(index, length)
self._notify_add(slice_) | python | {
"resource": ""
} |
q51880 | ObservableList._notify_remove_at | train | def _notify_remove_at(self, index, length=1):
"""Notify about an RemoveChange at a caertain index and length."""
slice_ = self._slice_at(index, length)
self._notify_remove(slice_) | python | {
"resource": ""
} |
q51881 | ObservableList._notify_remove | train | def _notify_remove(self, slice_):
"""Notify about a RemoveChange."""
change = RemoveChange(self, slice_)
self.notify_observers(change) | python | {
"resource": ""
} |
q51882 | ObservableList._slice_at | train | def _slice_at(self, index, length=1):
"""Create a slice for index and length."""
length_ = len(self)
if -length <= index < 0:
index += length_
return slice(index, index + length) | python | {
"resource": ""
} |
q51883 | ObservableList.append | train | def append(self, element):
"""See list.append."""
super(ObservableList, self).append(element)
self._notify_add_at(len(self) - 1) | python | {
"resource": ""
} |
q51884 | ObservableList.insert | train | def insert(self, index, item):
"""See list.insert."""
super(ObservableList, self).insert(index, item)
length = len(self)
if index >= length:
index = length - 1
elif index < 0:
index += length - 1
if index < 0:
index = 0
... | python | {
"resource": ""
} |
q51885 | ObservableList.extend | train | def extend(self, other):
"""See list.extend."""
index = len(self)
length = 0
for length, element in enumerate(other, 1):
super(ObservableList, self).append(element)
if length:
self._notify_add_at(index, length) | python | {
"resource": ""
} |
q51886 | ObservableList.pop | train | def pop(self, index=-1):
"""See list.pop."""
if not isinstance(index, int):
if PY2:
raise TypeError('an integer is required')
raise TypeError("'str' object cannot be interpreted as an integer")
length = len(self)
if -length <= index < length:
... | python | {
"resource": ""
} |
q51887 | ObservableList.remove | train | def remove(self, element):
"""See list.remove."""
try:
index = self.index(element)
except ValueError:
raise ValueError("list.remove(x): x not in list")
else:
self._notify_remove_at(index)
super(ObservableList, self).pop(index) | python | {
"resource": ""
} |
q51888 | ObservableList._notify_delete | train | def _notify_delete(self, index_or_slice):
"""Notify about a deletion at an index_or_slice.
:return: a function that notifies about an add at the same place.
"""
if isinstance(index_or_slice, int):
length = len(self)
if -length <= index_or_slice < length:
... | python | {
"resource": ""
} |
q51889 | _parse_filter_string | train | def _parse_filter_string(filter_string):
""" parse a filter string into a key-value pair """
assert "=" in filter_string, "filter string requires an '=', got {0}".format(filter_string)
split_values = filter_string.split('=')
assert len(split_values) == 2, "more than one equals found in filter string {0}... | python | {
"resource": ""
} |
q51890 | _create_stdout_logger | train | def _create_stdout_logger():
""" create a logger to stdout """
log = logging.getLogger(__name__)
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setFormatter(logging.Formatter('%(message)s'))
out_hdlr.setLevel(logging.INFO)
log.addHandler(out_hdlr)
log.setLevel(logging.INFO) | python | {
"resource": ""
} |
q51891 | Chain.push | train | def push(self, item, *, index=None):
"""Push item to the chain.
"""
if index is None:
self.__list.append(item)
else:
self.__list.insert(index, item)
name = getattr(item, 'name', None)
if name is not None:
self.__dict[name] = item | python | {
"resource": ""
} |
q51892 | Chain.pull | train | def pull(self, *, index=None):
"""Pull item from the chain.
"""
item = self.__list.pop(index)
name = getattr(item, 'name', None)
if name is not None:
del self.__dict[name]
return item | python | {
"resource": ""
} |
q51893 | get_cpu_usage | train | def get_cpu_usage(user=None, ignore_self=True):
"""
Returns the total CPU usage for all available cores.
:param user: If given, returns only the total CPU usage of all processes
for the given user.
:param ignore_self: If ``True`` the process that runs this script will
be ignored.
"""
... | python | {
"resource": ""
} |
q51894 | SerfClient.event | train | def event(self, name, payload=None, coalesce=True):
"""
Send an event to the cluster. Can take an optional payload as well,
which will be sent in the form that it's provided.
"""
return self.connection.call(
'event',
{'Name': name, 'Payload': payload, 'Coa... | python | {
"resource": ""
} |
q51895 | CreatedField | train | def CreatedField(name='created', tz_aware=False, **kwargs):
''' A shortcut field for creation time. It sets the current date and time
when it enters the database and then doesn't update on further saves.
If you've used the Django ORM, this is the equivalent of auto_now_add
:param tz_aware... | python | {
"resource": ""
} |
q51896 | NumberField.validate_wrap | train | def validate_wrap(self, value, *types):
''' Validates the type and value of ``value`` '''
for type in types:
if isinstance(value, type):
break
else:
self._fail_validation_type(value, *types)
if self.min is not None and value < self.min:
... | python | {
"resource": ""
} |
q51897 | DateTimeField.validate_wrap | train | def validate_wrap(self, value):
''' Validates the value's type as well as it being in the valid
date range'''
if not isinstance(value, datetime):
self._fail_validation_type(value, datetime)
if self.use_tz and value.tzinfo is None:
self._fail_validation(value,... | python | {
"resource": ""
} |
q51898 | TupleField.validate_wrap | train | def validate_wrap(self, value):
''' Checks that the correct number of elements are in ``value`` and that
each element validates agains the associated Field class
'''
if not isinstance(value, list) and not isinstance(value, tuple):
self._fail_validation_type(value, tuple, ... | python | {
"resource": ""
} |
q51899 | TupleField.wrap | train | def wrap(self, value):
''' Validate and then wrap ``value`` for insertion.
:param value: the tuple (or list) to wrap
'''
self.validate_wrap(value)
ret = []
for field, value in izip(self.types, value):
ret.append(field.wrap(value))
return ret | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.