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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
224,900
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: """ 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()
[ "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
224,901
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: """ 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
[ "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
224,902
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: """ 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
[ "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
224,903
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: """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])
[ "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
224,904
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: """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)
[ "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
224,905
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: """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])
[ "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
224,906
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: """ 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])
[ "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
224,907
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: """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
[ "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
224,908
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: """ 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)
[ "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
224,909
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: """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)
[ "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
224,910
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: """ 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
[ "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
224,911
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: """ 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
[ "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
224,912
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: """ 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)
[ "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
224,913
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: """ 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
[ "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
224,914
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]: """Convert the set to a list of 64 bools.""" 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
224,915
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]: """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))
[ "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
224,916
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: """ 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)
[ "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
224,917
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]: """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
[ "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
224,918
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: """ 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()
[ "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
224,919
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: """ 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
[ "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
224,920
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: """ 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
[ "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
224,921
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: """Closes the reader.""" 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
224,922
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): """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']))
[ "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
224,923
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): """ 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))
[ "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
224,924
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): """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)
[ "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
224,925
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): """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
[ "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
224,926
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): """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
[ "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
224,927
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): """Form an attributes dictionary from keyword args.""" 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
224,928
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): """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))
[ "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
224,929
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): """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)
[ "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
224,930
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): """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))
[ "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
224,931
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): """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)
[ "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
224,932
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): """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)
[ "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
224,933
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): """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)
[ "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
224,934
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): """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
[ "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
224,935
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): """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
[ "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
224,936
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): """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
[ "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
224,937
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): """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']
[ "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
224,938
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): """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
[ "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
224,939
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): """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
[ "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
224,940
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): """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
[ "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
224,941
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): """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)
[ "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
224,942
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): """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)}
[ "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
224,943
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): """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)}
[ "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
224,944
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): """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
[ "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
224,945
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): """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
[ "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
224,946
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): """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
[ "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
224,947
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): """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")
[ "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
224,948
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): """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()
[ "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
224,949
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'): """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
[ "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
224,950
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): """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
[ "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
224,951
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, ): """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
[ "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
224,952
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): """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
[ "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
224,953
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): """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
[ "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
224,954
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): """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
[ "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
224,955
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): """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
[ "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
224,956
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): """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
[ "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
224,957
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): """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
[ "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
224,958
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"): """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
[ "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
224,959
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): """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
[ "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
224,960
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): """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
[ "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
224,961
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(): """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
[ "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
224,962
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): """ 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)
[ "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
224,963
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): """Return full name or username.""" 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
224,964
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): """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']])
[ "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
224,965
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): """ 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']])
[ "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
224,966
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): """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)
[ "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
224,967
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): """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())
[ "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
224,968
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): """ 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 '', '', '', '', ''
[ "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
224,969
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): """ 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
[ "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
224,970
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): """ 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)
[ "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
224,971
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): """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
[ "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
224,972
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): """ 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)
[ "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
224,973
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): """Shorcut for return contents as json""" 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
224,974
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): """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]
[ "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
224,975
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 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)))
[ "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
224,976
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): """ 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)
[ "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
224,977
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 """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
[ "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
224,978
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): """ 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
[ "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
224,979
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): """ 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 []
[ "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
224,980
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): """ 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
[ "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
224,981
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): """ 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
[ "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
224,982
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): """ 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
[ "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
224,983
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): """ 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
[ "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
224,984
django-extensions/django-extensions
django_extensions/management/commands/dumpscript.py
Script._queue_models
def _queue_models(self, models, context): """ Work an an appropriate ordering for the models. This isn't essential, but makes the script look nicer because more instances can be defined on their first try. """ model_queue = [] number_remaining_models = len(models) # Max number of cycles allowed before we call it an infinite loop. MAX_CYCLES = number_remaining_models allowed_cycles = MAX_CYCLES while number_remaining_models > 0: previous_number_remaining_models = number_remaining_models model = models.pop(0) # If the model is ready to be processed, add it to the list if check_dependencies(model, model_queue, context["__avaliable_models"]): model_class = ModelCode(model=model, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options) model_queue.append(model_class) # Otherwise put the model back at the end of the list else: models.append(model) # Check for infinite loops. # This means there is a cyclic foreign key structure # That cannot be resolved by re-ordering number_remaining_models = len(models) if number_remaining_models == previous_number_remaining_models: allowed_cycles -= 1 if allowed_cycles <= 0: # Add the remaining models, but do not remove them from the model list missing_models = [ModelCode(model=m, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options) for m in models] model_queue += missing_models # Replace the models with the model class objects # (sure, this is a little bit of hackery) models[:] = missing_models break else: allowed_cycles = MAX_CYCLES return model_queue
python
def _queue_models(self, models, context): """ Work an an appropriate ordering for the models. This isn't essential, but makes the script look nicer because more instances can be defined on their first try. """ model_queue = [] number_remaining_models = len(models) # Max number of cycles allowed before we call it an infinite loop. MAX_CYCLES = number_remaining_models allowed_cycles = MAX_CYCLES while number_remaining_models > 0: previous_number_remaining_models = number_remaining_models model = models.pop(0) # If the model is ready to be processed, add it to the list if check_dependencies(model, model_queue, context["__avaliable_models"]): model_class = ModelCode(model=model, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options) model_queue.append(model_class) # Otherwise put the model back at the end of the list else: models.append(model) # Check for infinite loops. # This means there is a cyclic foreign key structure # That cannot be resolved by re-ordering number_remaining_models = len(models) if number_remaining_models == previous_number_remaining_models: allowed_cycles -= 1 if allowed_cycles <= 0: # Add the remaining models, but do not remove them from the model list missing_models = [ModelCode(model=m, context=context, stdout=self.stdout, stderr=self.stderr, options=self.options) for m in models] model_queue += missing_models # Replace the models with the model class objects # (sure, this is a little bit of hackery) models[:] = missing_models break else: allowed_cycles = MAX_CYCLES return model_queue
[ "def", "_queue_models", "(", "self", ",", "models", ",", "context", ")", ":", "model_queue", "=", "[", "]", "number_remaining_models", "=", "len", "(", "models", ")", "# Max number of cycles allowed before we call it an infinite loop.", "MAX_CYCLES", "=", "number_remain...
Work an an appropriate ordering for the models. This isn't essential, but makes the script look nicer because more instances can be defined on their first try.
[ "Work", "an", "an", "appropriate", "ordering", "for", "the", "models", ".", "This", "isn", "t", "essential", "but", "makes", "the", "script", "look", "nicer", "because", "more", "instances", "can", "be", "defined", "on", "their", "first", "try", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/dumpscript.py#L411-L454
224,985
django-extensions/django-extensions
django_extensions/management/commands/sqldiff.py
SQLDiff.sql_to_dict
def sql_to_dict(self, query, param): """ Execute query and return a dict sql_to_dict(query, param) -> list of dicts code from snippet at http://www.djangosnippets.org/snippets/1383/ """ cursor = connection.cursor() cursor.execute(query, param) fieldnames = [name[0] for name in cursor.description] result = [] for row in cursor.fetchall(): rowset = [] for field in zip(fieldnames, row): rowset.append(field) result.append(dict(rowset)) return result
python
def sql_to_dict(self, query, param): """ Execute query and return a dict sql_to_dict(query, param) -> list of dicts code from snippet at http://www.djangosnippets.org/snippets/1383/ """ cursor = connection.cursor() cursor.execute(query, param) fieldnames = [name[0] for name in cursor.description] result = [] for row in cursor.fetchall(): rowset = [] for field in zip(fieldnames, row): rowset.append(field) result.append(dict(rowset)) return result
[ "def", "sql_to_dict", "(", "self", ",", "query", ",", "param", ")", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "query", ",", "param", ")", "fieldnames", "=", "[", "name", "[", "0", "]", "for", "name", ...
Execute query and return a dict sql_to_dict(query, param) -> list of dicts code from snippet at http://www.djangosnippets.org/snippets/1383/
[ "Execute", "query", "and", "return", "a", "dict" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/sqldiff.py#L257-L274
224,986
django-extensions/django-extensions
django_extensions/management/commands/sqldiff.py
SQLDiff.print_diff
def print_diff(self, style=no_style()): """ Print differences to stdout """ if self.options['sql']: self.print_diff_sql(style) else: self.print_diff_text(style)
python
def print_diff(self, style=no_style()): """ Print differences to stdout """ if self.options['sql']: self.print_diff_sql(style) else: self.print_diff_text(style)
[ "def", "print_diff", "(", "self", ",", "style", "=", "no_style", "(", ")", ")", ":", "if", "self", ".", "options", "[", "'sql'", "]", ":", "self", ".", "print_diff_sql", "(", "style", ")", "else", ":", "self", ".", "print_diff_text", "(", "style", ")...
Print differences to stdout
[ "Print", "differences", "to", "stdout" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/sqldiff.py#L676-L681
224,987
django-extensions/django-extensions
django_extensions/templatetags/syntax_color.py
pygments_required
def pygments_required(func): """Raise ImportError if pygments is not installed.""" def wrapper(*args, **kwargs): if not HAS_PYGMENTS: # pragma: no cover raise ImportError( "Please install 'pygments' library to use syntax_color.") rv = func(*args, **kwargs) return rv return wrapper
python
def pygments_required(func): """Raise ImportError if pygments is not installed.""" def wrapper(*args, **kwargs): if not HAS_PYGMENTS: # pragma: no cover raise ImportError( "Please install 'pygments' library to use syntax_color.") rv = func(*args, **kwargs) return rv return wrapper
[ "def", "pygments_required", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "HAS_PYGMENTS", ":", "# pragma: no cover", "raise", "ImportError", "(", "\"Please install 'pygments' library to use syntax_color.\"...
Raise ImportError if pygments is not installed.
[ "Raise", "ImportError", "if", "pygments", "is", "not", "installed", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/templatetags/syntax_color.py#L54-L62
224,988
django-extensions/django-extensions
django_extensions/utils/dia2django.py
addparentstofks
def addparentstofks(rels, fks): """ Get a list of relations, between parents and sons and a dict of clases named in dia, and modifies the fks to add the parent as fk to get order on the output of classes and replaces the base class of the son, to put the class parent name. """ for j in rels: son = index(fks, j[1]) parent = index(fks, j[0]) fks[son][2] = fks[son][2].replace("models.Model", parent) if parent not in fks[son][0]: fks[son][0].append(parent)
python
def addparentstofks(rels, fks): """ Get a list of relations, between parents and sons and a dict of clases named in dia, and modifies the fks to add the parent as fk to get order on the output of classes and replaces the base class of the son, to put the class parent name. """ for j in rels: son = index(fks, j[1]) parent = index(fks, j[0]) fks[son][2] = fks[son][2].replace("models.Model", parent) if parent not in fks[son][0]: fks[son][0].append(parent)
[ "def", "addparentstofks", "(", "rels", ",", "fks", ")", ":", "for", "j", "in", "rels", ":", "son", "=", "index", "(", "fks", ",", "j", "[", "1", "]", ")", "parent", "=", "index", "(", "fks", ",", "j", "[", "0", "]", ")", "fks", "[", "son", ...
Get a list of relations, between parents and sons and a dict of clases named in dia, and modifies the fks to add the parent as fk to get order on the output of classes and replaces the base class of the son, to put the class parent name.
[ "Get", "a", "list", "of", "relations", "between", "parents", "and", "sons", "and", "a", "dict", "of", "clases", "named", "in", "dia", "and", "modifies", "the", "fks", "to", "add", "the", "parent", "as", "fk", "to", "get", "order", "on", "the", "output"...
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/utils/dia2django.py#L57-L69
224,989
django-extensions/django-extensions
django_extensions/management/shells.py
get_app_name
def get_app_name(mod_name): """ Retrieve application name from models.py module path >>> get_app_name('testapp.models.foo') 'testapp' 'testapp' instead of 'some.testapp' for compatibility: >>> get_app_name('some.testapp.models.foo') 'testapp' >>> get_app_name('some.models.testapp.models.foo') 'testapp' >>> get_app_name('testapp.foo') 'testapp' >>> get_app_name('some.testapp.foo') 'testapp' """ rparts = list(reversed(mod_name.split('.'))) try: try: return rparts[rparts.index(MODELS_MODULE_NAME) + 1] except ValueError: # MODELS_MODULE_NAME ('models' string) is not found return rparts[1] except IndexError: # Some weird model naming scheme like in Sentry. return mod_name
python
def get_app_name(mod_name): """ Retrieve application name from models.py module path >>> get_app_name('testapp.models.foo') 'testapp' 'testapp' instead of 'some.testapp' for compatibility: >>> get_app_name('some.testapp.models.foo') 'testapp' >>> get_app_name('some.models.testapp.models.foo') 'testapp' >>> get_app_name('testapp.foo') 'testapp' >>> get_app_name('some.testapp.foo') 'testapp' """ rparts = list(reversed(mod_name.split('.'))) try: try: return rparts[rparts.index(MODELS_MODULE_NAME) + 1] except ValueError: # MODELS_MODULE_NAME ('models' string) is not found return rparts[1] except IndexError: # Some weird model naming scheme like in Sentry. return mod_name
[ "def", "get_app_name", "(", "mod_name", ")", ":", "rparts", "=", "list", "(", "reversed", "(", "mod_name", ".", "split", "(", "'.'", ")", ")", ")", "try", ":", "try", ":", "return", "rparts", "[", "rparts", ".", "index", "(", "MODELS_MODULE_NAME", ")",...
Retrieve application name from models.py module path >>> get_app_name('testapp.models.foo') 'testapp' 'testapp' instead of 'some.testapp' for compatibility: >>> get_app_name('some.testapp.models.foo') 'testapp' >>> get_app_name('some.models.testapp.models.foo') 'testapp' >>> get_app_name('testapp.foo') 'testapp' >>> get_app_name('some.testapp.foo') 'testapp'
[ "Retrieve", "application", "name", "from", "models", ".", "py", "module", "path" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/shells.py#L46-L72
224,990
django-extensions/django-extensions
django_extensions/management/commands/merge_model_instances.py
get_generic_fields
def get_generic_fields(): """Return a list of all GenericForeignKeys in all models.""" generic_fields = [] for model in apps.get_models(): for field_name, field in model.__dict__.items(): if isinstance(field, GenericForeignKey): generic_fields.append(field) return generic_fields
python
def get_generic_fields(): """Return a list of all GenericForeignKeys in all models.""" generic_fields = [] for model in apps.get_models(): for field_name, field in model.__dict__.items(): if isinstance(field, GenericForeignKey): generic_fields.append(field) return generic_fields
[ "def", "get_generic_fields", "(", ")", ":", "generic_fields", "=", "[", "]", "for", "model", "in", "apps", ".", "get_models", "(", ")", ":", "for", "field_name", ",", "field", "in", "model", ".", "__dict__", ".", "items", "(", ")", ":", "if", "isinstan...
Return a list of all GenericForeignKeys in all models.
[ "Return", "a", "list", "of", "all", "GenericForeignKeys", "in", "all", "models", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/merge_model_instances.py#L78-L85
224,991
django-extensions/django-extensions
django_extensions/management/commands/merge_model_instances.py
Command.merge_model_instances
def merge_model_instances(self, primary_object, alias_objects): """ Merge several model instances into one, the `primary_object`. Use this function to merge model objects and migrate all of the related fields from the alias objects the primary object. """ generic_fields = get_generic_fields() # get related fields related_fields = list(filter( lambda x: x.is_relation is True, primary_object._meta.get_fields())) many_to_many_fields = list(filter( lambda x: x.many_to_many is True, related_fields)) related_fields = list(filter( lambda x: x.many_to_many is False, related_fields)) # Loop through all alias objects and migrate their references to the # primary object deleted_objects = [] deleted_objects_count = 0 for alias_object in alias_objects: # Migrate all foreign key references from alias object to primary # object. for many_to_many_field in many_to_many_fields: alias_varname = many_to_many_field.name related_objects = getattr(alias_object, alias_varname) for obj in related_objects.all(): try: # Handle regular M2M relationships. getattr(alias_object, alias_varname).remove(obj) getattr(primary_object, alias_varname).add(obj) except AttributeError: # Handle M2M relationships with a 'through' model. # This does not delete the 'through model. # TODO: Allow the user to delete a duplicate 'through' model. through_model = getattr(alias_object, alias_varname).through kwargs = { many_to_many_field.m2m_reverse_field_name(): obj, many_to_many_field.m2m_field_name(): alias_object, } through_model_instances = through_model.objects.filter(**kwargs) for instance in through_model_instances: # Re-attach the through model to the primary_object setattr( instance, many_to_many_field.m2m_field_name(), primary_object) instance.save() # TODO: Here, try to delete duplicate instances that are # disallowed by a unique_together constraint for related_field in related_fields: if related_field.one_to_many: alias_varname = related_field.get_accessor_name() related_objects = getattr(alias_object, alias_varname) for obj in related_objects.all(): field_name = related_field.field.name setattr(obj, field_name, primary_object) obj.save() elif related_field.one_to_one or related_field.many_to_one: alias_varname = related_field.name related_object = getattr(alias_object, alias_varname) primary_related_object = getattr(primary_object, alias_varname) if primary_related_object is None: setattr(primary_object, alias_varname, related_object) primary_object.save() elif related_field.one_to_one: self.stdout.write("Deleted {} with id {}\n".format( related_object, related_object.id)) related_object.delete() for field in generic_fields: filter_kwargs = {} filter_kwargs[field.fk_field] = alias_object._get_pk_val() filter_kwargs[field.ct_field] = field.get_content_type(alias_object) related_objects = field.model.objects.filter(**filter_kwargs) for generic_related_object in related_objects: setattr(generic_related_object, field.name, primary_object) generic_related_object.save() if alias_object.id: deleted_objects += [alias_object] self.stdout.write("Deleted {} with id {}\n".format( alias_object, alias_object.id)) alias_object.delete() deleted_objects_count += 1 return primary_object, deleted_objects, deleted_objects_count
python
def merge_model_instances(self, primary_object, alias_objects): """ Merge several model instances into one, the `primary_object`. Use this function to merge model objects and migrate all of the related fields from the alias objects the primary object. """ generic_fields = get_generic_fields() # get related fields related_fields = list(filter( lambda x: x.is_relation is True, primary_object._meta.get_fields())) many_to_many_fields = list(filter( lambda x: x.many_to_many is True, related_fields)) related_fields = list(filter( lambda x: x.many_to_many is False, related_fields)) # Loop through all alias objects and migrate their references to the # primary object deleted_objects = [] deleted_objects_count = 0 for alias_object in alias_objects: # Migrate all foreign key references from alias object to primary # object. for many_to_many_field in many_to_many_fields: alias_varname = many_to_many_field.name related_objects = getattr(alias_object, alias_varname) for obj in related_objects.all(): try: # Handle regular M2M relationships. getattr(alias_object, alias_varname).remove(obj) getattr(primary_object, alias_varname).add(obj) except AttributeError: # Handle M2M relationships with a 'through' model. # This does not delete the 'through model. # TODO: Allow the user to delete a duplicate 'through' model. through_model = getattr(alias_object, alias_varname).through kwargs = { many_to_many_field.m2m_reverse_field_name(): obj, many_to_many_field.m2m_field_name(): alias_object, } through_model_instances = through_model.objects.filter(**kwargs) for instance in through_model_instances: # Re-attach the through model to the primary_object setattr( instance, many_to_many_field.m2m_field_name(), primary_object) instance.save() # TODO: Here, try to delete duplicate instances that are # disallowed by a unique_together constraint for related_field in related_fields: if related_field.one_to_many: alias_varname = related_field.get_accessor_name() related_objects = getattr(alias_object, alias_varname) for obj in related_objects.all(): field_name = related_field.field.name setattr(obj, field_name, primary_object) obj.save() elif related_field.one_to_one or related_field.many_to_one: alias_varname = related_field.name related_object = getattr(alias_object, alias_varname) primary_related_object = getattr(primary_object, alias_varname) if primary_related_object is None: setattr(primary_object, alias_varname, related_object) primary_object.save() elif related_field.one_to_one: self.stdout.write("Deleted {} with id {}\n".format( related_object, related_object.id)) related_object.delete() for field in generic_fields: filter_kwargs = {} filter_kwargs[field.fk_field] = alias_object._get_pk_val() filter_kwargs[field.ct_field] = field.get_content_type(alias_object) related_objects = field.model.objects.filter(**filter_kwargs) for generic_related_object in related_objects: setattr(generic_related_object, field.name, primary_object) generic_related_object.save() if alias_object.id: deleted_objects += [alias_object] self.stdout.write("Deleted {} with id {}\n".format( alias_object, alias_object.id)) alias_object.delete() deleted_objects_count += 1 return primary_object, deleted_objects, deleted_objects_count
[ "def", "merge_model_instances", "(", "self", ",", "primary_object", ",", "alias_objects", ")", ":", "generic_fields", "=", "get_generic_fields", "(", ")", "# get related fields", "related_fields", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", ".", "i...
Merge several model instances into one, the `primary_object`. Use this function to merge model objects and migrate all of the related fields from the alias objects the primary object.
[ "Merge", "several", "model", "instances", "into", "one", "the", "primary_object", ".", "Use", "this", "function", "to", "merge", "model", "objects", "and", "migrate", "all", "of", "the", "related", "fields", "from", "the", "alias", "objects", "the", "primary",...
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/merge_model_instances.py#L132-L222
224,992
django-extensions/django-extensions
django_extensions/management/commands/graph_models.py
Command.add_arguments
def add_arguments(self, parser): """Unpack self.arguments for parser.add_arguments.""" parser.add_argument('app_label', nargs='*') for argument in self.arguments: parser.add_argument(*argument.split(' '), **self.arguments[argument])
python
def add_arguments(self, parser): """Unpack self.arguments for parser.add_arguments.""" parser.add_argument('app_label', nargs='*') for argument in self.arguments: parser.add_argument(*argument.split(' '), **self.arguments[argument])
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "'app_label'", ",", "nargs", "=", "'*'", ")", "for", "argument", "in", "self", ".", "arguments", ":", "parser", ".", "add_argument", "(", "*", "argument", "...
Unpack self.arguments for parser.add_arguments.
[ "Unpack", "self", ".", "arguments", "for", "parser", ".", "add_arguments", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/graph_models.py#L169-L173
224,993
django-extensions/django-extensions
django_extensions/management/commands/graph_models.py
Command.render_output_json
def render_output_json(self, graph_data, output_file=None): """Write model data to file or stdout in JSON format.""" if output_file: with open(output_file, 'wt') as json_output_f: json.dump(graph_data, json_output_f) else: self.stdout.write(json.dumps(graph_data))
python
def render_output_json(self, graph_data, output_file=None): """Write model data to file or stdout in JSON format.""" if output_file: with open(output_file, 'wt') as json_output_f: json.dump(graph_data, json_output_f) else: self.stdout.write(json.dumps(graph_data))
[ "def", "render_output_json", "(", "self", ",", "graph_data", ",", "output_file", "=", "None", ")", ":", "if", "output_file", ":", "with", "open", "(", "output_file", ",", "'wt'", ")", "as", "json_output_f", ":", "json", ".", "dump", "(", "graph_data", ",",...
Write model data to file or stdout in JSON format.
[ "Write", "model", "data", "to", "file", "or", "stdout", "in", "JSON", "format", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/graph_models.py#L246-L252
224,994
django-extensions/django-extensions
django_extensions/management/commands/graph_models.py
Command.render_output_pygraphviz
def render_output_pygraphviz(self, dotdata, **kwargs): """Render model data as image using pygraphviz""" if not HAS_PYGRAPHVIZ: raise CommandError("You need to install pygraphviz python module") version = pygraphviz.__version__.rstrip("-svn") try: if tuple(int(v) for v in version.split('.')) < (0, 36): # HACK around old/broken AGraph before version 0.36 (ubuntu ships with this old version) tmpfile = tempfile.NamedTemporaryFile() tmpfile.write(dotdata) tmpfile.seek(0) dotdata = tmpfile.name except ValueError: pass graph = pygraphviz.AGraph(dotdata) graph.layout(prog=kwargs['layout']) graph.draw(kwargs['outputfile'])
python
def render_output_pygraphviz(self, dotdata, **kwargs): """Render model data as image using pygraphviz""" if not HAS_PYGRAPHVIZ: raise CommandError("You need to install pygraphviz python module") version = pygraphviz.__version__.rstrip("-svn") try: if tuple(int(v) for v in version.split('.')) < (0, 36): # HACK around old/broken AGraph before version 0.36 (ubuntu ships with this old version) tmpfile = tempfile.NamedTemporaryFile() tmpfile.write(dotdata) tmpfile.seek(0) dotdata = tmpfile.name except ValueError: pass graph = pygraphviz.AGraph(dotdata) graph.layout(prog=kwargs['layout']) graph.draw(kwargs['outputfile'])
[ "def", "render_output_pygraphviz", "(", "self", ",", "dotdata", ",", "*", "*", "kwargs", ")", ":", "if", "not", "HAS_PYGRAPHVIZ", ":", "raise", "CommandError", "(", "\"You need to install pygraphviz python module\"", ")", "version", "=", "pygraphviz", ".", "__versio...
Render model data as image using pygraphviz
[ "Render", "model", "data", "as", "image", "using", "pygraphviz" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/graph_models.py#L254-L272
224,995
django-extensions/django-extensions
django_extensions/management/commands/graph_models.py
Command.render_output_pydot
def render_output_pydot(self, dotdata, **kwargs): """Render model data as image using pydot""" if not HAS_PYDOT: raise CommandError("You need to install pydot python module") graph = pydot.graph_from_dot_data(dotdata) if not graph: raise CommandError("pydot returned an error") if isinstance(graph, (list, tuple)): if len(graph) > 1: sys.stderr.write("Found more then one graph, rendering only the first one.\n") graph = graph[0] output_file = kwargs['outputfile'] formats = [ 'bmp', 'canon', 'cmap', 'cmapx', 'cmapx_np', 'dot', 'dia', 'emf', 'em', 'fplus', 'eps', 'fig', 'gd', 'gd2', 'gif', 'gv', 'imap', 'imap_np', 'ismap', 'jpe', 'jpeg', 'jpg', 'metafile', 'pdf', 'pic', 'plain', 'plain-ext', 'png', 'pov', 'ps', 'ps2', 'svg', 'svgz', 'tif', 'tiff', 'tk', 'vml', 'vmlz', 'vrml', 'wbmp', 'xdot', ] ext = output_file[output_file.rfind('.') + 1:] format_ = ext if ext in formats else 'raw' graph.write(output_file, format=format_)
python
def render_output_pydot(self, dotdata, **kwargs): """Render model data as image using pydot""" if not HAS_PYDOT: raise CommandError("You need to install pydot python module") graph = pydot.graph_from_dot_data(dotdata) if not graph: raise CommandError("pydot returned an error") if isinstance(graph, (list, tuple)): if len(graph) > 1: sys.stderr.write("Found more then one graph, rendering only the first one.\n") graph = graph[0] output_file = kwargs['outputfile'] formats = [ 'bmp', 'canon', 'cmap', 'cmapx', 'cmapx_np', 'dot', 'dia', 'emf', 'em', 'fplus', 'eps', 'fig', 'gd', 'gd2', 'gif', 'gv', 'imap', 'imap_np', 'ismap', 'jpe', 'jpeg', 'jpg', 'metafile', 'pdf', 'pic', 'plain', 'plain-ext', 'png', 'pov', 'ps', 'ps2', 'svg', 'svgz', 'tif', 'tiff', 'tk', 'vml', 'vmlz', 'vrml', 'wbmp', 'xdot', ] ext = output_file[output_file.rfind('.') + 1:] format_ = ext if ext in formats else 'raw' graph.write(output_file, format=format_)
[ "def", "render_output_pydot", "(", "self", ",", "dotdata", ",", "*", "*", "kwargs", ")", ":", "if", "not", "HAS_PYDOT", ":", "raise", "CommandError", "(", "\"You need to install pydot python module\"", ")", "graph", "=", "pydot", ".", "graph_from_dot_data", "(", ...
Render model data as image using pydot
[ "Render", "model", "data", "as", "image", "using", "pydot" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/graph_models.py#L274-L297
224,996
django-extensions/django-extensions
django_extensions/management/commands/show_urls.py
Command.extract_views_from_urlpatterns
def extract_views_from_urlpatterns(self, urlpatterns, base='', namespace=None): """ Return a list of views from a list of urlpatterns. Each object in the returned list is a three-tuple: (view_func, regex, name) """ views = [] for p in urlpatterns: if isinstance(p, (URLPattern, RegexURLPattern)): try: if not p.name: name = p.name elif namespace: name = '{0}:{1}'.format(namespace, p.name) else: name = p.name pattern = describe_pattern(p) views.append((p.callback, base + pattern, name)) except ViewDoesNotExist: continue elif isinstance(p, (URLResolver, RegexURLResolver)): try: patterns = p.url_patterns except ImportError: continue if namespace and p.namespace: _namespace = '{0}:{1}'.format(namespace, p.namespace) else: _namespace = (p.namespace or namespace) pattern = describe_pattern(p) if isinstance(p, LocaleRegexURLResolver): for language in self.LANGUAGES: with translation.override(language[0]): views.extend(self.extract_views_from_urlpatterns(patterns, base + pattern, namespace=_namespace)) else: views.extend(self.extract_views_from_urlpatterns(patterns, base + pattern, namespace=_namespace)) elif hasattr(p, '_get_callback'): try: views.append((p._get_callback(), base + describe_pattern(p), p.name)) except ViewDoesNotExist: continue elif hasattr(p, 'url_patterns') or hasattr(p, '_get_url_patterns'): try: patterns = p.url_patterns except ImportError: continue views.extend(self.extract_views_from_urlpatterns(patterns, base + describe_pattern(p), namespace=namespace)) else: raise TypeError("%s does not appear to be a urlpattern object" % p) return views
python
def extract_views_from_urlpatterns(self, urlpatterns, base='', namespace=None): """ Return a list of views from a list of urlpatterns. Each object in the returned list is a three-tuple: (view_func, regex, name) """ views = [] for p in urlpatterns: if isinstance(p, (URLPattern, RegexURLPattern)): try: if not p.name: name = p.name elif namespace: name = '{0}:{1}'.format(namespace, p.name) else: name = p.name pattern = describe_pattern(p) views.append((p.callback, base + pattern, name)) except ViewDoesNotExist: continue elif isinstance(p, (URLResolver, RegexURLResolver)): try: patterns = p.url_patterns except ImportError: continue if namespace and p.namespace: _namespace = '{0}:{1}'.format(namespace, p.namespace) else: _namespace = (p.namespace or namespace) pattern = describe_pattern(p) if isinstance(p, LocaleRegexURLResolver): for language in self.LANGUAGES: with translation.override(language[0]): views.extend(self.extract_views_from_urlpatterns(patterns, base + pattern, namespace=_namespace)) else: views.extend(self.extract_views_from_urlpatterns(patterns, base + pattern, namespace=_namespace)) elif hasattr(p, '_get_callback'): try: views.append((p._get_callback(), base + describe_pattern(p), p.name)) except ViewDoesNotExist: continue elif hasattr(p, 'url_patterns') or hasattr(p, '_get_url_patterns'): try: patterns = p.url_patterns except ImportError: continue views.extend(self.extract_views_from_urlpatterns(patterns, base + describe_pattern(p), namespace=namespace)) else: raise TypeError("%s does not appear to be a urlpattern object" % p) return views
[ "def", "extract_views_from_urlpatterns", "(", "self", ",", "urlpatterns", ",", "base", "=", "''", ",", "namespace", "=", "None", ")", ":", "views", "=", "[", "]", "for", "p", "in", "urlpatterns", ":", "if", "isinstance", "(", "p", ",", "(", "URLPattern",...
Return a list of views from a list of urlpatterns. Each object in the returned list is a three-tuple: (view_func, regex, name)
[ "Return", "a", "list", "of", "views", "from", "a", "list", "of", "urlpatterns", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/show_urls.py#L196-L245
224,997
django-extensions/django-extensions
django_extensions/admin/__init__.py
ForeignKeyAutocompleteAdminMixin.foreignkey_autocomplete
def foreignkey_autocomplete(self, request): """ Search in the fields of the given related model and returns the result as a simple string to be used by the jQuery Autocomplete plugin """ query = request.GET.get('q', None) app_label = request.GET.get('app_label', None) model_name = request.GET.get('model_name', None) search_fields = request.GET.get('search_fields', None) object_pk = request.GET.get('object_pk', None) try: to_string_function = self.related_string_functions[model_name] except KeyError: if six.PY3: to_string_function = lambda x: x.__str__() else: to_string_function = lambda x: x.__unicode__() if search_fields and app_label and model_name and (query or object_pk): def construct_search(field_name): # use different lookup methods depending on the notation if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name model = apps.get_model(app_label, model_name) queryset = model._default_manager.all() data = '' if query: for bit in query.split(): or_queries = [models.Q(**{construct_search(smart_str(field_name)): smart_str(bit)}) for field_name in search_fields.split(',')] other_qs = QuerySet(model) other_qs.query.select_related = queryset.query.select_related other_qs = other_qs.filter(reduce(operator.or_, or_queries)) queryset = queryset & other_qs additional_filter = self.get_related_filter(model, request) if additional_filter: queryset = queryset.filter(additional_filter) if self.autocomplete_limit: queryset = queryset[:self.autocomplete_limit] data = ''.join([six.u('%s|%s\n') % (to_string_function(f), f.pk) for f in queryset]) elif object_pk: try: obj = queryset.get(pk=object_pk) except Exception: # FIXME: use stricter exception checking pass else: data = to_string_function(obj) return HttpResponse(data, content_type='text/plain') return HttpResponseNotFound()
python
def foreignkey_autocomplete(self, request): """ Search in the fields of the given related model and returns the result as a simple string to be used by the jQuery Autocomplete plugin """ query = request.GET.get('q', None) app_label = request.GET.get('app_label', None) model_name = request.GET.get('model_name', None) search_fields = request.GET.get('search_fields', None) object_pk = request.GET.get('object_pk', None) try: to_string_function = self.related_string_functions[model_name] except KeyError: if six.PY3: to_string_function = lambda x: x.__str__() else: to_string_function = lambda x: x.__unicode__() if search_fields and app_label and model_name and (query or object_pk): def construct_search(field_name): # use different lookup methods depending on the notation if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name model = apps.get_model(app_label, model_name) queryset = model._default_manager.all() data = '' if query: for bit in query.split(): or_queries = [models.Q(**{construct_search(smart_str(field_name)): smart_str(bit)}) for field_name in search_fields.split(',')] other_qs = QuerySet(model) other_qs.query.select_related = queryset.query.select_related other_qs = other_qs.filter(reduce(operator.or_, or_queries)) queryset = queryset & other_qs additional_filter = self.get_related_filter(model, request) if additional_filter: queryset = queryset.filter(additional_filter) if self.autocomplete_limit: queryset = queryset[:self.autocomplete_limit] data = ''.join([six.u('%s|%s\n') % (to_string_function(f), f.pk) for f in queryset]) elif object_pk: try: obj = queryset.get(pk=object_pk) except Exception: # FIXME: use stricter exception checking pass else: data = to_string_function(obj) return HttpResponse(data, content_type='text/plain') return HttpResponseNotFound()
[ "def", "foreignkey_autocomplete", "(", "self", ",", "request", ")", ":", "query", "=", "request", ".", "GET", ".", "get", "(", "'q'", ",", "None", ")", "app_label", "=", "request", ".", "GET", ".", "get", "(", "'app_label'", ",", "None", ")", "model_na...
Search in the fields of the given related model and returns the result as a simple string to be used by the jQuery Autocomplete plugin
[ "Search", "in", "the", "fields", "of", "the", "given", "related", "model", "and", "returns", "the", "result", "as", "a", "simple", "string", "to", "be", "used", "by", "the", "jQuery", "Autocomplete", "plugin" ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/admin/__init__.py#L67-L126
224,998
django-extensions/django-extensions
django_extensions/admin/__init__.py
ForeignKeyAutocompleteAdminMixin.formfield_for_dbfield
def formfield_for_dbfield(self, db_field, **kwargs): """ Override the default widget for Foreignkey fields if they are specified in the related_search_fields class attribute. """ if isinstance(db_field, models.ForeignKey) and db_field.name in self.related_search_fields: help_text = self.get_help_text(db_field.name, db_field.remote_field.model._meta.object_name) if kwargs.get('help_text'): help_text = six.u('%s %s' % (kwargs['help_text'], help_text)) kwargs['widget'] = ForeignKeySearchInput(db_field.remote_field, self.related_search_fields[db_field.name]) kwargs['help_text'] = help_text return super(ForeignKeyAutocompleteAdminMixin, self).formfield_for_dbfield(db_field, **kwargs)
python
def formfield_for_dbfield(self, db_field, **kwargs): """ Override the default widget for Foreignkey fields if they are specified in the related_search_fields class attribute. """ if isinstance(db_field, models.ForeignKey) and db_field.name in self.related_search_fields: help_text = self.get_help_text(db_field.name, db_field.remote_field.model._meta.object_name) if kwargs.get('help_text'): help_text = six.u('%s %s' % (kwargs['help_text'], help_text)) kwargs['widget'] = ForeignKeySearchInput(db_field.remote_field, self.related_search_fields[db_field.name]) kwargs['help_text'] = help_text return super(ForeignKeyAutocompleteAdminMixin, self).formfield_for_dbfield(db_field, **kwargs)
[ "def", "formfield_for_dbfield", "(", "self", ",", "db_field", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "db_field", ",", "models", ".", "ForeignKey", ")", "and", "db_field", ".", "name", "in", "self", ".", "related_search_fields", ":", "h...
Override the default widget for Foreignkey fields if they are specified in the related_search_fields class attribute.
[ "Override", "the", "default", "widget", "for", "Foreignkey", "fields", "if", "they", "are", "specified", "in", "the", "related_search_fields", "class", "attribute", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/admin/__init__.py#L147-L158
224,999
django-extensions/django-extensions
django_extensions/management/technical_response.py
null_technical_500_response
def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500): """ Alternative function for django.views.debug.technical_500_response. Django's convert_exception_to_response() wrapper is called on each 'Middleware' object to avoid leaking exceptions. If an uncaught exception is raised, the wrapper calls technical_500_response() to create a response for django's debug view. Runserver_plus overrides the django debug view's technical_500_response() function to allow for an enhanced WSGI debugger view to be displayed. However, because Django calls convert_exception_to_response() on each object in the stack of Middleware objects, re-raising an error quickly pollutes the traceback displayed. Runserver_plus only needs needs traceback frames relevant to WSGIHandler Middleware objects, so only store the traceback if it is for a WSGIHandler. If an exception is not raised here, Django eventually throws an error for not getting a valid response object for its debug view. """ try: # Store the most recent tb for WSGI requests. The class can be found in the second frame of the tb if isinstance(tb.tb_next.tb_frame.f_locals.get('self'), WSGIHandler): tld.wsgi_tb = tb elif tld.wsgi_tb: tb = tld.wsgi_tb except AttributeError: pass six.reraise(exc_type, exc_value, tb)
python
def null_technical_500_response(request, exc_type, exc_value, tb, status_code=500): """ Alternative function for django.views.debug.technical_500_response. Django's convert_exception_to_response() wrapper is called on each 'Middleware' object to avoid leaking exceptions. If an uncaught exception is raised, the wrapper calls technical_500_response() to create a response for django's debug view. Runserver_plus overrides the django debug view's technical_500_response() function to allow for an enhanced WSGI debugger view to be displayed. However, because Django calls convert_exception_to_response() on each object in the stack of Middleware objects, re-raising an error quickly pollutes the traceback displayed. Runserver_plus only needs needs traceback frames relevant to WSGIHandler Middleware objects, so only store the traceback if it is for a WSGIHandler. If an exception is not raised here, Django eventually throws an error for not getting a valid response object for its debug view. """ try: # Store the most recent tb for WSGI requests. The class can be found in the second frame of the tb if isinstance(tb.tb_next.tb_frame.f_locals.get('self'), WSGIHandler): tld.wsgi_tb = tb elif tld.wsgi_tb: tb = tld.wsgi_tb except AttributeError: pass six.reraise(exc_type, exc_value, tb)
[ "def", "null_technical_500_response", "(", "request", ",", "exc_type", ",", "exc_value", ",", "tb", ",", "status_code", "=", "500", ")", ":", "try", ":", "# Store the most recent tb for WSGI requests. The class can be found in the second frame of the tb", "if", "isinstance", ...
Alternative function for django.views.debug.technical_500_response. Django's convert_exception_to_response() wrapper is called on each 'Middleware' object to avoid leaking exceptions. If an uncaught exception is raised, the wrapper calls technical_500_response() to create a response for django's debug view. Runserver_plus overrides the django debug view's technical_500_response() function to allow for an enhanced WSGI debugger view to be displayed. However, because Django calls convert_exception_to_response() on each object in the stack of Middleware objects, re-raising an error quickly pollutes the traceback displayed. Runserver_plus only needs needs traceback frames relevant to WSGIHandler Middleware objects, so only store the traceback if it is for a WSGIHandler. If an exception is not raised here, Django eventually throws an error for not getting a valid response object for its debug view.
[ "Alternative", "function", "for", "django", ".", "views", ".", "debug", ".", "technical_500_response", "." ]
7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/technical_response.py#L11-L37