id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
238,700 | niklasf/python-chess | chess/__init__.py | Board.root | def root(self: BoardT) -> BoardT:
"""Returns a copy of the root position."""
if self._stack:
board = type(self)(None, chess960=self.chess960)
self._stack[0].restore(board)
return board
else:
return self.copy(stack=False) | python | def root(self: BoardT) -> BoardT:
if self._stack:
board = type(self)(None, chess960=self.chess960)
self._stack[0].restore(board)
return board
else:
return self.copy(stack=False) | [
"def",
"root",
"(",
"self",
":",
"BoardT",
")",
"->",
"BoardT",
":",
"if",
"self",
".",
"_stack",
":",
"board",
"=",
"type",
"(",
"self",
")",
"(",
"None",
",",
"chess960",
"=",
"self",
".",
"chess960",
")",
"self",
".",
"_stack",
"[",
"0",
"]",
... | Returns a copy of the root position. | [
"Returns",
"a",
"copy",
"of",
"the",
"root",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1435-L1442 |
238,701 | niklasf/python-chess | chess/__init__.py | Board.is_check | def is_check(self) -> bool:
"""Returns if the current side to move is in check."""
king = self.king(self.turn)
return king is not None and self.is_attacked_by(not self.turn, king) | python | def is_check(self) -> bool:
king = self.king(self.turn)
return king is not None and self.is_attacked_by(not self.turn, king) | [
"def",
"is_check",
"(",
"self",
")",
"->",
"bool",
":",
"king",
"=",
"self",
".",
"king",
"(",
"self",
".",
"turn",
")",
"return",
"king",
"is",
"not",
"None",
"and",
"self",
".",
"is_attacked_by",
"(",
"not",
"self",
".",
"turn",
",",
"king",
")"
... | Returns if the current side to move is in check. | [
"Returns",
"if",
"the",
"current",
"side",
"to",
"move",
"is",
"in",
"check",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1540-L1543 |
238,702 | niklasf/python-chess | chess/__init__.py | Board.is_into_check | def is_into_check(self, move: Move) -> bool:
"""
Checks if the given move would leave the king in check or put it into
check. The move must be at least pseudo legal.
"""
king = self.king(self.turn)
if king is None:
return False
checkers = self.attackers_mask(not self.turn, king)
if checkers:
# If already in check, look if it is an evasion.
if move not in self._generate_evasions(king, checkers, BB_SQUARES[move.from_square], BB_SQUARES[move.to_square]):
return True
return not self._is_safe(king, self._slider_blockers(king), move) | python | def is_into_check(self, move: Move) -> bool:
king = self.king(self.turn)
if king is None:
return False
checkers = self.attackers_mask(not self.turn, king)
if checkers:
# If already in check, look if it is an evasion.
if move not in self._generate_evasions(king, checkers, BB_SQUARES[move.from_square], BB_SQUARES[move.to_square]):
return True
return not self._is_safe(king, self._slider_blockers(king), move) | [
"def",
"is_into_check",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"king",
"=",
"self",
".",
"king",
"(",
"self",
".",
"turn",
")",
"if",
"king",
"is",
"None",
":",
"return",
"False",
"checkers",
"=",
"self",
".",
"attackers_mask"... | Checks if the given move would leave the king in check or put it into
check. The move must be at least pseudo legal. | [
"Checks",
"if",
"the",
"given",
"move",
"would",
"leave",
"the",
"king",
"in",
"check",
"or",
"put",
"it",
"into",
"check",
".",
"The",
"move",
"must",
"be",
"at",
"least",
"pseudo",
"legal",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1545-L1560 |
238,703 | niklasf/python-chess | chess/__init__.py | Board.was_into_check | def was_into_check(self) -> bool:
"""
Checks if the king of the other side is attacked. Such a position is not
valid and could only be reached by an illegal move.
"""
king = self.king(not self.turn)
return king is not None and self.is_attacked_by(self.turn, king) | python | def was_into_check(self) -> bool:
king = self.king(not self.turn)
return king is not None and self.is_attacked_by(self.turn, king) | [
"def",
"was_into_check",
"(",
"self",
")",
"->",
"bool",
":",
"king",
"=",
"self",
".",
"king",
"(",
"not",
"self",
".",
"turn",
")",
"return",
"king",
"is",
"not",
"None",
"and",
"self",
".",
"is_attacked_by",
"(",
"self",
".",
"turn",
",",
"king",
... | Checks if the king of the other side is attacked. Such a position is not
valid and could only be reached by an illegal move. | [
"Checks",
"if",
"the",
"king",
"of",
"the",
"other",
"side",
"is",
"attacked",
".",
"Such",
"a",
"position",
"is",
"not",
"valid",
"and",
"could",
"only",
"be",
"reached",
"by",
"an",
"illegal",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1562-L1568 |
238,704 | niklasf/python-chess | chess/__init__.py | Board.result | def result(self, *, claim_draw: bool = False) -> str:
"""
Gets the game result.
``1-0``, ``0-1`` or ``1/2-1/2`` if the
:func:`game is over <chess.Board.is_game_over()>`. Otherwise, the
result is undetermined: ``*``.
"""
# Chess variant support.
if self.is_variant_loss():
return "0-1" if self.turn == WHITE else "1-0"
elif self.is_variant_win():
return "1-0" if self.turn == WHITE else "0-1"
elif self.is_variant_draw():
return "1/2-1/2"
# Checkmate.
if self.is_checkmate():
return "0-1" if self.turn == WHITE else "1-0"
# Draw claimed.
if claim_draw and self.can_claim_draw():
return "1/2-1/2"
# Seventyfive-move rule or fivefold repetition.
if self.is_seventyfive_moves() or self.is_fivefold_repetition():
return "1/2-1/2"
# Insufficient material.
if self.is_insufficient_material():
return "1/2-1/2"
# Stalemate.
if not any(self.generate_legal_moves()):
return "1/2-1/2"
# Undetermined.
return "*" | python | def result(self, *, claim_draw: bool = False) -> str:
# Chess variant support.
if self.is_variant_loss():
return "0-1" if self.turn == WHITE else "1-0"
elif self.is_variant_win():
return "1-0" if self.turn == WHITE else "0-1"
elif self.is_variant_draw():
return "1/2-1/2"
# Checkmate.
if self.is_checkmate():
return "0-1" if self.turn == WHITE else "1-0"
# Draw claimed.
if claim_draw and self.can_claim_draw():
return "1/2-1/2"
# Seventyfive-move rule or fivefold repetition.
if self.is_seventyfive_moves() or self.is_fivefold_repetition():
return "1/2-1/2"
# Insufficient material.
if self.is_insufficient_material():
return "1/2-1/2"
# Stalemate.
if not any(self.generate_legal_moves()):
return "1/2-1/2"
# Undetermined.
return "*" | [
"def",
"result",
"(",
"self",
",",
"*",
",",
"claim_draw",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"# Chess variant support.",
"if",
"self",
".",
"is_variant_loss",
"(",
")",
":",
"return",
"\"0-1\"",
"if",
"self",
".",
"turn",
"==",
"WHITE",
... | Gets the game result.
``1-0``, ``0-1`` or ``1/2-1/2`` if the
:func:`game is over <chess.Board.is_game_over()>`. Otherwise, the
result is undetermined: ``*``. | [
"Gets",
"the",
"game",
"result",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1686-L1723 |
238,705 | niklasf/python-chess | chess/__init__.py | Board.is_stalemate | def is_stalemate(self) -> bool:
"""Checks if the current position is a stalemate."""
if self.is_check():
return False
if self.is_variant_end():
return False
return not any(self.generate_legal_moves()) | python | def is_stalemate(self) -> bool:
if self.is_check():
return False
if self.is_variant_end():
return False
return not any(self.generate_legal_moves()) | [
"def",
"is_stalemate",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"is_check",
"(",
")",
":",
"return",
"False",
"if",
"self",
".",
"is_variant_end",
"(",
")",
":",
"return",
"False",
"return",
"not",
"any",
"(",
"self",
".",
"generate_lega... | Checks if the current position is a stalemate. | [
"Checks",
"if",
"the",
"current",
"position",
"is",
"a",
"stalemate",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1732-L1740 |
238,706 | niklasf/python-chess | chess/__init__.py | Board.can_claim_fifty_moves | def can_claim_fifty_moves(self) -> bool:
"""
Draw by the fifty-move rule can be claimed once the clock of halfmoves
since the last capture or pawn move becomes equal or greater to 100
and the side to move still has a legal move they can make.
"""
# Fifty-move rule.
if self.halfmove_clock >= 100:
if any(self.generate_legal_moves()):
return True
return False | python | def can_claim_fifty_moves(self) -> bool:
# Fifty-move rule.
if self.halfmove_clock >= 100:
if any(self.generate_legal_moves()):
return True
return False | [
"def",
"can_claim_fifty_moves",
"(",
"self",
")",
"->",
"bool",
":",
"# Fifty-move rule.",
"if",
"self",
".",
"halfmove_clock",
">=",
"100",
":",
"if",
"any",
"(",
"self",
".",
"generate_legal_moves",
"(",
")",
")",
":",
"return",
"True",
"return",
"False"
] | Draw by the fifty-move rule can be claimed once the clock of halfmoves
since the last capture or pawn move becomes equal or greater to 100
and the side to move still has a legal move they can make. | [
"Draw",
"by",
"the",
"fifty",
"-",
"move",
"rule",
"can",
"be",
"claimed",
"once",
"the",
"clock",
"of",
"halfmoves",
"since",
"the",
"last",
"capture",
"or",
"pawn",
"move",
"becomes",
"equal",
"or",
"greater",
"to",
"100",
"and",
"the",
"side",
"to",
... | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1832-L1843 |
238,707 | niklasf/python-chess | chess/__init__.py | Board.can_claim_threefold_repetition | def can_claim_threefold_repetition(self) -> bool:
"""
Draw by threefold repetition can be claimed if the position on the
board occured for the third time or if such a repetition is reached
with one of the possible legal moves.
Note that checking this can be slow: In the worst case
scenario every legal move has to be tested and the entire game has to
be replayed because there is no incremental transposition table.
"""
transposition_key = self._transposition_key()
transpositions = collections.Counter() # type: typing.Counter[Hashable]
transpositions.update((transposition_key, ))
# Count positions.
switchyard = []
while self.move_stack:
move = self.pop()
switchyard.append(move)
if self.is_irreversible(move):
break
transpositions.update((self._transposition_key(), ))
while switchyard:
self.push(switchyard.pop())
# Threefold repetition occured.
if transpositions[transposition_key] >= 3:
return True
# The next legal move is a threefold repetition.
for move in self.generate_legal_moves():
self.push(move)
try:
if transpositions[self._transposition_key()] >= 2:
return True
finally:
self.pop()
return False | python | def can_claim_threefold_repetition(self) -> bool:
transposition_key = self._transposition_key()
transpositions = collections.Counter() # type: typing.Counter[Hashable]
transpositions.update((transposition_key, ))
# Count positions.
switchyard = []
while self.move_stack:
move = self.pop()
switchyard.append(move)
if self.is_irreversible(move):
break
transpositions.update((self._transposition_key(), ))
while switchyard:
self.push(switchyard.pop())
# Threefold repetition occured.
if transpositions[transposition_key] >= 3:
return True
# The next legal move is a threefold repetition.
for move in self.generate_legal_moves():
self.push(move)
try:
if transpositions[self._transposition_key()] >= 2:
return True
finally:
self.pop()
return False | [
"def",
"can_claim_threefold_repetition",
"(",
"self",
")",
"->",
"bool",
":",
"transposition_key",
"=",
"self",
".",
"_transposition_key",
"(",
")",
"transpositions",
"=",
"collections",
".",
"Counter",
"(",
")",
"# type: typing.Counter[Hashable]",
"transpositions",
"... | Draw by threefold repetition can be claimed if the position on the
board occured for the third time or if such a repetition is reached
with one of the possible legal moves.
Note that checking this can be slow: In the worst case
scenario every legal move has to be tested and the entire game has to
be replayed because there is no incremental transposition table. | [
"Draw",
"by",
"threefold",
"repetition",
"can",
"be",
"claimed",
"if",
"the",
"position",
"on",
"the",
"board",
"occured",
"for",
"the",
"third",
"time",
"or",
"if",
"such",
"a",
"repetition",
"is",
"reached",
"with",
"one",
"of",
"the",
"possible",
"legal... | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L1845-L1886 |
238,708 | niklasf/python-chess | chess/__init__.py | Board.pop | def pop(self: BoardT) -> Move:
"""
Restores the previous position and returns the last move from the stack.
:raises: :exc:`IndexError` if the stack is empty.
"""
move = self.move_stack.pop()
self._stack.pop().restore(self)
return move | python | def pop(self: BoardT) -> Move:
move = self.move_stack.pop()
self._stack.pop().restore(self)
return move | [
"def",
"pop",
"(",
"self",
":",
"BoardT",
")",
"->",
"Move",
":",
"move",
"=",
"self",
".",
"move_stack",
".",
"pop",
"(",
")",
"self",
".",
"_stack",
".",
"pop",
"(",
")",
".",
"restore",
"(",
"self",
")",
"return",
"move"
] | Restores the previous position and returns the last move from the stack.
:raises: :exc:`IndexError` if the stack is empty. | [
"Restores",
"the",
"previous",
"position",
"and",
"returns",
"the",
"last",
"move",
"from",
"the",
"stack",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2048-L2056 |
238,709 | niklasf/python-chess | chess/__init__.py | Board.fen | def fen(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None) -> str:
"""
Gets a FEN representation of the position.
A FEN string (e.g.,
``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists
of the position part :func:`~chess.Board.board_fen()`, the
:data:`~chess.Board.turn`, the castling part
(:data:`~chess.Board.castling_rights`),
the en passant square (:data:`~chess.Board.ep_square`),
the :data:`~chess.Board.halfmove_clock`
and the :data:`~chess.Board.fullmove_number`.
:param shredder: Use :func:`~chess.Board.castling_shredder_fen()`
and encode castling rights by the file of the rook
(like ``HAha``) instead of the default
:func:`~chess.Board.castling_xfen()` (like ``KQkq``).
:param en_passant: By default, only fully legal en passant squares
are included (:func:`~chess.Board.has_legal_en_passant()`).
Pass ``fen`` to strictly follow the FEN specification
(always include the en passant square after a two-step pawn move)
or ``xfen`` to follow the X-FEN specification
(:func:`~chess.Board.has_pseudo_legal_en_passant()`).
:param promoted: Mark promoted pieces like ``Q~``. By default, this is
only enabled in chess variants where this is relevant.
"""
return " ".join([
self.epd(shredder=shredder, en_passant=en_passant, promoted=promoted),
str(self.halfmove_clock),
str(self.fullmove_number)
]) | python | def fen(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None) -> str:
return " ".join([
self.epd(shredder=shredder, en_passant=en_passant, promoted=promoted),
str(self.halfmove_clock),
str(self.fullmove_number)
]) | [
"def",
"fen",
"(",
"self",
",",
"*",
",",
"shredder",
":",
"bool",
"=",
"False",
",",
"en_passant",
":",
"str",
"=",
"\"legal\"",
",",
"promoted",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
")",
"->",
"str",
":",
"return",
"\" \"",
".",
"join"... | Gets a FEN representation of the position.
A FEN string (e.g.,
``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists
of the position part :func:`~chess.Board.board_fen()`, the
:data:`~chess.Board.turn`, the castling part
(:data:`~chess.Board.castling_rights`),
the en passant square (:data:`~chess.Board.ep_square`),
the :data:`~chess.Board.halfmove_clock`
and the :data:`~chess.Board.fullmove_number`.
:param shredder: Use :func:`~chess.Board.castling_shredder_fen()`
and encode castling rights by the file of the rook
(like ``HAha``) instead of the default
:func:`~chess.Board.castling_xfen()` (like ``KQkq``).
:param en_passant: By default, only fully legal en passant squares
are included (:func:`~chess.Board.has_legal_en_passant()`).
Pass ``fen`` to strictly follow the FEN specification
(always include the en passant square after a two-step pawn move)
or ``xfen`` to follow the X-FEN specification
(:func:`~chess.Board.has_pseudo_legal_en_passant()`).
:param promoted: Mark promoted pieces like ``Q~``. By default, this is
only enabled in chess variants where this is relevant. | [
"Gets",
"a",
"FEN",
"representation",
"of",
"the",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2118-L2148 |
238,710 | niklasf/python-chess | chess/__init__.py | Board.set_fen | def set_fen(self, fen: str) -> None:
"""
Parses a FEN and sets the position from it.
:raises: :exc:`ValueError` if the FEN string is invalid.
"""
parts = fen.split()
# Board part.
try:
board_part = parts.pop(0)
except IndexError:
raise ValueError("empty fen")
# Turn.
try:
turn_part = parts.pop(0)
except IndexError:
turn = WHITE
else:
if turn_part == "w":
turn = WHITE
elif turn_part == "b":
turn = BLACK
else:
raise ValueError("expected 'w' or 'b' for turn part of fen: {!r}".format(fen))
# Validate castling part.
try:
castling_part = parts.pop(0)
except IndexError:
castling_part = "-"
else:
if not FEN_CASTLING_REGEX.match(castling_part):
raise ValueError("invalid castling part in fen: {!r}".format(fen))
# En passant square.
try:
ep_part = parts.pop(0)
except IndexError:
ep_square = None
else:
try:
ep_square = None if ep_part == "-" else SQUARE_NAMES.index(ep_part)
except ValueError:
raise ValueError("invalid en passant part in fen: {!r}".format(fen))
# Check that the half-move part is valid.
try:
halfmove_part = parts.pop(0)
except IndexError:
halfmove_clock = 0
else:
try:
halfmove_clock = int(halfmove_part)
except ValueError:
raise ValueError("invalid half-move clock in fen: {!r}".format(fen))
if halfmove_clock < 0:
raise ValueError("half-move clock cannot be negative: {!r}".format(fen))
# Check that the full-move number part is valid.
# 0 is allowed for compability, but later replaced with 1.
try:
fullmove_part = parts.pop(0)
except IndexError:
fullmove_number = 1
else:
try:
fullmove_number = int(fullmove_part)
except ValueError:
raise ValueError("invalid fullmove number in fen: {!r}".format(fen))
if fullmove_number < 0:
raise ValueError("fullmove number cannot be negative: {!r}".format(fen))
fullmove_number = max(fullmove_number, 1)
# All parts should be consumed now.
if parts:
raise ValueError("fen string has more parts than expected: {!r}".format(fen))
# Validate the board part and set it.
self._set_board_fen(board_part)
# Apply.
self.turn = turn
self._set_castling_fen(castling_part)
self.ep_square = ep_square
self.halfmove_clock = halfmove_clock
self.fullmove_number = fullmove_number
self.clear_stack() | python | def set_fen(self, fen: str) -> None:
parts = fen.split()
# Board part.
try:
board_part = parts.pop(0)
except IndexError:
raise ValueError("empty fen")
# Turn.
try:
turn_part = parts.pop(0)
except IndexError:
turn = WHITE
else:
if turn_part == "w":
turn = WHITE
elif turn_part == "b":
turn = BLACK
else:
raise ValueError("expected 'w' or 'b' for turn part of fen: {!r}".format(fen))
# Validate castling part.
try:
castling_part = parts.pop(0)
except IndexError:
castling_part = "-"
else:
if not FEN_CASTLING_REGEX.match(castling_part):
raise ValueError("invalid castling part in fen: {!r}".format(fen))
# En passant square.
try:
ep_part = parts.pop(0)
except IndexError:
ep_square = None
else:
try:
ep_square = None if ep_part == "-" else SQUARE_NAMES.index(ep_part)
except ValueError:
raise ValueError("invalid en passant part in fen: {!r}".format(fen))
# Check that the half-move part is valid.
try:
halfmove_part = parts.pop(0)
except IndexError:
halfmove_clock = 0
else:
try:
halfmove_clock = int(halfmove_part)
except ValueError:
raise ValueError("invalid half-move clock in fen: {!r}".format(fen))
if halfmove_clock < 0:
raise ValueError("half-move clock cannot be negative: {!r}".format(fen))
# Check that the full-move number part is valid.
# 0 is allowed for compability, but later replaced with 1.
try:
fullmove_part = parts.pop(0)
except IndexError:
fullmove_number = 1
else:
try:
fullmove_number = int(fullmove_part)
except ValueError:
raise ValueError("invalid fullmove number in fen: {!r}".format(fen))
if fullmove_number < 0:
raise ValueError("fullmove number cannot be negative: {!r}".format(fen))
fullmove_number = max(fullmove_number, 1)
# All parts should be consumed now.
if parts:
raise ValueError("fen string has more parts than expected: {!r}".format(fen))
# Validate the board part and set it.
self._set_board_fen(board_part)
# Apply.
self.turn = turn
self._set_castling_fen(castling_part)
self.ep_square = ep_square
self.halfmove_clock = halfmove_clock
self.fullmove_number = fullmove_number
self.clear_stack() | [
"def",
"set_fen",
"(",
"self",
",",
"fen",
":",
"str",
")",
"->",
"None",
":",
"parts",
"=",
"fen",
".",
"split",
"(",
")",
"# Board part.",
"try",
":",
"board_part",
"=",
"parts",
".",
"pop",
"(",
"0",
")",
"except",
"IndexError",
":",
"raise",
"V... | Parses a FEN and sets the position from it.
:raises: :exc:`ValueError` if the FEN string is invalid. | [
"Parses",
"a",
"FEN",
"and",
"sets",
"the",
"position",
"from",
"it",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2157-L2248 |
238,711 | niklasf/python-chess | chess/__init__.py | Board.chess960_pos | def chess960_pos(self, *, ignore_turn: bool = False, ignore_castling: bool = False, ignore_counters: bool = True) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 956
or ``None`` if the current position is not a Chess960 starting
position.
By default white to move (**ignore_turn**) and full castling rights
(**ignore_castling**) are required, but move counters
(**ignore_counters**) are ignored.
"""
if self.ep_square:
return None
if not ignore_turn:
if self.turn != WHITE:
return None
if not ignore_castling:
if self.clean_castling_rights() != self.rooks:
return None
if not ignore_counters:
if self.fullmove_number != 1 or self.halfmove_clock != 0:
return None
return super().chess960_pos() | python | def chess960_pos(self, *, ignore_turn: bool = False, ignore_castling: bool = False, ignore_counters: bool = True) -> Optional[int]:
if self.ep_square:
return None
if not ignore_turn:
if self.turn != WHITE:
return None
if not ignore_castling:
if self.clean_castling_rights() != self.rooks:
return None
if not ignore_counters:
if self.fullmove_number != 1 or self.halfmove_clock != 0:
return None
return super().chess960_pos() | [
"def",
"chess960_pos",
"(",
"self",
",",
"*",
",",
"ignore_turn",
":",
"bool",
"=",
"False",
",",
"ignore_castling",
":",
"bool",
"=",
"False",
",",
"ignore_counters",
":",
"bool",
"=",
"True",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"self",... | Gets the Chess960 starting position index between 0 and 956
or ``None`` if the current position is not a Chess960 starting
position.
By default white to move (**ignore_turn**) and full castling rights
(**ignore_castling**) are required, but move counters
(**ignore_counters**) are ignored. | [
"Gets",
"the",
"Chess960",
"starting",
"position",
"index",
"between",
"0",
"and",
"956",
"or",
"None",
"if",
"the",
"current",
"position",
"is",
"not",
"a",
"Chess960",
"starting",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2312-L2337 |
238,712 | niklasf/python-chess | chess/__init__.py | Board.epd | def epd(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None, **operations: Union[None, str, int, float, Move, Iterable[Move]]) -> str:
"""
Gets an EPD representation of the current position.
See :func:`~chess.Board.fen()` for FEN formatting options (*shredder*,
*ep_square* and *promoted*).
EPD operations can be given as keyword arguments. Supported operands
are strings, integers, floats, moves, lists of moves and ``None``.
All other operands are converted to strings.
A list of moves for *pv* will be interpreted as a variation. All other
move lists are interpreted as a set of moves in the current position.
*hmvc* and *fmvc* are not included by default. You can use:
>>> import chess
>>>
>>> board = chess.Board()
>>> board.epd(hmvc=board.halfmove_clock, fmvc=board.fullmove_number)
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - hmvc 0; fmvc 1;'
"""
if en_passant == "fen":
ep_square = self.ep_square
elif en_passant == "xfen":
ep_square = self.ep_square if self.has_pseudo_legal_en_passant() else None
else:
ep_square = self.ep_square if self.has_legal_en_passant() else None
epd = [self.board_fen(promoted=promoted),
"w" if self.turn == WHITE else "b",
self.castling_shredder_fen() if shredder else self.castling_xfen(),
SQUARE_NAMES[ep_square] if ep_square is not None else "-"]
if operations:
epd.append(self._epd_operations(operations))
return " ".join(epd) | python | def epd(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None, **operations: Union[None, str, int, float, Move, Iterable[Move]]) -> str:
if en_passant == "fen":
ep_square = self.ep_square
elif en_passant == "xfen":
ep_square = self.ep_square if self.has_pseudo_legal_en_passant() else None
else:
ep_square = self.ep_square if self.has_legal_en_passant() else None
epd = [self.board_fen(promoted=promoted),
"w" if self.turn == WHITE else "b",
self.castling_shredder_fen() if shredder else self.castling_xfen(),
SQUARE_NAMES[ep_square] if ep_square is not None else "-"]
if operations:
epd.append(self._epd_operations(operations))
return " ".join(epd) | [
"def",
"epd",
"(",
"self",
",",
"*",
",",
"shredder",
":",
"bool",
"=",
"False",
",",
"en_passant",
":",
"str",
"=",
"\"legal\"",
",",
"promoted",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"*",
"*",
"operations",
":",
"Union",
"[",
"None... | Gets an EPD representation of the current position.
See :func:`~chess.Board.fen()` for FEN formatting options (*shredder*,
*ep_square* and *promoted*).
EPD operations can be given as keyword arguments. Supported operands
are strings, integers, floats, moves, lists of moves and ``None``.
All other operands are converted to strings.
A list of moves for *pv* will be interpreted as a variation. All other
move lists are interpreted as a set of moves in the current position.
*hmvc* and *fmvc* are not included by default. You can use:
>>> import chess
>>>
>>> board = chess.Board()
>>> board.epd(hmvc=board.halfmove_clock, fmvc=board.fullmove_number)
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - hmvc 0; fmvc 1;' | [
"Gets",
"an",
"EPD",
"representation",
"of",
"the",
"current",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2398-L2435 |
238,713 | niklasf/python-chess | chess/__init__.py | Board.lan | def lan(self, move: Move) -> str:
"""
Gets the long algebraic notation of the given move in the context of
the current position.
"""
return self._algebraic(move, long=True) | python | def lan(self, move: Move) -> str:
return self._algebraic(move, long=True) | [
"def",
"lan",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"str",
":",
"return",
"self",
".",
"_algebraic",
"(",
"move",
",",
"long",
"=",
"True",
")"
] | Gets the long algebraic notation of the given move in the context of
the current position. | [
"Gets",
"the",
"long",
"algebraic",
"notation",
"of",
"the",
"given",
"move",
"in",
"the",
"context",
"of",
"the",
"current",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2568-L2573 |
238,714 | niklasf/python-chess | chess/__init__.py | Board.parse_san | def parse_san(self, san: str) -> Move:
"""
Uses the current position as the context to parse a move in standard
algebraic notation and returns the corresponding move object.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the SAN is invalid or ambiguous.
"""
# Castling.
try:
if san in ["O-O", "O-O+", "O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_kingside_castling(move))
elif san in ["O-O-O", "O-O-O+", "O-O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_queenside_castling(move))
except StopIteration:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
# Match normal moves.
match = SAN_REGEX.match(san)
if not match:
# Null moves.
if san in ["--", "Z0"]:
return Move.null()
raise ValueError("invalid san: {!r}".format(san))
# Get target square.
to_square = SQUARE_NAMES.index(match.group(4))
to_mask = BB_SQUARES[to_square] & ~self.occupied_co[self.turn]
# Get the promotion type.
p = match.group(5)
promotion = p and PIECE_SYMBOLS.index(p[-1].lower())
# Filter by piece type.
if match.group(1):
piece_type = PIECE_SYMBOLS.index(match.group(1).lower())
from_mask = self.pieces_mask(piece_type, self.turn)
else:
from_mask = self.pawns
# Filter by source file.
if match.group(2):
from_mask &= BB_FILES[FILE_NAMES.index(match.group(2))]
# Filter by source rank.
if match.group(3):
from_mask &= BB_RANKS[int(match.group(3)) - 1]
# Match legal moves.
matched_move = None
for move in self.generate_legal_moves(from_mask, to_mask):
if move.promotion != promotion:
continue
if matched_move:
raise ValueError("ambiguous san: {!r} in {}".format(san, self.fen()))
matched_move = move
if not matched_move:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
return matched_move | python | def parse_san(self, san: str) -> Move:
# Castling.
try:
if san in ["O-O", "O-O+", "O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_kingside_castling(move))
elif san in ["O-O-O", "O-O-O+", "O-O-O#"]:
return next(move for move in self.generate_castling_moves() if self.is_queenside_castling(move))
except StopIteration:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
# Match normal moves.
match = SAN_REGEX.match(san)
if not match:
# Null moves.
if san in ["--", "Z0"]:
return Move.null()
raise ValueError("invalid san: {!r}".format(san))
# Get target square.
to_square = SQUARE_NAMES.index(match.group(4))
to_mask = BB_SQUARES[to_square] & ~self.occupied_co[self.turn]
# Get the promotion type.
p = match.group(5)
promotion = p and PIECE_SYMBOLS.index(p[-1].lower())
# Filter by piece type.
if match.group(1):
piece_type = PIECE_SYMBOLS.index(match.group(1).lower())
from_mask = self.pieces_mask(piece_type, self.turn)
else:
from_mask = self.pawns
# Filter by source file.
if match.group(2):
from_mask &= BB_FILES[FILE_NAMES.index(match.group(2))]
# Filter by source rank.
if match.group(3):
from_mask &= BB_RANKS[int(match.group(3)) - 1]
# Match legal moves.
matched_move = None
for move in self.generate_legal_moves(from_mask, to_mask):
if move.promotion != promotion:
continue
if matched_move:
raise ValueError("ambiguous san: {!r} in {}".format(san, self.fen()))
matched_move = move
if not matched_move:
raise ValueError("illegal san: {!r} in {}".format(san, self.fen()))
return matched_move | [
"def",
"parse_san",
"(",
"self",
",",
"san",
":",
"str",
")",
"->",
"Move",
":",
"# Castling.",
"try",
":",
"if",
"san",
"in",
"[",
"\"O-O\"",
",",
"\"O-O+\"",
",",
"\"O-O#\"",
"]",
":",
"return",
"next",
"(",
"move",
"for",
"move",
"in",
"self",
"... | Uses the current position as the context to parse a move in standard
algebraic notation and returns the corresponding move object.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the SAN is invalid or ambiguous. | [
"Uses",
"the",
"current",
"position",
"as",
"the",
"context",
"to",
"parse",
"a",
"move",
"in",
"standard",
"algebraic",
"notation",
"and",
"returns",
"the",
"corresponding",
"move",
"object",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2698-L2762 |
238,715 | niklasf/python-chess | chess/__init__.py | Board.push_san | def push_san(self, san: str) -> Move:
"""
Parses a move in standard algebraic notation, makes the move and puts
it on the the move stack.
Returns the move.
:raises: :exc:`ValueError` if neither legal nor a null move.
"""
move = self.parse_san(san)
self.push(move)
return move | python | def push_san(self, san: str) -> Move:
move = self.parse_san(san)
self.push(move)
return move | [
"def",
"push_san",
"(",
"self",
",",
"san",
":",
"str",
")",
"->",
"Move",
":",
"move",
"=",
"self",
".",
"parse_san",
"(",
"san",
")",
"self",
".",
"push",
"(",
"move",
")",
"return",
"move"
] | Parses a move in standard algebraic notation, makes the move and puts
it on the the move stack.
Returns the move.
:raises: :exc:`ValueError` if neither legal nor a null move. | [
"Parses",
"a",
"move",
"in",
"standard",
"algebraic",
"notation",
"makes",
"the",
"move",
"and",
"puts",
"it",
"on",
"the",
"the",
"move",
"stack",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2764-L2775 |
238,716 | niklasf/python-chess | chess/__init__.py | Board.uci | def uci(self, move: Move, *, chess960: Optional[bool] = None) -> str:
"""
Gets the UCI notation of the move.
*chess960* defaults to the mode of the board. Pass ``True`` to force
Chess960 mode.
"""
if chess960 is None:
chess960 = self.chess960
move = self._to_chess960(move)
move = self._from_chess960(chess960, move.from_square, move.to_square, move.promotion, move.drop)
return move.uci() | python | def uci(self, move: Move, *, chess960: Optional[bool] = None) -> str:
if chess960 is None:
chess960 = self.chess960
move = self._to_chess960(move)
move = self._from_chess960(chess960, move.from_square, move.to_square, move.promotion, move.drop)
return move.uci() | [
"def",
"uci",
"(",
"self",
",",
"move",
":",
"Move",
",",
"*",
",",
"chess960",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
")",
"->",
"str",
":",
"if",
"chess960",
"is",
"None",
":",
"chess960",
"=",
"self",
".",
"chess960",
"move",
"=",
"se... | Gets the UCI notation of the move.
*chess960* defaults to the mode of the board. Pass ``True`` to force
Chess960 mode. | [
"Gets",
"the",
"UCI",
"notation",
"of",
"the",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2777-L2789 |
238,717 | niklasf/python-chess | chess/__init__.py | Board.parse_uci | def parse_uci(self, uci: str) -> Move:
"""
Parses the given move in UCI notation.
Supports both Chess960 and standard UCI notation.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move).
"""
move = Move.from_uci(uci)
if not move:
return move
move = self._to_chess960(move)
move = self._from_chess960(self.chess960, move.from_square, move.to_square, move.promotion, move.drop)
if not self.is_legal(move):
raise ValueError("illegal uci: {!r} in {}".format(uci, self.fen()))
return move | python | def parse_uci(self, uci: str) -> Move:
move = Move.from_uci(uci)
if not move:
return move
move = self._to_chess960(move)
move = self._from_chess960(self.chess960, move.from_square, move.to_square, move.promotion, move.drop)
if not self.is_legal(move):
raise ValueError("illegal uci: {!r} in {}".format(uci, self.fen()))
return move | [
"def",
"parse_uci",
"(",
"self",
",",
"uci",
":",
"str",
")",
"->",
"Move",
":",
"move",
"=",
"Move",
".",
"from_uci",
"(",
"uci",
")",
"if",
"not",
"move",
":",
"return",
"move",
"move",
"=",
"self",
".",
"_to_chess960",
"(",
"move",
")",
"move",
... | Parses the given move in UCI notation.
Supports both Chess960 and standard UCI notation.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move). | [
"Parses",
"the",
"given",
"move",
"in",
"UCI",
"notation",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2791-L2813 |
238,718 | niklasf/python-chess | chess/__init__.py | Board.push_uci | def push_uci(self, uci: str) -> Move:
"""
Parses a move in UCI notation and puts it on the move stack.
Returns the move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move).
"""
move = self.parse_uci(uci)
self.push(move)
return move | python | def push_uci(self, uci: str) -> Move:
move = self.parse_uci(uci)
self.push(move)
return move | [
"def",
"push_uci",
"(",
"self",
",",
"uci",
":",
"str",
")",
"->",
"Move",
":",
"move",
"=",
"self",
".",
"parse_uci",
"(",
"uci",
")",
"self",
".",
"push",
"(",
"move",
")",
"return",
"move"
] | Parses a move in UCI notation and puts it on the move stack.
Returns the move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move). | [
"Parses",
"a",
"move",
"in",
"UCI",
"notation",
"and",
"puts",
"it",
"on",
"the",
"move",
"stack",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2815-L2826 |
238,719 | niklasf/python-chess | chess/__init__.py | Board.is_en_passant | def is_en_passant(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is an en passant capture."""
return (self.ep_square == move.to_square and
bool(self.pawns & BB_SQUARES[move.from_square]) and
abs(move.to_square - move.from_square) in [7, 9] and
not self.occupied & BB_SQUARES[move.to_square]) | python | def is_en_passant(self, move: Move) -> bool:
return (self.ep_square == move.to_square and
bool(self.pawns & BB_SQUARES[move.from_square]) and
abs(move.to_square - move.from_square) in [7, 9] and
not self.occupied & BB_SQUARES[move.to_square]) | [
"def",
"is_en_passant",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"return",
"(",
"self",
".",
"ep_square",
"==",
"move",
".",
"to_square",
"and",
"bool",
"(",
"self",
".",
"pawns",
"&",
"BB_SQUARES",
"[",
"move",
".",
"from_square"... | Checks if the given pseudo-legal move is an en passant capture. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"an",
"en",
"passant",
"capture",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2865-L2870 |
238,720 | niklasf/python-chess | chess/__init__.py | Board.is_capture | def is_capture(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is a capture."""
return bool(BB_SQUARES[move.to_square] & self.occupied_co[not self.turn]) or self.is_en_passant(move) | python | def is_capture(self, move: Move) -> bool:
return bool(BB_SQUARES[move.to_square] & self.occupied_co[not self.turn]) or self.is_en_passant(move) | [
"def",
"is_capture",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"BB_SQUARES",
"[",
"move",
".",
"to_square",
"]",
"&",
"self",
".",
"occupied_co",
"[",
"not",
"self",
".",
"turn",
"]",
")",
"or",
"self",
"... | Checks if the given pseudo-legal move is a capture. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"a",
"capture",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2872-L2874 |
238,721 | niklasf/python-chess | chess/__init__.py | Board.is_zeroing | def is_zeroing(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is a capture or pawn move."""
return bool(BB_SQUARES[move.from_square] & self.pawns or BB_SQUARES[move.to_square] & self.occupied_co[not self.turn]) | python | def is_zeroing(self, move: Move) -> bool:
return bool(BB_SQUARES[move.from_square] & self.pawns or BB_SQUARES[move.to_square] & self.occupied_co[not self.turn]) | [
"def",
"is_zeroing",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"BB_SQUARES",
"[",
"move",
".",
"from_square",
"]",
"&",
"self",
".",
"pawns",
"or",
"BB_SQUARES",
"[",
"move",
".",
"to_square",
"]",
"&",
"se... | Checks if the given pseudo-legal move is a capture or pawn move. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"a",
"capture",
"or",
"pawn",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2876-L2878 |
238,722 | niklasf/python-chess | chess/__init__.py | Board.is_irreversible | def is_irreversible(self, move: Move) -> bool:
"""
Checks if the given pseudo-legal move is irreversible.
In standard chess, pawn moves, captures and moves that destroy castling
rights are irreversible.
"""
backrank = BB_RANK_1 if self.turn == WHITE else BB_RANK_8
cr = self.clean_castling_rights() & backrank
return bool(self.is_zeroing(move) or
cr and BB_SQUARES[move.from_square] & self.kings & ~self.promoted or
cr & BB_SQUARES[move.from_square] or
cr & BB_SQUARES[move.to_square]) | python | def is_irreversible(self, move: Move) -> bool:
backrank = BB_RANK_1 if self.turn == WHITE else BB_RANK_8
cr = self.clean_castling_rights() & backrank
return bool(self.is_zeroing(move) or
cr and BB_SQUARES[move.from_square] & self.kings & ~self.promoted or
cr & BB_SQUARES[move.from_square] or
cr & BB_SQUARES[move.to_square]) | [
"def",
"is_irreversible",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"backrank",
"=",
"BB_RANK_1",
"if",
"self",
".",
"turn",
"==",
"WHITE",
"else",
"BB_RANK_8",
"cr",
"=",
"self",
".",
"clean_castling_rights",
"(",
")",
"&",
"backran... | Checks if the given pseudo-legal move is irreversible.
In standard chess, pawn moves, captures and moves that destroy castling
rights are irreversible. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"irreversible",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2880-L2892 |
238,723 | niklasf/python-chess | chess/__init__.py | Board.is_castling | def is_castling(self, move: Move) -> bool:
"""Checks if the given pseudo-legal move is a castling move."""
if self.kings & BB_SQUARES[move.from_square]:
diff = square_file(move.from_square) - square_file(move.to_square)
return abs(diff) > 1 or bool(self.rooks & self.occupied_co[self.turn] & BB_SQUARES[move.to_square])
return False | python | def is_castling(self, move: Move) -> bool:
if self.kings & BB_SQUARES[move.from_square]:
diff = square_file(move.from_square) - square_file(move.to_square)
return abs(diff) > 1 or bool(self.rooks & self.occupied_co[self.turn] & BB_SQUARES[move.to_square])
return False | [
"def",
"is_castling",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"if",
"self",
".",
"kings",
"&",
"BB_SQUARES",
"[",
"move",
".",
"from_square",
"]",
":",
"diff",
"=",
"square_file",
"(",
"move",
".",
"from_square",
")",
"-",
"squ... | Checks if the given pseudo-legal move is a castling move. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"a",
"castling",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2894-L2899 |
238,724 | niklasf/python-chess | chess/__init__.py | Board.is_kingside_castling | def is_kingside_castling(self, move: Move) -> bool:
"""
Checks if the given pseudo-legal move is a kingside castling move.
"""
return self.is_castling(move) and square_file(move.to_square) > square_file(move.from_square) | python | def is_kingside_castling(self, move: Move) -> bool:
return self.is_castling(move) and square_file(move.to_square) > square_file(move.from_square) | [
"def",
"is_kingside_castling",
"(",
"self",
",",
"move",
":",
"Move",
")",
"->",
"bool",
":",
"return",
"self",
".",
"is_castling",
"(",
"move",
")",
"and",
"square_file",
"(",
"move",
".",
"to_square",
")",
">",
"square_file",
"(",
"move",
".",
"from_sq... | Checks if the given pseudo-legal move is a kingside castling move. | [
"Checks",
"if",
"the",
"given",
"pseudo",
"-",
"legal",
"move",
"is",
"a",
"kingside",
"castling",
"move",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2901-L2905 |
238,725 | niklasf/python-chess | chess/__init__.py | Board.has_castling_rights | def has_castling_rights(self, color: Color) -> bool:
"""Checks if the given side has castling rights."""
backrank = BB_RANK_1 if color == WHITE else BB_RANK_8
return bool(self.clean_castling_rights() & backrank) | python | def has_castling_rights(self, color: Color) -> bool:
backrank = BB_RANK_1 if color == WHITE else BB_RANK_8
return bool(self.clean_castling_rights() & backrank) | [
"def",
"has_castling_rights",
"(",
"self",
",",
"color",
":",
"Color",
")",
"->",
"bool",
":",
"backrank",
"=",
"BB_RANK_1",
"if",
"color",
"==",
"WHITE",
"else",
"BB_RANK_8",
"return",
"bool",
"(",
"self",
".",
"clean_castling_rights",
"(",
")",
"&",
"bac... | Checks if the given side has castling rights. | [
"Checks",
"if",
"the",
"given",
"side",
"has",
"castling",
"rights",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2969-L2972 |
238,726 | niklasf/python-chess | chess/__init__.py | Board.has_chess960_castling_rights | def has_chess960_castling_rights(self) -> bool:
"""
Checks if there are castling rights that are only possible in Chess960.
"""
# Get valid Chess960 castling rights.
chess960 = self.chess960
self.chess960 = True
castling_rights = self.clean_castling_rights()
self.chess960 = chess960
# Standard chess castling rights can only be on the standard
# starting rook squares.
if castling_rights & ~BB_CORNERS:
return True
# If there are any castling rights in standard chess, the king must be
# on e1 or e8.
if castling_rights & BB_RANK_1 and not self.occupied_co[WHITE] & self.kings & BB_E1:
return True
if castling_rights & BB_RANK_8 and not self.occupied_co[BLACK] & self.kings & BB_E8:
return True
return False | python | def has_chess960_castling_rights(self) -> bool:
# Get valid Chess960 castling rights.
chess960 = self.chess960
self.chess960 = True
castling_rights = self.clean_castling_rights()
self.chess960 = chess960
# Standard chess castling rights can only be on the standard
# starting rook squares.
if castling_rights & ~BB_CORNERS:
return True
# If there are any castling rights in standard chess, the king must be
# on e1 or e8.
if castling_rights & BB_RANK_1 and not self.occupied_co[WHITE] & self.kings & BB_E1:
return True
if castling_rights & BB_RANK_8 and not self.occupied_co[BLACK] & self.kings & BB_E8:
return True
return False | [
"def",
"has_chess960_castling_rights",
"(",
"self",
")",
"->",
"bool",
":",
"# Get valid Chess960 castling rights.",
"chess960",
"=",
"self",
".",
"chess960",
"self",
".",
"chess960",
"=",
"True",
"castling_rights",
"=",
"self",
".",
"clean_castling_rights",
"(",
")... | Checks if there are castling rights that are only possible in Chess960. | [
"Checks",
"if",
"there",
"are",
"castling",
"rights",
"that",
"are",
"only",
"possible",
"in",
"Chess960",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3016-L3038 |
238,727 | niklasf/python-chess | chess/__init__.py | Board.status | def status(self) -> Status:
"""
Gets a bitmask of possible problems with the position.
Move making, generation and validation are only guaranteed to work on
a completely valid board.
:data:`~chess.STATUS_VALID` for a completely valid board.
Otherwise, bitwise combinations of:
:data:`~chess.STATUS_NO_WHITE_KING`,
:data:`~chess.STATUS_NO_BLACK_KING`,
:data:`~chess.STATUS_TOO_MANY_KINGS`,
:data:`~chess.STATUS_TOO_MANY_WHITE_PAWNS`,
:data:`~chess.STATUS_TOO_MANY_BLACK_PAWNS`,
:data:`~chess.STATUS_PAWNS_ON_BACKRANK`,
:data:`~chess.STATUS_TOO_MANY_WHITE_PIECES`,
:data:`~chess.STATUS_TOO_MANY_BLACK_PIECES`,
:data:`~chess.STATUS_BAD_CASTLING_RIGHTS`,
:data:`~chess.STATUS_INVALID_EP_SQUARE`,
:data:`~chess.STATUS_OPPOSITE_CHECK`,
:data:`~chess.STATUS_EMPTY`,
:data:`~chess.STATUS_RACE_CHECK`,
:data:`~chess.STATUS_RACE_OVER`,
:data:`~chess.STATUS_RACE_MATERIAL`.
"""
errors = STATUS_VALID
# There must be at least one piece.
if not self.occupied:
errors |= STATUS_EMPTY
# There must be exactly one king of each color.
if not self.occupied_co[WHITE] & self.kings:
errors |= STATUS_NO_WHITE_KING
if not self.occupied_co[BLACK] & self.kings:
errors |= STATUS_NO_BLACK_KING
if popcount(self.occupied & self.kings) > 2:
errors |= STATUS_TOO_MANY_KINGS
# There can not be more than 16 pieces of any color.
if popcount(self.occupied_co[WHITE]) > 16:
errors |= STATUS_TOO_MANY_WHITE_PIECES
if popcount(self.occupied_co[BLACK]) > 16:
errors |= STATUS_TOO_MANY_BLACK_PIECES
# There can not be more than 8 pawns of any color.
if popcount(self.occupied_co[WHITE] & self.pawns) > 8:
errors |= STATUS_TOO_MANY_WHITE_PAWNS
if popcount(self.occupied_co[BLACK] & self.pawns) > 8:
errors |= STATUS_TOO_MANY_BLACK_PAWNS
# Pawns can not be on the back rank.
if self.pawns & BB_BACKRANKS:
errors |= STATUS_PAWNS_ON_BACKRANK
# Castling rights.
if self.castling_rights != self.clean_castling_rights():
errors |= STATUS_BAD_CASTLING_RIGHTS
# En passant.
if self.ep_square != self._valid_ep_square():
errors |= STATUS_INVALID_EP_SQUARE
# Side to move giving check.
if self.was_into_check():
errors |= STATUS_OPPOSITE_CHECK
return errors | python | def status(self) -> Status:
errors = STATUS_VALID
# There must be at least one piece.
if not self.occupied:
errors |= STATUS_EMPTY
# There must be exactly one king of each color.
if not self.occupied_co[WHITE] & self.kings:
errors |= STATUS_NO_WHITE_KING
if not self.occupied_co[BLACK] & self.kings:
errors |= STATUS_NO_BLACK_KING
if popcount(self.occupied & self.kings) > 2:
errors |= STATUS_TOO_MANY_KINGS
# There can not be more than 16 pieces of any color.
if popcount(self.occupied_co[WHITE]) > 16:
errors |= STATUS_TOO_MANY_WHITE_PIECES
if popcount(self.occupied_co[BLACK]) > 16:
errors |= STATUS_TOO_MANY_BLACK_PIECES
# There can not be more than 8 pawns of any color.
if popcount(self.occupied_co[WHITE] & self.pawns) > 8:
errors |= STATUS_TOO_MANY_WHITE_PAWNS
if popcount(self.occupied_co[BLACK] & self.pawns) > 8:
errors |= STATUS_TOO_MANY_BLACK_PAWNS
# Pawns can not be on the back rank.
if self.pawns & BB_BACKRANKS:
errors |= STATUS_PAWNS_ON_BACKRANK
# Castling rights.
if self.castling_rights != self.clean_castling_rights():
errors |= STATUS_BAD_CASTLING_RIGHTS
# En passant.
if self.ep_square != self._valid_ep_square():
errors |= STATUS_INVALID_EP_SQUARE
# Side to move giving check.
if self.was_into_check():
errors |= STATUS_OPPOSITE_CHECK
return errors | [
"def",
"status",
"(",
"self",
")",
"->",
"Status",
":",
"errors",
"=",
"STATUS_VALID",
"# There must be at least one piece.",
"if",
"not",
"self",
".",
"occupied",
":",
"errors",
"|=",
"STATUS_EMPTY",
"# There must be exactly one king of each color.",
"if",
"not",
"se... | Gets a bitmask of possible problems with the position.
Move making, generation and validation are only guaranteed to work on
a completely valid board.
:data:`~chess.STATUS_VALID` for a completely valid board.
Otherwise, bitwise combinations of:
:data:`~chess.STATUS_NO_WHITE_KING`,
:data:`~chess.STATUS_NO_BLACK_KING`,
:data:`~chess.STATUS_TOO_MANY_KINGS`,
:data:`~chess.STATUS_TOO_MANY_WHITE_PAWNS`,
:data:`~chess.STATUS_TOO_MANY_BLACK_PAWNS`,
:data:`~chess.STATUS_PAWNS_ON_BACKRANK`,
:data:`~chess.STATUS_TOO_MANY_WHITE_PIECES`,
:data:`~chess.STATUS_TOO_MANY_BLACK_PIECES`,
:data:`~chess.STATUS_BAD_CASTLING_RIGHTS`,
:data:`~chess.STATUS_INVALID_EP_SQUARE`,
:data:`~chess.STATUS_OPPOSITE_CHECK`,
:data:`~chess.STATUS_EMPTY`,
:data:`~chess.STATUS_RACE_CHECK`,
:data:`~chess.STATUS_RACE_OVER`,
:data:`~chess.STATUS_RACE_MATERIAL`. | [
"Gets",
"a",
"bitmask",
"of",
"possible",
"problems",
"with",
"the",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3040-L3108 |
238,728 | niklasf/python-chess | chess/__init__.py | SquareSet.remove | def remove(self, square: Square) -> None:
"""
Removes a square from the set.
:raises: :exc:`KeyError` if the given square was not in the set.
"""
mask = BB_SQUARES[square]
if self.mask & mask:
self.mask ^= mask
else:
raise KeyError(square) | python | def remove(self, square: Square) -> None:
mask = BB_SQUARES[square]
if self.mask & mask:
self.mask ^= mask
else:
raise KeyError(square) | [
"def",
"remove",
"(",
"self",
",",
"square",
":",
"Square",
")",
"->",
"None",
":",
"mask",
"=",
"BB_SQUARES",
"[",
"square",
"]",
"if",
"self",
".",
"mask",
"&",
"mask",
":",
"self",
".",
"mask",
"^=",
"mask",
"else",
":",
"raise",
"KeyError",
"("... | Removes a square from the set.
:raises: :exc:`KeyError` if the given square was not in the set. | [
"Removes",
"a",
"square",
"from",
"the",
"set",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3695-L3705 |
238,729 | niklasf/python-chess | chess/__init__.py | SquareSet.pop | def pop(self) -> Square:
"""
Removes a square from the set and returns it.
:raises: :exc:`KeyError` on an empty set.
"""
if not self.mask:
raise KeyError("pop from empty SquareSet")
square = lsb(self.mask)
self.mask &= (self.mask - 1)
return square | python | def pop(self) -> Square:
if not self.mask:
raise KeyError("pop from empty SquareSet")
square = lsb(self.mask)
self.mask &= (self.mask - 1)
return square | [
"def",
"pop",
"(",
"self",
")",
"->",
"Square",
":",
"if",
"not",
"self",
".",
"mask",
":",
"raise",
"KeyError",
"(",
"\"pop from empty SquareSet\"",
")",
"square",
"=",
"lsb",
"(",
"self",
".",
"mask",
")",
"self",
".",
"mask",
"&=",
"(",
"self",
".... | Removes a square from the set and returns it.
:raises: :exc:`KeyError` on an empty set. | [
"Removes",
"a",
"square",
"from",
"the",
"set",
"and",
"returns",
"it",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3707-L3718 |
238,730 | niklasf/python-chess | chess/__init__.py | SquareSet.tolist | def tolist(self) -> List[bool]:
"""Convert the set to a list of 64 bools."""
result = [False] * 64
for square in self:
result[square] = True
return result | python | def tolist(self) -> List[bool]:
result = [False] * 64
for square in self:
result[square] = True
return result | [
"def",
"tolist",
"(",
"self",
")",
"->",
"List",
"[",
"bool",
"]",
":",
"result",
"=",
"[",
"False",
"]",
"*",
"64",
"for",
"square",
"in",
"self",
":",
"result",
"[",
"square",
"]",
"=",
"True",
"return",
"result"
] | Convert the set to a list of 64 bools. | [
"Convert",
"the",
"set",
"to",
"a",
"list",
"of",
"64",
"bools",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3734-L3739 |
238,731 | niklasf/python-chess | chess/variant.py | find_variant | def find_variant(name: str) -> Type[chess.Board]:
"""Looks for a variant board class by variant name."""
for variant in VARIANTS:
if any(alias.lower() == name.lower() for alias in variant.aliases):
return variant
raise ValueError("unsupported variant: {}".format(name)) | python | def find_variant(name: str) -> Type[chess.Board]:
for variant in VARIANTS:
if any(alias.lower() == name.lower() for alias in variant.aliases):
return variant
raise ValueError("unsupported variant: {}".format(name)) | [
"def",
"find_variant",
"(",
"name",
":",
"str",
")",
"->",
"Type",
"[",
"chess",
".",
"Board",
"]",
":",
"for",
"variant",
"in",
"VARIANTS",
":",
"if",
"any",
"(",
"alias",
".",
"lower",
"(",
")",
"==",
"name",
".",
"lower",
"(",
")",
"for",
"ali... | Looks for a variant board class by variant name. | [
"Looks",
"for",
"a",
"variant",
"board",
"class",
"by",
"variant",
"name",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/variant.py#L862-L867 |
238,732 | niklasf/python-chess | chess/polyglot.py | zobrist_hash | def zobrist_hash(board: chess.Board, *, _hasher: Callable[[chess.Board], int] = ZobristHasher(POLYGLOT_RANDOM_ARRAY)) -> int:
"""
Calculates the Polyglot Zobrist hash of the position.
A Zobrist hash is an XOR of pseudo-random values picked from
an array. Which values are picked is decided by features of the
position, such as piece positions, castling rights and en passant
squares.
"""
return _hasher(board) | python | def zobrist_hash(board: chess.Board, *, _hasher: Callable[[chess.Board], int] = ZobristHasher(POLYGLOT_RANDOM_ARRAY)) -> int:
return _hasher(board) | [
"def",
"zobrist_hash",
"(",
"board",
":",
"chess",
".",
"Board",
",",
"*",
",",
"_hasher",
":",
"Callable",
"[",
"[",
"chess",
".",
"Board",
"]",
",",
"int",
"]",
"=",
"ZobristHasher",
"(",
"POLYGLOT_RANDOM_ARRAY",
")",
")",
"->",
"int",
":",
"return",... | Calculates the Polyglot Zobrist hash of the position.
A Zobrist hash is an XOR of pseudo-random values picked from
an array. Which values are picked is decided by features of the
position, such as piece positions, castling rights and en passant
squares. | [
"Calculates",
"the",
"Polyglot",
"Zobrist",
"hash",
"of",
"the",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L291-L300 |
238,733 | niklasf/python-chess | chess/polyglot.py | MemoryMappedReader.find_all | def find_all(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = ()) -> Iterator[Entry]:
"""Seeks a specific position and yields corresponding entries."""
try:
key = int(board) # type: ignore
context = None # type: Optional[chess.Board]
except (TypeError, ValueError):
context = typing.cast(chess.Board, board)
key = zobrist_hash(context)
i = self.bisect_key_left(key)
size = len(self)
while i < size:
entry = self[i]
i += 1
if entry.key != key:
break
if entry.weight < minimum_weight:
continue
if context:
move = context._from_chess960(context.chess960, entry.move.from_square, entry.move.to_square, entry.move.promotion, entry.move.drop)
entry = Entry(entry.key, entry.raw_move, entry.weight, entry.learn, move)
if exclude_moves and entry.move in exclude_moves:
continue
if context and not context.is_legal(entry.move):
continue
yield entry | python | def find_all(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = ()) -> Iterator[Entry]:
try:
key = int(board) # type: ignore
context = None # type: Optional[chess.Board]
except (TypeError, ValueError):
context = typing.cast(chess.Board, board)
key = zobrist_hash(context)
i = self.bisect_key_left(key)
size = len(self)
while i < size:
entry = self[i]
i += 1
if entry.key != key:
break
if entry.weight < minimum_weight:
continue
if context:
move = context._from_chess960(context.chess960, entry.move.from_square, entry.move.to_square, entry.move.promotion, entry.move.drop)
entry = Entry(entry.key, entry.raw_move, entry.weight, entry.learn, move)
if exclude_moves and entry.move in exclude_moves:
continue
if context and not context.is_legal(entry.move):
continue
yield entry | [
"def",
"find_all",
"(",
"self",
",",
"board",
":",
"Union",
"[",
"chess",
".",
"Board",
",",
"int",
"]",
",",
"*",
",",
"minimum_weight",
":",
"int",
"=",
"1",
",",
"exclude_moves",
":",
"Container",
"[",
"chess",
".",
"Move",
"]",
"=",
"(",
")",
... | Seeks a specific position and yields corresponding entries. | [
"Seeks",
"a",
"specific",
"position",
"and",
"yields",
"corresponding",
"entries",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L387-L419 |
238,734 | niklasf/python-chess | chess/polyglot.py | MemoryMappedReader.find | def find(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = ()) -> Entry:
"""
Finds the main entry for the given position or Zobrist hash.
The main entry is the (first) entry with the highest weight.
By default, entries with weight ``0`` are excluded. This is a common
way to delete entries from an opening book without compacting it. Pass
*minimum_weight* ``0`` to select all entries.
:raises: :exc:`IndexError` if no entries are found. Use
:func:`~chess.polyglot.MemoryMappedReader.get()` if you prefer to
get ``None`` instead of an exception.
"""
try:
return max(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves), key=lambda entry: entry.weight)
except ValueError:
raise IndexError() | python | def find(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = ()) -> Entry:
try:
return max(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves), key=lambda entry: entry.weight)
except ValueError:
raise IndexError() | [
"def",
"find",
"(",
"self",
",",
"board",
":",
"Union",
"[",
"chess",
".",
"Board",
",",
"int",
"]",
",",
"*",
",",
"minimum_weight",
":",
"int",
"=",
"1",
",",
"exclude_moves",
":",
"Container",
"[",
"chess",
".",
"Move",
"]",
"=",
"(",
")",
")"... | Finds the main entry for the given position or Zobrist hash.
The main entry is the (first) entry with the highest weight.
By default, entries with weight ``0`` are excluded. This is a common
way to delete entries from an opening book without compacting it. Pass
*minimum_weight* ``0`` to select all entries.
:raises: :exc:`IndexError` if no entries are found. Use
:func:`~chess.polyglot.MemoryMappedReader.get()` if you prefer to
get ``None`` instead of an exception. | [
"Finds",
"the",
"main",
"entry",
"for",
"the",
"given",
"position",
"or",
"Zobrist",
"hash",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L421-L438 |
238,735 | niklasf/python-chess | chess/polyglot.py | MemoryMappedReader.choice | def choice(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:
"""
Uniformly selects a random entry for the given position.
:raises: :exc:`IndexError` if no entries are found.
"""
chosen_entry = None
for i, entry in enumerate(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves)):
if chosen_entry is None or random.randint(0, i) == i:
chosen_entry = entry
if chosen_entry is None:
raise IndexError()
return chosen_entry | python | def choice(self, board: Union[chess.Board, int], *, minimum_weight: int = 1, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:
chosen_entry = None
for i, entry in enumerate(self.find_all(board, minimum_weight=minimum_weight, exclude_moves=exclude_moves)):
if chosen_entry is None or random.randint(0, i) == i:
chosen_entry = entry
if chosen_entry is None:
raise IndexError()
return chosen_entry | [
"def",
"choice",
"(",
"self",
",",
"board",
":",
"Union",
"[",
"chess",
".",
"Board",
",",
"int",
"]",
",",
"*",
",",
"minimum_weight",
":",
"int",
"=",
"1",
",",
"exclude_moves",
":",
"Container",
"[",
"chess",
".",
"Move",
"]",
"=",
"(",
")",
"... | Uniformly selects a random entry for the given position.
:raises: :exc:`IndexError` if no entries are found. | [
"Uniformly",
"selects",
"a",
"random",
"entry",
"for",
"the",
"given",
"position",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L446-L461 |
238,736 | niklasf/python-chess | chess/polyglot.py | MemoryMappedReader.weighted_choice | def weighted_choice(self, board: Union[chess.Board, int], *, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:
"""
Selects a random entry for the given position, distributed by the
weights of the entries.
:raises: :exc:`IndexError` if no entries are found.
"""
total_weights = sum(entry.weight for entry in self.find_all(board, exclude_moves=exclude_moves))
if not total_weights:
raise IndexError()
choice = random.randint(0, total_weights - 1)
current_sum = 0
for entry in self.find_all(board, exclude_moves=exclude_moves):
current_sum += entry.weight
if current_sum > choice:
return entry
assert False | python | def weighted_choice(self, board: Union[chess.Board, int], *, exclude_moves: Container[chess.Move] = (), random=random) -> Entry:
total_weights = sum(entry.weight for entry in self.find_all(board, exclude_moves=exclude_moves))
if not total_weights:
raise IndexError()
choice = random.randint(0, total_weights - 1)
current_sum = 0
for entry in self.find_all(board, exclude_moves=exclude_moves):
current_sum += entry.weight
if current_sum > choice:
return entry
assert False | [
"def",
"weighted_choice",
"(",
"self",
",",
"board",
":",
"Union",
"[",
"chess",
".",
"Board",
",",
"int",
"]",
",",
"*",
",",
"exclude_moves",
":",
"Container",
"[",
"chess",
".",
"Move",
"]",
"=",
"(",
")",
",",
"random",
"=",
"random",
")",
"->"... | Selects a random entry for the given position, distributed by the
weights of the entries.
:raises: :exc:`IndexError` if no entries are found. | [
"Selects",
"a",
"random",
"entry",
"for",
"the",
"given",
"position",
"distributed",
"by",
"the",
"weights",
"of",
"the",
"entries",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L463-L482 |
238,737 | niklasf/python-chess | chess/polyglot.py | MemoryMappedReader.close | def close(self) -> None:
"""Closes the reader."""
if self.mmap is not None:
self.mmap.close()
try:
os.close(self.fd)
except OSError:
pass | python | def close(self) -> None:
if self.mmap is not None:
self.mmap.close()
try:
os.close(self.fd)
except OSError:
pass | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"mmap",
"is",
"not",
"None",
":",
"self",
".",
"mmap",
".",
"close",
"(",
")",
"try",
":",
"os",
".",
"close",
"(",
"self",
".",
"fd",
")",
"except",
"OSError",
":",
"pass"... | Closes the reader. | [
"Closes",
"the",
"reader",
"."
] | d91f986ca3e046b300a0d7d9ee2a13b07610fe1a | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/polyglot.py#L484-L492 |
238,738 | mapbox/mapbox-sdk-py | mapbox/encoding.py | _geom_points | def _geom_points(geom):
"""GeoJSON geometry to a sequence of point tuples
"""
if geom['type'] == 'Point':
yield tuple(geom['coordinates'])
elif geom['type'] in ('MultiPoint', 'LineString'):
for position in geom['coordinates']:
yield tuple(position)
else:
raise InvalidFeatureError(
"Unsupported geometry type:{0}".format(geom['type'])) | python | def _geom_points(geom):
if geom['type'] == 'Point':
yield tuple(geom['coordinates'])
elif geom['type'] in ('MultiPoint', 'LineString'):
for position in geom['coordinates']:
yield tuple(position)
else:
raise InvalidFeatureError(
"Unsupported geometry type:{0}".format(geom['type'])) | [
"def",
"_geom_points",
"(",
"geom",
")",
":",
"if",
"geom",
"[",
"'type'",
"]",
"==",
"'Point'",
":",
"yield",
"tuple",
"(",
"geom",
"[",
"'coordinates'",
"]",
")",
"elif",
"geom",
"[",
"'type'",
"]",
"in",
"(",
"'MultiPoint'",
",",
"'LineString'",
")"... | GeoJSON geometry to a sequence of point tuples | [
"GeoJSON",
"geometry",
"to",
"a",
"sequence",
"of",
"point",
"tuples"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/encoding.py#L7-L17 |
238,739 | mapbox/mapbox-sdk-py | mapbox/encoding.py | read_points | def read_points(features):
""" Iterable of features to a sequence of point tuples
Where "features" can be either GeoJSON mappings
or objects implementing the geo_interface
"""
for feature in features:
if isinstance(feature, (tuple, list)) and len(feature) == 2:
yield feature
elif hasattr(feature, '__geo_interface__'):
# An object implementing the geo_interface
try:
# Could be a Feature...
geom = feature.__geo_interface__['geometry']
for pt in _geom_points(geom):
yield pt
except KeyError:
# ... or a geometry directly
for pt in _geom_points(feature.__geo_interface__):
yield pt
elif 'type' in feature and feature['type'] == 'Feature':
# A GeoJSON-like mapping
geom = feature['geometry']
for pt in _geom_points(geom):
yield pt
elif 'coordinates' in feature:
geom = feature
for pt in _geom_points(geom):
yield pt
else:
raise InvalidFeatureError(
"Unknown object: Not a GeoJSON Point feature or "
"an object with __geo_interface__:\n{0}".format(feature)) | python | def read_points(features):
for feature in features:
if isinstance(feature, (tuple, list)) and len(feature) == 2:
yield feature
elif hasattr(feature, '__geo_interface__'):
# An object implementing the geo_interface
try:
# Could be a Feature...
geom = feature.__geo_interface__['geometry']
for pt in _geom_points(geom):
yield pt
except KeyError:
# ... or a geometry directly
for pt in _geom_points(feature.__geo_interface__):
yield pt
elif 'type' in feature and feature['type'] == 'Feature':
# A GeoJSON-like mapping
geom = feature['geometry']
for pt in _geom_points(geom):
yield pt
elif 'coordinates' in feature:
geom = feature
for pt in _geom_points(geom):
yield pt
else:
raise InvalidFeatureError(
"Unknown object: Not a GeoJSON Point feature or "
"an object with __geo_interface__:\n{0}".format(feature)) | [
"def",
"read_points",
"(",
"features",
")",
":",
"for",
"feature",
"in",
"features",
":",
"if",
"isinstance",
"(",
"feature",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"len",
"(",
"feature",
")",
"==",
"2",
":",
"yield",
"feature",
"elif",
"ha... | Iterable of features to a sequence of point tuples
Where "features" can be either GeoJSON mappings
or objects implementing the geo_interface | [
"Iterable",
"of",
"features",
"to",
"a",
"sequence",
"of",
"point",
"tuples",
"Where",
"features",
"can",
"be",
"either",
"GeoJSON",
"mappings",
"or",
"objects",
"implementing",
"the",
"geo_interface"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/encoding.py#L20-L56 |
238,740 | mapbox/mapbox-sdk-py | mapbox/encoding.py | encode_polyline | def encode_polyline(features):
"""Encode and iterable of features as a polyline
"""
points = list(read_points(features))
latlon_points = [(x[1], x[0]) for x in points]
return polyline.encode(latlon_points) | python | def encode_polyline(features):
points = list(read_points(features))
latlon_points = [(x[1], x[0]) for x in points]
return polyline.encode(latlon_points) | [
"def",
"encode_polyline",
"(",
"features",
")",
":",
"points",
"=",
"list",
"(",
"read_points",
"(",
"features",
")",
")",
"latlon_points",
"=",
"[",
"(",
"x",
"[",
"1",
"]",
",",
"x",
"[",
"0",
"]",
")",
"for",
"x",
"in",
"points",
"]",
"return",
... | Encode and iterable of features as a polyline | [
"Encode",
"and",
"iterable",
"of",
"features",
"as",
"a",
"polyline"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/encoding.py#L81-L86 |
238,741 | mapbox/mapbox-sdk-py | mapbox/services/directions.py | Directions.directions | def directions(self, features, profile='mapbox/driving',
alternatives=None, geometries=None, overview=None, steps=None,
continue_straight=None, waypoint_snapping=None, annotations=None,
language=None, **kwargs):
"""Request directions for waypoints encoded as GeoJSON features.
Parameters
----------
features : iterable
An collection of GeoJSON features
profile : str
Name of a Mapbox profile such as 'mapbox.driving'
alternatives : bool
Whether to try to return alternative routes, default: False
geometries : string
Type of geometry returned (geojson, polyline, polyline6)
overview : string or False
Type of returned overview geometry: 'full', 'simplified',
or False
steps : bool
Whether to return steps and turn-by-turn instructions,
default: False
continue_straight : bool
Direction of travel when departing intermediate waypoints
radiuses : iterable of numbers or 'unlimited'
Must be same length as features
waypoint_snapping : list
Controls snapping of waypoints
The list is zipped with the features collection and must
have the same length. Elements of the list must be one of:
- A number (interpretted as a snapping radius)
- The string 'unlimited' (unlimited snapping radius)
- A 3-element tuple consisting of (radius, angle, range)
- None (no snapping parameters specified for that waypoint)
annotations : str
Whether or not to return additional metadata along the route
Possible values are: 'duration', 'distance', 'speed', and
'congestion'. Several annotations can be used by joining
them with ','.
language : str
Language of returned turn-by-turn text instructions,
default: 'en'
Returns
-------
requests.Response
The response object has a geojson() method for access to
the route(s) as a GeoJSON-like FeatureCollection
dictionary.
"""
# backwards compatible, deprecated
if 'geometry' in kwargs and geometries is None:
geometries = kwargs['geometry']
warnings.warn('Use `geometries` instead of `geometry`',
errors.MapboxDeprecationWarning)
annotations = self._validate_annotations(annotations)
coordinates = encode_coordinates(
features, precision=6, min_limit=2, max_limit=25)
geometries = self._validate_geom_encoding(geometries)
overview = self._validate_geom_overview(overview)
profile = self._validate_profile(profile)
bearings, radii = self._validate_snapping(waypoint_snapping, features)
params = {}
if alternatives is not None:
params.update(
{'alternatives': 'true' if alternatives is True else 'false'})
if geometries is not None:
params.update({'geometries': geometries})
if overview is not None:
params.update(
{'overview': 'false' if overview is False else overview})
if steps is not None:
params.update(
{'steps': 'true' if steps is True else 'false'})
if continue_straight is not None:
params.update(
{'continue_straight': 'true' if steps is True else 'false'})
if annotations is not None:
params.update({'annotations': ','.join(annotations)})
if language is not None:
params.update({'language': language})
if radii is not None:
params.update(
{'radiuses': ';'.join(str(r) for r in radii)})
if bearings is not None:
params.update(
{'bearings': ';'.join(self._encode_bearing(b) for b in bearings)})
profile_ns, profile_name = profile.split('/')
uri = URITemplate(
self.baseuri + '/{profile_ns}/{profile_name}/{coordinates}.json').expand(
profile_ns=profile_ns, profile_name=profile_name, coordinates=coordinates)
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
def geojson():
return self._geojson(resp.json(), geom_format=geometries)
resp.geojson = geojson
return resp | python | def directions(self, features, profile='mapbox/driving',
alternatives=None, geometries=None, overview=None, steps=None,
continue_straight=None, waypoint_snapping=None, annotations=None,
language=None, **kwargs):
# backwards compatible, deprecated
if 'geometry' in kwargs and geometries is None:
geometries = kwargs['geometry']
warnings.warn('Use `geometries` instead of `geometry`',
errors.MapboxDeprecationWarning)
annotations = self._validate_annotations(annotations)
coordinates = encode_coordinates(
features, precision=6, min_limit=2, max_limit=25)
geometries = self._validate_geom_encoding(geometries)
overview = self._validate_geom_overview(overview)
profile = self._validate_profile(profile)
bearings, radii = self._validate_snapping(waypoint_snapping, features)
params = {}
if alternatives is not None:
params.update(
{'alternatives': 'true' if alternatives is True else 'false'})
if geometries is not None:
params.update({'geometries': geometries})
if overview is not None:
params.update(
{'overview': 'false' if overview is False else overview})
if steps is not None:
params.update(
{'steps': 'true' if steps is True else 'false'})
if continue_straight is not None:
params.update(
{'continue_straight': 'true' if steps is True else 'false'})
if annotations is not None:
params.update({'annotations': ','.join(annotations)})
if language is not None:
params.update({'language': language})
if radii is not None:
params.update(
{'radiuses': ';'.join(str(r) for r in radii)})
if bearings is not None:
params.update(
{'bearings': ';'.join(self._encode_bearing(b) for b in bearings)})
profile_ns, profile_name = profile.split('/')
uri = URITemplate(
self.baseuri + '/{profile_ns}/{profile_name}/{coordinates}.json').expand(
profile_ns=profile_ns, profile_name=profile_name, coordinates=coordinates)
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
def geojson():
return self._geojson(resp.json(), geom_format=geometries)
resp.geojson = geojson
return resp | [
"def",
"directions",
"(",
"self",
",",
"features",
",",
"profile",
"=",
"'mapbox/driving'",
",",
"alternatives",
"=",
"None",
",",
"geometries",
"=",
"None",
",",
"overview",
"=",
"None",
",",
"steps",
"=",
"None",
",",
"continue_straight",
"=",
"None",
",... | Request directions for waypoints encoded as GeoJSON features.
Parameters
----------
features : iterable
An collection of GeoJSON features
profile : str
Name of a Mapbox profile such as 'mapbox.driving'
alternatives : bool
Whether to try to return alternative routes, default: False
geometries : string
Type of geometry returned (geojson, polyline, polyline6)
overview : string or False
Type of returned overview geometry: 'full', 'simplified',
or False
steps : bool
Whether to return steps and turn-by-turn instructions,
default: False
continue_straight : bool
Direction of travel when departing intermediate waypoints
radiuses : iterable of numbers or 'unlimited'
Must be same length as features
waypoint_snapping : list
Controls snapping of waypoints
The list is zipped with the features collection and must
have the same length. Elements of the list must be one of:
- A number (interpretted as a snapping radius)
- The string 'unlimited' (unlimited snapping radius)
- A 3-element tuple consisting of (radius, angle, range)
- None (no snapping parameters specified for that waypoint)
annotations : str
Whether or not to return additional metadata along the route
Possible values are: 'duration', 'distance', 'speed', and
'congestion'. Several annotations can be used by joining
them with ','.
language : str
Language of returned turn-by-turn text instructions,
default: 'en'
Returns
-------
requests.Response
The response object has a geojson() method for access to
the route(s) as a GeoJSON-like FeatureCollection
dictionary. | [
"Request",
"directions",
"for",
"waypoints",
"encoded",
"as",
"GeoJSON",
"features",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/directions.py#L143-L249 |
238,742 | mapbox/mapbox-sdk-py | mapbox/services/matrix.py | DirectionsMatrix.matrix | def matrix(self, coordinates, profile='mapbox/driving',
sources=None, destinations=None, annotations=None):
"""Request a directions matrix for trips between coordinates
In the default case, the matrix returns a symmetric matrix,
using all input coordinates as sources and destinations. You may
also generate an asymmetric matrix, with only some coordinates
as sources or destinations:
Parameters
----------
coordinates : sequence
A sequence of coordinates, which may be represented as
GeoJSON features, GeoJSON geometries, or (longitude,
latitude) pairs.
profile : str
The trip travel mode. Valid modes are listed in the class's
valid_profiles attribute.
annotations : list
Used to specify the resulting matrices. Possible values are
listed in the class's valid_annotations attribute.
sources : list
Indices of source coordinates to include in the matrix.
Default is all coordinates.
destinations : list
Indices of destination coordinates to include in the
matrix. Default is all coordinates.
Returns
-------
requests.Response
Note: the directions matrix itself is obtained by calling the
response's json() method. The resulting mapping has a code,
the destinations and the sources, and depending of the
annotations specified, it can also contain a durations matrix,
a distances matrix or both of them (by default, only the
durations matrix is provided).
code : str
Status of the response
sources : list
Results of snapping selected coordinates to the nearest
addresses.
destinations : list
Results of snapping selected coordinates to the nearest
addresses.
durations : list
An array of arrays representing the matrix in row-major
order. durations[i][j] gives the travel time from the i-th
source to the j-th destination. All values are in seconds.
The duration between the same coordinate is always 0. If
a duration can not be found, the result is null.
distances : list
An array of arrays representing the matrix in row-major
order. distances[i][j] gives the distance from the i-th
source to the j-th destination. All values are in meters.
The distance between the same coordinate is always 0. If
a distance can not be found, the result is null.
"""
annotations = self._validate_annotations(annotations)
profile = self._validate_profile(profile)
coords = encode_waypoints(coordinates)
params = self._make_query(sources, destinations)
if annotations is not None:
params.update({'annotations': ','.join(annotations)})
uri = '{0}/{1}/{2}'.format(self.baseuri, profile, coords)
res = self.session.get(uri, params=params)
self.handle_http_error(res)
return res | python | def matrix(self, coordinates, profile='mapbox/driving',
sources=None, destinations=None, annotations=None):
annotations = self._validate_annotations(annotations)
profile = self._validate_profile(profile)
coords = encode_waypoints(coordinates)
params = self._make_query(sources, destinations)
if annotations is not None:
params.update({'annotations': ','.join(annotations)})
uri = '{0}/{1}/{2}'.format(self.baseuri, profile, coords)
res = self.session.get(uri, params=params)
self.handle_http_error(res)
return res | [
"def",
"matrix",
"(",
"self",
",",
"coordinates",
",",
"profile",
"=",
"'mapbox/driving'",
",",
"sources",
"=",
"None",
",",
"destinations",
"=",
"None",
",",
"annotations",
"=",
"None",
")",
":",
"annotations",
"=",
"self",
".",
"_validate_annotations",
"("... | Request a directions matrix for trips between coordinates
In the default case, the matrix returns a symmetric matrix,
using all input coordinates as sources and destinations. You may
also generate an asymmetric matrix, with only some coordinates
as sources or destinations:
Parameters
----------
coordinates : sequence
A sequence of coordinates, which may be represented as
GeoJSON features, GeoJSON geometries, or (longitude,
latitude) pairs.
profile : str
The trip travel mode. Valid modes are listed in the class's
valid_profiles attribute.
annotations : list
Used to specify the resulting matrices. Possible values are
listed in the class's valid_annotations attribute.
sources : list
Indices of source coordinates to include in the matrix.
Default is all coordinates.
destinations : list
Indices of destination coordinates to include in the
matrix. Default is all coordinates.
Returns
-------
requests.Response
Note: the directions matrix itself is obtained by calling the
response's json() method. The resulting mapping has a code,
the destinations and the sources, and depending of the
annotations specified, it can also contain a durations matrix,
a distances matrix or both of them (by default, only the
durations matrix is provided).
code : str
Status of the response
sources : list
Results of snapping selected coordinates to the nearest
addresses.
destinations : list
Results of snapping selected coordinates to the nearest
addresses.
durations : list
An array of arrays representing the matrix in row-major
order. durations[i][j] gives the travel time from the i-th
source to the j-th destination. All values are in seconds.
The duration between the same coordinate is always 0. If
a duration can not be found, the result is null.
distances : list
An array of arrays representing the matrix in row-major
order. distances[i][j] gives the distance from the i-th
source to the j-th destination. All values are in meters.
The distance between the same coordinate is always 0. If
a distance can not be found, the result is null. | [
"Request",
"a",
"directions",
"matrix",
"for",
"trips",
"between",
"coordinates"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/matrix.py#L65-L138 |
238,743 | mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets._attribs | def _attribs(self, name=None, description=None):
"""Form an attributes dictionary from keyword args."""
a = {}
if name:
a['name'] = name
if description:
a['description'] = description
return a | python | def _attribs(self, name=None, description=None):
a = {}
if name:
a['name'] = name
if description:
a['description'] = description
return a | [
"def",
"_attribs",
"(",
"self",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"a",
"=",
"{",
"}",
"if",
"name",
":",
"a",
"[",
"'name'",
"]",
"=",
"name",
"if",
"description",
":",
"a",
"[",
"'description'",
"]",
"=",
"desc... | Form an attributes dictionary from keyword args. | [
"Form",
"an",
"attributes",
"dictionary",
"from",
"keyword",
"args",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L25-L32 |
238,744 | mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.create | def create(self, name=None, description=None):
"""Creates a new, empty dataset.
Parameters
----------
name : str, optional
The name of the dataset.
description : str, optional
The description of the dataset.
Returns
-------
request.Response
The response contains the properties of a new dataset as a JSON object.
"""
uri = URITemplate(self.baseuri + '/{owner}').expand(
owner=self.username)
return self.session.post(uri, json=self._attribs(name, description)) | python | def create(self, name=None, description=None):
uri = URITemplate(self.baseuri + '/{owner}').expand(
owner=self.username)
return self.session.post(uri, json=self._attribs(name, description)) | [
"def",
"create",
"(",
"self",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}'",
")",
".",
"expand",
"(",
"owner",
"=",
"self",
".",
"username",
")",
"return... | Creates a new, empty dataset.
Parameters
----------
name : str, optional
The name of the dataset.
description : str, optional
The description of the dataset.
Returns
-------
request.Response
The response contains the properties of a new dataset as a JSON object. | [
"Creates",
"a",
"new",
"empty",
"dataset",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L34-L53 |
238,745 | mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.list | def list(self):
"""Lists all datasets for a particular account.
Returns
-------
request.Response
The response contains a list of JSON objects describing datasets.
"""
uri = URITemplate(self.baseuri + '/{owner}').expand(
owner=self.username)
return self.session.get(uri) | python | def list(self):
uri = URITemplate(self.baseuri + '/{owner}').expand(
owner=self.username)
return self.session.get(uri) | [
"def",
"list",
"(",
"self",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}'",
")",
".",
"expand",
"(",
"owner",
"=",
"self",
".",
"username",
")",
"return",
"self",
".",
"session",
".",
"get",
"(",
"uri",
")"
] | Lists all datasets for a particular account.
Returns
-------
request.Response
The response contains a list of JSON objects describing datasets. | [
"Lists",
"all",
"datasets",
"for",
"a",
"particular",
"account",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L55-L66 |
238,746 | mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.update_dataset | def update_dataset(self, dataset, name=None, description=None):
"""Updates a single dataset.
Parameters
----------
dataset : str
The dataset id.
name : str, optional
The name of the dataset.
description : str, optional
The description of the dataset.
Returns
-------
request.Response
The response contains the properties of the updated dataset as a JSON object.
"""
uri = URITemplate(self.baseuri + '/{owner}/{id}').expand(
owner=self.username, id=dataset)
return self.session.patch(uri, json=self._attribs(name, description)) | python | def update_dataset(self, dataset, name=None, description=None):
uri = URITemplate(self.baseuri + '/{owner}/{id}').expand(
owner=self.username, id=dataset)
return self.session.patch(uri, json=self._attribs(name, description)) | [
"def",
"update_dataset",
"(",
"self",
",",
"dataset",
",",
"name",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}/{id}'",
")",
".",
"expand",
"(",
"owner",
"=",
"self",
".... | Updates a single dataset.
Parameters
----------
dataset : str
The dataset id.
name : str, optional
The name of the dataset.
description : str, optional
The description of the dataset.
Returns
-------
request.Response
The response contains the properties of the updated dataset as a JSON object. | [
"Updates",
"a",
"single",
"dataset",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L86-L108 |
238,747 | mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.delete_dataset | def delete_dataset(self, dataset):
"""Deletes a single dataset, including all of the features that it contains.
Parameters
----------
dataset : str
The dataset id.
Returns
-------
HTTP status code.
"""
uri = URITemplate(self.baseuri + '/{owner}/{id}').expand(
owner=self.username, id=dataset)
return self.session.delete(uri) | python | def delete_dataset(self, dataset):
uri = URITemplate(self.baseuri + '/{owner}/{id}').expand(
owner=self.username, id=dataset)
return self.session.delete(uri) | [
"def",
"delete_dataset",
"(",
"self",
",",
"dataset",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}/{id}'",
")",
".",
"expand",
"(",
"owner",
"=",
"self",
".",
"username",
",",
"id",
"=",
"dataset",
")",
"return",
"s... | Deletes a single dataset, including all of the features that it contains.
Parameters
----------
dataset : str
The dataset id.
Returns
-------
HTTP status code. | [
"Deletes",
"a",
"single",
"dataset",
"including",
"all",
"of",
"the",
"features",
"that",
"it",
"contains",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L110-L125 |
238,748 | mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.list_features | def list_features(self, dataset, reverse=False, start=None, limit=None):
"""Lists features in a dataset.
Parameters
----------
dataset : str
The dataset id.
reverse : str, optional
List features in reverse order.
Possible value is "true".
start : str, optional
The id of the feature after which to start the list (pagination).
limit : str, optional
The maximum number of features to list (pagination).
Returns
-------
request.Response
The response contains the features of a dataset as a GeoJSON FeatureCollection.
"""
uri = URITemplate(self.baseuri + '/{owner}/{id}/features').expand(
owner=self.username, id=dataset)
params = {}
if reverse:
params['reverse'] = 'true'
if start:
params['start'] = start
if limit:
params['limit'] = int(limit)
return self.session.get(uri, params=params) | python | def list_features(self, dataset, reverse=False, start=None, limit=None):
uri = URITemplate(self.baseuri + '/{owner}/{id}/features').expand(
owner=self.username, id=dataset)
params = {}
if reverse:
params['reverse'] = 'true'
if start:
params['start'] = start
if limit:
params['limit'] = int(limit)
return self.session.get(uri, params=params) | [
"def",
"list_features",
"(",
"self",
",",
"dataset",
",",
"reverse",
"=",
"False",
",",
"start",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}/{id}/features'",
")",
".",
"expand"... | Lists features in a dataset.
Parameters
----------
dataset : str
The dataset id.
reverse : str, optional
List features in reverse order.
Possible value is "true".
start : str, optional
The id of the feature after which to start the list (pagination).
limit : str, optional
The maximum number of features to list (pagination).
Returns
-------
request.Response
The response contains the features of a dataset as a GeoJSON FeatureCollection. | [
"Lists",
"features",
"in",
"a",
"dataset",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L127-L162 |
238,749 | mapbox/mapbox-sdk-py | mapbox/services/datasets.py | Datasets.delete_feature | def delete_feature(self, dataset, fid):
"""Removes a feature from a dataset.
Parameters
----------
dataset : str
The dataset id.
fid : str
The feature id.
Returns
-------
HTTP status code.
"""
uri = URITemplate(
self.baseuri + '/{owner}/{did}/features/{fid}').expand(
owner=self.username, did=dataset, fid=fid)
return self.session.delete(uri) | python | def delete_feature(self, dataset, fid):
uri = URITemplate(
self.baseuri + '/{owner}/{did}/features/{fid}').expand(
owner=self.username, did=dataset, fid=fid)
return self.session.delete(uri) | [
"def",
"delete_feature",
"(",
"self",
",",
"dataset",
",",
"fid",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{owner}/{did}/features/{fid}'",
")",
".",
"expand",
"(",
"owner",
"=",
"self",
".",
"username",
",",
"did",
"=",
"... | Removes a feature from a dataset.
Parameters
----------
dataset : str
The dataset id.
fid : str
The feature id.
Returns
-------
HTTP status code. | [
"Removes",
"a",
"feature",
"from",
"a",
"dataset",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/datasets.py#L217-L236 |
238,750 | mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader._get_credentials | def _get_credentials(self):
"""Gets temporary S3 credentials to stage user-uploaded files
"""
uri = URITemplate(self.baseuri + '/{username}/credentials').expand(
username=self.username)
resp = self.session.post(uri)
self.handle_http_error(
resp,
custom_messages={
401: "Token is not authorized",
404: "Token does not have upload scope",
429: "Too many requests"})
return resp | python | def _get_credentials(self):
uri = URITemplate(self.baseuri + '/{username}/credentials').expand(
username=self.username)
resp = self.session.post(uri)
self.handle_http_error(
resp,
custom_messages={
401: "Token is not authorized",
404: "Token does not have upload scope",
429: "Too many requests"})
return resp | [
"def",
"_get_credentials",
"(",
"self",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{username}/credentials'",
")",
".",
"expand",
"(",
"username",
"=",
"self",
".",
"username",
")",
"resp",
"=",
"self",
".",
"session",
".",
... | Gets temporary S3 credentials to stage user-uploaded files | [
"Gets",
"temporary",
"S3",
"credentials",
"to",
"stage",
"user",
"-",
"uploaded",
"files"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L37-L51 |
238,751 | mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader._validate_tileset | def _validate_tileset(self, tileset):
"""Validate the tileset name and
ensure that it includes the username
"""
if '.' not in tileset:
tileset = "{0}.{1}".format(self.username, tileset)
pattern = '^[a-z0-9-_]{1,32}\.[a-z0-9-_]{1,32}$'
if not re.match(pattern, tileset, flags=re.IGNORECASE):
raise ValidationError(
'tileset {0} is invalid, must match r"{1}"'.format(
tileset, pattern))
return tileset | python | def _validate_tileset(self, tileset):
if '.' not in tileset:
tileset = "{0}.{1}".format(self.username, tileset)
pattern = '^[a-z0-9-_]{1,32}\.[a-z0-9-_]{1,32}$'
if not re.match(pattern, tileset, flags=re.IGNORECASE):
raise ValidationError(
'tileset {0} is invalid, must match r"{1}"'.format(
tileset, pattern))
return tileset | [
"def",
"_validate_tileset",
"(",
"self",
",",
"tileset",
")",
":",
"if",
"'.'",
"not",
"in",
"tileset",
":",
"tileset",
"=",
"\"{0}.{1}\"",
".",
"format",
"(",
"self",
".",
"username",
",",
"tileset",
")",
"pattern",
"=",
"'^[a-z0-9-_]{1,32}\\.[a-z0-9-_]{1,32}... | Validate the tileset name and
ensure that it includes the username | [
"Validate",
"the",
"tileset",
"name",
"and",
"ensure",
"that",
"it",
"includes",
"the",
"username"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L53-L66 |
238,752 | mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader._resolve_username | def _resolve_username(self, account, username):
"""Resolve username and handle deprecation of account kwarg"""
if account is not None:
warnings.warn(
"Use keyword argument 'username' instead of 'account'",
DeprecationWarning)
return username or account or self.username | python | def _resolve_username(self, account, username):
if account is not None:
warnings.warn(
"Use keyword argument 'username' instead of 'account'",
DeprecationWarning)
return username or account or self.username | [
"def",
"_resolve_username",
"(",
"self",
",",
"account",
",",
"username",
")",
":",
"if",
"account",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"Use keyword argument 'username' instead of 'account'\"",
",",
"DeprecationWarning",
")",
"return",
"userna... | Resolve username and handle deprecation of account kwarg | [
"Resolve",
"username",
"and",
"handle",
"deprecation",
"of",
"account",
"kwarg"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L69-L75 |
238,753 | mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader.stage | def stage(self, fileobj, creds=None, callback=None):
"""Stages data in a Mapbox-owned S3 bucket
If creds are not provided, temporary credentials will be
generated using the Mapbox API.
Parameters
----------
fileobj: file object or filename
A Python file object opened in binary mode or a filename.
creds: dict
AWS credentials allowing uploads to the destination bucket.
callback: func
A function that takes a number of bytes processed as its
sole argument.
Returns
-------
str
The URL of the staged data
"""
if not hasattr(fileobj, 'read'):
fileobj = open(fileobj, 'rb')
if not creds:
res = self._get_credentials()
creds = res.json()
session = boto3_session(
aws_access_key_id=creds['accessKeyId'],
aws_secret_access_key=creds['secretAccessKey'],
aws_session_token=creds['sessionToken'],
region_name='us-east-1')
s3 = session.resource('s3')
bucket = s3.Bucket(creds['bucket'])
key = creds['key']
bucket.upload_fileobj(fileobj, key, Callback=callback)
return creds['url'] | python | def stage(self, fileobj, creds=None, callback=None):
if not hasattr(fileobj, 'read'):
fileobj = open(fileobj, 'rb')
if not creds:
res = self._get_credentials()
creds = res.json()
session = boto3_session(
aws_access_key_id=creds['accessKeyId'],
aws_secret_access_key=creds['secretAccessKey'],
aws_session_token=creds['sessionToken'],
region_name='us-east-1')
s3 = session.resource('s3')
bucket = s3.Bucket(creds['bucket'])
key = creds['key']
bucket.upload_fileobj(fileobj, key, Callback=callback)
return creds['url'] | [
"def",
"stage",
"(",
"self",
",",
"fileobj",
",",
"creds",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"fileobj",
",",
"'read'",
")",
":",
"fileobj",
"=",
"open",
"(",
"fileobj",
",",
"'rb'",
")",
"if",
"not",
... | Stages data in a Mapbox-owned S3 bucket
If creds are not provided, temporary credentials will be
generated using the Mapbox API.
Parameters
----------
fileobj: file object or filename
A Python file object opened in binary mode or a filename.
creds: dict
AWS credentials allowing uploads to the destination bucket.
callback: func
A function that takes a number of bytes processed as its
sole argument.
Returns
-------
str
The URL of the staged data | [
"Stages",
"data",
"in",
"a",
"Mapbox",
"-",
"owned",
"S3",
"bucket"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L77-L117 |
238,754 | mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader.create | def create(self, stage_url, tileset, name=None, patch=False, bypass=False):
"""Create a tileset
Note: this step is refered to as "upload" in the API docs;
This class's upload() method is a high-level function
which acts like the Studio upload form.
Returns a response object where the json() contents are
an upload dict. Completion of the tileset may take several
seconds or minutes depending on size of the data. The status()
method of this class may be used to poll the API endpoint for
tileset creation status.
Parameters
----------
stage_url: str
URL to resource on S3, typically provided in the response
of this class's stage() method.
tileset: str
The id of the tileset set to be created. Username will be
prefixed if not present. For example, 'my-tileset' becomes
'{username}.my-tileset'.
name: str
A short name for the tileset that will appear in Mapbox
studio.
patch: bool
Optional patch mode which requires a flag on the owner's
account.
bypass: bool
Optional bypass validation mode for MBTiles which requires
a flag on the owner's account.
Returns
-------
requests.Response
"""
tileset = self._validate_tileset(tileset)
username, _name = tileset.split(".")
msg = {'tileset': tileset,
'url': stage_url}
if patch:
msg['patch'] = patch
if bypass:
msg['bypass_mbtiles_validation'] = bypass
msg['name'] = name if name else _name
uri = URITemplate(self.baseuri + '/{username}').expand(
username=username)
resp = self.session.post(uri, json=msg)
self.handle_http_error(resp)
return resp | python | def create(self, stage_url, tileset, name=None, patch=False, bypass=False):
tileset = self._validate_tileset(tileset)
username, _name = tileset.split(".")
msg = {'tileset': tileset,
'url': stage_url}
if patch:
msg['patch'] = patch
if bypass:
msg['bypass_mbtiles_validation'] = bypass
msg['name'] = name if name else _name
uri = URITemplate(self.baseuri + '/{username}').expand(
username=username)
resp = self.session.post(uri, json=msg)
self.handle_http_error(resp)
return resp | [
"def",
"create",
"(",
"self",
",",
"stage_url",
",",
"tileset",
",",
"name",
"=",
"None",
",",
"patch",
"=",
"False",
",",
"bypass",
"=",
"False",
")",
":",
"tileset",
"=",
"self",
".",
"_validate_tileset",
"(",
"tileset",
")",
"username",
",",
"_name"... | Create a tileset
Note: this step is refered to as "upload" in the API docs;
This class's upload() method is a high-level function
which acts like the Studio upload form.
Returns a response object where the json() contents are
an upload dict. Completion of the tileset may take several
seconds or minutes depending on size of the data. The status()
method of this class may be used to poll the API endpoint for
tileset creation status.
Parameters
----------
stage_url: str
URL to resource on S3, typically provided in the response
of this class's stage() method.
tileset: str
The id of the tileset set to be created. Username will be
prefixed if not present. For example, 'my-tileset' becomes
'{username}.my-tileset'.
name: str
A short name for the tileset that will appear in Mapbox
studio.
patch: bool
Optional patch mode which requires a flag on the owner's
account.
bypass: bool
Optional bypass validation mode for MBTiles which requires
a flag on the owner's account.
Returns
-------
requests.Response | [
"Create",
"a",
"tileset"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L119-L175 |
238,755 | mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader.list | def list(self, account=None, username=None):
"""List of all uploads
Returns a Response object, the json() method of which returns
a list of uploads
Parameters
----------
username : str
Account username, defaults to the service's username.
account : str, **deprecated**
Alias for username. Will be removed in version 1.0.
Returns
-------
requests.Response
"""
username = self._resolve_username(account, username)
uri = URITemplate(self.baseuri + '/{username}').expand(
username=username)
resp = self.session.get(uri)
self.handle_http_error(resp)
return resp | python | def list(self, account=None, username=None):
username = self._resolve_username(account, username)
uri = URITemplate(self.baseuri + '/{username}').expand(
username=username)
resp = self.session.get(uri)
self.handle_http_error(resp)
return resp | [
"def",
"list",
"(",
"self",
",",
"account",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"username",
"=",
"self",
".",
"_resolve_username",
"(",
"account",
",",
"username",
")",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{u... | List of all uploads
Returns a Response object, the json() method of which returns
a list of uploads
Parameters
----------
username : str
Account username, defaults to the service's username.
account : str, **deprecated**
Alias for username. Will be removed in version 1.0.
Returns
-------
requests.Response | [
"List",
"of",
"all",
"uploads"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L177-L199 |
238,756 | mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader.status | def status(self, upload, account=None, username=None):
"""Check status of upload
Parameters
----------
upload: str
The id of the upload or a dict with key 'id'.
username : str
Account username, defaults to the service's username.
account : str, **deprecated**
Alias for username. Will be removed in version 1.0.
Returns
-------
requests.Response
"""
username = self._resolve_username(account, username)
if isinstance(upload, dict):
upload_id = upload['id']
else:
upload_id = upload
uri = URITemplate(self.baseuri + '/{username}/{upload_id}').expand(
username=username, upload_id=upload_id)
resp = self.session.get(uri)
self.handle_http_error(resp)
return resp | python | def status(self, upload, account=None, username=None):
username = self._resolve_username(account, username)
if isinstance(upload, dict):
upload_id = upload['id']
else:
upload_id = upload
uri = URITemplate(self.baseuri + '/{username}/{upload_id}').expand(
username=username, upload_id=upload_id)
resp = self.session.get(uri)
self.handle_http_error(resp)
return resp | [
"def",
"status",
"(",
"self",
",",
"upload",
",",
"account",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"username",
"=",
"self",
".",
"_resolve_username",
"(",
"account",
",",
"username",
")",
"if",
"isinstance",
"(",
"upload",
",",
"dict",
"... | Check status of upload
Parameters
----------
upload: str
The id of the upload or a dict with key 'id'.
username : str
Account username, defaults to the service's username.
account : str, **deprecated**
Alias for username. Will be removed in version 1.0.
Returns
-------
requests.Response | [
"Check",
"status",
"of",
"upload"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L228-L253 |
238,757 | mapbox/mapbox-sdk-py | mapbox/services/uploads.py | Uploader.upload | def upload(self, fileobj, tileset, name=None, patch=False, callback=None, bypass=False):
"""Upload data and create a Mapbox tileset
Effectively replicates the Studio upload feature. Returns a
Response object, the json() of which returns a dict with upload
metadata.
Parameters
----------
fileobj: file object or str
A filename or a Python file object opened in binary mode.
tileset: str
A tileset identifier such as '{owner}.my-tileset'.
name: str
A short name for the tileset that will appear in Mapbox
studio.
patch: bool
Optional patch mode which requires a flag on the owner's
account.
bypass: bool
Optional bypass validation mode for MBTiles which requires
a flag on the owner's account.
callback: func
A function that takes a number of bytes processed as its
sole argument. May be used with a progress bar.
Returns
-------
requests.Response
"""
tileset = self._validate_tileset(tileset)
url = self.stage(fileobj, callback=callback)
return self.create(url, tileset, name=name, patch=patch, bypass=bypass) | python | def upload(self, fileobj, tileset, name=None, patch=False, callback=None, bypass=False):
tileset = self._validate_tileset(tileset)
url = self.stage(fileobj, callback=callback)
return self.create(url, tileset, name=name, patch=patch, bypass=bypass) | [
"def",
"upload",
"(",
"self",
",",
"fileobj",
",",
"tileset",
",",
"name",
"=",
"None",
",",
"patch",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"bypass",
"=",
"False",
")",
":",
"tileset",
"=",
"self",
".",
"_validate_tileset",
"(",
"tileset",
... | Upload data and create a Mapbox tileset
Effectively replicates the Studio upload feature. Returns a
Response object, the json() of which returns a dict with upload
metadata.
Parameters
----------
fileobj: file object or str
A filename or a Python file object opened in binary mode.
tileset: str
A tileset identifier such as '{owner}.my-tileset'.
name: str
A short name for the tileset that will appear in Mapbox
studio.
patch: bool
Optional patch mode which requires a flag on the owner's
account.
bypass: bool
Optional bypass validation mode for MBTiles which requires
a flag on the owner's account.
callback: func
A function that takes a number of bytes processed as its
sole argument. May be used with a progress bar.
Returns
-------
requests.Response | [
"Upload",
"data",
"and",
"create",
"a",
"Mapbox",
"tileset"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L255-L287 |
238,758 | mapbox/mapbox-sdk-py | mapbox/services/geocoding.py | Geocoder._validate_country_codes | def _validate_country_codes(self, ccs):
"""Validate country code filters for use in requests."""
for cc in ccs:
if cc not in self.country_codes:
raise InvalidCountryCodeError(cc)
return {'country': ",".join(ccs)} | python | def _validate_country_codes(self, ccs):
for cc in ccs:
if cc not in self.country_codes:
raise InvalidCountryCodeError(cc)
return {'country': ",".join(ccs)} | [
"def",
"_validate_country_codes",
"(",
"self",
",",
"ccs",
")",
":",
"for",
"cc",
"in",
"ccs",
":",
"if",
"cc",
"not",
"in",
"self",
".",
"country_codes",
":",
"raise",
"InvalidCountryCodeError",
"(",
"cc",
")",
"return",
"{",
"'country'",
":",
"\",\"",
... | Validate country code filters for use in requests. | [
"Validate",
"country",
"code",
"filters",
"for",
"use",
"in",
"requests",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/geocoding.py#L28-L33 |
238,759 | mapbox/mapbox-sdk-py | mapbox/services/geocoding.py | Geocoder._validate_place_types | def _validate_place_types(self, types):
"""Validate place types and return a mapping for use in requests."""
for pt in types:
if pt not in self.place_types:
raise InvalidPlaceTypeError(pt)
return {'types': ",".join(types)} | python | def _validate_place_types(self, types):
for pt in types:
if pt not in self.place_types:
raise InvalidPlaceTypeError(pt)
return {'types': ",".join(types)} | [
"def",
"_validate_place_types",
"(",
"self",
",",
"types",
")",
":",
"for",
"pt",
"in",
"types",
":",
"if",
"pt",
"not",
"in",
"self",
".",
"place_types",
":",
"raise",
"InvalidPlaceTypeError",
"(",
"pt",
")",
"return",
"{",
"'types'",
":",
"\",\"",
".",... | Validate place types and return a mapping for use in requests. | [
"Validate",
"place",
"types",
"and",
"return",
"a",
"mapping",
"for",
"use",
"in",
"requests",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/geocoding.py#L35-L40 |
238,760 | mapbox/mapbox-sdk-py | mapbox/services/geocoding.py | Geocoder.forward | def forward(self, address, types=None, lon=None, lat=None,
country=None, bbox=None, limit=None, languages=None):
"""Returns a Requests response object that contains a GeoJSON
collection of places matching the given address.
`response.geojson()` returns the geocoding result as GeoJSON.
`response.status_code` returns the HTTP API status code.
Place results may be constrained to those of one or more types
or be biased toward a given longitude and latitude.
See: https://www.mapbox.com/api-documentation/search/#geocoding."""
uri = URITemplate(self.baseuri + '/{dataset}/{query}.json').expand(
dataset=self.name, query=address.encode('utf-8'))
params = {}
if country:
params.update(self._validate_country_codes(country))
if types:
params.update(self._validate_place_types(types))
if lon is not None and lat is not None:
params.update(proximity='{0},{1}'.format(
round(float(lon), self.precision.get('proximity', 3)),
round(float(lat), self.precision.get('proximity', 3))))
if languages:
params.update(language=','.join(languages))
if bbox is not None:
params.update(bbox='{0},{1},{2},{3}'.format(*bbox))
if limit is not None:
params.update(limit='{0}'.format(limit))
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
# for consistency with other services
def geojson():
return resp.json()
resp.geojson = geojson
return resp | python | def forward(self, address, types=None, lon=None, lat=None,
country=None, bbox=None, limit=None, languages=None):
uri = URITemplate(self.baseuri + '/{dataset}/{query}.json').expand(
dataset=self.name, query=address.encode('utf-8'))
params = {}
if country:
params.update(self._validate_country_codes(country))
if types:
params.update(self._validate_place_types(types))
if lon is not None and lat is not None:
params.update(proximity='{0},{1}'.format(
round(float(lon), self.precision.get('proximity', 3)),
round(float(lat), self.precision.get('proximity', 3))))
if languages:
params.update(language=','.join(languages))
if bbox is not None:
params.update(bbox='{0},{1},{2},{3}'.format(*bbox))
if limit is not None:
params.update(limit='{0}'.format(limit))
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
# for consistency with other services
def geojson():
return resp.json()
resp.geojson = geojson
return resp | [
"def",
"forward",
"(",
"self",
",",
"address",
",",
"types",
"=",
"None",
",",
"lon",
"=",
"None",
",",
"lat",
"=",
"None",
",",
"country",
"=",
"None",
",",
"bbox",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"languages",
"=",
"None",
")",
":",... | Returns a Requests response object that contains a GeoJSON
collection of places matching the given address.
`response.geojson()` returns the geocoding result as GeoJSON.
`response.status_code` returns the HTTP API status code.
Place results may be constrained to those of one or more types
or be biased toward a given longitude and latitude.
See: https://www.mapbox.com/api-documentation/search/#geocoding. | [
"Returns",
"a",
"Requests",
"response",
"object",
"that",
"contains",
"a",
"GeoJSON",
"collection",
"of",
"places",
"matching",
"the",
"given",
"address",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/geocoding.py#L42-L79 |
238,761 | mapbox/mapbox-sdk-py | mapbox/services/geocoding.py | Geocoder.reverse | def reverse(self, lon, lat, types=None, limit=None):
"""Returns a Requests response object that contains a GeoJSON
collection of places near the given longitude and latitude.
`response.geojson()` returns the geocoding result as GeoJSON.
`response.status_code` returns the HTTP API status code.
See: https://www.mapbox.com/api-documentation/search/#reverse-geocoding."""
uri = URITemplate(self.baseuri + '/{dataset}/{lon},{lat}.json').expand(
dataset=self.name,
lon=str(round(float(lon), self.precision.get('reverse', 5))),
lat=str(round(float(lat), self.precision.get('reverse', 5))))
params = {}
if types:
types = list(types)
params.update(self._validate_place_types(types))
if limit is not None:
if not types or len(types) != 1:
raise InvalidPlaceTypeError(
'Specify a single type when using limit with reverse geocoding')
params.update(limit='{0}'.format(limit))
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
# for consistency with other services
def geojson():
return resp.json()
resp.geojson = geojson
return resp | python | def reverse(self, lon, lat, types=None, limit=None):
uri = URITemplate(self.baseuri + '/{dataset}/{lon},{lat}.json').expand(
dataset=self.name,
lon=str(round(float(lon), self.precision.get('reverse', 5))),
lat=str(round(float(lat), self.precision.get('reverse', 5))))
params = {}
if types:
types = list(types)
params.update(self._validate_place_types(types))
if limit is not None:
if not types or len(types) != 1:
raise InvalidPlaceTypeError(
'Specify a single type when using limit with reverse geocoding')
params.update(limit='{0}'.format(limit))
resp = self.session.get(uri, params=params)
self.handle_http_error(resp)
# for consistency with other services
def geojson():
return resp.json()
resp.geojson = geojson
return resp | [
"def",
"reverse",
"(",
"self",
",",
"lon",
",",
"lat",
",",
"types",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"uri",
"=",
"URITemplate",
"(",
"self",
".",
"baseuri",
"+",
"'/{dataset}/{lon},{lat}.json'",
")",
".",
"expand",
"(",
"dataset",
"="... | Returns a Requests response object that contains a GeoJSON
collection of places near the given longitude and latitude.
`response.geojson()` returns the geocoding result as GeoJSON.
`response.status_code` returns the HTTP API status code.
See: https://www.mapbox.com/api-documentation/search/#reverse-geocoding. | [
"Returns",
"a",
"Requests",
"response",
"object",
"that",
"contains",
"a",
"GeoJSON",
"collection",
"of",
"places",
"near",
"the",
"given",
"longitude",
"and",
"latitude",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/geocoding.py#L81-L113 |
238,762 | mapbox/mapbox-sdk-py | mapbox/services/base.py | Session | def Session(access_token=None, env=None):
"""Create an HTTP session.
Parameters
----------
access_token : str
Mapbox access token string (optional).
env : dict, optional
A dict that subsitutes for os.environ.
Returns
-------
requests.Session
"""
if env is None:
env = os.environ.copy()
access_token = (
access_token or
env.get('MapboxAccessToken') or
env.get('MAPBOX_ACCESS_TOKEN'))
session = requests.Session()
session.params.update(access_token=access_token)
session.headers.update({
'User-Agent': 'mapbox-sdk-py/{0} {1}'.format(
__version__, requests.utils.default_user_agent())})
return session | python | def Session(access_token=None, env=None):
if env is None:
env = os.environ.copy()
access_token = (
access_token or
env.get('MapboxAccessToken') or
env.get('MAPBOX_ACCESS_TOKEN'))
session = requests.Session()
session.params.update(access_token=access_token)
session.headers.update({
'User-Agent': 'mapbox-sdk-py/{0} {1}'.format(
__version__, requests.utils.default_user_agent())})
return session | [
"def",
"Session",
"(",
"access_token",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
"is",
"None",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"access_token",
"=",
"(",
"access_token",
"or",
"env",
".",
"get",
"(",
... | Create an HTTP session.
Parameters
----------
access_token : str
Mapbox access token string (optional).
env : dict, optional
A dict that subsitutes for os.environ.
Returns
-------
requests.Session | [
"Create",
"an",
"HTTP",
"session",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/base.py#L14-L39 |
238,763 | mapbox/mapbox-sdk-py | mapbox/services/base.py | Service.username | def username(self):
"""The username in the service's access token
Returns
-------
str
"""
token = self.session.params.get('access_token')
if not token:
raise errors.TokenError(
"session does not have a valid access_token param")
data = token.split('.')[1]
# replace url chars and add padding
# (https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770)
data = data.replace('-', '+').replace('_', '/') + "==="
try:
return json.loads(base64.b64decode(data).decode('utf-8'))['u']
except (ValueError, KeyError):
raise errors.TokenError(
"access_token does not contain username") | python | def username(self):
token = self.session.params.get('access_token')
if not token:
raise errors.TokenError(
"session does not have a valid access_token param")
data = token.split('.')[1]
# replace url chars and add padding
# (https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770)
data = data.replace('-', '+').replace('_', '/') + "==="
try:
return json.loads(base64.b64decode(data).decode('utf-8'))['u']
except (ValueError, KeyError):
raise errors.TokenError(
"access_token does not contain username") | [
"def",
"username",
"(",
"self",
")",
":",
"token",
"=",
"self",
".",
"session",
".",
"params",
".",
"get",
"(",
"'access_token'",
")",
"if",
"not",
"token",
":",
"raise",
"errors",
".",
"TokenError",
"(",
"\"session does not have a valid access_token param\"",
... | The username in the service's access token
Returns
-------
str | [
"The",
"username",
"in",
"the",
"service",
"s",
"access",
"token"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/base.py#L101-L120 |
238,764 | mapbox/mapbox-sdk-py | mapbox/services/base.py | Service.handle_http_error | def handle_http_error(self, response, custom_messages=None,
raise_for_status=False):
"""Converts service errors to Python exceptions
Parameters
----------
response : requests.Response
A service response.
custom_messages : dict, optional
A mapping of custom exception messages to HTTP status codes.
raise_for_status : bool, optional
If True, the requests library provides Python exceptions.
Returns
-------
None
"""
if not custom_messages:
custom_messages = {}
if response.status_code in custom_messages.keys():
raise errors.HTTPError(custom_messages[response.status_code])
if raise_for_status:
response.raise_for_status() | python | def handle_http_error(self, response, custom_messages=None,
raise_for_status=False):
if not custom_messages:
custom_messages = {}
if response.status_code in custom_messages.keys():
raise errors.HTTPError(custom_messages[response.status_code])
if raise_for_status:
response.raise_for_status() | [
"def",
"handle_http_error",
"(",
"self",
",",
"response",
",",
"custom_messages",
"=",
"None",
",",
"raise_for_status",
"=",
"False",
")",
":",
"if",
"not",
"custom_messages",
":",
"custom_messages",
"=",
"{",
"}",
"if",
"response",
".",
"status_code",
"in",
... | Converts service errors to Python exceptions
Parameters
----------
response : requests.Response
A service response.
custom_messages : dict, optional
A mapping of custom exception messages to HTTP status codes.
raise_for_status : bool, optional
If True, the requests library provides Python exceptions.
Returns
-------
None | [
"Converts",
"service",
"errors",
"to",
"Python",
"exceptions"
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/base.py#L122-L144 |
238,765 | mapbox/mapbox-sdk-py | mapbox/services/mapmatching.py | MapMatcher.match | def match(self, feature, gps_precision=None, profile='mapbox.driving'):
"""Match features to OpenStreetMap data."""
profile = self._validate_profile(profile)
feature = self._validate_feature(feature)
geojson_line_feature = json.dumps(feature)
uri = URITemplate(self.baseuri + '/{profile}.json').expand(
profile=profile)
params = None
if gps_precision:
params = {'gps_precision': gps_precision}
res = self.session.post(uri, data=geojson_line_feature, params=params,
headers={'Content-Type': 'application/json'})
self.handle_http_error(res)
def geojson():
return res.json()
res.geojson = geojson
return res | python | def match(self, feature, gps_precision=None, profile='mapbox.driving'):
profile = self._validate_profile(profile)
feature = self._validate_feature(feature)
geojson_line_feature = json.dumps(feature)
uri = URITemplate(self.baseuri + '/{profile}.json').expand(
profile=profile)
params = None
if gps_precision:
params = {'gps_precision': gps_precision}
res = self.session.post(uri, data=geojson_line_feature, params=params,
headers={'Content-Type': 'application/json'})
self.handle_http_error(res)
def geojson():
return res.json()
res.geojson = geojson
return res | [
"def",
"match",
"(",
"self",
",",
"feature",
",",
"gps_precision",
"=",
"None",
",",
"profile",
"=",
"'mapbox.driving'",
")",
":",
"profile",
"=",
"self",
".",
"_validate_profile",
"(",
"profile",
")",
"feature",
"=",
"self",
".",
"_validate_feature",
"(",
... | Match features to OpenStreetMap data. | [
"Match",
"features",
"to",
"OpenStreetMap",
"data",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/mapmatching.py#L33-L55 |
238,766 | mapbox/mapbox-sdk-py | mapbox/services/tilequery.py | Tilequery._validate_geometry | def _validate_geometry(self, geometry):
"""Validates geometry, raising error if invalid."""
if geometry is not None and geometry not in self.valid_geometries:
raise InvalidParameterError("{} is not a valid geometry".format(geometry))
return geometry | python | def _validate_geometry(self, geometry):
if geometry is not None and geometry not in self.valid_geometries:
raise InvalidParameterError("{} is not a valid geometry".format(geometry))
return geometry | [
"def",
"_validate_geometry",
"(",
"self",
",",
"geometry",
")",
":",
"if",
"geometry",
"is",
"not",
"None",
"and",
"geometry",
"not",
"in",
"self",
".",
"valid_geometries",
":",
"raise",
"InvalidParameterError",
"(",
"\"{} is not a valid geometry\"",
".",
"format"... | Validates geometry, raising error if invalid. | [
"Validates",
"geometry",
"raising",
"error",
"if",
"invalid",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/tilequery.py#L72-L78 |
238,767 | mapbox/mapbox-sdk-py | mapbox/services/tilequery.py | Tilequery.tilequery | def tilequery(
self,
map_id,
lon=None,
lat=None,
radius=None,
limit=None,
dedupe=None,
geometry=None,
layers=None,
):
"""Returns data about specific features
from a vector tileset.
Parameters
----------
map_id : str or list
The tileset's unique identifier in the
format username.id.
map_id may be either a str with one value
or a list with multiple values.
lon : float
The longitude to query, where -180
is the minimum value and 180 is the
maximum value.
lat : float
The latitude to query, where -85.0511
is the minimum value and 85.0511 is the
maximum value.
radius : int, optional
The approximate distance in meters to
query, where 0 is the minimum value.
(There is no maximum value.)
If None, the default value is 0.
limit : int, optional
The number of features to return, where
1 is the minimum value and 50 is the
maximum value.
If None, the default value is 5.
dedupe : bool, optional
Whether to remove duplicate results.
If None, the default value is True.
geometry : str, optional
The geometry type to query.
layers : list, optional
The list of layers to query.
If a specified layer does not exist,
then the Tilequery API will skip it.
If no layers exist, then the API will
return an empty GeoJSON FeatureCollection.
Returns
-------
request.Response
The response object with a GeoJSON
FeatureCollection of features at or near
the specified longitude and latitude.
"""
# If map_id is a list, then convert it to a str
# of comma-separated values.
if isinstance(map_id, list):
map_id = ",".join(map_id)
# Validate lon and lat.
lon = self._validate_lon(lon)
lat = self._validate_lat(lat)
# Create dict to assist in building URI resource path.
path_values = dict(
api_name=self.api_name, lon=lon, lat=lat
)
# Build URI resource path.
path_part = "/" + map_id + "/{api_name}/{lon},{lat}.json"
uri = URITemplate(self.base_uri + path_part).expand(**path_values)
# Build URI query_parameters.
query_parameters = dict()
if radius is not None:
radius = self._validate_radius(radius)
query_parameters["radius"] = radius
if limit is not None:
limit = self._validate_limit(limit)
query_parameters["limit"] = limit
if dedupe is not None:
query_parameters["dedupe"] = "true" if True else "false"
if geometry is not None:
geometry = self._validate_geometry(geometry)
query_parameters["geometry"] = geometry
if layers is not None:
query_parameters["layers"] = ",".join(layers)
# Send HTTP GET request.
response = self.session.get(uri, params=query_parameters)
self.handle_http_error(response)
# To be consistent with other services,
# add geojson method to response object.
def geojson():
return response.json()
response.geojson = geojson
return response | python | def tilequery(
self,
map_id,
lon=None,
lat=None,
radius=None,
limit=None,
dedupe=None,
geometry=None,
layers=None,
):
# If map_id is a list, then convert it to a str
# of comma-separated values.
if isinstance(map_id, list):
map_id = ",".join(map_id)
# Validate lon and lat.
lon = self._validate_lon(lon)
lat = self._validate_lat(lat)
# Create dict to assist in building URI resource path.
path_values = dict(
api_name=self.api_name, lon=lon, lat=lat
)
# Build URI resource path.
path_part = "/" + map_id + "/{api_name}/{lon},{lat}.json"
uri = URITemplate(self.base_uri + path_part).expand(**path_values)
# Build URI query_parameters.
query_parameters = dict()
if radius is not None:
radius = self._validate_radius(radius)
query_parameters["radius"] = radius
if limit is not None:
limit = self._validate_limit(limit)
query_parameters["limit"] = limit
if dedupe is not None:
query_parameters["dedupe"] = "true" if True else "false"
if geometry is not None:
geometry = self._validate_geometry(geometry)
query_parameters["geometry"] = geometry
if layers is not None:
query_parameters["layers"] = ",".join(layers)
# Send HTTP GET request.
response = self.session.get(uri, params=query_parameters)
self.handle_http_error(response)
# To be consistent with other services,
# add geojson method to response object.
def geojson():
return response.json()
response.geojson = geojson
return response | [
"def",
"tilequery",
"(",
"self",
",",
"map_id",
",",
"lon",
"=",
"None",
",",
"lat",
"=",
"None",
",",
"radius",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"dedupe",
"=",
"None",
",",
"geometry",
"=",
"None",
",",
"layers",
"=",
"None",
",",
")... | Returns data about specific features
from a vector tileset.
Parameters
----------
map_id : str or list
The tileset's unique identifier in the
format username.id.
map_id may be either a str with one value
or a list with multiple values.
lon : float
The longitude to query, where -180
is the minimum value and 180 is the
maximum value.
lat : float
The latitude to query, where -85.0511
is the minimum value and 85.0511 is the
maximum value.
radius : int, optional
The approximate distance in meters to
query, where 0 is the minimum value.
(There is no maximum value.)
If None, the default value is 0.
limit : int, optional
The number of features to return, where
1 is the minimum value and 50 is the
maximum value.
If None, the default value is 5.
dedupe : bool, optional
Whether to remove duplicate results.
If None, the default value is True.
geometry : str, optional
The geometry type to query.
layers : list, optional
The list of layers to query.
If a specified layer does not exist,
then the Tilequery API will skip it.
If no layers exist, then the API will
return an empty GeoJSON FeatureCollection.
Returns
-------
request.Response
The response object with a GeoJSON
FeatureCollection of features at or near
the specified longitude and latitude. | [
"Returns",
"data",
"about",
"specific",
"features",
"from",
"a",
"vector",
"tileset",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/tilequery.py#L80-L209 |
238,768 | mapbox/mapbox-sdk-py | mapbox/services/maps.py | Maps._validate_file_format | def _validate_file_format(self, file_format):
"""Validates file format, raising error if invalid."""
if file_format not in self.valid_file_formats:
raise InvalidFileFormatError(
"{} is not a valid file format".format(file_format)
)
return file_format | python | def _validate_file_format(self, file_format):
if file_format not in self.valid_file_formats:
raise InvalidFileFormatError(
"{} is not a valid file format".format(file_format)
)
return file_format | [
"def",
"_validate_file_format",
"(",
"self",
",",
"file_format",
")",
":",
"if",
"file_format",
"not",
"in",
"self",
".",
"valid_file_formats",
":",
"raise",
"InvalidFileFormatError",
"(",
"\"{} is not a valid file format\"",
".",
"format",
"(",
"file_format",
")",
... | Validates file format, raising error if invalid. | [
"Validates",
"file",
"format",
"raising",
"error",
"if",
"invalid",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/maps.py#L122-L130 |
238,769 | mapbox/mapbox-sdk-py | mapbox/services/maps.py | Maps._validate_feature_format | def _validate_feature_format(self, feature_format):
"""Validates feature format, raising error if invalid."""
if feature_format not in self.valid_feature_formats:
raise InvalidFeatureFormatError(
"{} is not a valid feature format".format(feature_format)
)
return feature_format | python | def _validate_feature_format(self, feature_format):
if feature_format not in self.valid_feature_formats:
raise InvalidFeatureFormatError(
"{} is not a valid feature format".format(feature_format)
)
return feature_format | [
"def",
"_validate_feature_format",
"(",
"self",
",",
"feature_format",
")",
":",
"if",
"feature_format",
"not",
"in",
"self",
".",
"valid_feature_formats",
":",
"raise",
"InvalidFeatureFormatError",
"(",
"\"{} is not a valid feature format\"",
".",
"format",
"(",
"featu... | Validates feature format, raising error if invalid. | [
"Validates",
"feature",
"format",
"raising",
"error",
"if",
"invalid",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/maps.py#L144-L152 |
238,770 | mapbox/mapbox-sdk-py | mapbox/services/maps.py | Maps._validate_marker_name | def _validate_marker_name(self, marker_name):
"""Validates marker name, raising error if invalid."""
if marker_name not in self.valid_marker_names:
raise InvalidMarkerNameError(
"{} is not a valid marker name".format(marker_name)
)
return marker_name | python | def _validate_marker_name(self, marker_name):
if marker_name not in self.valid_marker_names:
raise InvalidMarkerNameError(
"{} is not a valid marker name".format(marker_name)
)
return marker_name | [
"def",
"_validate_marker_name",
"(",
"self",
",",
"marker_name",
")",
":",
"if",
"marker_name",
"not",
"in",
"self",
".",
"valid_marker_names",
":",
"raise",
"InvalidMarkerNameError",
"(",
"\"{} is not a valid marker name\"",
".",
"format",
"(",
"marker_name",
")",
... | Validates marker name, raising error if invalid. | [
"Validates",
"marker",
"name",
"raising",
"error",
"if",
"invalid",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/maps.py#L154-L162 |
238,771 | mapbox/mapbox-sdk-py | mapbox/services/maps.py | Maps._validate_label | def _validate_label(self, label):
"""Validates label, raising error if invalid."""
letter_pattern = compile("^[a-z]{1}$")
number_pattern = compile("^[0]{1}$|^[1-9]{1,2}$")
icon_pattern = compile("^[a-zA-Z ]{1,}$")
if not match(letter_pattern, label)\
and not match(number_pattern, label)\
and not match(icon_pattern, label):
raise InvalidLabelError(
"{} is not a valid label".format(label)
)
return label | python | def _validate_label(self, label):
letter_pattern = compile("^[a-z]{1}$")
number_pattern = compile("^[0]{1}$|^[1-9]{1,2}$")
icon_pattern = compile("^[a-zA-Z ]{1,}$")
if not match(letter_pattern, label)\
and not match(number_pattern, label)\
and not match(icon_pattern, label):
raise InvalidLabelError(
"{} is not a valid label".format(label)
)
return label | [
"def",
"_validate_label",
"(",
"self",
",",
"label",
")",
":",
"letter_pattern",
"=",
"compile",
"(",
"\"^[a-z]{1}$\"",
")",
"number_pattern",
"=",
"compile",
"(",
"\"^[0]{1}$|^[1-9]{1,2}$\"",
")",
"icon_pattern",
"=",
"compile",
"(",
"\"^[a-zA-Z ]{1,}$\"",
")",
"... | Validates label, raising error if invalid. | [
"Validates",
"label",
"raising",
"error",
"if",
"invalid",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/maps.py#L164-L178 |
238,772 | mapbox/mapbox-sdk-py | mapbox/services/maps.py | Maps._validate_color | def _validate_color(self, color):
"""Validates color, raising error if invalid."""
three_digit_pattern = compile("^[a-f0-9]{3}$")
six_digit_pattern = compile("^[a-f0-9]{6}$")
if not match(three_digit_pattern, color)\
and not match(six_digit_pattern, color):
raise InvalidColorError(
"{} is not a valid color".format(color)
)
return color | python | def _validate_color(self, color):
three_digit_pattern = compile("^[a-f0-9]{3}$")
six_digit_pattern = compile("^[a-f0-9]{6}$")
if not match(three_digit_pattern, color)\
and not match(six_digit_pattern, color):
raise InvalidColorError(
"{} is not a valid color".format(color)
)
return color | [
"def",
"_validate_color",
"(",
"self",
",",
"color",
")",
":",
"three_digit_pattern",
"=",
"compile",
"(",
"\"^[a-f0-9]{3}$\"",
")",
"six_digit_pattern",
"=",
"compile",
"(",
"\"^[a-f0-9]{6}$\"",
")",
"if",
"not",
"match",
"(",
"three_digit_pattern",
",",
"color",... | Validates color, raising error if invalid. | [
"Validates",
"color",
"raising",
"error",
"if",
"invalid",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/maps.py#L180-L192 |
238,773 | mapbox/mapbox-sdk-py | mapbox/services/maps.py | Maps.tile | def tile(self, map_id, x, y, z, retina=False,
file_format="png", style_id=None, timestamp=None):
"""Returns an image tile, vector tile, or UTFGrid
in the specified file format.
Parameters
----------
map_id : str
The tile's unique identifier in the format username.id.
x : int
The tile's column, where 0 is the minimum value
and ((2**z) - 1) is the maximum value.
y : int
The tile's row, where 0 is the minimum value
and ((2**z) - 1) is the maximum value.
z : int
The tile's zoom level, where 0 is the minimum value
and 20 is the maximum value.
retina : bool, optional
The tile's scale, where True indicates Retina scale
(double scale) and False indicates regular scale.
The default value is false.
file_format : str, optional
The tile's file format.
The default value is png.
style_id : str, optional
The tile's style id.
style_id must be used together with timestamp.
timestamp : str, optional
The style id's ISO-formatted timestamp, found by
accessing the "modified" property of a style object.
timestamp must be used together with style_id.
Returns
-------
request.Response
The response object with a tile in the specified format.
"""
# Check x, y, and z.
if x is None or y is None or z is None:
raise ValidationError(
"x, y, and z must be not be None"
)
# Validate x, y, z, retina, and file_format.
x = self._validate_x(x, z)
y = self._validate_y(y, z)
z = self._validate_z(z)
retina = self._validate_retina(retina)
file_format = self._validate_file_format(file_format)
# Create dict to assist in building URI resource path.
path_values = dict(
map_id=map_id,
x=str(x),
y=str(y),
z=str(z)
)
# Start building URI resource path.
path_part = "/{map_id}/{z}/{x}/{y}"
uri = URITemplate(self.base_uri + path_part).expand(**path_values)
# Finish building URI resource path.
# As in static.py, this two-part process avoids
# undesired escaping of "@" in "@2x."
path_part = "{}.{}".format(retina, file_format)
uri += path_part
# Validate timestamp and build URI query parameters.
query_parameters = dict()
if style_id is not None and timestamp is not None:
timestamp = self._validate_timestamp(timestamp)
style = "{}@{}".format(style_id, timestamp)
query_parameters["style"] = style
# Send HTTP GET request.
response = self.session.get(uri, params=query_parameters)
self.handle_http_error(response)
return response | python | def tile(self, map_id, x, y, z, retina=False,
file_format="png", style_id=None, timestamp=None):
# Check x, y, and z.
if x is None or y is None or z is None:
raise ValidationError(
"x, y, and z must be not be None"
)
# Validate x, y, z, retina, and file_format.
x = self._validate_x(x, z)
y = self._validate_y(y, z)
z = self._validate_z(z)
retina = self._validate_retina(retina)
file_format = self._validate_file_format(file_format)
# Create dict to assist in building URI resource path.
path_values = dict(
map_id=map_id,
x=str(x),
y=str(y),
z=str(z)
)
# Start building URI resource path.
path_part = "/{map_id}/{z}/{x}/{y}"
uri = URITemplate(self.base_uri + path_part).expand(**path_values)
# Finish building URI resource path.
# As in static.py, this two-part process avoids
# undesired escaping of "@" in "@2x."
path_part = "{}.{}".format(retina, file_format)
uri += path_part
# Validate timestamp and build URI query parameters.
query_parameters = dict()
if style_id is not None and timestamp is not None:
timestamp = self._validate_timestamp(timestamp)
style = "{}@{}".format(style_id, timestamp)
query_parameters["style"] = style
# Send HTTP GET request.
response = self.session.get(uri, params=query_parameters)
self.handle_http_error(response)
return response | [
"def",
"tile",
"(",
"self",
",",
"map_id",
",",
"x",
",",
"y",
",",
"z",
",",
"retina",
"=",
"False",
",",
"file_format",
"=",
"\"png\"",
",",
"style_id",
"=",
"None",
",",
"timestamp",
"=",
"None",
")",
":",
"# Check x, y, and z.",
"if",
"x",
"is",
... | Returns an image tile, vector tile, or UTFGrid
in the specified file format.
Parameters
----------
map_id : str
The tile's unique identifier in the format username.id.
x : int
The tile's column, where 0 is the minimum value
and ((2**z) - 1) is the maximum value.
y : int
The tile's row, where 0 is the minimum value
and ((2**z) - 1) is the maximum value.
z : int
The tile's zoom level, where 0 is the minimum value
and 20 is the maximum value.
retina : bool, optional
The tile's scale, where True indicates Retina scale
(double scale) and False indicates regular scale.
The default value is false.
file_format : str, optional
The tile's file format.
The default value is png.
style_id : str, optional
The tile's style id.
style_id must be used together with timestamp.
timestamp : str, optional
The style id's ISO-formatted timestamp, found by
accessing the "modified" property of a style object.
timestamp must be used together with style_id.
Returns
-------
request.Response
The response object with a tile in the specified format. | [
"Returns",
"an",
"image",
"tile",
"vector",
"tile",
"or",
"UTFGrid",
"in",
"the",
"specified",
"file",
"format",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/maps.py#L194-L295 |
238,774 | mapbox/mapbox-sdk-py | mapbox/services/maps.py | Maps.features | def features(self, map_id, feature_format="json"):
"""Returns vector features from Mapbox Editor projects
as GeoJSON or KML.
Parameters
----------
map_id : str
The map's unique identifier in the format username.id.
feature_format : str, optional
The vector's feature format.
The default value is json.
Returns
-------
request.Response
The response object with vector features.
"""
# Validate feature_format.
feature_format = self._validate_feature_format(feature_format)
# Create dict to assist in building URI resource path.
path_values = dict(
map_id=map_id,
feature_format=feature_format
)
# Build URI resource path.
path_part = "/{map_id}/features.{feature_format}"
uri = URITemplate(self.base_uri + path_part).expand(**path_values)
# Send HTTP GET request.
response = self.session.get(uri)
self.handle_http_error(response)
return response | python | def features(self, map_id, feature_format="json"):
# Validate feature_format.
feature_format = self._validate_feature_format(feature_format)
# Create dict to assist in building URI resource path.
path_values = dict(
map_id=map_id,
feature_format=feature_format
)
# Build URI resource path.
path_part = "/{map_id}/features.{feature_format}"
uri = URITemplate(self.base_uri + path_part).expand(**path_values)
# Send HTTP GET request.
response = self.session.get(uri)
self.handle_http_error(response)
return response | [
"def",
"features",
"(",
"self",
",",
"map_id",
",",
"feature_format",
"=",
"\"json\"",
")",
":",
"# Validate feature_format.",
"feature_format",
"=",
"self",
".",
"_validate_feature_format",
"(",
"feature_format",
")",
"# Create dict to assist in building URI resource path.... | Returns vector features from Mapbox Editor projects
as GeoJSON or KML.
Parameters
----------
map_id : str
The map's unique identifier in the format username.id.
feature_format : str, optional
The vector's feature format.
The default value is json.
Returns
-------
request.Response
The response object with vector features. | [
"Returns",
"vector",
"features",
"from",
"Mapbox",
"Editor",
"projects",
"as",
"GeoJSON",
"or",
"KML",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/maps.py#L297-L338 |
238,775 | mapbox/mapbox-sdk-py | mapbox/services/maps.py | Maps.metadata | def metadata(self, map_id, secure=False):
"""Returns TileJSON metadata for a tileset.
Parameters
----------
map_id : str
The map's unique identifier in the format username.id.
secure : bool, optional
The representation of the requested resources,
where True indicates representation as HTTPS endpoints.
The default value is False.
Returns
-------
request.Response
The response object with TileJSON metadata for the
specified tileset.
"""
# Create dict to assist in building URI resource path.
path_values = dict(
map_id=map_id
)
# Build URI resource path.
path_part = "/{map_id}.json"
uri = URITemplate(self.base_uri + path_part).expand(**path_values)
# Build URI query parameters.
query_parameters = dict()
if secure:
query_parameters["secure"] = ""
# Send HTTP GET request.
response = self.session.get(uri, params=query_parameters)
self.handle_http_error(response)
return response | python | def metadata(self, map_id, secure=False):
# Create dict to assist in building URI resource path.
path_values = dict(
map_id=map_id
)
# Build URI resource path.
path_part = "/{map_id}.json"
uri = URITemplate(self.base_uri + path_part).expand(**path_values)
# Build URI query parameters.
query_parameters = dict()
if secure:
query_parameters["secure"] = ""
# Send HTTP GET request.
response = self.session.get(uri, params=query_parameters)
self.handle_http_error(response)
return response | [
"def",
"metadata",
"(",
"self",
",",
"map_id",
",",
"secure",
"=",
"False",
")",
":",
"# Create dict to assist in building URI resource path.",
"path_values",
"=",
"dict",
"(",
"map_id",
"=",
"map_id",
")",
"# Build URI resource path.",
"path_part",
"=",
"\"/{map_id}.... | Returns TileJSON metadata for a tileset.
Parameters
----------
map_id : str
The map's unique identifier in the format username.id.
secure : bool, optional
The representation of the requested resources,
where True indicates representation as HTTPS endpoints.
The default value is False.
Returns
-------
request.Response
The response object with TileJSON metadata for the
specified tileset. | [
"Returns",
"TileJSON",
"metadata",
"for",
"a",
"tileset",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/maps.py#L340-L384 |
238,776 | mapbox/mapbox-sdk-py | mapbox/services/maps.py | Maps.marker | def marker(self, marker_name=None, label=None,
color=None, retina=False):
"""Returns a single marker image without any
background map.
Parameters
----------
marker_name : str
The marker's shape and size.
label : str, optional
The marker's alphanumeric label.
Options are a through z, 0 through 99, or the
name of a valid Maki icon.
color : str, optional
The marker's color.
Options are three- or six-digit hexadecimal
color codes.
retina : bool, optional
The marker's scale, where True indicates Retina scale
(double scale) and False indicates regular scale.
The default value is false.
Returns
-------
request.Response
The response object with the specified marker.
"""
# Check for marker_name.
if marker_name is None:
raise ValidationError(
"marker_name is a required argument"
)
# Validate marker_name and retina.
marker_name = self._validate_marker_name(marker_name)
retina = self._validate_retina(retina)
# Create dict and start building URI resource path.
path_values = dict(
marker_name=marker_name
)
path_part = "/marker/{marker_name}"
# Validate label, update dict,
# and continue building URI resource path.
if label is not None:
label = self._validate_label(label)
path_values["label"] = label
path_part += "-{label}"
# Validate color, update dict,
# and continue building URI resource path.
if color is not None:
color = self._validate_color(color)
path_values["color"] = color
path_part += "+{color}"
uri = URITemplate(self.base_uri + path_part).expand(**path_values)
# Finish building URI resource path.
path_part = "{}.png".format(retina)
uri += path_part
# Send HTTP GET request.
response = self.session.get(uri)
self.handle_http_error(response)
return response | python | def marker(self, marker_name=None, label=None,
color=None, retina=False):
# Check for marker_name.
if marker_name is None:
raise ValidationError(
"marker_name is a required argument"
)
# Validate marker_name and retina.
marker_name = self._validate_marker_name(marker_name)
retina = self._validate_retina(retina)
# Create dict and start building URI resource path.
path_values = dict(
marker_name=marker_name
)
path_part = "/marker/{marker_name}"
# Validate label, update dict,
# and continue building URI resource path.
if label is not None:
label = self._validate_label(label)
path_values["label"] = label
path_part += "-{label}"
# Validate color, update dict,
# and continue building URI resource path.
if color is not None:
color = self._validate_color(color)
path_values["color"] = color
path_part += "+{color}"
uri = URITemplate(self.base_uri + path_part).expand(**path_values)
# Finish building URI resource path.
path_part = "{}.png".format(retina)
uri += path_part
# Send HTTP GET request.
response = self.session.get(uri)
self.handle_http_error(response)
return response | [
"def",
"marker",
"(",
"self",
",",
"marker_name",
"=",
"None",
",",
"label",
"=",
"None",
",",
"color",
"=",
"None",
",",
"retina",
"=",
"False",
")",
":",
"# Check for marker_name.",
"if",
"marker_name",
"is",
"None",
":",
"raise",
"ValidationError",
"(",... | Returns a single marker image without any
background map.
Parameters
----------
marker_name : str
The marker's shape and size.
label : str, optional
The marker's alphanumeric label.
Options are a through z, 0 through 99, or the
name of a valid Maki icon.
color : str, optional
The marker's color.
Options are three- or six-digit hexadecimal
color codes.
retina : bool, optional
The marker's scale, where True indicates Retina scale
(double scale) and False indicates regular scale.
The default value is false.
Returns
-------
request.Response
The response object with the specified marker. | [
"Returns",
"a",
"single",
"marker",
"image",
"without",
"any",
"background",
"map",
"."
] | 72d19dbcf2d254a6ea08129a726471fd21f13023 | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/maps.py#L386-L468 |
238,777 | django-extensions/django-extensions | django_extensions/management/commands/runserver_plus.py | set_werkzeug_log_color | def set_werkzeug_log_color():
"""Try to set color to the werkzeug log."""
from django.core.management.color import color_style
from werkzeug.serving import WSGIRequestHandler
from werkzeug._internal import _log
_style = color_style()
_orig_log = WSGIRequestHandler.log
def werk_log(self, type, message, *args):
try:
msg = '%s - - [%s] %s' % (
self.address_string(),
self.log_date_time_string(),
message % args,
)
http_code = str(args[1])
except Exception:
return _orig_log(type, message, *args)
# Utilize terminal colors, if available
if http_code[0] == '2':
# Put 2XX first, since it should be the common case
msg = _style.HTTP_SUCCESS(msg)
elif http_code[0] == '1':
msg = _style.HTTP_INFO(msg)
elif http_code == '304':
msg = _style.HTTP_NOT_MODIFIED(msg)
elif http_code[0] == '3':
msg = _style.HTTP_REDIRECT(msg)
elif http_code == '404':
msg = _style.HTTP_NOT_FOUND(msg)
elif http_code[0] == '4':
msg = _style.HTTP_BAD_REQUEST(msg)
else:
# Any 5XX, or any other response
msg = _style.HTTP_SERVER_ERROR(msg)
_log(type, msg)
WSGIRequestHandler.log = werk_log | python | def set_werkzeug_log_color():
from django.core.management.color import color_style
from werkzeug.serving import WSGIRequestHandler
from werkzeug._internal import _log
_style = color_style()
_orig_log = WSGIRequestHandler.log
def werk_log(self, type, message, *args):
try:
msg = '%s - - [%s] %s' % (
self.address_string(),
self.log_date_time_string(),
message % args,
)
http_code = str(args[1])
except Exception:
return _orig_log(type, message, *args)
# Utilize terminal colors, if available
if http_code[0] == '2':
# Put 2XX first, since it should be the common case
msg = _style.HTTP_SUCCESS(msg)
elif http_code[0] == '1':
msg = _style.HTTP_INFO(msg)
elif http_code == '304':
msg = _style.HTTP_NOT_MODIFIED(msg)
elif http_code[0] == '3':
msg = _style.HTTP_REDIRECT(msg)
elif http_code == '404':
msg = _style.HTTP_NOT_FOUND(msg)
elif http_code[0] == '4':
msg = _style.HTTP_BAD_REQUEST(msg)
else:
# Any 5XX, or any other response
msg = _style.HTTP_SERVER_ERROR(msg)
_log(type, msg)
WSGIRequestHandler.log = werk_log | [
"def",
"set_werkzeug_log_color",
"(",
")",
":",
"from",
"django",
".",
"core",
".",
"management",
".",
"color",
"import",
"color_style",
"from",
"werkzeug",
".",
"serving",
"import",
"WSGIRequestHandler",
"from",
"werkzeug",
".",
"_internal",
"import",
"_log",
"... | Try to set color to the werkzeug log. | [
"Try",
"to",
"set",
"color",
"to",
"the",
"werkzeug",
"log",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/runserver_plus.py#L423-L463 |
238,778 | django-extensions/django-extensions | django_extensions/db/fields/__init__.py | AutoSlugField._slug_strip | def _slug_strip(self, value):
"""
Clean up a slug by removing slug separator characters that occur at
the beginning or end of a slug.
If an alternate separator is used, it will also replace any instances
of the default '-' separator with the new separator.
"""
re_sep = '(?:-|%s)' % re.escape(self.separator)
value = re.sub('%s+' % re_sep, self.separator, value)
return re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value) | python | def _slug_strip(self, value):
re_sep = '(?:-|%s)' % re.escape(self.separator)
value = re.sub('%s+' % re_sep, self.separator, value)
return re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value) | [
"def",
"_slug_strip",
"(",
"self",
",",
"value",
")",
":",
"re_sep",
"=",
"'(?:-|%s)'",
"%",
"re",
".",
"escape",
"(",
"self",
".",
"separator",
")",
"value",
"=",
"re",
".",
"sub",
"(",
"'%s+'",
"%",
"re_sep",
",",
"self",
".",
"separator",
",",
"... | Clean up a slug by removing slug separator characters that occur at
the beginning or end of a slug.
If an alternate separator is used, it will also replace any instances
of the default '-' separator with the new separator. | [
"Clean",
"up",
"a",
"slug",
"by",
"removing",
"slug",
"separator",
"characters",
"that",
"occur",
"at",
"the",
"beginning",
"or",
"end",
"of",
"a",
"slug",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/db/fields/__init__.py#L134-L144 |
238,779 | django-extensions/django-extensions | django_extensions/management/commands/export_emails.py | full_name | def full_name(first_name, last_name, username, **extra):
"""Return full name or username."""
name = " ".join(n for n in [first_name, last_name] if n)
if not name:
return username
return name | python | def full_name(first_name, last_name, username, **extra):
name = " ".join(n for n in [first_name, last_name] if n)
if not name:
return username
return name | [
"def",
"full_name",
"(",
"first_name",
",",
"last_name",
",",
"username",
",",
"*",
"*",
"extra",
")",
":",
"name",
"=",
"\" \"",
".",
"join",
"(",
"n",
"for",
"n",
"in",
"[",
"first_name",
",",
"last_name",
"]",
"if",
"n",
")",
"if",
"not",
"name"... | Return full name or username. | [
"Return",
"full",
"name",
"or",
"username",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/export_emails.py#L23-L28 |
238,780 | django-extensions/django-extensions | django_extensions/management/commands/export_emails.py | Command.google | def google(self, qs):
"""CSV format suitable for importing into google GMail"""
csvf = writer(sys.stdout)
csvf.writerow(['Name', 'Email'])
for ent in qs:
csvf.writerow([full_name(**ent), ent['email']]) | python | def google(self, qs):
csvf = writer(sys.stdout)
csvf.writerow(['Name', 'Email'])
for ent in qs:
csvf.writerow([full_name(**ent), ent['email']]) | [
"def",
"google",
"(",
"self",
",",
"qs",
")",
":",
"csvf",
"=",
"writer",
"(",
"sys",
".",
"stdout",
")",
"csvf",
".",
"writerow",
"(",
"[",
"'Name'",
",",
"'Email'",
"]",
")",
"for",
"ent",
"in",
"qs",
":",
"csvf",
".",
"writerow",
"(",
"[",
"... | CSV format suitable for importing into google GMail | [
"CSV",
"format",
"suitable",
"for",
"importing",
"into",
"google",
"GMail"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/export_emails.py#L88-L93 |
238,781 | django-extensions/django-extensions | django_extensions/management/commands/export_emails.py | Command.linkedin | def linkedin(self, qs):
"""
CSV format suitable for importing into linkedin Groups.
perfect for pre-approving members of a linkedin group.
"""
csvf = writer(sys.stdout)
csvf.writerow(['First Name', 'Last Name', 'Email'])
for ent in qs:
csvf.writerow([ent['first_name'], ent['last_name'], ent['email']]) | python | def linkedin(self, qs):
csvf = writer(sys.stdout)
csvf.writerow(['First Name', 'Last Name', 'Email'])
for ent in qs:
csvf.writerow([ent['first_name'], ent['last_name'], ent['email']]) | [
"def",
"linkedin",
"(",
"self",
",",
"qs",
")",
":",
"csvf",
"=",
"writer",
"(",
"sys",
".",
"stdout",
")",
"csvf",
".",
"writerow",
"(",
"[",
"'First Name'",
",",
"'Last Name'",
",",
"'Email'",
"]",
")",
"for",
"ent",
"in",
"qs",
":",
"csvf",
".",... | CSV format suitable for importing into linkedin Groups.
perfect for pre-approving members of a linkedin group. | [
"CSV",
"format",
"suitable",
"for",
"importing",
"into",
"linkedin",
"Groups",
".",
"perfect",
"for",
"pre",
"-",
"approving",
"members",
"of",
"a",
"linkedin",
"group",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/export_emails.py#L95-L103 |
238,782 | django-extensions/django-extensions | django_extensions/management/commands/export_emails.py | Command.outlook | def outlook(self, qs):
"""CSV format suitable for importing into outlook"""
csvf = writer(sys.stdout)
columns = ['Name', 'E-mail Address', 'Notes', 'E-mail 2 Address', 'E-mail 3 Address',
'Mobile Phone', 'Pager', 'Company', 'Job Title', 'Home Phone', 'Home Phone 2',
'Home Fax', 'Home Address', 'Business Phone', 'Business Phone 2',
'Business Fax', 'Business Address', 'Other Phone', 'Other Fax', 'Other Address']
csvf.writerow(columns)
empty = [''] * (len(columns) - 2)
for ent in qs:
csvf.writerow([full_name(**ent), ent['email']] + empty) | python | def outlook(self, qs):
csvf = writer(sys.stdout)
columns = ['Name', 'E-mail Address', 'Notes', 'E-mail 2 Address', 'E-mail 3 Address',
'Mobile Phone', 'Pager', 'Company', 'Job Title', 'Home Phone', 'Home Phone 2',
'Home Fax', 'Home Address', 'Business Phone', 'Business Phone 2',
'Business Fax', 'Business Address', 'Other Phone', 'Other Fax', 'Other Address']
csvf.writerow(columns)
empty = [''] * (len(columns) - 2)
for ent in qs:
csvf.writerow([full_name(**ent), ent['email']] + empty) | [
"def",
"outlook",
"(",
"self",
",",
"qs",
")",
":",
"csvf",
"=",
"writer",
"(",
"sys",
".",
"stdout",
")",
"columns",
"=",
"[",
"'Name'",
",",
"'E-mail Address'",
",",
"'Notes'",
",",
"'E-mail 2 Address'",
",",
"'E-mail 3 Address'",
",",
"'Mobile Phone'",
... | CSV format suitable for importing into outlook | [
"CSV",
"format",
"suitable",
"for",
"importing",
"into",
"outlook"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/export_emails.py#L105-L115 |
238,783 | django-extensions/django-extensions | django_extensions/management/commands/export_emails.py | Command.vcard | def vcard(self, qs):
"""VCARD format."""
try:
import vobject
except ImportError:
print(self.style.ERROR("Please install vobject to use the vcard export format."))
sys.exit(1)
out = sys.stdout
for ent in qs:
card = vobject.vCard()
card.add('fn').value = full_name(**ent)
if not ent['last_name'] and not ent['first_name']:
# fallback to fullname, if both first and lastname are not declared
card.add('n').value = vobject.vcard.Name(full_name(**ent))
else:
card.add('n').value = vobject.vcard.Name(ent['last_name'], ent['first_name'])
emailpart = card.add('email')
emailpart.value = ent['email']
emailpart.type_param = 'INTERNET'
out.write(card.serialize()) | python | def vcard(self, qs):
try:
import vobject
except ImportError:
print(self.style.ERROR("Please install vobject to use the vcard export format."))
sys.exit(1)
out = sys.stdout
for ent in qs:
card = vobject.vCard()
card.add('fn').value = full_name(**ent)
if not ent['last_name'] and not ent['first_name']:
# fallback to fullname, if both first and lastname are not declared
card.add('n').value = vobject.vcard.Name(full_name(**ent))
else:
card.add('n').value = vobject.vcard.Name(ent['last_name'], ent['first_name'])
emailpart = card.add('email')
emailpart.value = ent['email']
emailpart.type_param = 'INTERNET'
out.write(card.serialize()) | [
"def",
"vcard",
"(",
"self",
",",
"qs",
")",
":",
"try",
":",
"import",
"vobject",
"except",
"ImportError",
":",
"print",
"(",
"self",
".",
"style",
".",
"ERROR",
"(",
"\"Please install vobject to use the vcard export format.\"",
")",
")",
"sys",
".",
"exit",
... | VCARD format. | [
"VCARD",
"format",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/export_emails.py#L117-L138 |
238,784 | django-extensions/django-extensions | django_extensions/management/mysql.py | parse_mysql_cnf | def parse_mysql_cnf(dbinfo):
"""
Attempt to parse mysql database config file for connection settings.
Ideally we would hook into django's code to do this, but read_default_file is handled by the mysql C libs
so we have to emulate the behaviour
Settings that are missing will return ''
returns (user, password, database_name, database_host, database_port)
"""
read_default_file = dbinfo.get('OPTIONS', {}).get('read_default_file')
if read_default_file:
config = configparser.RawConfigParser({
'user': '',
'password': '',
'database': '',
'host': '',
'port': '',
'socket': '',
})
import os
config.read(os.path.expanduser(read_default_file))
try:
user = config.get('client', 'user')
password = config.get('client', 'password')
database_name = config.get('client', 'database')
database_host = config.get('client', 'host')
database_port = config.get('client', 'port')
socket = config.get('client', 'socket')
if database_host == 'localhost' and socket:
# mysql actually uses a socket if host is localhost
database_host = socket
return user, password, database_name, database_host, database_port
except configparser.NoSectionError:
pass
return '', '', '', '', '' | python | def parse_mysql_cnf(dbinfo):
read_default_file = dbinfo.get('OPTIONS', {}).get('read_default_file')
if read_default_file:
config = configparser.RawConfigParser({
'user': '',
'password': '',
'database': '',
'host': '',
'port': '',
'socket': '',
})
import os
config.read(os.path.expanduser(read_default_file))
try:
user = config.get('client', 'user')
password = config.get('client', 'password')
database_name = config.get('client', 'database')
database_host = config.get('client', 'host')
database_port = config.get('client', 'port')
socket = config.get('client', 'socket')
if database_host == 'localhost' and socket:
# mysql actually uses a socket if host is localhost
database_host = socket
return user, password, database_name, database_host, database_port
except configparser.NoSectionError:
pass
return '', '', '', '', '' | [
"def",
"parse_mysql_cnf",
"(",
"dbinfo",
")",
":",
"read_default_file",
"=",
"dbinfo",
".",
"get",
"(",
"'OPTIONS'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'read_default_file'",
")",
"if",
"read_default_file",
":",
"config",
"=",
"configparser",
".",
"RawConf... | Attempt to parse mysql database config file for connection settings.
Ideally we would hook into django's code to do this, but read_default_file is handled by the mysql C libs
so we have to emulate the behaviour
Settings that are missing will return ''
returns (user, password, database_name, database_host, database_port) | [
"Attempt",
"to",
"parse",
"mysql",
"database",
"config",
"file",
"for",
"connection",
"settings",
".",
"Ideally",
"we",
"would",
"hook",
"into",
"django",
"s",
"code",
"to",
"do",
"this",
"but",
"read_default_file",
"is",
"handled",
"by",
"the",
"mysql",
"C"... | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/mysql.py#L5-L43 |
238,785 | django-extensions/django-extensions | django_extensions/management/jobs.py | get_jobs | def get_jobs(when=None, only_scheduled=False):
"""
Return a dictionary mapping of job names together with their respective
application class.
"""
# FIXME: HACK: make sure the project dir is on the path when executed as ./manage.py
try:
cpath = os.path.dirname(os.path.realpath(sys.argv[0]))
ppath = os.path.dirname(cpath)
if ppath not in sys.path:
sys.path.append(ppath)
except Exception:
pass
_jobs = {}
for app_name in [app.name for app in apps.get_app_configs()]:
scandirs = (None, 'minutely', 'quarter_hourly', 'hourly', 'daily', 'weekly', 'monthly', 'yearly')
if when:
scandirs = None, when
for subdir in scandirs:
try:
path = find_job_module(app_name, subdir)
for name in find_jobs(path):
if (app_name, name) in _jobs:
raise JobError("Duplicate job %s" % name)
job = import_job(app_name, name, subdir)
if only_scheduled and job.when is None:
# only include jobs which are scheduled
continue
if when and job.when != when:
# generic job not in same schedule
continue
_jobs[(app_name, name)] = job
except ImportError:
# No job module -- continue scanning
pass
return _jobs | python | def get_jobs(when=None, only_scheduled=False):
# FIXME: HACK: make sure the project dir is on the path when executed as ./manage.py
try:
cpath = os.path.dirname(os.path.realpath(sys.argv[0]))
ppath = os.path.dirname(cpath)
if ppath not in sys.path:
sys.path.append(ppath)
except Exception:
pass
_jobs = {}
for app_name in [app.name for app in apps.get_app_configs()]:
scandirs = (None, 'minutely', 'quarter_hourly', 'hourly', 'daily', 'weekly', 'monthly', 'yearly')
if when:
scandirs = None, when
for subdir in scandirs:
try:
path = find_job_module(app_name, subdir)
for name in find_jobs(path):
if (app_name, name) in _jobs:
raise JobError("Duplicate job %s" % name)
job = import_job(app_name, name, subdir)
if only_scheduled and job.when is None:
# only include jobs which are scheduled
continue
if when and job.when != when:
# generic job not in same schedule
continue
_jobs[(app_name, name)] = job
except ImportError:
# No job module -- continue scanning
pass
return _jobs | [
"def",
"get_jobs",
"(",
"when",
"=",
"None",
",",
"only_scheduled",
"=",
"False",
")",
":",
"# FIXME: HACK: make sure the project dir is on the path when executed as ./manage.py",
"try",
":",
"cpath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
... | Return a dictionary mapping of job names together with their respective
application class. | [
"Return",
"a",
"dictionary",
"mapping",
"of",
"job",
"names",
"together",
"with",
"their",
"respective",
"application",
"class",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/jobs.py#L102-L139 |
238,786 | django-extensions/django-extensions | django_extensions/management/commands/runjobs.py | Command.runjobs_by_signals | def runjobs_by_signals(self, when, options):
""" Run jobs from the signals """
# Thanks for Ian Holsman for the idea and code
from django_extensions.management import signals
from django.conf import settings
verbosity = options["verbosity"]
for app_name in settings.INSTALLED_APPS:
try:
__import__(app_name + '.management', '', '', [''])
except ImportError:
pass
for app in (app.models_module for app in apps.get_app_configs() if app.models_module):
if verbosity > 1:
app_name = '.'.join(app.__name__.rsplit('.')[:-1])
print("Sending %s job signal for: %s" % (when, app_name))
if when == 'minutely':
signals.run_minutely_jobs.send(sender=app, app=app)
elif when == 'quarter_hourly':
signals.run_quarter_hourly_jobs.send(sender=app, app=app)
elif when == 'hourly':
signals.run_hourly_jobs.send(sender=app, app=app)
elif when == 'daily':
signals.run_daily_jobs.send(sender=app, app=app)
elif when == 'weekly':
signals.run_weekly_jobs.send(sender=app, app=app)
elif when == 'monthly':
signals.run_monthly_jobs.send(sender=app, app=app)
elif when == 'yearly':
signals.run_yearly_jobs.send(sender=app, app=app) | python | def runjobs_by_signals(self, when, options):
# Thanks for Ian Holsman for the idea and code
from django_extensions.management import signals
from django.conf import settings
verbosity = options["verbosity"]
for app_name in settings.INSTALLED_APPS:
try:
__import__(app_name + '.management', '', '', [''])
except ImportError:
pass
for app in (app.models_module for app in apps.get_app_configs() if app.models_module):
if verbosity > 1:
app_name = '.'.join(app.__name__.rsplit('.')[:-1])
print("Sending %s job signal for: %s" % (when, app_name))
if when == 'minutely':
signals.run_minutely_jobs.send(sender=app, app=app)
elif when == 'quarter_hourly':
signals.run_quarter_hourly_jobs.send(sender=app, app=app)
elif when == 'hourly':
signals.run_hourly_jobs.send(sender=app, app=app)
elif when == 'daily':
signals.run_daily_jobs.send(sender=app, app=app)
elif when == 'weekly':
signals.run_weekly_jobs.send(sender=app, app=app)
elif when == 'monthly':
signals.run_monthly_jobs.send(sender=app, app=app)
elif when == 'yearly':
signals.run_yearly_jobs.send(sender=app, app=app) | [
"def",
"runjobs_by_signals",
"(",
"self",
",",
"when",
",",
"options",
")",
":",
"# Thanks for Ian Holsman for the idea and code",
"from",
"django_extensions",
".",
"management",
"import",
"signals",
"from",
"django",
".",
"conf",
"import",
"settings",
"verbosity",
"=... | Run jobs from the signals | [
"Run",
"jobs",
"from",
"the",
"signals"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/runjobs.py#L44-L74 |
238,787 | django-extensions/django-extensions | django_extensions/__init__.py | get_version | def get_version(version):
"""Dynamically calculate the version based on VERSION tuple."""
if len(version) > 2 and version[2] is not None:
if isinstance(version[2], int):
str_version = "%s.%s.%s" % version[:3]
else:
str_version = "%s.%s_%s" % version[:3]
else:
str_version = "%s.%s" % version[:2]
return str_version | python | def get_version(version):
if len(version) > 2 and version[2] is not None:
if isinstance(version[2], int):
str_version = "%s.%s.%s" % version[:3]
else:
str_version = "%s.%s_%s" % version[:3]
else:
str_version = "%s.%s" % version[:2]
return str_version | [
"def",
"get_version",
"(",
"version",
")",
":",
"if",
"len",
"(",
"version",
")",
">",
"2",
"and",
"version",
"[",
"2",
"]",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"version",
"[",
"2",
"]",
",",
"int",
")",
":",
"str_version",
"=",
"\... | Dynamically calculate the version based on VERSION tuple. | [
"Dynamically",
"calculate",
"the",
"version",
"based",
"on",
"VERSION",
"tuple",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/__init__.py#L5-L15 |
238,788 | django-extensions/django-extensions | django_extensions/templatetags/indent_text.py | indentby | def indentby(parser, token):
"""
Add indentation to text between the tags by the given indentation level.
{% indentby <indent_level> [if <statement>] %}
...
{% endindentby %}
Arguments:
indent_level - Number of spaces to indent text with.
statement - Only apply indent_level if the boolean statement evalutates to True.
"""
args = token.split_contents()
largs = len(args)
if largs not in (2, 4):
raise template.TemplateSyntaxError("indentby tag requires 1 or 3 arguments")
indent_level = args[1]
if_statement = None
if largs == 4:
if_statement = args[3]
nodelist = parser.parse(('endindentby', ))
parser.delete_first_token()
return IndentByNode(nodelist, indent_level, if_statement) | python | def indentby(parser, token):
args = token.split_contents()
largs = len(args)
if largs not in (2, 4):
raise template.TemplateSyntaxError("indentby tag requires 1 or 3 arguments")
indent_level = args[1]
if_statement = None
if largs == 4:
if_statement = args[3]
nodelist = parser.parse(('endindentby', ))
parser.delete_first_token()
return IndentByNode(nodelist, indent_level, if_statement) | [
"def",
"indentby",
"(",
"parser",
",",
"token",
")",
":",
"args",
"=",
"token",
".",
"split_contents",
"(",
")",
"largs",
"=",
"len",
"(",
"args",
")",
"if",
"largs",
"not",
"in",
"(",
"2",
",",
"4",
")",
":",
"raise",
"template",
".",
"TemplateSyn... | Add indentation to text between the tags by the given indentation level.
{% indentby <indent_level> [if <statement>] %}
...
{% endindentby %}
Arguments:
indent_level - Number of spaces to indent text with.
statement - Only apply indent_level if the boolean statement evalutates to True. | [
"Add",
"indentation",
"to",
"text",
"between",
"the",
"tags",
"by",
"the",
"given",
"indentation",
"level",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/templatetags/indent_text.py#L33-L55 |
238,789 | django-extensions/django-extensions | django_extensions/management/commands/pipchecker.py | Command._urlopen_as_json | def _urlopen_as_json(self, url, headers=None):
"""Shorcut for return contents as json"""
req = Request(url, headers=headers)
return json.loads(urlopen(req).read()) | python | def _urlopen_as_json(self, url, headers=None):
req = Request(url, headers=headers)
return json.loads(urlopen(req).read()) | [
"def",
"_urlopen_as_json",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
")",
":",
"req",
"=",
"Request",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"return",
"json",
".",
"loads",
"(",
"urlopen",
"(",
"req",
")",
".",
"read",
"(",
")... | Shorcut for return contents as json | [
"Shorcut",
"for",
"return",
"contents",
"as",
"json"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/pipchecker.py#L116-L119 |
238,790 | django-extensions/django-extensions | django_extensions/management/commands/pipchecker.py | Command.check_pypi | def check_pypi(self):
"""If the requirement is frozen to pypi, check for a new version."""
for dist in get_installed_distributions():
name = dist.project_name
if name in self.reqs.keys():
self.reqs[name]["dist"] = dist
pypi = ServerProxy("https://pypi.python.org/pypi")
for name, req in list(self.reqs.items()):
if req["url"]:
continue # skipping github packages.
elif "dist" in req:
dist = req["dist"]
dist_version = LooseVersion(dist.version)
available = pypi.package_releases(req["pip_req"].name, True) or pypi.package_releases(req["pip_req"].name.replace('-', '_'), True)
available_version = self._available_version(dist_version, available)
if not available_version:
msg = self.style.WARN("release is not on pypi (check capitalization and/or --extra-index-url)")
elif self.options['show_newer'] and dist_version > available_version:
msg = self.style.INFO("{0} available (newer installed)".format(available_version))
elif available_version > dist_version:
msg = self.style.INFO("{0} available".format(available_version))
else:
msg = "up to date"
del self.reqs[name]
continue
pkg_info = self.style.BOLD("{dist.project_name} {dist.version}".format(dist=dist))
else:
msg = "not installed"
pkg_info = name
self.stdout.write("{pkg_info:40} {msg}".format(pkg_info=pkg_info, msg=msg))
del self.reqs[name] | python | def check_pypi(self):
for dist in get_installed_distributions():
name = dist.project_name
if name in self.reqs.keys():
self.reqs[name]["dist"] = dist
pypi = ServerProxy("https://pypi.python.org/pypi")
for name, req in list(self.reqs.items()):
if req["url"]:
continue # skipping github packages.
elif "dist" in req:
dist = req["dist"]
dist_version = LooseVersion(dist.version)
available = pypi.package_releases(req["pip_req"].name, True) or pypi.package_releases(req["pip_req"].name.replace('-', '_'), True)
available_version = self._available_version(dist_version, available)
if not available_version:
msg = self.style.WARN("release is not on pypi (check capitalization and/or --extra-index-url)")
elif self.options['show_newer'] and dist_version > available_version:
msg = self.style.INFO("{0} available (newer installed)".format(available_version))
elif available_version > dist_version:
msg = self.style.INFO("{0} available".format(available_version))
else:
msg = "up to date"
del self.reqs[name]
continue
pkg_info = self.style.BOLD("{dist.project_name} {dist.version}".format(dist=dist))
else:
msg = "not installed"
pkg_info = name
self.stdout.write("{pkg_info:40} {msg}".format(pkg_info=pkg_info, msg=msg))
del self.reqs[name] | [
"def",
"check_pypi",
"(",
"self",
")",
":",
"for",
"dist",
"in",
"get_installed_distributions",
"(",
")",
":",
"name",
"=",
"dist",
".",
"project_name",
"if",
"name",
"in",
"self",
".",
"reqs",
".",
"keys",
"(",
")",
":",
"self",
".",
"reqs",
"[",
"n... | If the requirement is frozen to pypi, check for a new version. | [
"If",
"the",
"requirement",
"is",
"frozen",
"to",
"pypi",
"check",
"for",
"a",
"new",
"version",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/pipchecker.py#L132-L164 |
238,791 | django-extensions/django-extensions | django_extensions/management/commands/pipchecker.py | Command.check_other | def check_other(self):
"""
If the requirement is frozen somewhere other than pypi or github, skip.
If you have a private pypi or use --extra-index-url, consider contributing
support here.
"""
if self.reqs:
self.stdout.write(self.style.ERROR("\nOnly pypi and github based requirements are supported:"))
for name, req in self.reqs.items():
if "dist" in req:
pkg_info = "{dist.project_name} {dist.version}".format(dist=req["dist"])
elif "url" in req:
pkg_info = "{url}".format(url=req["url"])
else:
pkg_info = "unknown package"
self.stdout.write(self.style.BOLD("{pkg_info:40} is not a pypi or github requirement".format(pkg_info=pkg_info))) | python | def check_other(self):
if self.reqs:
self.stdout.write(self.style.ERROR("\nOnly pypi and github based requirements are supported:"))
for name, req in self.reqs.items():
if "dist" in req:
pkg_info = "{dist.project_name} {dist.version}".format(dist=req["dist"])
elif "url" in req:
pkg_info = "{url}".format(url=req["url"])
else:
pkg_info = "unknown package"
self.stdout.write(self.style.BOLD("{pkg_info:40} is not a pypi or github requirement".format(pkg_info=pkg_info))) | [
"def",
"check_other",
"(",
"self",
")",
":",
"if",
"self",
".",
"reqs",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"style",
".",
"ERROR",
"(",
"\"\\nOnly pypi and github based requirements are supported:\"",
")",
")",
"for",
"name",
",",
"re... | If the requirement is frozen somewhere other than pypi or github, skip.
If you have a private pypi or use --extra-index-url, consider contributing
support here. | [
"If",
"the",
"requirement",
"is",
"frozen",
"somewhere",
"other",
"than",
"pypi",
"or",
"github",
"skip",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/pipchecker.py#L297-L313 |
238,792 | django-extensions/django-extensions | django_extensions/db/fields/encrypted.py | BaseEncryptedField.get_crypt_class | def get_crypt_class(self):
"""
Get the Keyczar class to use.
The class can be customized with the ENCRYPTED_FIELD_MODE setting. By default,
this setting is DECRYPT_AND_ENCRYPT. Set this to ENCRYPT to disable decryption.
This is necessary if you are only providing public keys to Keyczar.
Returns:
keyczar.Encrypter if ENCRYPTED_FIELD_MODE is ENCRYPT.
keyczar.Crypter if ENCRYPTED_FIELD_MODE is DECRYPT_AND_ENCRYPT.
Override this method to customize the type of Keyczar class returned.
"""
crypt_type = getattr(settings, 'ENCRYPTED_FIELD_MODE', 'DECRYPT_AND_ENCRYPT')
if crypt_type == 'ENCRYPT':
crypt_class_name = 'Encrypter'
elif crypt_type == 'DECRYPT_AND_ENCRYPT':
crypt_class_name = 'Crypter'
else:
raise ImproperlyConfigured(
'ENCRYPTED_FIELD_MODE must be either DECRYPT_AND_ENCRYPT '
'or ENCRYPT, not %s.' % crypt_type)
return getattr(keyczar, crypt_class_name) | python | def get_crypt_class(self):
crypt_type = getattr(settings, 'ENCRYPTED_FIELD_MODE', 'DECRYPT_AND_ENCRYPT')
if crypt_type == 'ENCRYPT':
crypt_class_name = 'Encrypter'
elif crypt_type == 'DECRYPT_AND_ENCRYPT':
crypt_class_name = 'Crypter'
else:
raise ImproperlyConfigured(
'ENCRYPTED_FIELD_MODE must be either DECRYPT_AND_ENCRYPT '
'or ENCRYPT, not %s.' % crypt_type)
return getattr(keyczar, crypt_class_name) | [
"def",
"get_crypt_class",
"(",
"self",
")",
":",
"crypt_type",
"=",
"getattr",
"(",
"settings",
",",
"'ENCRYPTED_FIELD_MODE'",
",",
"'DECRYPT_AND_ENCRYPT'",
")",
"if",
"crypt_type",
"==",
"'ENCRYPT'",
":",
"crypt_class_name",
"=",
"'Encrypter'",
"elif",
"crypt_type"... | Get the Keyczar class to use.
The class can be customized with the ENCRYPTED_FIELD_MODE setting. By default,
this setting is DECRYPT_AND_ENCRYPT. Set this to ENCRYPT to disable decryption.
This is necessary if you are only providing public keys to Keyczar.
Returns:
keyczar.Encrypter if ENCRYPTED_FIELD_MODE is ENCRYPT.
keyczar.Crypter if ENCRYPTED_FIELD_MODE is DECRYPT_AND_ENCRYPT.
Override this method to customize the type of Keyczar class returned. | [
"Get",
"the",
"Keyczar",
"class",
"to",
"use",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/db/fields/encrypted.py#L46-L69 |
238,793 | django-extensions/django-extensions | django_extensions/management/commands/sqldsn.py | Command._postgresql | def _postgresql(self, dbhost, dbport, dbname, dbuser, dbpass, dsn_style=None): # noqa
"""PostgreSQL psycopg2 driver accepts two syntaxes
Plus a string for .pgpass file
"""
dsn = []
if dsn_style is None or dsn_style == 'all' or dsn_style == 'keyvalue':
dsnstr = "host='{0}' dbname='{2}' user='{3}' password='{4}'"
if dbport is not None:
dsnstr += " port='{1}'"
dsn.append(dsnstr.format(dbhost,
dbport,
dbname,
dbuser,
dbpass,))
if dsn_style == 'all' or dsn_style == 'kwargs':
dsnstr = "host='{0}', database='{2}', user='{3}', password='{4}'"
if dbport is not None:
dsnstr += ", port='{1}'"
dsn.append(dsnstr.format(dbhost,
dbport,
dbname,
dbuser,
dbpass))
if dsn_style == 'all' or dsn_style == 'uri':
dsnstr = "postgresql://{user}:{password}@{host}/{name}"
dsn.append(dsnstr.format(
host="{host}:{port}".format(host=dbhost, port=dbport) if dbport else dbhost, # noqa
name=dbname, user=dbuser, password=dbpass))
if dsn_style == 'all' or dsn_style == 'pgpass':
dsn.append(':'.join(map(str, filter(
None, [dbhost, dbport, dbname, dbuser, dbpass]))))
return dsn | python | def _postgresql(self, dbhost, dbport, dbname, dbuser, dbpass, dsn_style=None): # noqa
dsn = []
if dsn_style is None or dsn_style == 'all' or dsn_style == 'keyvalue':
dsnstr = "host='{0}' dbname='{2}' user='{3}' password='{4}'"
if dbport is not None:
dsnstr += " port='{1}'"
dsn.append(dsnstr.format(dbhost,
dbport,
dbname,
dbuser,
dbpass,))
if dsn_style == 'all' or dsn_style == 'kwargs':
dsnstr = "host='{0}', database='{2}', user='{3}', password='{4}'"
if dbport is not None:
dsnstr += ", port='{1}'"
dsn.append(dsnstr.format(dbhost,
dbport,
dbname,
dbuser,
dbpass))
if dsn_style == 'all' or dsn_style == 'uri':
dsnstr = "postgresql://{user}:{password}@{host}/{name}"
dsn.append(dsnstr.format(
host="{host}:{port}".format(host=dbhost, port=dbport) if dbport else dbhost, # noqa
name=dbname, user=dbuser, password=dbpass))
if dsn_style == 'all' or dsn_style == 'pgpass':
dsn.append(':'.join(map(str, filter(
None, [dbhost, dbport, dbname, dbuser, dbpass]))))
return dsn | [
"def",
"_postgresql",
"(",
"self",
",",
"dbhost",
",",
"dbport",
",",
"dbname",
",",
"dbuser",
",",
"dbpass",
",",
"dsn_style",
"=",
"None",
")",
":",
"# noqa",
"dsn",
"=",
"[",
"]",
"if",
"dsn_style",
"is",
"None",
"or",
"dsn_style",
"==",
"'all'",
... | PostgreSQL psycopg2 driver accepts two syntaxes
Plus a string for .pgpass file | [
"PostgreSQL",
"psycopg2",
"driver",
"accepts",
"two",
"syntaxes"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/sqldsn.py#L100-L141 |
238,794 | django-extensions/django-extensions | django_extensions/management/commands/dumpscript.py | check_dependencies | def check_dependencies(model, model_queue, avaliable_models):
""" Check that all the depenedencies for this model are already in the queue. """
# A list of allowed links: existing fields, itself and the special case ContentType
allowed_links = [m.model.__name__ for m in model_queue] + [model.__name__, 'ContentType']
# For each ForeignKey or ManyToMany field, check that a link is possible
for field in model._meta.fields:
if not field.remote_field:
continue
if field.remote_field.model.__name__ not in allowed_links:
if field.remote_field.model not in avaliable_models:
continue
return False
for field in model._meta.many_to_many:
if not field.remote_field:
continue
if field.remote_field.model.__name__ not in allowed_links:
return False
return True | python | def check_dependencies(model, model_queue, avaliable_models):
# A list of allowed links: existing fields, itself and the special case ContentType
allowed_links = [m.model.__name__ for m in model_queue] + [model.__name__, 'ContentType']
# For each ForeignKey or ManyToMany field, check that a link is possible
for field in model._meta.fields:
if not field.remote_field:
continue
if field.remote_field.model.__name__ not in allowed_links:
if field.remote_field.model not in avaliable_models:
continue
return False
for field in model._meta.many_to_many:
if not field.remote_field:
continue
if field.remote_field.model.__name__ not in allowed_links:
return False
return True | [
"def",
"check_dependencies",
"(",
"model",
",",
"model_queue",
",",
"avaliable_models",
")",
":",
"# A list of allowed links: existing fields, itself and the special case ContentType",
"allowed_links",
"=",
"[",
"m",
".",
"model",
".",
"__name__",
"for",
"m",
"in",
"model... | Check that all the depenedencies for this model are already in the queue. | [
"Check",
"that",
"all",
"the",
"depenedencies",
"for",
"this",
"model",
"are",
"already",
"in",
"the",
"queue",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/dumpscript.py#L712-L733 |
238,795 | django-extensions/django-extensions | django_extensions/management/commands/dumpscript.py | Code.get_import_lines | def get_import_lines(self):
""" Take the stored imports and converts them to lines """
if self.imports:
return ["from %s import %s" % (value, key) for key, value in self.imports.items()]
else:
return [] | python | def get_import_lines(self):
if self.imports:
return ["from %s import %s" % (value, key) for key, value in self.imports.items()]
else:
return [] | [
"def",
"get_import_lines",
"(",
"self",
")",
":",
"if",
"self",
".",
"imports",
":",
"return",
"[",
"\"from %s import %s\"",
"%",
"(",
"value",
",",
"key",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"imports",
".",
"items",
"(",
")",
"]",
"e... | Take the stored imports and converts them to lines | [
"Take",
"the",
"stored",
"imports",
"and",
"converts",
"them",
"to",
"lines"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/dumpscript.py#L178-L183 |
238,796 | django-extensions/django-extensions | django_extensions/management/commands/dumpscript.py | InstanceCode.skip | def skip(self):
"""
Determine whether or not this object should be skipped.
If this model instance is a parent of a single subclassed
instance, skip it. The subclassed instance will create this
parent instance for us.
TODO: Allow the user to force its creation?
"""
if self.skip_me is not None:
return self.skip_me
cls = self.instance.__class__
using = router.db_for_write(cls, instance=self.instance)
collector = Collector(using=using)
collector.collect([self.instance], collect_related=False)
sub_objects = sum([list(i) for i in collector.data.values()], [])
sub_objects_parents = [so._meta.parents for so in sub_objects]
if [self.model in p for p in sub_objects_parents].count(True) == 1:
# since this instance isn't explicitly created, it's variable name
# can't be referenced in the script, so record None in context dict
pk_name = self.instance._meta.pk.name
key = '%s_%s' % (self.model.__name__, getattr(self.instance, pk_name))
self.context[key] = None
self.skip_me = True
else:
self.skip_me = False
return self.skip_me | python | def skip(self):
if self.skip_me is not None:
return self.skip_me
cls = self.instance.__class__
using = router.db_for_write(cls, instance=self.instance)
collector = Collector(using=using)
collector.collect([self.instance], collect_related=False)
sub_objects = sum([list(i) for i in collector.data.values()], [])
sub_objects_parents = [so._meta.parents for so in sub_objects]
if [self.model in p for p in sub_objects_parents].count(True) == 1:
# since this instance isn't explicitly created, it's variable name
# can't be referenced in the script, so record None in context dict
pk_name = self.instance._meta.pk.name
key = '%s_%s' % (self.model.__name__, getattr(self.instance, pk_name))
self.context[key] = None
self.skip_me = True
else:
self.skip_me = False
return self.skip_me | [
"def",
"skip",
"(",
"self",
")",
":",
"if",
"self",
".",
"skip_me",
"is",
"not",
"None",
":",
"return",
"self",
".",
"skip_me",
"cls",
"=",
"self",
".",
"instance",
".",
"__class__",
"using",
"=",
"router",
".",
"db_for_write",
"(",
"cls",
",",
"inst... | Determine whether or not this object should be skipped.
If this model instance is a parent of a single subclassed
instance, skip it. The subclassed instance will create this
parent instance for us.
TODO: Allow the user to force its creation? | [
"Determine",
"whether",
"or",
"not",
"this",
"object",
"should",
"be",
"skipped",
".",
"If",
"this",
"model",
"instance",
"is",
"a",
"parent",
"of",
"a",
"single",
"subclassed",
"instance",
"skip",
"it",
".",
"The",
"subclassed",
"instance",
"will",
"create"... | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/dumpscript.py#L299-L327 |
238,797 | django-extensions/django-extensions | django_extensions/management/commands/dumpscript.py | InstanceCode.instantiate | def instantiate(self):
""" Write lines for instantiation """
# e.g. model_name_35 = Model()
code_lines = []
if not self.instantiated:
code_lines.append("%s = %s()" % (self.variable_name, self.model.__name__))
self.instantiated = True
# Store our variable name for future foreign key references
pk_name = self.instance._meta.pk.name
key = '%s_%s' % (self.model.__name__, getattr(self.instance, pk_name))
self.context[key] = self.variable_name
return code_lines | python | def instantiate(self):
# e.g. model_name_35 = Model()
code_lines = []
if not self.instantiated:
code_lines.append("%s = %s()" % (self.variable_name, self.model.__name__))
self.instantiated = True
# Store our variable name for future foreign key references
pk_name = self.instance._meta.pk.name
key = '%s_%s' % (self.model.__name__, getattr(self.instance, pk_name))
self.context[key] = self.variable_name
return code_lines | [
"def",
"instantiate",
"(",
"self",
")",
":",
"# e.g. model_name_35 = Model()",
"code_lines",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"instantiated",
":",
"code_lines",
".",
"append",
"(",
"\"%s = %s()\"",
"%",
"(",
"self",
".",
"variable_name",
",",
"self",
... | Write lines for instantiation | [
"Write",
"lines",
"for",
"instantiation"
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/dumpscript.py#L329-L343 |
238,798 | django-extensions/django-extensions | django_extensions/management/commands/dumpscript.py | InstanceCode.get_waiting_list | def get_waiting_list(self, force=False):
""" Add lines for any waiting fields that can be completed now. """
code_lines = []
skip_autofield = self.options['skip_autofield']
# Process normal fields
for field in list(self.waiting_list):
try:
# Find the value, add the line, remove from waiting list and move on
value = get_attribute_value(self.instance, field, self.context, force=force, skip_autofield=skip_autofield)
code_lines.append('%s.%s = %s' % (self.variable_name, field.name, value))
self.waiting_list.remove(field)
except SkipValue:
# Remove from the waiting list and move on
self.waiting_list.remove(field)
continue
except DoLater:
# Move on, maybe next time
continue
return code_lines | python | def get_waiting_list(self, force=False):
code_lines = []
skip_autofield = self.options['skip_autofield']
# Process normal fields
for field in list(self.waiting_list):
try:
# Find the value, add the line, remove from waiting list and move on
value = get_attribute_value(self.instance, field, self.context, force=force, skip_autofield=skip_autofield)
code_lines.append('%s.%s = %s' % (self.variable_name, field.name, value))
self.waiting_list.remove(field)
except SkipValue:
# Remove from the waiting list and move on
self.waiting_list.remove(field)
continue
except DoLater:
# Move on, maybe next time
continue
return code_lines | [
"def",
"get_waiting_list",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"code_lines",
"=",
"[",
"]",
"skip_autofield",
"=",
"self",
".",
"options",
"[",
"'skip_autofield'",
"]",
"# Process normal fields",
"for",
"field",
"in",
"list",
"(",
"self",
".",... | Add lines for any waiting fields that can be completed now. | [
"Add",
"lines",
"for",
"any",
"waiting",
"fields",
"that",
"can",
"be",
"completed",
"now",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/dumpscript.py#L345-L366 |
238,799 | django-extensions/django-extensions | django_extensions/management/commands/dumpscript.py | InstanceCode.get_many_to_many_lines | def get_many_to_many_lines(self, force=False):
""" Generate lines that define many to many relations for this instance. """
lines = []
for field, rel_items in self.many_to_many_waiting_list.items():
for rel_item in list(rel_items):
try:
pk_name = rel_item._meta.pk.name
key = '%s_%s' % (rel_item.__class__.__name__, getattr(rel_item, pk_name))
value = "%s" % self.context[key]
lines.append('%s.%s.add(%s)' % (self.variable_name, field.name, value))
self.many_to_many_waiting_list[field].remove(rel_item)
except KeyError:
if force:
item_locator = orm_item_locator(rel_item)
self.context["__extra_imports"][rel_item._meta.object_name] = rel_item.__module__
lines.append('%s.%s.add( %s )' % (self.variable_name, field.name, item_locator))
self.many_to_many_waiting_list[field].remove(rel_item)
if lines:
lines.append("")
return lines | python | def get_many_to_many_lines(self, force=False):
lines = []
for field, rel_items in self.many_to_many_waiting_list.items():
for rel_item in list(rel_items):
try:
pk_name = rel_item._meta.pk.name
key = '%s_%s' % (rel_item.__class__.__name__, getattr(rel_item, pk_name))
value = "%s" % self.context[key]
lines.append('%s.%s.add(%s)' % (self.variable_name, field.name, value))
self.many_to_many_waiting_list[field].remove(rel_item)
except KeyError:
if force:
item_locator = orm_item_locator(rel_item)
self.context["__extra_imports"][rel_item._meta.object_name] = rel_item.__module__
lines.append('%s.%s.add( %s )' % (self.variable_name, field.name, item_locator))
self.many_to_many_waiting_list[field].remove(rel_item)
if lines:
lines.append("")
return lines | [
"def",
"get_many_to_many_lines",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"field",
",",
"rel_items",
"in",
"self",
".",
"many_to_many_waiting_list",
".",
"items",
"(",
")",
":",
"for",
"rel_item",
"in",
"list",
"(... | Generate lines that define many to many relations for this instance. | [
"Generate",
"lines",
"that",
"define",
"many",
"to",
"many",
"relations",
"for",
"this",
"instance",
"."
] | 7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8 | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/dumpscript.py#L368-L391 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.