Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
ActionSimulator.sample
(self, valid_only=True, rng=None)
Sample a random (valid) action from the action space.
Sample a random (valid) action from the action space.
def sample(self, valid_only=True, rng=None) -> ActionLike: """Sample a random (valid) action from the action space.""" return self._action_mapper.sample(valid_only=valid_only, rng=rng)
[ "def", "sample", "(", "self", ",", "valid_only", "=", "True", ",", "rng", "=", "None", ")", "->", "ActionLike", ":", "return", "self", ".", "_action_mapper", ".", "sample", "(", "valid_only", "=", "valid_only", ",", "rng", "=", "rng", ")" ]
[ 116, 4 ]
[ 118, 73 ]
python
en
['en', 'en', 'en']
True
ActionSimulator.action_space_dim
(self)
Return dimension of the actions space.
Return dimension of the actions space.
def action_space_dim(self) -> int: """Return dimension of the actions space.""" return len(self._action_mapper.DIMENSION_TYPES)
[ "def", "action_space_dim", "(", "self", ")", "->", "int", ":", "return", "len", "(", "self", ".", "_action_mapper", ".", "DIMENSION_TYPES", ")" ]
[ 121, 4 ]
[ 123, 55 ]
python
en
['en', 'en', 'en']
True
ActionSimulator.build_discrete_action_space
(self, max_actions, seed=1)
Build a mapping from the given number of action to the action space. Args: max_actions: int, maximum number of discrete actions. seed: int, random seed to generate the subspace. Returns: discrete_actions: tuple of actions of length max_actions.
Build a mapping from the given number of action to the action space.
def build_discrete_action_space(self, max_actions, seed=1) -> Sequence[ActionLike]: """Build a mapping from the given number of action to the action space. Args: max_actions: int, maximum number of discrete actions. seed: int, random seed to generate the subspace. Returns: discrete_actions: tuple of actions of length max_actions. """ rng = np.random.RandomState(seed=seed) return [self.sample(rng=rng) for _ in range(max_actions)]
[ "def", "build_discrete_action_space", "(", "self", ",", "max_actions", ",", "seed", "=", "1", ")", "->", "Sequence", "[", "ActionLike", "]", ":", "rng", "=", "np", ".", "random", ".", "RandomState", "(", "seed", "=", "seed", ")", "return", "[", "self", ".", "sample", "(", "rng", "=", "rng", ")", "for", "_", "in", "range", "(", "max_actions", ")", "]" ]
[ 125, 4 ]
[ 137, 65 ]
python
en
['en', 'en', 'en']
True
ActionSimulator.initial_scenes
(self)
Represents intial scene for each task before agent input. uint8 array with shape (task, height, width).
Represents intial scene for each task before agent input.
def initial_scenes(self) -> np.ndarray: """Represents intial scene for each task before agent input. uint8 array with shape (task, height, width). """ return self._initial_scenes
[ "def", "initial_scenes", "(", "self", ")", "->", "np", ".", "ndarray", ":", "return", "self", ".", "_initial_scenes" ]
[ 140, 4 ]
[ 145, 35 ]
python
en
['en', 'en', 'en']
True
ActionSimulator.initial_featurized_objects
(self)
Inital scene objects featurized for each task before agent input. List (length tasks) of FeaturizedObjects containing float arrays of size (number scene objects, OBJECT_FEATURE_SIZE).
Inital scene objects featurized for each task before agent input. List (length tasks) of FeaturizedObjects containing float arrays of size (number scene objects, OBJECT_FEATURE_SIZE).
def initial_featurized_objects(self) -> np.ndarray: """Inital scene objects featurized for each task before agent input. List (length tasks) of FeaturizedObjects containing float arrays of size (number scene objects, OBJECT_FEATURE_SIZE). """ return self._initial_featurized_objects
[ "def", "initial_featurized_objects", "(", "self", ")", "->", "np", ".", "ndarray", ":", "return", "self", ".", "_initial_featurized_objects" ]
[ 148, 4 ]
[ 154, 47 ]
python
en
['en', 'en', 'en']
True
ActionSimulator.goals
(self)
Represents goals for each task. uint8 array with shape (task, 3). Each goal is encoded with three numbers: (obj_type1, obj_type2, rel). All three are less than MAX_GOAL. To be more precise, obj_types are less than MAX_OBJECT_TYPE and rel is less than MAX_RELATION.
Represents goals for each task.
def goals(self) -> Optional[np.ndarray]: """Represents goals for each task. uint8 array with shape (task, 3). Each goal is encoded with three numbers: (obj_type1, obj_type2, rel). All three are less than MAX_GOAL. To be more precise, obj_types are less than MAX_OBJECT_TYPE and rel is less than MAX_RELATION. """ return self._goals
[ "def", "goals", "(", "self", ")", "->", "Optional", "[", "np", ".", "ndarray", "]", ":", "return", "self", ".", "_goals" ]
[ 157, 4 ]
[ 165, 26 ]
python
en
['en', 'en', 'en']
True
ActionSimulator.task_ids
(self)
Tuple of task ids in simulator.
Tuple of task ids in simulator.
def task_ids(self) -> Tuple[str, ...]: """Tuple of task ids in simulator. """ return self._task_ids
[ "def", "task_ids", "(", "self", ")", "->", "Tuple", "[", "str", ",", "...", "]", ":", "return", "self", ".", "_task_ids" ]
[ 168, 4 ]
[ 171, 29 ]
python
en
['en', 'it', 'en']
True
ActionSimulator.simulate_single
(self, task_index: int, action: ActionLike, need_images: bool = True, stride: int = phyre.simulator.DEFAULT_STRIDE, stable: bool = False )
Deprecated in version 0.2.0 in favor of simulate_action. Runs simluation for the action. Args: task_index: index of the task. action: numpy array or list of self.action_space_dim floats in [0, 1]. need_images: whether simulation images are needed. stride: int, defines the striding for the simulation images array. Higher striding will result in less images and less compute. Note, that this parameter doesn't affect simulation FPS. Ignored if need_images is False. stable: if True, will simulate a few actions in the neigborhood of the actions and return STABLY_SOLVED status iff all neigbour actions are either SOLVED or INVALID. Otherwise UNSTABLY_SOLVED is returned. SOLVED is never returned if stable is set. Returns: * If need_images is True, returns a pair (status, images). * If status is INVALID_INPUT images is None. * Otherwise images is an array contains intermediate observations. * If need_images is False: returns (status, None).
Deprecated in version 0.2.0 in favor of simulate_action. Runs simluation for the action.
def simulate_single(self, task_index: int, action: ActionLike, need_images: bool = True, stride: int = phyre.simulator.DEFAULT_STRIDE, stable: bool = False ) -> Tuple[SimulationStatus, MaybeImages]: """Deprecated in version 0.2.0 in favor of simulate_action. Runs simluation for the action. Args: task_index: index of the task. action: numpy array or list of self.action_space_dim floats in [0, 1]. need_images: whether simulation images are needed. stride: int, defines the striding for the simulation images array. Higher striding will result in less images and less compute. Note, that this parameter doesn't affect simulation FPS. Ignored if need_images is False. stable: if True, will simulate a few actions in the neigborhood of the actions and return STABLY_SOLVED status iff all neigbour actions are either SOLVED or INVALID. Otherwise UNSTABLY_SOLVED is returned. SOLVED is never returned if stable is set. Returns: * If need_images is True, returns a pair (status, images). * If status is INVALID_INPUT images is None. * Otherwise images is an array contains intermediate observations. * If need_images is False: returns (status, None). """ simulation = self.simulate_action(task_index, action, need_images=need_images, need_featurized_objects=False, stride=stride, stable=stable) return simulation.status, simulation.images
[ "def", "simulate_single", "(", "self", ",", "task_index", ":", "int", ",", "action", ":", "ActionLike", ",", "need_images", ":", "bool", "=", "True", ",", "stride", ":", "int", "=", "phyre", ".", "simulator", ".", "DEFAULT_STRIDE", ",", "stable", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "SimulationStatus", ",", "MaybeImages", "]", ":", "simulation", "=", "self", ".", "simulate_action", "(", "task_index", ",", "action", ",", "need_images", "=", "need_images", ",", "need_featurized_objects", "=", "False", ",", "stride", "=", "stride", ",", "stable", "=", "stable", ")", "return", "simulation", ".", "status", ",", "simulation", ".", "images" ]
[ 218, 4 ]
[ 255, 51 ]
python
en
['en', 'en', 'en']
True
ActionSimulator.simulate_action
(self, task_index: int, action: ActionLike, *, need_images: bool = True, need_featurized_objects: bool = False, stride: int = phyre.simulator.DEFAULT_STRIDE, stable: bool = False, perturb_step: int = -1, # Ideally the nframes default needs to stay in sync with # src/simulator/task_utils.h:kMaxSteps nframes: int = 1000, stop_after_solved: bool = True, )
Runs simluation for the action. Args: task_index: index of the task. action: numpy array or list of self.action_space_dim floats in [0, 1]. need_images: whether simulation images are needed. need_featurized_objects: whether simulation featurized_objects are needed. stride: int, defines the striding for the simulation images array. Higher striding will result in less images and less compute. Note, that this parameter doesn't affect simulation FPS. Ignored if need_images is False. stable: if True, will simulate a few actions in the neigborhood of the actions and return STABLY_SOLVED status iff all neigbour actions are either SOLVED or INVALID. Otherwise UNSTABLY_SOLVED is returned. SOLVED is never returned if stable is set. perturb_step: If not -1, it perturbs the simulation at this step nframes: Generates that many frames of simulation. By default a large number => generate all. stop_after_solved: Stop the simulation once it's solved (used to be the default anyway, adding an option to disable it) Returns: * phyre.simulation.Simulation object containing the result of the simulation. * SimulationStatus, images, and featurized_objects are easily accesible with simulation.simulation_status, simulation.images, and simulation.featurized_objects.
Runs simluation for the action.
def simulate_action(self, task_index: int, action: ActionLike, *, need_images: bool = True, need_featurized_objects: bool = False, stride: int = phyre.simulator.DEFAULT_STRIDE, stable: bool = False, perturb_step: int = -1, # Ideally the nframes default needs to stay in sync with # src/simulator/task_utils.h:kMaxSteps nframes: int = 1000, stop_after_solved: bool = True, ) -> phyre.simulation.Simulation: """Runs simluation for the action. Args: task_index: index of the task. action: numpy array or list of self.action_space_dim floats in [0, 1]. need_images: whether simulation images are needed. need_featurized_objects: whether simulation featurized_objects are needed. stride: int, defines the striding for the simulation images array. Higher striding will result in less images and less compute. Note, that this parameter doesn't affect simulation FPS. Ignored if need_images is False. stable: if True, will simulate a few actions in the neigborhood of the actions and return STABLY_SOLVED status iff all neigbour actions are either SOLVED or INVALID. Otherwise UNSTABLY_SOLVED is returned. SOLVED is never returned if stable is set. perturb_step: If not -1, it perturbs the simulation at this step nframes: Generates that many frames of simulation. By default a large number => generate all. stop_after_solved: Stop the simulation once it's solved (used to be the default anyway, adding an option to disable it) Returns: * phyre.simulation.Simulation object containing the result of the simulation. * SimulationStatus, images, and featurized_objects are easily accesible with simulation.simulation_status, simulation.images, and simulation.featurized_objects. """ user_input, is_valid = self._get_user_input(action) if not is_valid: return phyre.simulation.Simulation( status=SimulationStatus.INVALID_INPUT) main_status, images, objects = self._simulate_user_input( task_index, user_input, need_images, need_featurized_objects, stride, perturb_step=perturb_step, nframes=nframes, stop_after_solved=stop_after_solved) if not stable or not main_status.is_solved(): return phyre.simulation.Simulation(status=main_status, images=images, featurized_objects=objects) for modified_user_input in _yield_user_input_neighborhood(user_input): status, _, _ = self._simulate_user_input( task_index, modified_user_input, need_images=False, need_featurized_objects=False, stride=stride, perturb_step=perturb_step, nframes=nframes, stop_after_solved=stop_after_solved ) if status.is_not_solved(): return phyre.simulation.Simulation( status=SimulationStatus.UNSTABLY_SOLVED, images=images, featurized_objects=objects) return phyre.simulation.Simulation( status=SimulationStatus.STABLY_SOLVED, images=images, featurized_objects=objects)
[ "def", "simulate_action", "(", "self", ",", "task_index", ":", "int", ",", "action", ":", "ActionLike", ",", "*", ",", "need_images", ":", "bool", "=", "True", ",", "need_featurized_objects", ":", "bool", "=", "False", ",", "stride", ":", "int", "=", "phyre", ".", "simulator", ".", "DEFAULT_STRIDE", ",", "stable", ":", "bool", "=", "False", ",", "perturb_step", ":", "int", "=", "-", "1", ",", "# Ideally the nframes default needs to stay in sync with", "# src/simulator/task_utils.h:kMaxSteps", "nframes", ":", "int", "=", "1000", ",", "stop_after_solved", ":", "bool", "=", "True", ",", ")", "->", "phyre", ".", "simulation", ".", "Simulation", ":", "user_input", ",", "is_valid", "=", "self", ".", "_get_user_input", "(", "action", ")", "if", "not", "is_valid", ":", "return", "phyre", ".", "simulation", ".", "Simulation", "(", "status", "=", "SimulationStatus", ".", "INVALID_INPUT", ")", "main_status", ",", "images", ",", "objects", "=", "self", ".", "_simulate_user_input", "(", "task_index", ",", "user_input", ",", "need_images", ",", "need_featurized_objects", ",", "stride", ",", "perturb_step", "=", "perturb_step", ",", "nframes", "=", "nframes", ",", "stop_after_solved", "=", "stop_after_solved", ")", "if", "not", "stable", "or", "not", "main_status", ".", "is_solved", "(", ")", ":", "return", "phyre", ".", "simulation", ".", "Simulation", "(", "status", "=", "main_status", ",", "images", "=", "images", ",", "featurized_objects", "=", "objects", ")", "for", "modified_user_input", "in", "_yield_user_input_neighborhood", "(", "user_input", ")", ":", "status", ",", "_", ",", "_", "=", "self", ".", "_simulate_user_input", "(", "task_index", ",", "modified_user_input", ",", "need_images", "=", "False", ",", "need_featurized_objects", "=", "False", ",", "stride", "=", "stride", ",", "perturb_step", "=", "perturb_step", ",", "nframes", "=", "nframes", ",", "stop_after_solved", "=", "stop_after_solved", ")", "if", "status", ".", "is_not_solved", "(", ")", ":", "return", "phyre", ".", "simulation", ".", "Simulation", "(", "status", "=", "SimulationStatus", ".", "UNSTABLY_SOLVED", ",", "images", "=", "images", ",", "featurized_objects", "=", "objects", ")", "return", "phyre", ".", "simulation", ".", "Simulation", "(", "status", "=", "SimulationStatus", ".", "STABLY_SOLVED", ",", "images", "=", "images", ",", "featurized_objects", "=", "objects", ")" ]
[ 257, 4 ]
[ 333, 39 ]
python
en
['en', 'en', 'en']
True
read_configuration
( filepath, find_others=False, ignore_option_errors=False)
Read given configuration file and returns options from it as a dict. :param str|unicode filepath: Path to configuration file to get options from. :param bool find_others: Whether to search for other configuration files which could be on in various places. :param bool ignore_option_errors: Whether to silently ignore options, values of which could not be resolved (e.g. due to exceptions in directives such as file:, attr:, etc.). If False exceptions are propagated as expected. :rtype: dict
Read given configuration file and returns options from it as a dict.
def read_configuration( filepath, find_others=False, ignore_option_errors=False): """Read given configuration file and returns options from it as a dict. :param str|unicode filepath: Path to configuration file to get options from. :param bool find_others: Whether to search for other configuration files which could be on in various places. :param bool ignore_option_errors: Whether to silently ignore options, values of which could not be resolved (e.g. due to exceptions in directives such as file:, attr:, etc.). If False exceptions are propagated as expected. :rtype: dict """ from setuptools.dist import Distribution, _Distribution filepath = os.path.abspath(filepath) if not os.path.isfile(filepath): raise DistutilsFileError( 'Configuration file %s does not exist.' % filepath) current_directory = os.getcwd() os.chdir(os.path.dirname(filepath)) try: dist = Distribution() filenames = dist.find_config_files() if find_others else [] if filepath not in filenames: filenames.append(filepath) _Distribution.parse_config_files(dist, filenames=filenames) handlers = parse_configuration( dist, dist.command_options, ignore_option_errors=ignore_option_errors) finally: os.chdir(current_directory) return configuration_to_dict(handlers)
[ "def", "read_configuration", "(", "filepath", ",", "find_others", "=", "False", ",", "ignore_option_errors", "=", "False", ")", ":", "from", "setuptools", ".", "dist", "import", "Distribution", ",", "_Distribution", "filepath", "=", "os", ".", "path", ".", "abspath", "(", "filepath", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "filepath", ")", ":", "raise", "DistutilsFileError", "(", "'Configuration file %s does not exist.'", "%", "filepath", ")", "current_directory", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "os", ".", "path", ".", "dirname", "(", "filepath", ")", ")", "try", ":", "dist", "=", "Distribution", "(", ")", "filenames", "=", "dist", ".", "find_config_files", "(", ")", "if", "find_others", "else", "[", "]", "if", "filepath", "not", "in", "filenames", ":", "filenames", ".", "append", "(", "filepath", ")", "_Distribution", ".", "parse_config_files", "(", "dist", ",", "filenames", "=", "filenames", ")", "handlers", "=", "parse_configuration", "(", "dist", ",", "dist", ".", "command_options", ",", "ignore_option_errors", "=", "ignore_option_errors", ")", "finally", ":", "os", ".", "chdir", "(", "current_directory", ")", "return", "configuration_to_dict", "(", "handlers", ")" ]
[ 12, 0 ]
[ 56, 42 ]
python
en
['en', 'en', 'en']
True
configuration_to_dict
(handlers)
Returns configuration data gathered by given handlers as a dict. :param list[ConfigHandler] handlers: Handlers list, usually from parse_configuration() :rtype: dict
Returns configuration data gathered by given handlers as a dict.
def configuration_to_dict(handlers): """Returns configuration data gathered by given handlers as a dict. :param list[ConfigHandler] handlers: Handlers list, usually from parse_configuration() :rtype: dict """ config_dict = defaultdict(dict) for handler in handlers: obj_alias = handler.section_prefix target_obj = handler.target_obj for option in handler.set_options: getter = getattr(target_obj, 'get_%s' % option, None) if getter is None: value = getattr(target_obj, option) else: value = getter() config_dict[obj_alias][option] = value return config_dict
[ "def", "configuration_to_dict", "(", "handlers", ")", ":", "config_dict", "=", "defaultdict", "(", "dict", ")", "for", "handler", "in", "handlers", ":", "obj_alias", "=", "handler", ".", "section_prefix", "target_obj", "=", "handler", ".", "target_obj", "for", "option", "in", "handler", ".", "set_options", ":", "getter", "=", "getattr", "(", "target_obj", ",", "'get_%s'", "%", "option", ",", "None", ")", "if", "getter", "is", "None", ":", "value", "=", "getattr", "(", "target_obj", ",", "option", ")", "else", ":", "value", "=", "getter", "(", ")", "config_dict", "[", "obj_alias", "]", "[", "option", "]", "=", "value", "return", "config_dict" ]
[ 59, 0 ]
[ 85, 22 ]
python
en
['en', 'en', 'en']
True
parse_configuration
( distribution, command_options, ignore_option_errors=False)
Performs additional parsing of configuration options for a distribution. Returns a list of used option handlers. :param Distribution distribution: :param dict command_options: :param bool ignore_option_errors: Whether to silently ignore options, values of which could not be resolved (e.g. due to exceptions in directives such as file:, attr:, etc.). If False exceptions are propagated as expected. :rtype: list
Performs additional parsing of configuration options for a distribution.
def parse_configuration( distribution, command_options, ignore_option_errors=False): """Performs additional parsing of configuration options for a distribution. Returns a list of used option handlers. :param Distribution distribution: :param dict command_options: :param bool ignore_option_errors: Whether to silently ignore options, values of which could not be resolved (e.g. due to exceptions in directives such as file:, attr:, etc.). If False exceptions are propagated as expected. :rtype: list """ meta = ConfigMetadataHandler( distribution.metadata, command_options, ignore_option_errors) meta.parse() options = ConfigOptionsHandler( distribution, command_options, ignore_option_errors) options.parse() return meta, options
[ "def", "parse_configuration", "(", "distribution", ",", "command_options", ",", "ignore_option_errors", "=", "False", ")", ":", "meta", "=", "ConfigMetadataHandler", "(", "distribution", ".", "metadata", ",", "command_options", ",", "ignore_option_errors", ")", "meta", ".", "parse", "(", ")", "options", "=", "ConfigOptionsHandler", "(", "distribution", ",", "command_options", ",", "ignore_option_errors", ")", "options", ".", "parse", "(", ")", "return", "meta", ",", "options" ]
[ 88, 0 ]
[ 111, 24 ]
python
en
['en', 'en', 'en']
True
ConfigHandler.parsers
(self)
Metadata item name to parser function mapping.
Metadata item name to parser function mapping.
def parsers(self): """Metadata item name to parser function mapping.""" raise NotImplementedError( '%s must provide .parsers property' % self.__class__.__name__)
[ "def", "parsers", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'%s must provide .parsers property'", "%", "self", ".", "__class__", ".", "__name__", ")" ]
[ 147, 4 ]
[ 150, 74 ]
python
en
['en', 'jv', 'en']
True
ConfigHandler._parse_list
(cls, value, separator=',')
Represents value as a list. Value is split either by separator (defaults to comma) or by lines. :param value: :param separator: List items separator character. :rtype: list
Represents value as a list.
def _parse_list(cls, value, separator=','): """Represents value as a list. Value is split either by separator (defaults to comma) or by lines. :param value: :param separator: List items separator character. :rtype: list """ if isinstance(value, list): # _get_parser_compound case return value if '\n' in value: value = value.splitlines() else: value = value.split(separator) return [chunk.strip() for chunk in value if chunk.strip()]
[ "def", "_parse_list", "(", "cls", ",", "value", ",", "separator", "=", "','", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "# _get_parser_compound case", "return", "value", "if", "'\\n'", "in", "value", ":", "value", "=", "value", ".", "splitlines", "(", ")", "else", ":", "value", "=", "value", ".", "split", "(", "separator", ")", "return", "[", "chunk", ".", "strip", "(", ")", "for", "chunk", "in", "value", "if", "chunk", ".", "strip", "(", ")", "]" ]
[ 191, 4 ]
[ 208, 66 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._parse_dict
(cls, value)
Represents value as a dict. :param value: :rtype: dict
Represents value as a dict.
def _parse_dict(cls, value): """Represents value as a dict. :param value: :rtype: dict """ separator = '=' result = {} for line in cls._parse_list(value): key, sep, val = line.partition(separator) if sep != separator: raise DistutilsOptionError( 'Unable to parse option value to dict: %s' % value) result[key.strip()] = val.strip() return result
[ "def", "_parse_dict", "(", "cls", ",", "value", ")", ":", "separator", "=", "'='", "result", "=", "{", "}", "for", "line", "in", "cls", ".", "_parse_list", "(", "value", ")", ":", "key", ",", "sep", ",", "val", "=", "line", ".", "partition", "(", "separator", ")", "if", "sep", "!=", "separator", ":", "raise", "DistutilsOptionError", "(", "'Unable to parse option value to dict: %s'", "%", "value", ")", "result", "[", "key", ".", "strip", "(", ")", "]", "=", "val", ".", "strip", "(", ")", "return", "result" ]
[ 211, 4 ]
[ 226, 21 ]
python
en
['en', 'ca', 'en']
True
ConfigHandler._parse_bool
(cls, value)
Represents value as boolean. :param value: :rtype: bool
Represents value as boolean.
def _parse_bool(cls, value): """Represents value as boolean. :param value: :rtype: bool """ value = value.lower() return value in ('1', 'true', 'yes')
[ "def", "_parse_bool", "(", "cls", ",", "value", ")", ":", "value", "=", "value", ".", "lower", "(", ")", "return", "value", "in", "(", "'1'", ",", "'true'", ",", "'yes'", ")" ]
[ 229, 4 ]
[ 236, 44 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._parse_file
(cls, value)
Represents value as a string, allowing including text from nearest files using `file:` directive. Directive is sandboxed and won't reach anything outside directory with setup.py. Examples: file: LICENSE file: README.rst, CHANGELOG.md, src/file.txt :param str value: :rtype: str
Represents value as a string, allowing including text from nearest files using `file:` directive.
def _parse_file(cls, value): """Represents value as a string, allowing including text from nearest files using `file:` directive. Directive is sandboxed and won't reach anything outside directory with setup.py. Examples: file: LICENSE file: README.rst, CHANGELOG.md, src/file.txt :param str value: :rtype: str """ include_directive = 'file:' if not isinstance(value, string_types): return value if not value.startswith(include_directive): return value spec = value[len(include_directive):] filepaths = (os.path.abspath(path.strip()) for path in spec.split(',')) return '\n'.join( cls._read_file(path) for path in filepaths if (cls._assert_local(path) or True) and os.path.isfile(path) )
[ "def", "_parse_file", "(", "cls", ",", "value", ")", ":", "include_directive", "=", "'file:'", "if", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "return", "value", "if", "not", "value", ".", "startswith", "(", "include_directive", ")", ":", "return", "value", "spec", "=", "value", "[", "len", "(", "include_directive", ")", ":", "]", "filepaths", "=", "(", "os", ".", "path", ".", "abspath", "(", "path", ".", "strip", "(", ")", ")", "for", "path", "in", "spec", ".", "split", "(", "','", ")", ")", "return", "'\\n'", ".", "join", "(", "cls", ".", "_read_file", "(", "path", ")", "for", "path", "in", "filepaths", "if", "(", "cls", ".", "_assert_local", "(", "path", ")", "or", "True", ")", "and", "os", ".", "path", ".", "isfile", "(", "path", ")", ")" ]
[ 239, 4 ]
[ 268, 9 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._parse_attr
(cls, value)
Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str
Represents value as a module attribute.
def _parse_attr(cls, value): """Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str """ attr_directive = 'attr:' if not value.startswith(attr_directive): return value attrs_path = value.replace(attr_directive, '').strip().split('.') attr_name = attrs_path.pop() module_name = '.'.join(attrs_path) module_name = module_name or '__init__' sys.path.insert(0, os.getcwd()) try: module = import_module(module_name) value = getattr(module, attr_name) finally: sys.path = sys.path[1:] return value
[ "def", "_parse_attr", "(", "cls", ",", "value", ")", ":", "attr_directive", "=", "'attr:'", "if", "not", "value", ".", "startswith", "(", "attr_directive", ")", ":", "return", "value", "attrs_path", "=", "value", ".", "replace", "(", "attr_directive", ",", "''", ")", ".", "strip", "(", ")", ".", "split", "(", "'.'", ")", "attr_name", "=", "attrs_path", ".", "pop", "(", ")", "module_name", "=", "'.'", ".", "join", "(", "attrs_path", ")", "module_name", "=", "module_name", "or", "'__init__'", "sys", ".", "path", ".", "insert", "(", "0", ",", "os", ".", "getcwd", "(", ")", ")", "try", ":", "module", "=", "import_module", "(", "module_name", ")", "value", "=", "getattr", "(", "module", ",", "attr_name", ")", "finally", ":", "sys", ".", "path", "=", "sys", ".", "path", "[", "1", ":", "]", "return", "value" ]
[ 282, 4 ]
[ 310, 20 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._get_parser_compound
(cls, *parse_methods)
Returns parser function to represents value as a list. Parses a value applying given methods one after another. :param parse_methods: :rtype: callable
Returns parser function to represents value as a list.
def _get_parser_compound(cls, *parse_methods): """Returns parser function to represents value as a list. Parses a value applying given methods one after another. :param parse_methods: :rtype: callable """ def parse(value): parsed = value for method in parse_methods: parsed = method(parsed) return parsed return parse
[ "def", "_get_parser_compound", "(", "cls", ",", "*", "parse_methods", ")", ":", "def", "parse", "(", "value", ")", ":", "parsed", "=", "value", "for", "method", "in", "parse_methods", ":", "parsed", "=", "method", "(", "parsed", ")", "return", "parsed", "return", "parse" ]
[ 313, 4 ]
[ 329, 20 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._parse_section_to_dict
(cls, section_options, values_parser=None)
Parses section options into a dictionary. Optionally applies a given parser to values. :param dict section_options: :param callable values_parser: :rtype: dict
Parses section options into a dictionary.
def _parse_section_to_dict(cls, section_options, values_parser=None): """Parses section options into a dictionary. Optionally applies a given parser to values. :param dict section_options: :param callable values_parser: :rtype: dict """ value = {} values_parser = values_parser or (lambda val: val) for key, (_, val) in section_options.items(): value[key] = values_parser(val) return value
[ "def", "_parse_section_to_dict", "(", "cls", ",", "section_options", ",", "values_parser", "=", "None", ")", ":", "value", "=", "{", "}", "values_parser", "=", "values_parser", "or", "(", "lambda", "val", ":", "val", ")", "for", "key", ",", "(", "_", ",", "val", ")", "in", "section_options", ".", "items", "(", ")", ":", "value", "[", "key", "]", "=", "values_parser", "(", "val", ")", "return", "value" ]
[ 332, 4 ]
[ 345, 20 ]
python
en
['en', 'en', 'en']
True
ConfigHandler.parse_section
(self, section_options)
Parses configuration file section. :param dict section_options:
Parses configuration file section.
def parse_section(self, section_options): """Parses configuration file section. :param dict section_options: """ for (name, (_, value)) in section_options.items(): try: self[name] = value except KeyError: pass
[ "def", "parse_section", "(", "self", ",", "section_options", ")", ":", "for", "(", "name", ",", "(", "_", ",", "value", ")", ")", "in", "section_options", ".", "items", "(", ")", ":", "try", ":", "self", "[", "name", "]", "=", "value", "except", "KeyError", ":", "pass" ]
[ 347, 4 ]
[ 357, 20 ]
python
en
['en', 'en', 'en']
True
ConfigHandler.parse
(self)
Parses configuration file items from one or more related sections.
Parses configuration file items from one or more related sections.
def parse(self): """Parses configuration file items from one or more related sections. """ for section_name, section_options in self.sections.items(): method_postfix = '' if section_name: # [section.option] variant method_postfix = '_%s' % section_name section_parser_method = getattr( self, # Dots in section names are tranlsated into dunderscores. ('parse_section%s' % method_postfix).replace('.', '__'), None) if section_parser_method is None: raise DistutilsOptionError( 'Unsupported distribution option section: [%s.%s]' % ( self.section_prefix, section_name)) section_parser_method(section_options)
[ "def", "parse", "(", "self", ")", ":", "for", "section_name", ",", "section_options", "in", "self", ".", "sections", ".", "items", "(", ")", ":", "method_postfix", "=", "''", "if", "section_name", ":", "# [section.option] variant", "method_postfix", "=", "'_%s'", "%", "section_name", "section_parser_method", "=", "getattr", "(", "self", ",", "# Dots in section names are tranlsated into dunderscores.", "(", "'parse_section%s'", "%", "method_postfix", ")", ".", "replace", "(", "'.'", ",", "'__'", ")", ",", "None", ")", "if", "section_parser_method", "is", "None", ":", "raise", "DistutilsOptionError", "(", "'Unsupported distribution option section: [%s.%s]'", "%", "(", "self", ".", "section_prefix", ",", "section_name", ")", ")", "section_parser_method", "(", "section_options", ")" ]
[ 359, 4 ]
[ 381, 50 ]
python
en
['en', 'en', 'en']
True
ConfigMetadataHandler.parsers
(self)
Metadata item name to parser function mapping.
Metadata item name to parser function mapping.
def parsers(self): """Metadata item name to parser function mapping.""" parse_list = self._parse_list parse_file = self._parse_file parse_dict = self._parse_dict return { 'platforms': parse_list, 'keywords': parse_list, 'provides': parse_list, 'requires': parse_list, 'obsoletes': parse_list, 'classifiers': self._get_parser_compound(parse_file, parse_list), 'license': parse_file, 'description': parse_file, 'long_description': parse_file, 'version': self._parse_version, 'project_urls': parse_dict, }
[ "def", "parsers", "(", "self", ")", ":", "parse_list", "=", "self", ".", "_parse_list", "parse_file", "=", "self", ".", "_parse_file", "parse_dict", "=", "self", ".", "_parse_dict", "return", "{", "'platforms'", ":", "parse_list", ",", "'keywords'", ":", "parse_list", ",", "'provides'", ":", "parse_list", ",", "'requires'", ":", "parse_list", ",", "'obsoletes'", ":", "parse_list", ",", "'classifiers'", ":", "self", ".", "_get_parser_compound", "(", "parse_file", ",", "parse_list", ")", ",", "'license'", ":", "parse_file", ",", "'description'", ":", "parse_file", ",", "'long_description'", ":", "parse_file", ",", "'version'", ":", "self", ".", "_parse_version", ",", "'project_urls'", ":", "parse_dict", ",", "}" ]
[ 402, 4 ]
[ 420, 9 ]
python
en
['en', 'jv', 'en']
True
ConfigMetadataHandler._parse_version
(self, value)
Parses `version` option value. :param value: :rtype: str
Parses `version` option value.
def _parse_version(self, value): """Parses `version` option value. :param value: :rtype: str """ version = self._parse_attr(value) if callable(version): version = version() if not isinstance(version, string_types): if hasattr(version, '__iter__'): version = '.'.join(map(str, version)) else: version = '%s' % version return version
[ "def", "_parse_version", "(", "self", ",", "value", ")", ":", "version", "=", "self", ".", "_parse_attr", "(", "value", ")", "if", "callable", "(", "version", ")", ":", "version", "=", "version", "(", ")", "if", "not", "isinstance", "(", "version", ",", "string_types", ")", ":", "if", "hasattr", "(", "version", ",", "'__iter__'", ")", ":", "version", "=", "'.'", ".", "join", "(", "map", "(", "str", ",", "version", ")", ")", "else", ":", "version", "=", "'%s'", "%", "version", "return", "version" ]
[ 422, 4 ]
[ 440, 22 ]
python
en
['en', 'fr', 'en']
True
ConfigOptionsHandler.parsers
(self)
Metadata item name to parser function mapping.
Metadata item name to parser function mapping.
def parsers(self): """Metadata item name to parser function mapping.""" parse_list = self._parse_list parse_list_semicolon = partial(self._parse_list, separator=';') parse_bool = self._parse_bool parse_dict = self._parse_dict return { 'zip_safe': parse_bool, 'use_2to3': parse_bool, 'include_package_data': parse_bool, 'package_dir': parse_dict, 'use_2to3_fixers': parse_list, 'use_2to3_exclude_fixers': parse_list, 'convert_2to3_doctests': parse_list, 'scripts': parse_list, 'eager_resources': parse_list, 'dependency_links': parse_list, 'namespace_packages': parse_list, 'install_requires': parse_list_semicolon, 'setup_requires': parse_list_semicolon, 'tests_require': parse_list_semicolon, 'packages': self._parse_packages, 'entry_points': self._parse_file, 'py_modules': parse_list, }
[ "def", "parsers", "(", "self", ")", ":", "parse_list", "=", "self", ".", "_parse_list", "parse_list_semicolon", "=", "partial", "(", "self", ".", "_parse_list", ",", "separator", "=", "';'", ")", "parse_bool", "=", "self", ".", "_parse_bool", "parse_dict", "=", "self", ".", "_parse_dict", "return", "{", "'zip_safe'", ":", "parse_bool", ",", "'use_2to3'", ":", "parse_bool", ",", "'include_package_data'", ":", "parse_bool", ",", "'package_dir'", ":", "parse_dict", ",", "'use_2to3_fixers'", ":", "parse_list", ",", "'use_2to3_exclude_fixers'", ":", "parse_list", ",", "'convert_2to3_doctests'", ":", "parse_list", ",", "'scripts'", ":", "parse_list", ",", "'eager_resources'", ":", "parse_list", ",", "'dependency_links'", ":", "parse_list", ",", "'namespace_packages'", ":", "parse_list", ",", "'install_requires'", ":", "parse_list_semicolon", ",", "'setup_requires'", ":", "parse_list_semicolon", ",", "'tests_require'", ":", "parse_list_semicolon", ",", "'packages'", ":", "self", ".", "_parse_packages", ",", "'entry_points'", ":", "self", ".", "_parse_file", ",", "'py_modules'", ":", "parse_list", ",", "}" ]
[ 448, 4 ]
[ 473, 9 ]
python
en
['en', 'jv', 'en']
True
ConfigOptionsHandler._parse_packages
(self, value)
Parses `packages` option value. :param value: :rtype: list
Parses `packages` option value.
def _parse_packages(self, value): """Parses `packages` option value. :param value: :rtype: list """ find_directive = 'find:' if not value.startswith(find_directive): return self._parse_list(value) # Read function arguments from a dedicated section. find_kwargs = self.parse_section_packages__find( self.sections.get('packages.find', {})) from setuptools import find_packages return find_packages(**find_kwargs)
[ "def", "_parse_packages", "(", "self", ",", "value", ")", ":", "find_directive", "=", "'find:'", "if", "not", "value", ".", "startswith", "(", "find_directive", ")", ":", "return", "self", ".", "_parse_list", "(", "value", ")", "# Read function arguments from a dedicated section.", "find_kwargs", "=", "self", ".", "parse_section_packages__find", "(", "self", ".", "sections", ".", "get", "(", "'packages.find'", ",", "{", "}", ")", ")", "from", "setuptools", "import", "find_packages", "return", "find_packages", "(", "*", "*", "find_kwargs", ")" ]
[ 475, 4 ]
[ 492, 43 ]
python
en
['en', 'en', 'en']
True
ConfigOptionsHandler.parse_section_packages__find
(self, section_options)
Parses `packages.find` configuration file section. To be used in conjunction with _parse_packages(). :param dict section_options:
Parses `packages.find` configuration file section.
def parse_section_packages__find(self, section_options): """Parses `packages.find` configuration file section. To be used in conjunction with _parse_packages(). :param dict section_options: """ section_data = self._parse_section_to_dict( section_options, self._parse_list) valid_keys = ['where', 'include', 'exclude'] find_kwargs = dict( [(k, v) for k, v in section_data.items() if k in valid_keys and v]) where = find_kwargs.get('where') if where is not None: find_kwargs['where'] = where[0] # cast list to single val return find_kwargs
[ "def", "parse_section_packages__find", "(", "self", ",", "section_options", ")", ":", "section_data", "=", "self", ".", "_parse_section_to_dict", "(", "section_options", ",", "self", ".", "_parse_list", ")", "valid_keys", "=", "[", "'where'", ",", "'include'", ",", "'exclude'", "]", "find_kwargs", "=", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "section_data", ".", "items", "(", ")", "if", "k", "in", "valid_keys", "and", "v", "]", ")", "where", "=", "find_kwargs", ".", "get", "(", "'where'", ")", "if", "where", "is", "not", "None", ":", "find_kwargs", "[", "'where'", "]", "=", "where", "[", "0", "]", "# cast list to single val", "return", "find_kwargs" ]
[ 494, 4 ]
[ 513, 26 ]
python
en
['en', 'en', 'en']
True
ConfigOptionsHandler.parse_section_entry_points
(self, section_options)
Parses `entry_points` configuration file section. :param dict section_options:
Parses `entry_points` configuration file section.
def parse_section_entry_points(self, section_options): """Parses `entry_points` configuration file section. :param dict section_options: """ parsed = self._parse_section_to_dict(section_options, self._parse_list) self['entry_points'] = parsed
[ "def", "parse_section_entry_points", "(", "self", ",", "section_options", ")", ":", "parsed", "=", "self", ".", "_parse_section_to_dict", "(", "section_options", ",", "self", ".", "_parse_list", ")", "self", "[", "'entry_points'", "]", "=", "parsed" ]
[ 515, 4 ]
[ 521, 37 ]
python
en
['en', 'en', 'en']
True
ConfigOptionsHandler.parse_section_package_data
(self, section_options)
Parses `package_data` configuration file section. :param dict section_options:
Parses `package_data` configuration file section.
def parse_section_package_data(self, section_options): """Parses `package_data` configuration file section. :param dict section_options: """ self['package_data'] = self._parse_package_data(section_options)
[ "def", "parse_section_package_data", "(", "self", ",", "section_options", ")", ":", "self", "[", "'package_data'", "]", "=", "self", ".", "_parse_package_data", "(", "section_options", ")" ]
[ 533, 4 ]
[ 538, 72 ]
python
en
['en', 'en', 'en']
True
ConfigOptionsHandler.parse_section_exclude_package_data
(self, section_options)
Parses `exclude_package_data` configuration file section. :param dict section_options:
Parses `exclude_package_data` configuration file section.
def parse_section_exclude_package_data(self, section_options): """Parses `exclude_package_data` configuration file section. :param dict section_options: """ self['exclude_package_data'] = self._parse_package_data( section_options)
[ "def", "parse_section_exclude_package_data", "(", "self", ",", "section_options", ")", ":", "self", "[", "'exclude_package_data'", "]", "=", "self", ".", "_parse_package_data", "(", "section_options", ")" ]
[ 540, 4 ]
[ 546, 28 ]
python
en
['en', 'en', 'en']
True
ConfigOptionsHandler.parse_section_extras_require
(self, section_options)
Parses `extras_require` configuration file section. :param dict section_options:
Parses `extras_require` configuration file section.
def parse_section_extras_require(self, section_options): """Parses `extras_require` configuration file section. :param dict section_options: """ parse_list = partial(self._parse_list, separator=';') self['extras_require'] = self._parse_section_to_dict( section_options, parse_list)
[ "def", "parse_section_extras_require", "(", "self", ",", "section_options", ")", ":", "parse_list", "=", "partial", "(", "self", ".", "_parse_list", ",", "separator", "=", "';'", ")", "self", "[", "'extras_require'", "]", "=", "self", ".", "_parse_section_to_dict", "(", "section_options", ",", "parse_list", ")" ]
[ 548, 4 ]
[ 555, 40 ]
python
en
['es', 'en', 'en']
True
CaseInsensitiveDict.lower_items
(self)
Like iteritems(), but with all lowercase keys.
Like iteritems(), but with all lowercase keys.
def lower_items(self): """Like iteritems(), but with all lowercase keys.""" return ( (lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items() )
[ "def", "lower_items", "(", "self", ")", ":", "return", "(", "(", "lowerkey", ",", "keyval", "[", "1", "]", ")", "for", "(", "lowerkey", ",", "keyval", ")", "in", "self", ".", "_store", ".", "items", "(", ")", ")" ]
[ 64, 4 ]
[ 70, 9 ]
python
en
['en', 'en', 'en']
True
fix_shape_and_type_for_serving
(placeholder)
Fixes the shape and type of serving input strings. Given placeholder tensor, return parsed and processed feature tensor. Args: placeholder: Placeholder tensor holding raw data from serving input function. Returns: Parsed and processed feature tensor.
Fixes the shape and type of serving input strings.
def fix_shape_and_type_for_serving(placeholder): """Fixes the shape and type of serving input strings. Given placeholder tensor, return parsed and processed feature tensor. Args: placeholder: Placeholder tensor holding raw data from serving input function. Returns: Parsed and processed feature tensor. """ cur_batch_size = tf.shape(input=placeholder, out_type=tf.int64)[0] # String split each string in batch and output values from the resulting # SparseTensors # shape = (batch_size, seq_len) split_string = tf.stack(values=tf.map_fn( fn=lambda x: tf.string_split( source=[placeholder[x]], delimiter=";").values, elems=tf.range( start=0, limit=cur_batch_size, dtype=tf.int64), dtype=tf.string), axis=0) # Convert each string in the split tensor to float # shape = (batch_size, seq_len) feature_tensor = tf.string_to_number( string_tensor=split_string, out_type=tf.float64) return feature_tensor
[ "def", "fix_shape_and_type_for_serving", "(", "placeholder", ")", ":", "cur_batch_size", "=", "tf", ".", "shape", "(", "input", "=", "placeholder", ",", "out_type", "=", "tf", ".", "int64", ")", "[", "0", "]", "# String split each string in batch and output values from the resulting", "# SparseTensors", "# shape = (batch_size, seq_len)", "split_string", "=", "tf", ".", "stack", "(", "values", "=", "tf", ".", "map_fn", "(", "fn", "=", "lambda", "x", ":", "tf", ".", "string_split", "(", "source", "=", "[", "placeholder", "[", "x", "]", "]", ",", "delimiter", "=", "\";\"", ")", ".", "values", ",", "elems", "=", "tf", ".", "range", "(", "start", "=", "0", ",", "limit", "=", "cur_batch_size", ",", "dtype", "=", "tf", ".", "int64", ")", ",", "dtype", "=", "tf", ".", "string", ")", ",", "axis", "=", "0", ")", "# Convert each string in the split tensor to float", "# shape = (batch_size, seq_len)", "feature_tensor", "=", "tf", ".", "string_to_number", "(", "string_tensor", "=", "split_string", ",", "out_type", "=", "tf", ".", "float64", ")", "return", "feature_tensor" ]
[ 4, 0 ]
[ 33, 23 ]
python
en
['en', 'en', 'en']
True
get_shape_and_set_modified_shape_2D
(tensor, additional_dimension_sizes)
Fixes the shape and type of serving input strings. Given feature tensor and additional dimension size, sequence length, fixes dynamic shape ambiguity of last dimension so that we will be able to use it in our DNN (since tf.layers.dense require the last dimension to be known). Args: tensor: tf.float64 vector feature tensor. additional_dimension_sizes: Additional dimension size, namely sequence length. Returns: Feature tensor with set static shape for sequence length.
Fixes the shape and type of serving input strings.
def get_shape_and_set_modified_shape_2D(tensor, additional_dimension_sizes): """Fixes the shape and type of serving input strings. Given feature tensor and additional dimension size, sequence length, fixes dynamic shape ambiguity of last dimension so that we will be able to use it in our DNN (since tf.layers.dense require the last dimension to be known). Args: tensor: tf.float64 vector feature tensor. additional_dimension_sizes: Additional dimension size, namely sequence length. Returns: Feature tensor with set static shape for sequence length. """ # Get static shape for tensor and convert it to list shape = tensor.get_shape().as_list() # Set outer shape to additional_dimension_sizes[0] since know this is the # correct size shape[1] = additional_dimension_sizes[0] # Set the shape of tensor to our modified shape # shape = (batch_size, additional_dimension_sizes[0]) tensor.set_shape(shape=shape) return tensor
[ "def", "get_shape_and_set_modified_shape_2D", "(", "tensor", ",", "additional_dimension_sizes", ")", ":", "# Get static shape for tensor and convert it to list", "shape", "=", "tensor", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "# Set outer shape to additional_dimension_sizes[0] since know this is the", "# correct size", "shape", "[", "1", "]", "=", "additional_dimension_sizes", "[", "0", "]", "# Set the shape of tensor to our modified shape", "# shape = (batch_size, additional_dimension_sizes[0])", "tensor", ".", "set_shape", "(", "shape", "=", "shape", ")", "return", "tensor" ]
[ 36, 0 ]
[ 61, 15 ]
python
en
['en', 'en', 'en']
True
serving_input_fn
(feat_names, seq_len)
Serving input function. Given the sequence length, return ServingInputReceiver object. Args: feat_names: List of string names of features. seq_len: Number of timesteps in sequence. Returns: ServingInputReceiver object containing features and receiver tensors.
Serving input function.
def serving_input_fn(feat_names, seq_len): """Serving input function. Given the sequence length, return ServingInputReceiver object. Args: feat_names: List of string names of features. seq_len: Number of timesteps in sequence. Returns: ServingInputReceiver object containing features and receiver tensors. """ # Create placeholders to accept the data sent to the model at serving time # All features come in as a batch of strings, shape = (batch_size,), # this was so because of passing the arrays to online ml-engine prediction feature_placeholders = { feature: tf.placeholder( dtype=tf.string, shape=[None]) for feature in feat_names } # Create feature tensors features = {key: fix_shape_and_type_for_serving(placeholder=tensor) for key, tensor in feature_placeholders.items()} # Fix dynamic shape ambiguity of feature tensors for our DNN features = {key: get_shape_and_set_modified_shape_2D( tensor=tensor, additional_dimension_sizes=[seq_len]) for key, tensor in features.items()} return tf.estimator.export.ServingInputReceiver( features=features, receiver_tensors=feature_placeholders)
[ "def", "serving_input_fn", "(", "feat_names", ",", "seq_len", ")", ":", "# Create placeholders to accept the data sent to the model at serving time", "# All features come in as a batch of strings, shape = (batch_size,),", "# this was so because of passing the arrays to online ml-engine prediction", "feature_placeholders", "=", "{", "feature", ":", "tf", ".", "placeholder", "(", "dtype", "=", "tf", ".", "string", ",", "shape", "=", "[", "None", "]", ")", "for", "feature", "in", "feat_names", "}", "# Create feature tensors", "features", "=", "{", "key", ":", "fix_shape_and_type_for_serving", "(", "placeholder", "=", "tensor", ")", "for", "key", ",", "tensor", "in", "feature_placeholders", ".", "items", "(", ")", "}", "# Fix dynamic shape ambiguity of feature tensors for our DNN", "features", "=", "{", "key", ":", "get_shape_and_set_modified_shape_2D", "(", "tensor", "=", "tensor", ",", "additional_dimension_sizes", "=", "[", "seq_len", "]", ")", "for", "key", ",", "tensor", "in", "features", ".", "items", "(", ")", "}", "return", "tf", ".", "estimator", ".", "export", ".", "ServingInputReceiver", "(", "features", "=", "features", ",", "receiver_tensors", "=", "feature_placeholders", ")" ]
[ 64, 0 ]
[ 95, 63 ]
python
en
['en', 'en', 'en']
True
DashboardsServiceAsyncClient.from_service_account_info
(cls, info: dict, *args, **kwargs)
Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: DashboardsServiceAsyncClient: The constructed client.
Creates an instance of this client using the provided credentials info.
def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: DashboardsServiceAsyncClient: The constructed client. """ return DashboardsServiceClient.from_service_account_info.__func__(DashboardsServiceAsyncClient, info, *args, **kwargs)
[ "def", "from_service_account_info", "(", "cls", ",", "info", ":", "dict", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "DashboardsServiceClient", ".", "from_service_account_info", ".", "__func__", "(", "DashboardsServiceAsyncClient", ",", "info", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 84, 4 ]
[ 96, 126 ]
python
en
['en', 'en', 'en']
True
DashboardsServiceAsyncClient.from_service_account_file
(cls, filename: str, *args, **kwargs)
Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: DashboardsServiceAsyncClient: The constructed client.
Creates an instance of this client using the provided credentials file.
def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: DashboardsServiceAsyncClient: The constructed client. """ return DashboardsServiceClient.from_service_account_file.__func__(DashboardsServiceAsyncClient, filename, *args, **kwargs)
[ "def", "from_service_account_file", "(", "cls", ",", "filename", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "DashboardsServiceClient", ".", "from_service_account_file", ".", "__func__", "(", "DashboardsServiceAsyncClient", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 99, 4 ]
[ 112, 130 ]
python
en
['en', 'en', 'en']
True
DashboardsServiceAsyncClient.transport
(self)
Returns the transport used by the client instance. Returns: DashboardsServiceTransport: The transport used by the client instance.
Returns the transport used by the client instance.
def transport(self) -> DashboardsServiceTransport: """Returns the transport used by the client instance. Returns: DashboardsServiceTransport: The transport used by the client instance. """ return self._client.transport
[ "def", "transport", "(", "self", ")", "->", "DashboardsServiceTransport", ":", "return", "self", ".", "_client", ".", "transport" ]
[ 117, 4 ]
[ 123, 37 ]
python
en
['en', 'en', 'en']
True
DashboardsServiceAsyncClient.__init__
( self, *, credentials: ga_credentials.Credentials = None, transport: Union[str, DashboardsServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, )
Instantiates the dashboards service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.DashboardsServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason.
Instantiates the dashboards service client.
def __init__( self, *, credentials: ga_credentials.Credentials = None, transport: Union[str, DashboardsServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the dashboards service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.DashboardsServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ self._client = DashboardsServiceClient( credentials=credentials, transport=transport, client_options=client_options, client_info=client_info, )
[ "def", "__init__", "(", "self", ",", "*", ",", "credentials", ":", "ga_credentials", ".", "Credentials", "=", "None", ",", "transport", ":", "Union", "[", "str", ",", "DashboardsServiceTransport", "]", "=", "\"grpc_asyncio\"", ",", "client_options", ":", "ClientOptions", "=", "None", ",", "client_info", ":", "gapic_v1", ".", "client_info", ".", "ClientInfo", "=", "DEFAULT_CLIENT_INFO", ",", ")", "->", "None", ":", "self", ".", "_client", "=", "DashboardsServiceClient", "(", "credentials", "=", "credentials", ",", "transport", "=", "transport", ",", "client_options", "=", "client_options", ",", "client_info", "=", "client_info", ",", ")" ]
[ 129, 4 ]
[ 174, 9 ]
python
en
['en', 'en', 'en']
True
DashboardsServiceAsyncClient.create_dashboard
( self, request: Union[dashboards_service.CreateDashboardRequest, dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), )
r"""Creates a new custom dashboard. For examples on how you can use this API to create dashboards, see `Managing dashboards by API <https://cloud.google.com/monitoring/dashboards/api-dashboard>`__. This method requires the ``monitoring.dashboards.create`` permission on the specified project. For more information about permissions, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__. Args: request (Union[google.cloud.monitoring_dashboard_v1.types.CreateDashboardRequest, dict]): The request object. The `CreateDashboard` request. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.monitoring_dashboard_v1.types.Dashboard: A Google Stackdriver dashboard. Dashboards define the content and layout of pages in the Stackdriver web application.
r"""Creates a new custom dashboard. For examples on how you can use this API to create dashboards, see `Managing dashboards by API <https://cloud.google.com/monitoring/dashboards/api-dashboard>`__. This method requires the ``monitoring.dashboards.create`` permission on the specified project. For more information about permissions, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__.
async def create_dashboard( self, request: Union[dashboards_service.CreateDashboardRequest, dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> dashboard.Dashboard: r"""Creates a new custom dashboard. For examples on how you can use this API to create dashboards, see `Managing dashboards by API <https://cloud.google.com/monitoring/dashboards/api-dashboard>`__. This method requires the ``monitoring.dashboards.create`` permission on the specified project. For more information about permissions, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__. Args: request (Union[google.cloud.monitoring_dashboard_v1.types.CreateDashboardRequest, dict]): The request object. The `CreateDashboard` request. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.monitoring_dashboard_v1.types.Dashboard: A Google Stackdriver dashboard. Dashboards define the content and layout of pages in the Stackdriver web application. """ # Create or coerce a protobuf request object. request = dashboards_service.CreateDashboardRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.create_dashboard, default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response
[ "async", "def", "create_dashboard", "(", "self", ",", "request", ":", "Union", "[", "dashboards_service", ".", "CreateDashboardRequest", ",", "dict", "]", "=", "None", ",", "*", ",", "retry", ":", "OptionalRetry", "=", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", ":", "float", "=", "None", ",", "metadata", ":", "Sequence", "[", "Tuple", "[", "str", ",", "str", "]", "]", "=", "(", ")", ",", ")", "->", "dashboard", ".", "Dashboard", ":", "# Create or coerce a protobuf request object.", "request", "=", "dashboards_service", ".", "CreateDashboardRequest", "(", "request", ")", "# Wrap the RPC method; this adds retry and timeout information,", "# and friendly error handling.", "rpc", "=", "gapic_v1", ".", "method_async", ".", "wrap_method", "(", "self", ".", "_client", ".", "_transport", ".", "create_dashboard", ",", "default_timeout", "=", "30.0", ",", "client_info", "=", "DEFAULT_CLIENT_INFO", ",", ")", "# Certain fields should be provided within the metadata header;", "# add these here.", "metadata", "=", "tuple", "(", "metadata", ")", "+", "(", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "(", "(", "\"parent\"", ",", "request", ".", "parent", ")", ",", ")", ")", ",", ")", "# Send the request.", "response", "=", "await", "rpc", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ",", ")", "# Done; return the response.", "return", "response" ]
[ 176, 4 ]
[ 230, 23 ]
python
en
['en', 'en', 'en']
True
DashboardsServiceAsyncClient.list_dashboards
( self, request: Union[dashboards_service.ListDashboardsRequest, dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), )
r"""Lists the existing dashboards. This method requires the ``monitoring.dashboards.list`` permission on the specified project. For more information, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__. Args: request (Union[google.cloud.monitoring_dashboard_v1.types.ListDashboardsRequest, dict]): The request object. The `ListDashboards` request. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.monitoring_dashboard_v1.services.dashboards_service.pagers.ListDashboardsAsyncPager: The ListDashboards request. Iterating over this object will yield results and resolve additional pages automatically.
r"""Lists the existing dashboards.
async def list_dashboards( self, request: Union[dashboards_service.ListDashboardsRequest, dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListDashboardsAsyncPager: r"""Lists the existing dashboards. This method requires the ``monitoring.dashboards.list`` permission on the specified project. For more information, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__. Args: request (Union[google.cloud.monitoring_dashboard_v1.types.ListDashboardsRequest, dict]): The request object. The `ListDashboards` request. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.monitoring_dashboard_v1.services.dashboards_service.pagers.ListDashboardsAsyncPager: The ListDashboards request. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. request = dashboards_service.ListDashboardsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.list_dashboards, default_timeout=None, client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListDashboardsAsyncPager( method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response
[ "async", "def", "list_dashboards", "(", "self", ",", "request", ":", "Union", "[", "dashboards_service", ".", "ListDashboardsRequest", ",", "dict", "]", "=", "None", ",", "*", ",", "retry", ":", "OptionalRetry", "=", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", ":", "float", "=", "None", ",", "metadata", ":", "Sequence", "[", "Tuple", "[", "str", ",", "str", "]", "]", "=", "(", ")", ",", ")", "->", "pagers", ".", "ListDashboardsAsyncPager", ":", "# Create or coerce a protobuf request object.", "request", "=", "dashboards_service", ".", "ListDashboardsRequest", "(", "request", ")", "# Wrap the RPC method; this adds retry and timeout information,", "# and friendly error handling.", "rpc", "=", "gapic_v1", ".", "method_async", ".", "wrap_method", "(", "self", ".", "_client", ".", "_transport", ".", "list_dashboards", ",", "default_timeout", "=", "None", ",", "client_info", "=", "DEFAULT_CLIENT_INFO", ",", ")", "# Certain fields should be provided within the metadata header;", "# add these here.", "metadata", "=", "tuple", "(", "metadata", ")", "+", "(", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "(", "(", "\"parent\"", ",", "request", ".", "parent", ")", ",", ")", ")", ",", ")", "# Send the request.", "response", "=", "await", "rpc", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ",", ")", "# This method is paged; wrap the response in a pager, which provides", "# an `__aiter__` convenience method.", "response", "=", "pagers", ".", "ListDashboardsAsyncPager", "(", "method", "=", "rpc", ",", "request", "=", "request", ",", "response", "=", "response", ",", "metadata", "=", "metadata", ",", ")", "# Done; return the response.", "return", "response" ]
[ 232, 4 ]
[ 291, 23 ]
python
en
['en', 'en', 'en']
True
DashboardsServiceAsyncClient.get_dashboard
( self, request: Union[dashboards_service.GetDashboardRequest, dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), )
r"""Fetches a specific dashboard. This method requires the ``monitoring.dashboards.get`` permission on the specified dashboard. For more information, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__. Args: request (Union[google.cloud.monitoring_dashboard_v1.types.GetDashboardRequest, dict]): The request object. The `GetDashboard` request. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.monitoring_dashboard_v1.types.Dashboard: A Google Stackdriver dashboard. Dashboards define the content and layout of pages in the Stackdriver web application.
r"""Fetches a specific dashboard.
async def get_dashboard( self, request: Union[dashboards_service.GetDashboardRequest, dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> dashboard.Dashboard: r"""Fetches a specific dashboard. This method requires the ``monitoring.dashboards.get`` permission on the specified dashboard. For more information, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__. Args: request (Union[google.cloud.monitoring_dashboard_v1.types.GetDashboardRequest, dict]): The request object. The `GetDashboard` request. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.monitoring_dashboard_v1.types.Dashboard: A Google Stackdriver dashboard. Dashboards define the content and layout of pages in the Stackdriver web application. """ # Create or coerce a protobuf request object. request = dashboards_service.GetDashboardRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.get_dashboard, default_timeout=None, client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response
[ "async", "def", "get_dashboard", "(", "self", ",", "request", ":", "Union", "[", "dashboards_service", ".", "GetDashboardRequest", ",", "dict", "]", "=", "None", ",", "*", ",", "retry", ":", "OptionalRetry", "=", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", ":", "float", "=", "None", ",", "metadata", ":", "Sequence", "[", "Tuple", "[", "str", ",", "str", "]", "]", "=", "(", ")", ",", ")", "->", "dashboard", ".", "Dashboard", ":", "# Create or coerce a protobuf request object.", "request", "=", "dashboards_service", ".", "GetDashboardRequest", "(", "request", ")", "# Wrap the RPC method; this adds retry and timeout information,", "# and friendly error handling.", "rpc", "=", "gapic_v1", ".", "method_async", ".", "wrap_method", "(", "self", ".", "_client", ".", "_transport", ".", "get_dashboard", ",", "default_timeout", "=", "None", ",", "client_info", "=", "DEFAULT_CLIENT_INFO", ",", ")", "# Certain fields should be provided within the metadata header;", "# add these here.", "metadata", "=", "tuple", "(", "metadata", ")", "+", "(", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "(", "(", "\"name\"", ",", "request", ".", "name", ")", ",", ")", ")", ",", ")", "# Send the request.", "response", "=", "await", "rpc", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ",", ")", "# Done; return the response.", "return", "response" ]
[ 293, 4 ]
[ 346, 23 ]
python
en
['en', 'en', 'en']
True
DashboardsServiceAsyncClient.delete_dashboard
( self, request: Union[dashboards_service.DeleteDashboardRequest, dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), )
r"""Deletes an existing custom dashboard. This method requires the ``monitoring.dashboards.delete`` permission on the specified dashboard. For more information, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__. Args: request (Union[google.cloud.monitoring_dashboard_v1.types.DeleteDashboardRequest, dict]): The request object. The `DeleteDashboard` request. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata.
r"""Deletes an existing custom dashboard.
async def delete_dashboard( self, request: Union[dashboards_service.DeleteDashboardRequest, dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> None: r"""Deletes an existing custom dashboard. This method requires the ``monitoring.dashboards.delete`` permission on the specified dashboard. For more information, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__. Args: request (Union[google.cloud.monitoring_dashboard_v1.types.DeleteDashboardRequest, dict]): The request object. The `DeleteDashboard` request. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ # Create or coerce a protobuf request object. request = dashboards_service.DeleteDashboardRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.delete_dashboard, default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. await rpc( request, retry=retry, timeout=timeout, metadata=metadata, )
[ "async", "def", "delete_dashboard", "(", "self", ",", "request", ":", "Union", "[", "dashboards_service", ".", "DeleteDashboardRequest", ",", "dict", "]", "=", "None", ",", "*", ",", "retry", ":", "OptionalRetry", "=", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", ":", "float", "=", "None", ",", "metadata", ":", "Sequence", "[", "Tuple", "[", "str", ",", "str", "]", "]", "=", "(", ")", ",", ")", "->", "None", ":", "# Create or coerce a protobuf request object.", "request", "=", "dashboards_service", ".", "DeleteDashboardRequest", "(", "request", ")", "# Wrap the RPC method; this adds retry and timeout information,", "# and friendly error handling.", "rpc", "=", "gapic_v1", ".", "method_async", ".", "wrap_method", "(", "self", ".", "_client", ".", "_transport", ".", "delete_dashboard", ",", "default_timeout", "=", "30.0", ",", "client_info", "=", "DEFAULT_CLIENT_INFO", ",", ")", "# Certain fields should be provided within the metadata header;", "# add these here.", "metadata", "=", "tuple", "(", "metadata", ")", "+", "(", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "(", "(", "\"name\"", ",", "request", ".", "name", ")", ",", ")", ")", ",", ")", "# Send the request.", "await", "rpc", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ",", ")" ]
[ 348, 4 ]
[ 392, 9 ]
python
en
['en', 'cy', 'en']
True
DashboardsServiceAsyncClient.update_dashboard
( self, request: Union[dashboards_service.UpdateDashboardRequest, dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), )
r"""Replaces an existing custom dashboard with a new definition. This method requires the ``monitoring.dashboards.update`` permission on the specified dashboard. For more information, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__. Args: request (Union[google.cloud.monitoring_dashboard_v1.types.UpdateDashboardRequest, dict]): The request object. The `UpdateDashboard` request. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.monitoring_dashboard_v1.types.Dashboard: A Google Stackdriver dashboard. Dashboards define the content and layout of pages in the Stackdriver web application.
r"""Replaces an existing custom dashboard with a new definition.
async def update_dashboard( self, request: Union[dashboards_service.UpdateDashboardRequest, dict] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> dashboard.Dashboard: r"""Replaces an existing custom dashboard with a new definition. This method requires the ``monitoring.dashboards.update`` permission on the specified dashboard. For more information, see `Cloud Identity and Access Management <https://cloud.google.com/iam>`__. Args: request (Union[google.cloud.monitoring_dashboard_v1.types.UpdateDashboardRequest, dict]): The request object. The `UpdateDashboard` request. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.monitoring_dashboard_v1.types.Dashboard: A Google Stackdriver dashboard. Dashboards define the content and layout of pages in the Stackdriver web application. """ # Create or coerce a protobuf request object. request = dashboards_service.UpdateDashboardRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( self._client._transport.update_dashboard, default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, ) # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( (("dashboard.name", request.dashboard.name),) ), ) # Send the request. response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response
[ "async", "def", "update_dashboard", "(", "self", ",", "request", ":", "Union", "[", "dashboards_service", ".", "UpdateDashboardRequest", ",", "dict", "]", "=", "None", ",", "*", ",", "retry", ":", "OptionalRetry", "=", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", ":", "float", "=", "None", ",", "metadata", ":", "Sequence", "[", "Tuple", "[", "str", ",", "str", "]", "]", "=", "(", ")", ",", ")", "->", "dashboard", ".", "Dashboard", ":", "# Create or coerce a protobuf request object.", "request", "=", "dashboards_service", ".", "UpdateDashboardRequest", "(", "request", ")", "# Wrap the RPC method; this adds retry and timeout information,", "# and friendly error handling.", "rpc", "=", "gapic_v1", ".", "method_async", ".", "wrap_method", "(", "self", ".", "_client", ".", "_transport", ".", "update_dashboard", ",", "default_timeout", "=", "30.0", ",", "client_info", "=", "DEFAULT_CLIENT_INFO", ",", ")", "# Certain fields should be provided within the metadata header;", "# add these here.", "metadata", "=", "tuple", "(", "metadata", ")", "+", "(", "gapic_v1", ".", "routing_header", ".", "to_grpc_metadata", "(", "(", "(", "\"dashboard.name\"", ",", "request", ".", "dashboard", ".", "name", ")", ",", ")", ")", ",", ")", "# Send the request.", "response", "=", "await", "rpc", "(", "request", ",", "retry", "=", "retry", ",", "timeout", "=", "timeout", ",", "metadata", "=", "metadata", ",", ")", "# Done; return the response.", "return", "response" ]
[ 394, 4 ]
[ 449, 23 ]
python
en
['en', 'en', 'en']
True
_const_compare_digest_backport
(a, b)
Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise.
Compare two digests of equal length in constant time.
def _const_compare_digest_backport(a, b): """ Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise. """ result = abs(len(a) - len(b)) for left, right in zip(bytearray(a), bytearray(b)): result |= left ^ right return result == 0
[ "def", "_const_compare_digest_backport", "(", "a", ",", "b", ")", ":", "result", "=", "abs", "(", "len", "(", "a", ")", "-", "len", "(", "b", ")", ")", "for", "left", ",", "right", "in", "zip", "(", "bytearray", "(", "a", ")", ",", "bytearray", "(", "b", ")", ")", ":", "result", "|=", "left", "^", "right", "return", "result", "==", "0" ]
[ 29, 0 ]
[ 39, 22 ]
python
en
['en', 'error', 'th']
False
assert_fingerprint
(cert, fingerprint)
Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons.
Checks if given fingerprint matches the supplied certificate.
def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ fingerprint = fingerprint.replace(":", "").lower() digest_length = len(fingerprint) hashfunc = HASHFUNC_MAP.get(digest_length) if not hashfunc: raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint)) # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) cert_digest = hashfunc(cert).digest() if not _const_compare_digest(cert_digest, fingerprint_bytes): raise SSLError( 'Fingerprints did not match. Expected "{0}", got "{1}".'.format( fingerprint, hexlify(cert_digest) ) )
[ "def", "assert_fingerprint", "(", "cert", ",", "fingerprint", ")", ":", "fingerprint", "=", "fingerprint", ".", "replace", "(", "\":\"", ",", "\"\"", ")", ".", "lower", "(", ")", "digest_length", "=", "len", "(", "fingerprint", ")", "hashfunc", "=", "HASHFUNC_MAP", ".", "get", "(", "digest_length", ")", "if", "not", "hashfunc", ":", "raise", "SSLError", "(", "\"Fingerprint of invalid length: {0}\"", ".", "format", "(", "fingerprint", ")", ")", "# We need encode() here for py32; works on py2 and p33.", "fingerprint_bytes", "=", "unhexlify", "(", "fingerprint", ".", "encode", "(", ")", ")", "cert_digest", "=", "hashfunc", "(", "cert", ")", ".", "digest", "(", ")", "if", "not", "_const_compare_digest", "(", "cert_digest", ",", "fingerprint_bytes", ")", ":", "raise", "SSLError", "(", "'Fingerprints did not match. Expected \"{0}\", got \"{1}\".'", ".", "format", "(", "fingerprint", ",", "hexlify", "(", "cert_digest", ")", ")", ")" ]
[ 181, 0 ]
[ 207, 9 ]
python
en
['en', 'error', 'th']
False
resolve_cert_reqs
(candidate)
Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_REQUIRED`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbreviation. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket.
Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_REQUIRED`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbreviation. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket.
def resolve_cert_reqs(candidate): """ Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_REQUIRED`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbreviation. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket. """ if candidate is None: return CERT_REQUIRED if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, "CERT_" + candidate) return res return candidate
[ "def", "resolve_cert_reqs", "(", "candidate", ")", ":", "if", "candidate", "is", "None", ":", "return", "CERT_REQUIRED", "if", "isinstance", "(", "candidate", ",", "str", ")", ":", "res", "=", "getattr", "(", "ssl", ",", "candidate", ",", "None", ")", "if", "res", "is", "None", ":", "res", "=", "getattr", "(", "ssl", ",", "\"CERT_\"", "+", "candidate", ")", "return", "res", "return", "candidate" ]
[ 210, 0 ]
[ 230, 20 ]
python
en
['en', 'error', 'th']
False
resolve_ssl_version
(candidate)
like resolve_cert_reqs
like resolve_cert_reqs
def resolve_ssl_version(candidate): """ like resolve_cert_reqs """ if candidate is None: return PROTOCOL_TLS if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, "PROTOCOL_" + candidate) return res return candidate
[ "def", "resolve_ssl_version", "(", "candidate", ")", ":", "if", "candidate", "is", "None", ":", "return", "PROTOCOL_TLS", "if", "isinstance", "(", "candidate", ",", "str", ")", ":", "res", "=", "getattr", "(", "ssl", ",", "candidate", ",", "None", ")", "if", "res", "is", "None", ":", "res", "=", "getattr", "(", "ssl", ",", "\"PROTOCOL_\"", "+", "candidate", ")", "return", "res", "return", "candidate" ]
[ 233, 0 ]
[ 246, 20 ]
python
en
['en', 'error', 'th']
False
create_urllib3_context
( ssl_version=None, cert_reqs=None, options=None, ciphers=None )
All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext
All arguments have the same meaning as ``ssl_wrap_socket``.
def create_urllib3_context( ssl_version=None, cert_reqs=None, options=None, ciphers=None ): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ # PROTOCOL_TLS is deprecated in Python 3.10 if not ssl_version or ssl_version == PROTOCOL_TLS: ssl_version = PROTOCOL_TLS_CLIENT context = SSLContext(ssl_version) context.set_ciphers(ciphers or DEFAULT_CIPHERS) # Setting the default here, as we may have no ssl module on import cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION # TLSv1.2 only. Unless set explicitly, do not request tickets. # This may save some bandwidth on wire, and although the ticket is encrypted, # there is a risk associated with it being on wire, # if the server is not rotating its ticketing keys properly. options |= OP_NO_TICKET context.options |= options # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is # necessary for conditional client cert authentication with TLS 1.3. # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older # versions of Python. We only enable on Python 3.7.4+ or if certificate # verification is enabled to work around Python issue #37428 # See: https://bugs.python.org/issue37428 if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr( context, "post_handshake_auth", None ) is not None: context.post_handshake_auth = True def disable_check_hostname(): if ( getattr(context, "check_hostname", None) is not None ): # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False # The order of the below lines setting verify_mode and check_hostname # matter due to safe-guards SSLContext has to prevent an SSLContext with # check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more # complex because we don't know whether PROTOCOL_TLS_CLIENT will be used # or not so we don't know the initial state of the freshly created SSLContext. if cert_reqs == ssl.CERT_REQUIRED: context.verify_mode = cert_reqs disable_check_hostname() else: disable_check_hostname() context.verify_mode = cert_reqs # Enable logging of TLS session keys via defacto standard environment variable # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values. if hasattr(context, "keylog_filename"): sslkeylogfile = os.environ.get("SSLKEYLOGFILE") if sslkeylogfile: context.keylog_filename = sslkeylogfile return context
[ "def", "create_urllib3_context", "(", "ssl_version", "=", "None", ",", "cert_reqs", "=", "None", ",", "options", "=", "None", ",", "ciphers", "=", "None", ")", ":", "# PROTOCOL_TLS is deprecated in Python 3.10", "if", "not", "ssl_version", "or", "ssl_version", "==", "PROTOCOL_TLS", ":", "ssl_version", "=", "PROTOCOL_TLS_CLIENT", "context", "=", "SSLContext", "(", "ssl_version", ")", "context", ".", "set_ciphers", "(", "ciphers", "or", "DEFAULT_CIPHERS", ")", "# Setting the default here, as we may have no ssl module on import", "cert_reqs", "=", "ssl", ".", "CERT_REQUIRED", "if", "cert_reqs", "is", "None", "else", "cert_reqs", "if", "options", "is", "None", ":", "options", "=", "0", "# SSLv2 is easily broken and is considered harmful and dangerous", "options", "|=", "OP_NO_SSLv2", "# SSLv3 has several problems and is now dangerous", "options", "|=", "OP_NO_SSLv3", "# Disable compression to prevent CRIME attacks for OpenSSL 1.0+", "# (issue #309)", "options", "|=", "OP_NO_COMPRESSION", "# TLSv1.2 only. Unless set explicitly, do not request tickets.", "# This may save some bandwidth on wire, and although the ticket is encrypted,", "# there is a risk associated with it being on wire,", "# if the server is not rotating its ticketing keys properly.", "options", "|=", "OP_NO_TICKET", "context", ".", "options", "|=", "options", "# Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is", "# necessary for conditional client cert authentication with TLS 1.3.", "# The attribute is None for OpenSSL <= 1.1.0 or does not exist in older", "# versions of Python. We only enable on Python 3.7.4+ or if certificate", "# verification is enabled to work around Python issue #37428", "# See: https://bugs.python.org/issue37428", "if", "(", "cert_reqs", "==", "ssl", ".", "CERT_REQUIRED", "or", "sys", ".", "version_info", ">=", "(", "3", ",", "7", ",", "4", ")", ")", "and", "getattr", "(", "context", ",", "\"post_handshake_auth\"", ",", "None", ")", "is", "not", "None", ":", "context", ".", "post_handshake_auth", "=", "True", "def", "disable_check_hostname", "(", ")", ":", "if", "(", "getattr", "(", "context", ",", "\"check_hostname\"", ",", "None", ")", "is", "not", "None", ")", ":", "# Platform-specific: Python 3.2", "# We do our own verification, including fingerprints and alternative", "# hostnames. So disable it here", "context", ".", "check_hostname", "=", "False", "# The order of the below lines setting verify_mode and check_hostname", "# matter due to safe-guards SSLContext has to prevent an SSLContext with", "# check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more", "# complex because we don't know whether PROTOCOL_TLS_CLIENT will be used", "# or not so we don't know the initial state of the freshly created SSLContext.", "if", "cert_reqs", "==", "ssl", ".", "CERT_REQUIRED", ":", "context", ".", "verify_mode", "=", "cert_reqs", "disable_check_hostname", "(", ")", "else", ":", "disable_check_hostname", "(", ")", "context", ".", "verify_mode", "=", "cert_reqs", "# Enable logging of TLS session keys via defacto standard environment variable", "# 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.", "if", "hasattr", "(", "context", ",", "\"keylog_filename\"", ")", ":", "sslkeylogfile", "=", "os", ".", "environ", ".", "get", "(", "\"SSLKEYLOGFILE\"", ")", "if", "sslkeylogfile", ":", "context", ".", "keylog_filename", "=", "sslkeylogfile", "return", "context" ]
[ 249, 0 ]
[ 351, 18 ]
python
en
['en', 'en', 'en']
True
ssl_wrap_socket
( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None, key_password=None, ca_cert_data=None, tls_in_tls=False, )
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted. :param ca_cert_data: Optional string containing CA certificates in PEM format suitable for passing as the cadata parameter to SSLContext.load_verify_locations() :param tls_in_tls: Use SSLTransport to wrap the existing socket.
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`.
def ssl_wrap_socket( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None, key_password=None, ca_cert_data=None, tls_in_tls=False, ): """ All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted. :param ca_cert_data: Optional string containing CA certificates in PEM format suitable for passing as the cadata parameter to SSLContext.load_verify_locations() :param tls_in_tls: Use SSLTransport to wrap the existing socket. """ context = ssl_context if context is None: # Note: This branch of code and all the variables in it are no longer # used by urllib3 itself. We should consider deprecating and removing # this code. context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs or ca_cert_dir or ca_cert_data: try: context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) except (IOError, OSError) as e: raise SSLError(e) elif ssl_context is None and hasattr(context, "load_default_certs"): # try to load OS default certs; works well on Windows (require Python3.4+) context.load_default_certs() # Attempt to detect if we get the goofy behavior of the # keyfile being encrypted and OpenSSL asking for the # passphrase via the terminal and instead error out. if keyfile and key_password is None and _is_key_file_encrypted(keyfile): raise SSLError("Client private key is encrypted, password is required") if certfile: if key_password is None: context.load_cert_chain(certfile, keyfile) else: context.load_cert_chain(certfile, keyfile, key_password) try: if hasattr(context, "set_alpn_protocols"): context.set_alpn_protocols(ALPN_PROTOCOLS) except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols pass # If we detect server_hostname is an IP address then the SNI # extension should not be used according to RFC3546 Section 3.1 use_sni_hostname = server_hostname and not is_ipaddress(server_hostname) # SecureTransport uses server_hostname in certificate verification. send_sni = (use_sni_hostname and HAS_SNI) or ( IS_SECURETRANSPORT and server_hostname ) # Do not warn the user if server_hostname is an invalid SNI hostname. if not HAS_SNI and use_sni_hostname: warnings.warn( "An HTTPS request has been made, but the SNI (Server Name " "Indication) extension to TLS is not available on this platform. " "This may cause the server to present an incorrect TLS " "certificate, which can cause validation failures. You can upgrade to " "a newer version of Python to solve this. For more information, see " "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html" "#ssl-warnings", SNIMissingWarning, ) if send_sni: ssl_sock = _ssl_wrap_socket_impl( sock, context, tls_in_tls, server_hostname=server_hostname ) else: ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls) return ssl_sock
[ "def", "ssl_wrap_socket", "(", "sock", ",", "keyfile", "=", "None", ",", "certfile", "=", "None", ",", "cert_reqs", "=", "None", ",", "ca_certs", "=", "None", ",", "server_hostname", "=", "None", ",", "ssl_version", "=", "None", ",", "ciphers", "=", "None", ",", "ssl_context", "=", "None", ",", "ca_cert_dir", "=", "None", ",", "key_password", "=", "None", ",", "ca_cert_data", "=", "None", ",", "tls_in_tls", "=", "False", ",", ")", ":", "context", "=", "ssl_context", "if", "context", "is", "None", ":", "# Note: This branch of code and all the variables in it are no longer", "# used by urllib3 itself. We should consider deprecating and removing", "# this code.", "context", "=", "create_urllib3_context", "(", "ssl_version", ",", "cert_reqs", ",", "ciphers", "=", "ciphers", ")", "if", "ca_certs", "or", "ca_cert_dir", "or", "ca_cert_data", ":", "try", ":", "context", ".", "load_verify_locations", "(", "ca_certs", ",", "ca_cert_dir", ",", "ca_cert_data", ")", "except", "(", "IOError", ",", "OSError", ")", "as", "e", ":", "raise", "SSLError", "(", "e", ")", "elif", "ssl_context", "is", "None", "and", "hasattr", "(", "context", ",", "\"load_default_certs\"", ")", ":", "# try to load OS default certs; works well on Windows (require Python3.4+)", "context", ".", "load_default_certs", "(", ")", "# Attempt to detect if we get the goofy behavior of the", "# keyfile being encrypted and OpenSSL asking for the", "# passphrase via the terminal and instead error out.", "if", "keyfile", "and", "key_password", "is", "None", "and", "_is_key_file_encrypted", "(", "keyfile", ")", ":", "raise", "SSLError", "(", "\"Client private key is encrypted, password is required\"", ")", "if", "certfile", ":", "if", "key_password", "is", "None", ":", "context", ".", "load_cert_chain", "(", "certfile", ",", "keyfile", ")", "else", ":", "context", ".", "load_cert_chain", "(", "certfile", ",", "keyfile", ",", "key_password", ")", "try", ":", "if", "hasattr", "(", "context", ",", "\"set_alpn_protocols\"", ")", ":", "context", ".", "set_alpn_protocols", "(", "ALPN_PROTOCOLS", ")", "except", "NotImplementedError", ":", "# Defensive: in CI, we always have set_alpn_protocols", "pass", "# If we detect server_hostname is an IP address then the SNI", "# extension should not be used according to RFC3546 Section 3.1", "use_sni_hostname", "=", "server_hostname", "and", "not", "is_ipaddress", "(", "server_hostname", ")", "# SecureTransport uses server_hostname in certificate verification.", "send_sni", "=", "(", "use_sni_hostname", "and", "HAS_SNI", ")", "or", "(", "IS_SECURETRANSPORT", "and", "server_hostname", ")", "# Do not warn the user if server_hostname is an invalid SNI hostname.", "if", "not", "HAS_SNI", "and", "use_sni_hostname", ":", "warnings", ".", "warn", "(", "\"An HTTPS request has been made, but the SNI (Server Name \"", "\"Indication) extension to TLS is not available on this platform. \"", "\"This may cause the server to present an incorrect TLS \"", "\"certificate, which can cause validation failures. You can upgrade to \"", "\"a newer version of Python to solve this. For more information, see \"", "\"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"", "\"#ssl-warnings\"", ",", "SNIMissingWarning", ",", ")", "if", "send_sni", ":", "ssl_sock", "=", "_ssl_wrap_socket_impl", "(", "sock", ",", "context", ",", "tls_in_tls", ",", "server_hostname", "=", "server_hostname", ")", "else", ":", "ssl_sock", "=", "_ssl_wrap_socket_impl", "(", "sock", ",", "context", ",", "tls_in_tls", ")", "return", "ssl_sock" ]
[ 354, 0 ]
[ 453, 19 ]
python
en
['en', 'error', 'th']
False
is_ipaddress
(hostname)
Detects whether the hostname given is an IPv4 or IPv6 address. Also detects IPv6 addresses with Zone IDs. :param str hostname: Hostname to examine. :return: True if the hostname is an IP address, False otherwise.
Detects whether the hostname given is an IPv4 or IPv6 address. Also detects IPv6 addresses with Zone IDs.
def is_ipaddress(hostname): """Detects whether the hostname given is an IPv4 or IPv6 address. Also detects IPv6 addresses with Zone IDs. :param str hostname: Hostname to examine. :return: True if the hostname is an IP address, False otherwise. """ if not six.PY2 and isinstance(hostname, bytes): # IDN A-label bytes are ASCII compatible. hostname = hostname.decode("ascii") return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname))
[ "def", "is_ipaddress", "(", "hostname", ")", ":", "if", "not", "six", ".", "PY2", "and", "isinstance", "(", "hostname", ",", "bytes", ")", ":", "# IDN A-label bytes are ASCII compatible.", "hostname", "=", "hostname", ".", "decode", "(", "\"ascii\"", ")", "return", "bool", "(", "IPV4_RE", ".", "match", "(", "hostname", ")", "or", "BRACELESS_IPV6_ADDRZ_RE", ".", "match", "(", "hostname", ")", ")" ]
[ 456, 0 ]
[ 466, 83 ]
python
en
['en', 'en', 'en']
True
_is_key_file_encrypted
(key_file)
Detects if a key file is encrypted or not.
Detects if a key file is encrypted or not.
def _is_key_file_encrypted(key_file): """Detects if a key file is encrypted or not.""" with open(key_file, "r") as f: for line in f: # Look for Proc-Type: 4,ENCRYPTED if "ENCRYPTED" in line: return True return False
[ "def", "_is_key_file_encrypted", "(", "key_file", ")", ":", "with", "open", "(", "key_file", ",", "\"r\"", ")", "as", "f", ":", "for", "line", "in", "f", ":", "# Look for Proc-Type: 4,ENCRYPTED", "if", "\"ENCRYPTED\"", "in", "line", ":", "return", "True", "return", "False" ]
[ 469, 0 ]
[ 477, 16 ]
python
en
['en', 'en', 'en']
True
Mercurial.get_revision
(cls, location)
Return the repository-local changeset revision number, as an integer.
Return the repository-local changeset revision number, as an integer.
def get_revision(cls, location): # type: (str) -> str """ Return the repository-local changeset revision number, as an integer. """ current_revision = cls.run_command( ['parents', '--template={rev}'], show_stdout=False, stdout_only=True, cwd=location, ).strip() return current_revision
[ "def", "get_revision", "(", "cls", ",", "location", ")", ":", "# type: (str) -> str", "current_revision", "=", "cls", ".", "run_command", "(", "[", "'parents'", ",", "'--template={rev}'", "]", ",", "show_stdout", "=", "False", ",", "stdout_only", "=", "True", ",", "cwd", "=", "location", ",", ")", ".", "strip", "(", ")", "return", "current_revision" ]
[ 84, 4 ]
[ 95, 31 ]
python
en
['en', 'error', 'th']
False
Mercurial.get_requirement_revision
(cls, location)
Return the changeset identification hash, as a 40-character hexadecimal string
Return the changeset identification hash, as a 40-character hexadecimal string
def get_requirement_revision(cls, location): # type: (str) -> str """ Return the changeset identification hash, as a 40-character hexadecimal string """ current_rev_hash = cls.run_command( ['parents', '--template={node}'], show_stdout=False, stdout_only=True, cwd=location, ).strip() return current_rev_hash
[ "def", "get_requirement_revision", "(", "cls", ",", "location", ")", ":", "# type: (str) -> str", "current_rev_hash", "=", "cls", ".", "run_command", "(", "[", "'parents'", ",", "'--template={node}'", "]", ",", "show_stdout", "=", "False", ",", "stdout_only", "=", "True", ",", "cwd", "=", "location", ",", ")", ".", "strip", "(", ")", "return", "current_rev_hash" ]
[ 98, 4 ]
[ 110, 31 ]
python
en
['en', 'error', 'th']
False
Mercurial.is_commit_id_equal
(cls, dest, name)
Always assume the versions don't match
Always assume the versions don't match
def is_commit_id_equal(cls, dest, name): # type: (str, Optional[str]) -> bool """Always assume the versions don't match""" return False
[ "def", "is_commit_id_equal", "(", "cls", ",", "dest", ",", "name", ")", ":", "# type: (str, Optional[str]) -> bool", "return", "False" ]
[ 113, 4 ]
[ 116, 20 ]
python
en
['en', 'en', 'en']
True
Mercurial.get_subdirectory
(cls, location)
Return the path to Python project root, relative to the repo root. Return None if the project root is in the repo root.
Return the path to Python project root, relative to the repo root. Return None if the project root is in the repo root.
def get_subdirectory(cls, location): # type: (str) -> Optional[str] """ Return the path to Python project root, relative to the repo root. Return None if the project root is in the repo root. """ # find the repo root repo_root = cls.run_command( ['root'], show_stdout=False, stdout_only=True, cwd=location ).strip() if not os.path.isabs(repo_root): repo_root = os.path.abspath(os.path.join(location, repo_root)) return find_path_to_project_root_from_repo_root(location, repo_root)
[ "def", "get_subdirectory", "(", "cls", ",", "location", ")", ":", "# type: (str) -> Optional[str]", "# find the repo root", "repo_root", "=", "cls", ".", "run_command", "(", "[", "'root'", "]", ",", "show_stdout", "=", "False", ",", "stdout_only", "=", "True", ",", "cwd", "=", "location", ")", ".", "strip", "(", ")", "if", "not", "os", ".", "path", ".", "isabs", "(", "repo_root", ")", ":", "repo_root", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "location", ",", "repo_root", ")", ")", "return", "find_path_to_project_root_from_repo_root", "(", "location", ",", "repo_root", ")" ]
[ 119, 4 ]
[ 131, 76 ]
python
en
['en', 'error', 'th']
False
create_dataset
(file_pattern, batch_size, mode)
Creates tf.data Dataset Object to feed into model. Args: file_pattern: str, file patterns to TFRecord data. batch_size: int, batch size for training. mode: tf.estimator.ModeKeys (TRAIN/EVAL). Returns: tf.data Dataset object.
Creates tf.data Dataset Object to feed into model.
def create_dataset(file_pattern, batch_size, mode): """Creates tf.data Dataset Object to feed into model. Args: file_pattern: str, file patterns to TFRecord data. batch_size: int, batch size for training. mode: tf.estimator.ModeKeys (TRAIN/EVAL). Returns: tf.data Dataset object. """ def _parse(serialized_example): """Parse serialized example and return feature_dict and label. Args: serialized_example: tf.example to parse. Returns: Parsed features dictionary and label. """ feature_map = { 'dayofweek': tf.io.FixedLenFeature([], tf.int64), 'dropofflat': tf.io.FixedLenFeature([], tf.float32), 'dropofflon': tf.io.FixedLenFeature([], tf.float32), 'fare_amount': tf.io.FixedLenFeature([], tf.float32), 'hourofday': tf.io.FixedLenFeature([], tf.int64), 'passengers': tf.io.FixedLenFeature([], tf.float32), 'pickuplat': tf.io.FixedLenFeature([], tf.float32), 'pickuplon': tf.io.FixedLenFeature([], tf.float32) } # Parse the serialized data into a dictionary. parsed_example = tf.io.parse_single_example( serialized=serialized_example, features=feature_map) features = add_engineered(parsed_example) label = features.pop("fare_amount") return features, label # Create a TensorFlow Dataset-object which has functionality # for reading and shuffling data from TFRecords files. files = tf.io.gfile.glob(file_pattern) dataset = tf.data.TFRecordDataset( filenames=files, compression_type="GZIP") # Parse the serialized data in the TFRecords files.. dataset = dataset.map(_parse) if mode == tf.estimator.ModeKeys.TRAIN: # Repeat the dataset the given number of times. dataset = dataset.repeat().shuffle( buffer_size=10*batch_size) # Get a batch of data with the given size. dataset = dataset.batch(batch_size) # Get the next batch of images and labels. return dataset
[ "def", "create_dataset", "(", "file_pattern", ",", "batch_size", ",", "mode", ")", ":", "def", "_parse", "(", "serialized_example", ")", ":", "\"\"\"Parse serialized example and return feature_dict and label.\n\n Args:\n serialized_example: tf.example to parse.\n\n Returns:\n Parsed features dictionary and label.\n \"\"\"", "feature_map", "=", "{", "'dayofweek'", ":", "tf", ".", "io", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "int64", ")", ",", "'dropofflat'", ":", "tf", ".", "io", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "float32", ")", ",", "'dropofflon'", ":", "tf", ".", "io", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "float32", ")", ",", "'fare_amount'", ":", "tf", ".", "io", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "float32", ")", ",", "'hourofday'", ":", "tf", ".", "io", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "int64", ")", ",", "'passengers'", ":", "tf", ".", "io", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "float32", ")", ",", "'pickuplat'", ":", "tf", ".", "io", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "float32", ")", ",", "'pickuplon'", ":", "tf", ".", "io", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "float32", ")", "}", "# Parse the serialized data into a dictionary.", "parsed_example", "=", "tf", ".", "io", ".", "parse_single_example", "(", "serialized", "=", "serialized_example", ",", "features", "=", "feature_map", ")", "features", "=", "add_engineered", "(", "parsed_example", ")", "label", "=", "features", ".", "pop", "(", "\"fare_amount\"", ")", "return", "features", ",", "label", "# Create a TensorFlow Dataset-object which has functionality", "# for reading and shuffling data from TFRecords files.", "files", "=", "tf", ".", "io", ".", "gfile", ".", "glob", "(", "file_pattern", ")", "dataset", "=", "tf", ".", "data", ".", "TFRecordDataset", "(", "filenames", "=", "files", ",", "compression_type", "=", "\"GZIP\"", ")", "# Parse the serialized data in the TFRecords files..", "dataset", "=", "dataset", ".", "map", "(", "_parse", ")", "if", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", ":", "# Repeat the dataset the given number of times.", "dataset", "=", "dataset", ".", "repeat", "(", ")", ".", "shuffle", "(", "buffer_size", "=", "10", "*", "batch_size", ")", "# Get a batch of data with the given size.", "dataset", "=", "dataset", ".", "batch", "(", "batch_size", ")", "# Get the next batch of images and labels.", "return", "dataset" ]
[ 8, 0 ]
[ 69, 18 ]
python
en
['en', 'en', 'en']
True
add_engineered
(features)
Add engineered features to features dict. Args: features: dict, dictionary of input features. Returns: features: dict, dictionary with engineered features added.
Add engineered features to features dict.
def add_engineered(features): """Add engineered features to features dict. Args: features: dict, dictionary of input features. Returns: features: dict, dictionary with engineered features added. """ features["londiff"] = features["dropofflon"] - features["pickuplon"] features["latdiff"] = features["dropofflat"] - features["pickuplat"] features["euclidean"] = tf.math.sqrt( features["londiff"]**2 + features["latdiff"]**2) return features
[ "def", "add_engineered", "(", "features", ")", ":", "features", "[", "\"londiff\"", "]", "=", "features", "[", "\"dropofflon\"", "]", "-", "features", "[", "\"pickuplon\"", "]", "features", "[", "\"latdiff\"", "]", "=", "features", "[", "\"dropofflat\"", "]", "-", "features", "[", "\"pickuplat\"", "]", "features", "[", "\"euclidean\"", "]", "=", "tf", ".", "math", ".", "sqrt", "(", "features", "[", "\"londiff\"", "]", "**", "2", "+", "features", "[", "\"latdiff\"", "]", "**", "2", ")", "return", "features" ]
[ 72, 0 ]
[ 85, 19 ]
python
en
['en', 'en', 'en']
True
serving_input_fn
()
Creates serving input receiver for EvalSpec. Returns: tf.estimator.export.ServingInputReceiver object containing placeholders and features.
Creates serving input receiver for EvalSpec.
def serving_input_fn(): """Creates serving input receiver for EvalSpec. Returns: tf.estimator.export.ServingInputReceiver object containing placeholders and features. """ inputs = { "dayofweek": tf.compat.v1.placeholder( dtype=tf.dtypes.int64, shape=[None], name="dayofweek"), "hourofday": tf.compat.v1.placeholder( dtype=tf.dtypes.int64, shape=[None], name="hourofday"), "pickuplon": tf.compat.v1.placeholder( dtype=tf.dtypes.float32, shape=[None], name="pickuplon"), "pickuplat": tf.compat.v1.placeholder( dtype=tf.dtypes.float32, shape=[None], name="pickuplat"), "dropofflon": tf.compat.v1.placeholder( dtype=tf.dtypes.float32, shape=[None], name="dropofflon"), "dropofflat": tf.compat.v1.placeholder( dtype=tf.dtypes.float32, shape=[None], name="dropofflat"), "passengers": tf.compat.v1.placeholder( dtype=tf.dtypes.float32, shape=[None], name="passengers") } features = add_engineered(inputs) return tf.estimator.export.ServingInputReceiver( features=features, receiver_tensors=inputs)
[ "def", "serving_input_fn", "(", ")", ":", "inputs", "=", "{", "\"dayofweek\"", ":", "tf", ".", "compat", ".", "v1", ".", "placeholder", "(", "dtype", "=", "tf", ".", "dtypes", ".", "int64", ",", "shape", "=", "[", "None", "]", ",", "name", "=", "\"dayofweek\"", ")", ",", "\"hourofday\"", ":", "tf", ".", "compat", ".", "v1", ".", "placeholder", "(", "dtype", "=", "tf", ".", "dtypes", ".", "int64", ",", "shape", "=", "[", "None", "]", ",", "name", "=", "\"hourofday\"", ")", ",", "\"pickuplon\"", ":", "tf", ".", "compat", ".", "v1", ".", "placeholder", "(", "dtype", "=", "tf", ".", "dtypes", ".", "float32", ",", "shape", "=", "[", "None", "]", ",", "name", "=", "\"pickuplon\"", ")", ",", "\"pickuplat\"", ":", "tf", ".", "compat", ".", "v1", ".", "placeholder", "(", "dtype", "=", "tf", ".", "dtypes", ".", "float32", ",", "shape", "=", "[", "None", "]", ",", "name", "=", "\"pickuplat\"", ")", ",", "\"dropofflon\"", ":", "tf", ".", "compat", ".", "v1", ".", "placeholder", "(", "dtype", "=", "tf", ".", "dtypes", ".", "float32", ",", "shape", "=", "[", "None", "]", ",", "name", "=", "\"dropofflon\"", ")", ",", "\"dropofflat\"", ":", "tf", ".", "compat", ".", "v1", ".", "placeholder", "(", "dtype", "=", "tf", ".", "dtypes", ".", "float32", ",", "shape", "=", "[", "None", "]", ",", "name", "=", "\"dropofflat\"", ")", ",", "\"passengers\"", ":", "tf", ".", "compat", ".", "v1", ".", "placeholder", "(", "dtype", "=", "tf", ".", "dtypes", ".", "float32", ",", "shape", "=", "[", "None", "]", ",", "name", "=", "\"passengers\"", ")", "}", "features", "=", "add_engineered", "(", "inputs", ")", "return", "tf", ".", "estimator", ".", "export", ".", "ServingInputReceiver", "(", "features", "=", "features", ",", "receiver_tensors", "=", "inputs", ")" ]
[ 88, 0 ]
[ 115, 51 ]
python
en
['en', 'pt', 'en']
True
train_and_evaluate
(args)
Build tf.estimator.DNNRegressor and call train_and_evaluate loop. Args: args: dict, dictionary of command line arguments from task.py.
Build tf.estimator.DNNRegressor and call train_and_evaluate loop.
def train_and_evaluate(args): """Build tf.estimator.DNNRegressor and call train_and_evaluate loop. Args: args: dict, dictionary of command line arguments from task.py. """ feat_cols = [ tf.feature_column.numeric_column('dayofweek'), tf.feature_column.numeric_column('hourofday'), tf.feature_column.numeric_column('pickuplat'), tf.feature_column.numeric_column('pickuplon'), tf.feature_column.numeric_column('dropofflat'), tf.feature_column.numeric_column('dropofflon'), tf.feature_column.numeric_column('passengers'), tf.feature_column.numeric_column('euclidean'), tf.feature_column.numeric_column('latdiff'), tf.feature_column.numeric_column('londiff') ] estimator = tf.estimator.DNNRegressor( feature_columns=feat_cols, hidden_units=args['hidden_units'].split(' '), model_dir=args['output_dir'] ) train_spec = tf.estimator.TrainSpec( input_fn=lambda: create_dataset( file_pattern=args['train_data_path'], batch_size=args['train_batch_size'], mode=tf.estimator.ModeKeys.TRAIN), max_steps=300 ) exporter = exporter = tf.estimator.LatestExporter( name="exporter", serving_input_receiver_fn=serving_input_fn) eval_spec = tf.estimator.EvalSpec( input_fn=lambda: create_dataset( file_pattern=args['eval_data_path'], batch_size=args['eval_batch_size'], mode=tf.estimator.ModeKeys.EVAL), exporters=exporter, steps=50 ) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
[ "def", "train_and_evaluate", "(", "args", ")", ":", "feat_cols", "=", "[", "tf", ".", "feature_column", ".", "numeric_column", "(", "'dayofweek'", ")", ",", "tf", ".", "feature_column", ".", "numeric_column", "(", "'hourofday'", ")", ",", "tf", ".", "feature_column", ".", "numeric_column", "(", "'pickuplat'", ")", ",", "tf", ".", "feature_column", ".", "numeric_column", "(", "'pickuplon'", ")", ",", "tf", ".", "feature_column", ".", "numeric_column", "(", "'dropofflat'", ")", ",", "tf", ".", "feature_column", ".", "numeric_column", "(", "'dropofflon'", ")", ",", "tf", ".", "feature_column", ".", "numeric_column", "(", "'passengers'", ")", ",", "tf", ".", "feature_column", ".", "numeric_column", "(", "'euclidean'", ")", ",", "tf", ".", "feature_column", ".", "numeric_column", "(", "'latdiff'", ")", ",", "tf", ".", "feature_column", ".", "numeric_column", "(", "'londiff'", ")", "]", "estimator", "=", "tf", ".", "estimator", ".", "DNNRegressor", "(", "feature_columns", "=", "feat_cols", ",", "hidden_units", "=", "args", "[", "'hidden_units'", "]", ".", "split", "(", "' '", ")", ",", "model_dir", "=", "args", "[", "'output_dir'", "]", ")", "train_spec", "=", "tf", ".", "estimator", ".", "TrainSpec", "(", "input_fn", "=", "lambda", ":", "create_dataset", "(", "file_pattern", "=", "args", "[", "'train_data_path'", "]", ",", "batch_size", "=", "args", "[", "'train_batch_size'", "]", ",", "mode", "=", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", ")", ",", "max_steps", "=", "300", ")", "exporter", "=", "exporter", "=", "tf", ".", "estimator", ".", "LatestExporter", "(", "name", "=", "\"exporter\"", ",", "serving_input_receiver_fn", "=", "serving_input_fn", ")", "eval_spec", "=", "tf", ".", "estimator", ".", "EvalSpec", "(", "input_fn", "=", "lambda", ":", "create_dataset", "(", "file_pattern", "=", "args", "[", "'eval_data_path'", "]", ",", "batch_size", "=", "args", "[", "'eval_batch_size'", "]", ",", "mode", "=", "tf", ".", "estimator", ".", "ModeKeys", ".", "EVAL", ")", ",", "exporters", "=", "exporter", ",", "steps", "=", "50", ")", "tf", ".", "estimator", ".", "train_and_evaluate", "(", "estimator", ",", "train_spec", ",", "eval_spec", ")" ]
[ 118, 0 ]
[ 164, 69 ]
python
en
['en', 'it', 'en']
True
client
()
Yields a test client, AND creates and later cleans up a dummy collection for sessions.
Yields a test client, AND creates and later cleans up a dummy collection for sessions.
def client(): """ Yields a test client, AND creates and later cleans up a dummy collection for sessions. """ main.app.testing = True # Override the Firestore collection used for sessions in main main.sessions = main.db.collection(str(uuid.uuid4())) client = main.app.test_client() yield client # Clean up session objects created in test collection for doc_ref in main.sessions.list_documents(): doc_ref.delete()
[ "def", "client", "(", ")", ":", "main", ".", "app", ".", "testing", "=", "True", "# Override the Firestore collection used for sessions in main", "main", ".", "sessions", "=", "main", ".", "db", ".", "collection", "(", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ")", "client", "=", "main", ".", "app", ".", "test_client", "(", ")", "yield", "client", "# Clean up session objects created in test collection", "for", "doc_ref", "in", "main", ".", "sessions", ".", "list_documents", "(", ")", ":", "doc_ref", ".", "delete", "(", ")" ]
[ 22, 0 ]
[ 36, 24 ]
python
en
['en', 'en', 'en']
True
command_bmi
(bot, user, channel, args)
Calculates your body mass index. Usage: bmi height(cm)/weight(kg)
Calculates your body mass index. Usage: bmi height(cm)/weight(kg)
def command_bmi(bot, user, channel, args): "Calculates your body mass index. Usage: bmi height(cm)/weight(kg)" data = args.split("/") if len(data) != 2: return bot.say(channel, "Usage: bmi height(cm)/weight(kg)") else: bmi = print_bmi(calc_bmi(int(data[0]), int(data[1]))) return bot.say(channel, "{}, {}".format(get_nick(user), bmi))
[ "def", "command_bmi", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "data", "=", "args", ".", "split", "(", "\"/\"", ")", "if", "len", "(", "data", ")", "!=", "2", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Usage: bmi height(cm)/weight(kg)\"", ")", "else", ":", "bmi", "=", "print_bmi", "(", "calc_bmi", "(", "int", "(", "data", "[", "0", "]", ")", ",", "int", "(", "data", "[", "1", "]", ")", ")", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"{}, {}\"", ".", "format", "(", "get_nick", "(", "user", ")", ",", "bmi", ")", ")" ]
[ 30, 0 ]
[ 37, 69 ]
python
en
['es', 'en', 'en']
True
Field.__init__
(self, feat, index)
Initialize on the feature object and the integer index of the field within the feature.
Initialize on the feature object and the integer index of the field within the feature.
def __init__(self, feat, index): """ Initialize on the feature object and the integer index of the field within the feature. """ # Setting the feature pointer and index. self._feat = feat self._index = index # Getting the pointer for this field. fld_ptr = capi.get_feat_field_defn(feat.ptr, index) if not fld_ptr: raise GDALException('Cannot create OGR Field, invalid pointer given.') self.ptr = fld_ptr # Setting the class depending upon the OGR Field Type (OFT) self.__class__ = OGRFieldTypes[self.type]
[ "def", "__init__", "(", "self", ",", "feat", ",", "index", ")", ":", "# Setting the feature pointer and index.", "self", ".", "_feat", "=", "feat", "self", ".", "_index", "=", "index", "# Getting the pointer for this field.", "fld_ptr", "=", "capi", ".", "get_feat_field_defn", "(", "feat", ".", "ptr", ",", "index", ")", "if", "not", "fld_ptr", ":", "raise", "GDALException", "(", "'Cannot create OGR Field, invalid pointer given.'", ")", "self", ".", "ptr", "=", "fld_ptr", "# Setting the class depending upon the OGR Field Type (OFT)", "self", ".", "__class__", "=", "OGRFieldTypes", "[", "self", ".", "type", "]" ]
[ 18, 4 ]
[ 34, 49 ]
python
en
['en', 'error', 'th']
False
Field.__str__
(self)
Return the string representation of the Field.
Return the string representation of the Field.
def __str__(self): "Return the string representation of the Field." return str(self.value).strip()
[ "def", "__str__", "(", "self", ")", ":", "return", "str", "(", "self", ".", "value", ")", ".", "strip", "(", ")" ]
[ 36, 4 ]
[ 38, 38 ]
python
en
['en', 'en', 'en']
True
Field.as_double
(self)
Retrieve the Field's value as a double (float).
Retrieve the Field's value as a double (float).
def as_double(self): "Retrieve the Field's value as a double (float)." return capi.get_field_as_double(self._feat.ptr, self._index) if self.is_set else None
[ "def", "as_double", "(", "self", ")", ":", "return", "capi", ".", "get_field_as_double", "(", "self", ".", "_feat", ".", "ptr", ",", "self", ".", "_index", ")", "if", "self", ".", "is_set", "else", "None" ]
[ 41, 4 ]
[ 43, 93 ]
python
en
['en', 'ga', 'en']
True
Field.as_int
(self, is_64=False)
Retrieve the Field's value as an integer.
Retrieve the Field's value as an integer.
def as_int(self, is_64=False): "Retrieve the Field's value as an integer." if is_64: return capi.get_field_as_integer64(self._feat.ptr, self._index) if self.is_set else None else: return capi.get_field_as_integer(self._feat.ptr, self._index) if self.is_set else None
[ "def", "as_int", "(", "self", ",", "is_64", "=", "False", ")", ":", "if", "is_64", ":", "return", "capi", ".", "get_field_as_integer64", "(", "self", ".", "_feat", ".", "ptr", ",", "self", ".", "_index", ")", "if", "self", ".", "is_set", "else", "None", "else", ":", "return", "capi", ".", "get_field_as_integer", "(", "self", ".", "_feat", ".", "ptr", ",", "self", ".", "_index", ")", "if", "self", ".", "is_set", "else", "None" ]
[ 45, 4 ]
[ 50, 98 ]
python
en
['en', 'ga', 'en']
True
Field.as_string
(self)
Retrieve the Field's value as a string.
Retrieve the Field's value as a string.
def as_string(self): "Retrieve the Field's value as a string." if not self.is_set: return None string = capi.get_field_as_string(self._feat.ptr, self._index) return force_str(string, encoding=self._feat.encoding, strings_only=True)
[ "def", "as_string", "(", "self", ")", ":", "if", "not", "self", ".", "is_set", ":", "return", "None", "string", "=", "capi", ".", "get_field_as_string", "(", "self", ".", "_feat", ".", "ptr", ",", "self", ".", "_index", ")", "return", "force_str", "(", "string", ",", "encoding", "=", "self", ".", "_feat", ".", "encoding", ",", "strings_only", "=", "True", ")" ]
[ 52, 4 ]
[ 57, 81 ]
python
en
['en', 'sk', 'en']
True
Field.as_datetime
(self)
Retrieve the Field's value as a tuple of date & time components.
Retrieve the Field's value as a tuple of date & time components.
def as_datetime(self): "Retrieve the Field's value as a tuple of date & time components." if not self.is_set: return None yy, mm, dd, hh, mn, ss, tz = [c_int() for i in range(7)] status = capi.get_field_as_datetime( self._feat.ptr, self._index, byref(yy), byref(mm), byref(dd), byref(hh), byref(mn), byref(ss), byref(tz)) if status: return (yy, mm, dd, hh, mn, ss, tz) else: raise GDALException('Unable to retrieve date & time information from the field.')
[ "def", "as_datetime", "(", "self", ")", ":", "if", "not", "self", ".", "is_set", ":", "return", "None", "yy", ",", "mm", ",", "dd", ",", "hh", ",", "mn", ",", "ss", ",", "tz", "=", "[", "c_int", "(", ")", "for", "i", "in", "range", "(", "7", ")", "]", "status", "=", "capi", ".", "get_field_as_datetime", "(", "self", ".", "_feat", ".", "ptr", ",", "self", ".", "_index", ",", "byref", "(", "yy", ")", ",", "byref", "(", "mm", ")", ",", "byref", "(", "dd", ")", ",", "byref", "(", "hh", ")", ",", "byref", "(", "mn", ")", ",", "byref", "(", "ss", ")", ",", "byref", "(", "tz", ")", ")", "if", "status", ":", "return", "(", "yy", ",", "mm", ",", "dd", ",", "hh", ",", "mn", ",", "ss", ",", "tz", ")", "else", ":", "raise", "GDALException", "(", "'Unable to retrieve date & time information from the field.'", ")" ]
[ 59, 4 ]
[ 70, 93 ]
python
en
['en', 'en', 'en']
True
Field.is_set
(self)
Return True if the value of this field isn't null, False otherwise.
Return True if the value of this field isn't null, False otherwise.
def is_set(self): "Return True if the value of this field isn't null, False otherwise." return capi.is_field_set(self._feat.ptr, self._index)
[ "def", "is_set", "(", "self", ")", ":", "return", "capi", ".", "is_field_set", "(", "self", ".", "_feat", ".", "ptr", ",", "self", ".", "_index", ")" ]
[ 74, 4 ]
[ 76, 61 ]
python
en
['en', 'en', 'en']
True
Field.name
(self)
Return the name of this Field.
Return the name of this Field.
def name(self): "Return the name of this Field." name = capi.get_field_name(self.ptr) return force_str(name, encoding=self._feat.encoding, strings_only=True)
[ "def", "name", "(", "self", ")", ":", "name", "=", "capi", ".", "get_field_name", "(", "self", ".", "ptr", ")", "return", "force_str", "(", "name", ",", "encoding", "=", "self", ".", "_feat", ".", "encoding", ",", "strings_only", "=", "True", ")" ]
[ 79, 4 ]
[ 82, 79 ]
python
en
['en', 'en', 'en']
True
Field.precision
(self)
Return the precision of this Field.
Return the precision of this Field.
def precision(self): "Return the precision of this Field." return capi.get_field_precision(self.ptr)
[ "def", "precision", "(", "self", ")", ":", "return", "capi", ".", "get_field_precision", "(", "self", ".", "ptr", ")" ]
[ 85, 4 ]
[ 87, 49 ]
python
en
['en', 'en', 'en']
True
Field.type
(self)
Return the OGR type of this Field.
Return the OGR type of this Field.
def type(self): "Return the OGR type of this Field." return capi.get_field_type(self.ptr)
[ "def", "type", "(", "self", ")", ":", "return", "capi", ".", "get_field_type", "(", "self", ".", "ptr", ")" ]
[ 90, 4 ]
[ 92, 44 ]
python
en
['en', 'en', 'en']
True
Field.type_name
(self)
Return the OGR field type name for this Field.
Return the OGR field type name for this Field.
def type_name(self): "Return the OGR field type name for this Field." return capi.get_field_type_name(self.type)
[ "def", "type_name", "(", "self", ")", ":", "return", "capi", ".", "get_field_type_name", "(", "self", ".", "type", ")" ]
[ 95, 4 ]
[ 97, 50 ]
python
en
['en', 'en', 'en']
True
Field.value
(self)
Return the value of this Field.
Return the value of this Field.
def value(self): "Return the value of this Field." # Default is to get the field as a string. return self.as_string()
[ "def", "value", "(", "self", ")", ":", "# Default is to get the field as a string.", "return", "self", ".", "as_string", "(", ")" ]
[ 100, 4 ]
[ 103, 31 ]
python
en
['en', 'en', 'en']
True
Field.width
(self)
Return the width of this Field.
Return the width of this Field.
def width(self): "Return the width of this Field." return capi.get_field_width(self.ptr)
[ "def", "width", "(", "self", ")", ":", "return", "capi", ".", "get_field_width", "(", "self", ".", "ptr", ")" ]
[ 106, 4 ]
[ 108, 45 ]
python
en
['en', 'en', 'en']
True
OFTInteger.value
(self)
Return an integer contained in this field.
Return an integer contained in this field.
def value(self): "Return an integer contained in this field." return self.as_int(self._bit64)
[ "def", "value", "(", "self", ")", ":", "return", "self", ".", "as_int", "(", "self", ".", "_bit64", ")" ]
[ 116, 4 ]
[ 118, 39 ]
python
en
['en', 'en', 'en']
True
OFTInteger.type
(self)
GDAL uses OFTReals to represent OFTIntegers in created shapefiles -- forcing the type here since the underlying field type may actually be OFTReal.
GDAL uses OFTReals to represent OFTIntegers in created shapefiles -- forcing the type here since the underlying field type may actually be OFTReal.
def type(self): """ GDAL uses OFTReals to represent OFTIntegers in created shapefiles -- forcing the type here since the underlying field type may actually be OFTReal. """ return 0
[ "def", "type", "(", "self", ")", ":", "return", "0" ]
[ 121, 4 ]
[ 127, 16 ]
python
en
['en', 'error', 'th']
False
OFTReal.value
(self)
Return a float contained in this field.
Return a float contained in this field.
def value(self): "Return a float contained in this field." return self.as_double()
[ "def", "value", "(", "self", ")", ":", "return", "self", ".", "as_double", "(", ")" ]
[ 132, 4 ]
[ 134, 31 ]
python
en
['en', 'en', 'en']
True
OFTDate.value
(self)
Return a Python `date` object for the OFTDate field.
Return a Python `date` object for the OFTDate field.
def value(self): "Return a Python `date` object for the OFTDate field." try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return date(yy.value, mm.value, dd.value) except (TypeError, ValueError, GDALException): return None
[ "def", "value", "(", "self", ")", ":", "try", ":", "yy", ",", "mm", ",", "dd", ",", "hh", ",", "mn", ",", "ss", ",", "tz", "=", "self", ".", "as_datetime", "(", ")", "return", "date", "(", "yy", ".", "value", ",", "mm", ".", "value", ",", "dd", ".", "value", ")", "except", "(", "TypeError", ",", "ValueError", ",", "GDALException", ")", ":", "return", "None" ]
[ 153, 4 ]
[ 159, 23 ]
python
en
['en', 'en', 'en']
True
OFTDateTime.value
(self)
Return a Python `datetime` object for this OFTDateTime field.
Return a Python `datetime` object for this OFTDateTime field.
def value(self): "Return a Python `datetime` object for this OFTDateTime field." # TODO: Adapt timezone information. # See https://lists.osgeo.org/pipermail/gdal-dev/2006-February/007990.html # The `tz` variable has values of: 0=unknown, 1=localtime (ambiguous), # 100=GMT, 104=GMT+1, 80=GMT-5, etc. try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return datetime(yy.value, mm.value, dd.value, hh.value, mn.value, ss.value) except (TypeError, ValueError, GDALException): return None
[ "def", "value", "(", "self", ")", ":", "# TODO: Adapt timezone information.", "# See https://lists.osgeo.org/pipermail/gdal-dev/2006-February/007990.html", "# The `tz` variable has values of: 0=unknown, 1=localtime (ambiguous),", "# 100=GMT, 104=GMT+1, 80=GMT-5, etc.", "try", ":", "yy", ",", "mm", ",", "dd", ",", "hh", ",", "mn", ",", "ss", ",", "tz", "=", "self", ".", "as_datetime", "(", ")", "return", "datetime", "(", "yy", ".", "value", ",", "mm", ".", "value", ",", "dd", ".", "value", ",", "hh", ".", "value", ",", "mn", ".", "value", ",", "ss", ".", "value", ")", "except", "(", "TypeError", ",", "ValueError", ",", "GDALException", ")", ":", "return", "None" ]
[ 164, 4 ]
[ 174, 23 ]
python
en
['en', 'en', 'en']
True
OFTTime.value
(self)
Return a Python `time` object for this OFTTime field.
Return a Python `time` object for this OFTTime field.
def value(self): "Return a Python `time` object for this OFTTime field." try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return time(hh.value, mn.value, ss.value) except (ValueError, GDALException): return None
[ "def", "value", "(", "self", ")", ":", "try", ":", "yy", ",", "mm", ",", "dd", ",", "hh", ",", "mn", ",", "ss", ",", "tz", "=", "self", ".", "as_datetime", "(", ")", "return", "time", "(", "hh", ".", "value", ",", "mn", ".", "value", ",", "ss", ".", "value", ")", "except", "(", "ValueError", ",", "GDALException", ")", ":", "return", "None" ]
[ 179, 4 ]
[ 185, 23 ]
python
en
['en', 'en', 'en']
True
parse_rule
(rule)
Parse a rule and return it as generator. Each iteration yields tuples in the form ``(converter, arguments, variable)``. If the converter is `None` it's a static url part, otherwise it's a dynamic one. :internal:
Parse a rule and return it as generator. Each iteration yields tuples in the form ``(converter, arguments, variable)``. If the converter is `None` it's a static url part, otherwise it's a dynamic one.
def parse_rule(rule): """Parse a rule and return it as generator. Each iteration yields tuples in the form ``(converter, arguments, variable)``. If the converter is `None` it's a static url part, otherwise it's a dynamic one. :internal: """ pos = 0 end = len(rule) do_match = _rule_re.match used_names = set() while pos < end: m = do_match(rule, pos) if m is None: break data = m.groupdict() if data["static"]: yield None, None, data["static"] variable = data["variable"] converter = data["converter"] or "default" if variable in used_names: raise ValueError("variable name %r used twice." % variable) used_names.add(variable) yield converter, data["args"] or None, variable pos = m.end() if pos < end: remaining = rule[pos:] if ">" in remaining or "<" in remaining: raise ValueError("malformed url rule: %r" % rule) yield None, None, remaining
[ "def", "parse_rule", "(", "rule", ")", ":", "pos", "=", "0", "end", "=", "len", "(", "rule", ")", "do_match", "=", "_rule_re", ".", "match", "used_names", "=", "set", "(", ")", "while", "pos", "<", "end", ":", "m", "=", "do_match", "(", "rule", ",", "pos", ")", "if", "m", "is", "None", ":", "break", "data", "=", "m", ".", "groupdict", "(", ")", "if", "data", "[", "\"static\"", "]", ":", "yield", "None", ",", "None", ",", "data", "[", "\"static\"", "]", "variable", "=", "data", "[", "\"variable\"", "]", "converter", "=", "data", "[", "\"converter\"", "]", "or", "\"default\"", "if", "variable", "in", "used_names", ":", "raise", "ValueError", "(", "\"variable name %r used twice.\"", "%", "variable", ")", "used_names", ".", "add", "(", "variable", ")", "yield", "converter", ",", "data", "[", "\"args\"", "]", "or", "None", ",", "variable", "pos", "=", "m", ".", "end", "(", ")", "if", "pos", "<", "end", ":", "remaining", "=", "rule", "[", "pos", ":", "]", "if", "\">\"", "in", "remaining", "or", "\"<\"", "in", "remaining", ":", "raise", "ValueError", "(", "\"malformed url rule: %r\"", "%", "rule", ")", "yield", "None", ",", "None", ",", "remaining" ]
[ 197, 0 ]
[ 226, 35 ]
python
en
['en', 'en', 'en']
True
_prefix_names
(src)
ast parse and prefix names with `.` to avoid collision with user vars
ast parse and prefix names with `.` to avoid collision with user vars
def _prefix_names(src): """ast parse and prefix names with `.` to avoid collision with user vars""" tree = ast.parse(src).body[0] if isinstance(tree, ast.Expr): tree = tree.value for node in ast.walk(tree): if isinstance(node, ast.Name): node.id = "." + node.id return tree
[ "def", "_prefix_names", "(", "src", ")", ":", "tree", "=", "ast", ".", "parse", "(", "src", ")", ".", "body", "[", "0", "]", "if", "isinstance", "(", "tree", ",", "ast", ".", "Expr", ")", ":", "tree", "=", "tree", ".", "value", "for", "node", "in", "ast", ".", "walk", "(", "tree", ")", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "Name", ")", ":", "node", ".", "id", "=", "\".\"", "+", "node", ".", "id", "return", "tree" ]
[ 488, 0 ]
[ 496, 15 ]
python
en
['en', 'en', 'en']
True
RuleFactory.get_rules
(self, map)
Subclasses of `RuleFactory` have to override this method and return an iterable of rules.
Subclasses of `RuleFactory` have to override this method and return an iterable of rules.
def get_rules(self, map): """Subclasses of `RuleFactory` have to override this method and return an iterable of rules.""" raise NotImplementedError()
[ "def", "get_rules", "(", "self", ",", "map", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 337, 4 ]
[ 340, 35 ]
python
en
['en', 'en', 'en']
True
Map.is_endpoint_expecting
(self, endpoint, *arguments)
Iterate over all rules and check if the endpoint expects the arguments provided. This is for example useful if you have some URLs that expect a language code and others that do not and you want to wrap the builder a bit so that the current language code is automatically added if not provided but endpoints expect it. :param endpoint: the endpoint to check. :param arguments: this function accepts one or more arguments as positional arguments. Each one of them is checked.
Iterate over all rules and check if the endpoint expects the arguments provided. This is for example useful if you have some URLs that expect a language code and others that do not and you want to wrap the builder a bit so that the current language code is automatically added if not provided but endpoints expect it.
def is_endpoint_expecting(self, endpoint, *arguments): """Iterate over all rules and check if the endpoint expects the arguments provided. This is for example useful if you have some URLs that expect a language code and others that do not and you want to wrap the builder a bit so that the current language code is automatically added if not provided but endpoints expect it. :param endpoint: the endpoint to check. :param arguments: this function accepts one or more arguments as positional arguments. Each one of them is checked. """ self.update() arguments = set(arguments) for rule in self._rules_by_endpoint[endpoint]: if arguments.issubset(rule.arguments): return True return False
[ "def", "is_endpoint_expecting", "(", "self", ",", "endpoint", ",", "*", "arguments", ")", ":", "self", ".", "update", "(", ")", "arguments", "=", "set", "(", "arguments", ")", "for", "rule", "in", "self", ".", "_rules_by_endpoint", "[", "endpoint", "]", ":", "if", "arguments", ".", "issubset", "(", "rule", ".", "arguments", ")", ":", "return", "True", "return", "False" ]
[ 1361, 4 ]
[ 1379, 20 ]
python
en
['en', 'en', 'en']
True
Map.iter_rules
(self, endpoint=None)
Iterate over all rules or the rules of an endpoint. :param endpoint: if provided only the rules for that endpoint are returned. :return: an iterator
Iterate over all rules or the rules of an endpoint.
def iter_rules(self, endpoint=None): """Iterate over all rules or the rules of an endpoint. :param endpoint: if provided only the rules for that endpoint are returned. :return: an iterator """ self.update() if endpoint is not None: return iter(self._rules_by_endpoint[endpoint]) return iter(self._rules)
[ "def", "iter_rules", "(", "self", ",", "endpoint", "=", "None", ")", ":", "self", ".", "update", "(", ")", "if", "endpoint", "is", "not", "None", ":", "return", "iter", "(", "self", ".", "_rules_by_endpoint", "[", "endpoint", "]", ")", "return", "iter", "(", "self", ".", "_rules", ")" ]
[ 1381, 4 ]
[ 1391, 32 ]
python
en
['en', 'en', 'en']
True
Map.add
(self, rulefactory)
Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map. :param rulefactory: a :class:`Rule` or :class:`RuleFactory`
Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map.
def add(self, rulefactory): """Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map. :param rulefactory: a :class:`Rule` or :class:`RuleFactory` """ for rule in rulefactory.get_rules(self): rule.bind(self) self._rules.append(rule) self._rules_by_endpoint.setdefault(rule.endpoint, []).append(rule) self._remap = True
[ "def", "add", "(", "self", ",", "rulefactory", ")", ":", "for", "rule", "in", "rulefactory", ".", "get_rules", "(", "self", ")", ":", "rule", ".", "bind", "(", "self", ")", "self", ".", "_rules", ".", "append", "(", "rule", ")", "self", ".", "_rules_by_endpoint", ".", "setdefault", "(", "rule", ".", "endpoint", ",", "[", "]", ")", ".", "append", "(", "rule", ")", "self", ".", "_remap", "=", "True" ]
[ 1393, 4 ]
[ 1403, 26 ]
python
en
['en', 'en', 'en']
True
Map.bind
( self, server_name, script_name=None, subdomain=None, url_scheme="http", default_method="GET", path_info=None, query_args=None, )
Return a new :class:`MapAdapter` with the details specified to the call. Note that `script_name` will default to ``'/'`` if not further specified or `None`. The `server_name` at least is a requirement because the HTTP RFC requires absolute URLs for redirects and so all redirect exceptions raised by Werkzeug will contain the full canonical URL. If no path_info is passed to :meth:`match` it will use the default path info passed to bind. While this doesn't really make sense for manual bind calls, it's useful if you bind a map to a WSGI environment which already contains the path info. `subdomain` will default to the `default_subdomain` for this map if no defined. If there is no `default_subdomain` you cannot use the subdomain feature. .. versionadded:: 0.7 `query_args` added .. versionadded:: 0.8 `query_args` can now also be a string. .. versionchanged:: 0.15 ``path_info`` defaults to ``'/'`` if ``None``.
Return a new :class:`MapAdapter` with the details specified to the call. Note that `script_name` will default to ``'/'`` if not further specified or `None`. The `server_name` at least is a requirement because the HTTP RFC requires absolute URLs for redirects and so all redirect exceptions raised by Werkzeug will contain the full canonical URL.
def bind( self, server_name, script_name=None, subdomain=None, url_scheme="http", default_method="GET", path_info=None, query_args=None, ): """Return a new :class:`MapAdapter` with the details specified to the call. Note that `script_name` will default to ``'/'`` if not further specified or `None`. The `server_name` at least is a requirement because the HTTP RFC requires absolute URLs for redirects and so all redirect exceptions raised by Werkzeug will contain the full canonical URL. If no path_info is passed to :meth:`match` it will use the default path info passed to bind. While this doesn't really make sense for manual bind calls, it's useful if you bind a map to a WSGI environment which already contains the path info. `subdomain` will default to the `default_subdomain` for this map if no defined. If there is no `default_subdomain` you cannot use the subdomain feature. .. versionadded:: 0.7 `query_args` added .. versionadded:: 0.8 `query_args` can now also be a string. .. versionchanged:: 0.15 ``path_info`` defaults to ``'/'`` if ``None``. """ server_name = server_name.lower() if self.host_matching: if subdomain is not None: raise RuntimeError("host matching enabled and a subdomain was provided") elif subdomain is None: subdomain = self.default_subdomain if script_name is None: script_name = "/" if path_info is None: path_info = "/" try: server_name = _encode_idna(server_name) except UnicodeError: raise BadHost() return MapAdapter( self, server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args, )
[ "def", "bind", "(", "self", ",", "server_name", ",", "script_name", "=", "None", ",", "subdomain", "=", "None", ",", "url_scheme", "=", "\"http\"", ",", "default_method", "=", "\"GET\"", ",", "path_info", "=", "None", ",", "query_args", "=", "None", ",", ")", ":", "server_name", "=", "server_name", ".", "lower", "(", ")", "if", "self", ".", "host_matching", ":", "if", "subdomain", "is", "not", "None", ":", "raise", "RuntimeError", "(", "\"host matching enabled and a subdomain was provided\"", ")", "elif", "subdomain", "is", "None", ":", "subdomain", "=", "self", ".", "default_subdomain", "if", "script_name", "is", "None", ":", "script_name", "=", "\"/\"", "if", "path_info", "is", "None", ":", "path_info", "=", "\"/\"", "try", ":", "server_name", "=", "_encode_idna", "(", "server_name", ")", "except", "UnicodeError", ":", "raise", "BadHost", "(", ")", "return", "MapAdapter", "(", "self", ",", "server_name", ",", "script_name", ",", "subdomain", ",", "url_scheme", ",", "path_info", ",", "default_method", ",", "query_args", ",", ")" ]
[ 1405, 4 ]
[ 1463, 9 ]
python
en
['en', 'en', 'en']
True
Map.bind_to_environ
(self, environ, server_name=None, subdomain=None)
Like :meth:`bind` but you can pass it an WSGI environment and it will fetch the information from that dictionary. Note that because of limitations in the protocol there is no way to get the current subdomain and real `server_name` from the environment. If you don't provide it, Werkzeug will use `SERVER_NAME` and `SERVER_PORT` (or `HTTP_HOST` if provided) as used `server_name` with disabled subdomain feature. If `subdomain` is `None` but an environment and a server name is provided it will calculate the current subdomain automatically. Example: `server_name` is ``'example.com'`` and the `SERVER_NAME` in the wsgi `environ` is ``'staging.dev.example.com'`` the calculated subdomain will be ``'staging.dev'``. If the object passed as environ has an environ attribute, the value of this attribute is used instead. This allows you to pass request objects. Additionally `PATH_INFO` added as a default of the :class:`MapAdapter` so that you don't have to pass the path info to the match method. .. versionchanged:: 0.5 previously this method accepted a bogus `calculate_subdomain` parameter that did not have any effect. It was removed because of that. .. versionchanged:: 0.8 This will no longer raise a ValueError when an unexpected server name was passed. :param environ: a WSGI environment. :param server_name: an optional server name hint (see above). :param subdomain: optionally the current subdomain (see above).
Like :meth:`bind` but you can pass it an WSGI environment and it will fetch the information from that dictionary. Note that because of limitations in the protocol there is no way to get the current subdomain and real `server_name` from the environment. If you don't provide it, Werkzeug will use `SERVER_NAME` and `SERVER_PORT` (or `HTTP_HOST` if provided) as used `server_name` with disabled subdomain feature.
def bind_to_environ(self, environ, server_name=None, subdomain=None): """Like :meth:`bind` but you can pass it an WSGI environment and it will fetch the information from that dictionary. Note that because of limitations in the protocol there is no way to get the current subdomain and real `server_name` from the environment. If you don't provide it, Werkzeug will use `SERVER_NAME` and `SERVER_PORT` (or `HTTP_HOST` if provided) as used `server_name` with disabled subdomain feature. If `subdomain` is `None` but an environment and a server name is provided it will calculate the current subdomain automatically. Example: `server_name` is ``'example.com'`` and the `SERVER_NAME` in the wsgi `environ` is ``'staging.dev.example.com'`` the calculated subdomain will be ``'staging.dev'``. If the object passed as environ has an environ attribute, the value of this attribute is used instead. This allows you to pass request objects. Additionally `PATH_INFO` added as a default of the :class:`MapAdapter` so that you don't have to pass the path info to the match method. .. versionchanged:: 0.5 previously this method accepted a bogus `calculate_subdomain` parameter that did not have any effect. It was removed because of that. .. versionchanged:: 0.8 This will no longer raise a ValueError when an unexpected server name was passed. :param environ: a WSGI environment. :param server_name: an optional server name hint (see above). :param subdomain: optionally the current subdomain (see above). """ environ = _get_environ(environ) wsgi_server_name = get_host(environ).lower() if server_name is None: server_name = wsgi_server_name else: server_name = server_name.lower() if subdomain is None and not self.host_matching: cur_server_name = wsgi_server_name.split(".") real_server_name = server_name.split(".") offset = -len(real_server_name) if cur_server_name[offset:] != real_server_name: # This can happen even with valid configs if the server was # accesssed directly by IP address under some situations. # Instead of raising an exception like in Werkzeug 0.7 or # earlier we go by an invalid subdomain which will result # in a 404 error on matching. subdomain = "<invalid>" else: subdomain = ".".join(filter(None, cur_server_name[:offset])) def _get_wsgi_string(name): val = environ.get(name) if val is not None: return wsgi_decoding_dance(val, self.charset) script_name = _get_wsgi_string("SCRIPT_NAME") path_info = _get_wsgi_string("PATH_INFO") query_args = _get_wsgi_string("QUERY_STRING") return Map.bind( self, server_name, script_name, subdomain, environ["wsgi.url_scheme"], environ["REQUEST_METHOD"], path_info, query_args=query_args, )
[ "def", "bind_to_environ", "(", "self", ",", "environ", ",", "server_name", "=", "None", ",", "subdomain", "=", "None", ")", ":", "environ", "=", "_get_environ", "(", "environ", ")", "wsgi_server_name", "=", "get_host", "(", "environ", ")", ".", "lower", "(", ")", "if", "server_name", "is", "None", ":", "server_name", "=", "wsgi_server_name", "else", ":", "server_name", "=", "server_name", ".", "lower", "(", ")", "if", "subdomain", "is", "None", "and", "not", "self", ".", "host_matching", ":", "cur_server_name", "=", "wsgi_server_name", ".", "split", "(", "\".\"", ")", "real_server_name", "=", "server_name", ".", "split", "(", "\".\"", ")", "offset", "=", "-", "len", "(", "real_server_name", ")", "if", "cur_server_name", "[", "offset", ":", "]", "!=", "real_server_name", ":", "# This can happen even with valid configs if the server was", "# accesssed directly by IP address under some situations.", "# Instead of raising an exception like in Werkzeug 0.7 or", "# earlier we go by an invalid subdomain which will result", "# in a 404 error on matching.", "subdomain", "=", "\"<invalid>\"", "else", ":", "subdomain", "=", "\".\"", ".", "join", "(", "filter", "(", "None", ",", "cur_server_name", "[", ":", "offset", "]", ")", ")", "def", "_get_wsgi_string", "(", "name", ")", ":", "val", "=", "environ", ".", "get", "(", "name", ")", "if", "val", "is", "not", "None", ":", "return", "wsgi_decoding_dance", "(", "val", ",", "self", ".", "charset", ")", "script_name", "=", "_get_wsgi_string", "(", "\"SCRIPT_NAME\"", ")", "path_info", "=", "_get_wsgi_string", "(", "\"PATH_INFO\"", ")", "query_args", "=", "_get_wsgi_string", "(", "\"QUERY_STRING\"", ")", "return", "Map", ".", "bind", "(", "self", ",", "server_name", ",", "script_name", ",", "subdomain", ",", "environ", "[", "\"wsgi.url_scheme\"", "]", ",", "environ", "[", "\"REQUEST_METHOD\"", "]", ",", "path_info", ",", "query_args", "=", "query_args", ",", ")" ]
[ 1465, 4 ]
[ 1539, 9 ]
python
en
['en', 'en', 'en']
True
Map.update
(self)
Called before matching and building to keep the compiled rules in the correct order after things changed.
Called before matching and building to keep the compiled rules in the correct order after things changed.
def update(self): """Called before matching and building to keep the compiled rules in the correct order after things changed. """ if not self._remap: return with self._remap_lock: if not self._remap: return self._rules.sort(key=lambda x: x.match_compare_key()) for rules in itervalues(self._rules_by_endpoint): rules.sort(key=lambda x: x.build_compare_key()) self._remap = False
[ "def", "update", "(", "self", ")", ":", "if", "not", "self", ".", "_remap", ":", "return", "with", "self", ".", "_remap_lock", ":", "if", "not", "self", ".", "_remap", ":", "return", "self", ".", "_rules", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "match_compare_key", "(", ")", ")", "for", "rules", "in", "itervalues", "(", "self", ".", "_rules_by_endpoint", ")", ":", "rules", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "build_compare_key", "(", ")", ")", "self", ".", "_remap", "=", "False" ]
[ 1541, 4 ]
[ 1555, 31 ]
python
en
['en', 'en', 'en']
True
MapAdapter.dispatch
( self, view_func, path_info=None, method=None, catch_http_exceptions=False )
Does the complete dispatching process. `view_func` is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can display nicer error messages by just catching them by hand. If you want to stick with the default error messages you can pass it ``catch_http_exceptions=True`` and it will catch the http exceptions. Here a small example for the dispatch usage:: from werkzeug.wrappers import Request, Response from werkzeug.wsgi import responder from werkzeug.routing import Map, Rule def on_index(request): return Response('Hello from the index') url_map = Map([Rule('/', endpoint='index')]) views = {'index': on_index} @responder def application(environ, start_response): request = Request(environ) urls = url_map.bind_to_environ(environ) return urls.dispatch(lambda e, v: views[e](request, **v), catch_http_exceptions=True) Keep in mind that this method might return exception objects, too, so use :class:`Response.force_type` to get a response object. :param view_func: a function that is called with the endpoint as first argument and the value dict as second. Has to dispatch to the actual view function with this information. (see above) :param path_info: the path info to use for matching. Overrides the path info specified on binding. :param method: the HTTP method used for matching. Overrides the method specified on binding. :param catch_http_exceptions: set to `True` to catch any of the werkzeug :class:`HTTPException`\\s.
Does the complete dispatching process. `view_func` is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can display nicer error messages by just catching them by hand. If you want to stick with the default error messages you can pass it ``catch_http_exceptions=True`` and it will catch the http exceptions.
def dispatch( self, view_func, path_info=None, method=None, catch_http_exceptions=False ): """Does the complete dispatching process. `view_func` is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can display nicer error messages by just catching them by hand. If you want to stick with the default error messages you can pass it ``catch_http_exceptions=True`` and it will catch the http exceptions. Here a small example for the dispatch usage:: from werkzeug.wrappers import Request, Response from werkzeug.wsgi import responder from werkzeug.routing import Map, Rule def on_index(request): return Response('Hello from the index') url_map = Map([Rule('/', endpoint='index')]) views = {'index': on_index} @responder def application(environ, start_response): request = Request(environ) urls = url_map.bind_to_environ(environ) return urls.dispatch(lambda e, v: views[e](request, **v), catch_http_exceptions=True) Keep in mind that this method might return exception objects, too, so use :class:`Response.force_type` to get a response object. :param view_func: a function that is called with the endpoint as first argument and the value dict as second. Has to dispatch to the actual view function with this information. (see above) :param path_info: the path info to use for matching. Overrides the path info specified on binding. :param method: the HTTP method used for matching. Overrides the method specified on binding. :param catch_http_exceptions: set to `True` to catch any of the werkzeug :class:`HTTPException`\\s. """ try: try: endpoint, args = self.match(path_info, method) except RequestRedirect as e: return e return view_func(endpoint, args) except HTTPException as e: if catch_http_exceptions: return e raise
[ "def", "dispatch", "(", "self", ",", "view_func", ",", "path_info", "=", "None", ",", "method", "=", "None", ",", "catch_http_exceptions", "=", "False", ")", ":", "try", ":", "try", ":", "endpoint", ",", "args", "=", "self", ".", "match", "(", "path_info", ",", "method", ")", "except", "RequestRedirect", "as", "e", ":", "return", "e", "return", "view_func", "(", "endpoint", ",", "args", ")", "except", "HTTPException", "as", "e", ":", "if", "catch_http_exceptions", ":", "return", "e", "raise" ]
[ 1591, 4 ]
[ 1645, 17 ]
python
en
['en', 'en', 'en']
True
MapAdapter.match
(self, path_info=None, method=None, return_rule=False, query_args=None)
The usage is simple: you just pass the match method the current path info as well as the method (which defaults to `GET`). The following things can then happen: - you receive a `NotFound` exception that indicates that no URL is matching. A `NotFound` exception is also a WSGI application you can call to get a default page not found page (happens to be the same object as `werkzeug.exceptions.NotFound`) - you receive a `MethodNotAllowed` exception that indicates that there is a match for this URL but not for the current request method. This is useful for RESTful applications. - you receive a `RequestRedirect` exception with a `new_url` attribute. This exception is used to notify you about a request Werkzeug requests from your WSGI application. This is for example the case if you request ``/foo`` although the correct URL is ``/foo/`` You can use the `RequestRedirect` instance as response-like object similar to all other subclasses of `HTTPException`. - you get a tuple in the form ``(endpoint, arguments)`` if there is a match (unless `return_rule` is True, in which case you get a tuple in the form ``(rule, arguments)``) If the path info is not passed to the match method the default path info of the map is used (defaults to the root URL if not defined explicitly). All of the exceptions raised are subclasses of `HTTPException` so they can be used as WSGI responses. They will all render generic error or redirect pages. Here is a small example for matching: >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/<int:id>', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.match("/", "GET") ('index', {}) >>> urls.match("/downloads/42") ('downloads/show', {'id': 42}) And here is what happens on redirect and missing URLs: >>> urls.match("/downloads") Traceback (most recent call last): ... RequestRedirect: http://example.com/downloads/ >>> urls.match("/missing") Traceback (most recent call last): ... NotFound: 404 Not Found :param path_info: the path info to use for matching. Overrides the path info specified on binding. :param method: the HTTP method used for matching. Overrides the method specified on binding. :param return_rule: return the rule that matched instead of just the endpoint (defaults to `False`). :param query_args: optional query arguments that are used for automatic redirects as string or dictionary. It's currently not possible to use the query arguments for URL matching. .. versionadded:: 0.6 `return_rule` was added. .. versionadded:: 0.7 `query_args` was added. .. versionchanged:: 0.8 `query_args` can now also be a string.
The usage is simple: you just pass the match method the current path info as well as the method (which defaults to `GET`). The following things can then happen:
def match(self, path_info=None, method=None, return_rule=False, query_args=None): """The usage is simple: you just pass the match method the current path info as well as the method (which defaults to `GET`). The following things can then happen: - you receive a `NotFound` exception that indicates that no URL is matching. A `NotFound` exception is also a WSGI application you can call to get a default page not found page (happens to be the same object as `werkzeug.exceptions.NotFound`) - you receive a `MethodNotAllowed` exception that indicates that there is a match for this URL but not for the current request method. This is useful for RESTful applications. - you receive a `RequestRedirect` exception with a `new_url` attribute. This exception is used to notify you about a request Werkzeug requests from your WSGI application. This is for example the case if you request ``/foo`` although the correct URL is ``/foo/`` You can use the `RequestRedirect` instance as response-like object similar to all other subclasses of `HTTPException`. - you get a tuple in the form ``(endpoint, arguments)`` if there is a match (unless `return_rule` is True, in which case you get a tuple in the form ``(rule, arguments)``) If the path info is not passed to the match method the default path info of the map is used (defaults to the root URL if not defined explicitly). All of the exceptions raised are subclasses of `HTTPException` so they can be used as WSGI responses. They will all render generic error or redirect pages. Here is a small example for matching: >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/<int:id>', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.match("/", "GET") ('index', {}) >>> urls.match("/downloads/42") ('downloads/show', {'id': 42}) And here is what happens on redirect and missing URLs: >>> urls.match("/downloads") Traceback (most recent call last): ... RequestRedirect: http://example.com/downloads/ >>> urls.match("/missing") Traceback (most recent call last): ... NotFound: 404 Not Found :param path_info: the path info to use for matching. Overrides the path info specified on binding. :param method: the HTTP method used for matching. Overrides the method specified on binding. :param return_rule: return the rule that matched instead of just the endpoint (defaults to `False`). :param query_args: optional query arguments that are used for automatic redirects as string or dictionary. It's currently not possible to use the query arguments for URL matching. .. versionadded:: 0.6 `return_rule` was added. .. versionadded:: 0.7 `query_args` was added. .. versionchanged:: 0.8 `query_args` can now also be a string. """ self.map.update() if path_info is None: path_info = self.path_info else: path_info = to_unicode(path_info, self.map.charset) if query_args is None: query_args = self.query_args method = (method or self.default_method).upper() path = u"%s|%s" % ( self.map.host_matching and self.server_name or self.subdomain, path_info and "/%s" % path_info.lstrip("/"), ) have_match_for = set() for rule in self.map._rules: try: rv = rule.match(path, method) except RequestSlash: raise RequestRedirect( self.make_redirect_url( url_quote(path_info, self.map.charset, safe="/:|+") + "/", query_args, ) ) except RequestAliasRedirect as e: raise RequestRedirect( self.make_alias_redirect_url( path, rule.endpoint, e.matched_values, method, query_args ) ) if rv is None: continue if rule.methods is not None and method not in rule.methods: have_match_for.update(rule.methods) continue if self.map.redirect_defaults: redirect_url = self.get_default_redirect(rule, method, rv, query_args) if redirect_url is not None: raise RequestRedirect(redirect_url) if rule.redirect_to is not None: if isinstance(rule.redirect_to, string_types): def _handle_match(match): value = rv[match.group(1)] return rule._converters[match.group(1)].to_url(value) redirect_url = _simple_rule_re.sub(_handle_match, rule.redirect_to) else: redirect_url = rule.redirect_to(self, **rv) raise RequestRedirect( str( url_join( "%s://%s%s%s" % ( self.url_scheme or "http", self.subdomain + "." if self.subdomain else "", self.server_name, self.script_name, ), redirect_url, ) ) ) if return_rule: return rule, rv else: return rule.endpoint, rv if have_match_for: raise MethodNotAllowed(valid_methods=list(have_match_for)) raise NotFound()
[ "def", "match", "(", "self", ",", "path_info", "=", "None", ",", "method", "=", "None", ",", "return_rule", "=", "False", ",", "query_args", "=", "None", ")", ":", "self", ".", "map", ".", "update", "(", ")", "if", "path_info", "is", "None", ":", "path_info", "=", "self", ".", "path_info", "else", ":", "path_info", "=", "to_unicode", "(", "path_info", ",", "self", ".", "map", ".", "charset", ")", "if", "query_args", "is", "None", ":", "query_args", "=", "self", ".", "query_args", "method", "=", "(", "method", "or", "self", ".", "default_method", ")", ".", "upper", "(", ")", "path", "=", "u\"%s|%s\"", "%", "(", "self", ".", "map", ".", "host_matching", "and", "self", ".", "server_name", "or", "self", ".", "subdomain", ",", "path_info", "and", "\"/%s\"", "%", "path_info", ".", "lstrip", "(", "\"/\"", ")", ",", ")", "have_match_for", "=", "set", "(", ")", "for", "rule", "in", "self", ".", "map", ".", "_rules", ":", "try", ":", "rv", "=", "rule", ".", "match", "(", "path", ",", "method", ")", "except", "RequestSlash", ":", "raise", "RequestRedirect", "(", "self", ".", "make_redirect_url", "(", "url_quote", "(", "path_info", ",", "self", ".", "map", ".", "charset", ",", "safe", "=", "\"/:|+\"", ")", "+", "\"/\"", ",", "query_args", ",", ")", ")", "except", "RequestAliasRedirect", "as", "e", ":", "raise", "RequestRedirect", "(", "self", ".", "make_alias_redirect_url", "(", "path", ",", "rule", ".", "endpoint", ",", "e", ".", "matched_values", ",", "method", ",", "query_args", ")", ")", "if", "rv", "is", "None", ":", "continue", "if", "rule", ".", "methods", "is", "not", "None", "and", "method", "not", "in", "rule", ".", "methods", ":", "have_match_for", ".", "update", "(", "rule", ".", "methods", ")", "continue", "if", "self", ".", "map", ".", "redirect_defaults", ":", "redirect_url", "=", "self", ".", "get_default_redirect", "(", "rule", ",", "method", ",", "rv", ",", "query_args", ")", "if", "redirect_url", "is", "not", "None", ":", "raise", "RequestRedirect", "(", "redirect_url", ")", "if", "rule", ".", "redirect_to", "is", "not", "None", ":", "if", "isinstance", "(", "rule", ".", "redirect_to", ",", "string_types", ")", ":", "def", "_handle_match", "(", "match", ")", ":", "value", "=", "rv", "[", "match", ".", "group", "(", "1", ")", "]", "return", "rule", ".", "_converters", "[", "match", ".", "group", "(", "1", ")", "]", ".", "to_url", "(", "value", ")", "redirect_url", "=", "_simple_rule_re", ".", "sub", "(", "_handle_match", ",", "rule", ".", "redirect_to", ")", "else", ":", "redirect_url", "=", "rule", ".", "redirect_to", "(", "self", ",", "*", "*", "rv", ")", "raise", "RequestRedirect", "(", "str", "(", "url_join", "(", "\"%s://%s%s%s\"", "%", "(", "self", ".", "url_scheme", "or", "\"http\"", ",", "self", ".", "subdomain", "+", "\".\"", "if", "self", ".", "subdomain", "else", "\"\"", ",", "self", ".", "server_name", ",", "self", ".", "script_name", ",", ")", ",", "redirect_url", ",", ")", ")", ")", "if", "return_rule", ":", "return", "rule", ",", "rv", "else", ":", "return", "rule", ".", "endpoint", ",", "rv", "if", "have_match_for", ":", "raise", "MethodNotAllowed", "(", "valid_methods", "=", "list", "(", "have_match_for", ")", ")", "raise", "NotFound", "(", ")" ]
[ 1647, 4 ]
[ 1798, 24 ]
python
en
['en', 'en', 'en']
True
MapAdapter.test
(self, path_info=None, method=None)
Test if a rule would match. Works like `match` but returns `True` if the URL matches, or `False` if it does not exist. :param path_info: the path info to use for matching. Overrides the path info specified on binding. :param method: the HTTP method used for matching. Overrides the method specified on binding.
Test if a rule would match. Works like `match` but returns `True` if the URL matches, or `False` if it does not exist.
def test(self, path_info=None, method=None): """Test if a rule would match. Works like `match` but returns `True` if the URL matches, or `False` if it does not exist. :param path_info: the path info to use for matching. Overrides the path info specified on binding. :param method: the HTTP method used for matching. Overrides the method specified on binding. """ try: self.match(path_info, method) except RequestRedirect: pass except HTTPException: return False return True
[ "def", "test", "(", "self", ",", "path_info", "=", "None", ",", "method", "=", "None", ")", ":", "try", ":", "self", ".", "match", "(", "path_info", ",", "method", ")", "except", "RequestRedirect", ":", "pass", "except", "HTTPException", ":", "return", "False", "return", "True" ]
[ 1800, 4 ]
[ 1815, 19 ]
python
en
['en', 'en', 'en']
True
MapAdapter.allowed_methods
(self, path_info=None)
Returns the valid methods that match for a given path. .. versionadded:: 0.7
Returns the valid methods that match for a given path.
def allowed_methods(self, path_info=None): """Returns the valid methods that match for a given path. .. versionadded:: 0.7 """ try: self.match(path_info, method="--") except MethodNotAllowed as e: return e.valid_methods except HTTPException: pass return []
[ "def", "allowed_methods", "(", "self", ",", "path_info", "=", "None", ")", ":", "try", ":", "self", ".", "match", "(", "path_info", ",", "method", "=", "\"--\"", ")", "except", "MethodNotAllowed", "as", "e", ":", "return", "e", ".", "valid_methods", "except", "HTTPException", ":", "pass", "return", "[", "]" ]
[ 1817, 4 ]
[ 1828, 17 ]
python
en
['en', 'en', 'en']
True
MapAdapter.get_host
(self, domain_part)
Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name.
Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name.
def get_host(self, domain_part): """Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name. """ if self.map.host_matching: if domain_part is None: return self.server_name return to_unicode(domain_part, "ascii") subdomain = domain_part if subdomain is None: subdomain = self.subdomain else: subdomain = to_unicode(subdomain, "ascii") return (subdomain + u"." if subdomain else u"") + self.server_name
[ "def", "get_host", "(", "self", ",", "domain_part", ")", ":", "if", "self", ".", "map", ".", "host_matching", ":", "if", "domain_part", "is", "None", ":", "return", "self", ".", "server_name", "return", "to_unicode", "(", "domain_part", ",", "\"ascii\"", ")", "subdomain", "=", "domain_part", "if", "subdomain", "is", "None", ":", "subdomain", "=", "self", ".", "subdomain", "else", ":", "subdomain", "=", "to_unicode", "(", "subdomain", ",", "\"ascii\"", ")", "return", "(", "subdomain", "+", "u\".\"", "if", "subdomain", "else", "u\"\"", ")", "+", "self", ".", "server_name" ]
[ 1830, 4 ]
[ 1844, 74 ]
python
en
['en', 'en', 'en']
True
MapAdapter.get_default_redirect
(self, rule, method, values, query_args)
A helper that returns the URL to redirect to if it finds one. This is used for default redirecting only. :internal:
A helper that returns the URL to redirect to if it finds one. This is used for default redirecting only.
def get_default_redirect(self, rule, method, values, query_args): """A helper that returns the URL to redirect to if it finds one. This is used for default redirecting only. :internal: """ assert self.map.redirect_defaults for r in self.map._rules_by_endpoint[rule.endpoint]: # every rule that comes after this one, including ourself # has a lower priority for the defaults. We order the ones # with the highest priority up for building. if r is rule: break if r.provides_defaults_for(rule) and r.suitable_for(values, method): values.update(r.defaults) domain_part, path = r.build(values) return self.make_redirect_url(path, query_args, domain_part=domain_part)
[ "def", "get_default_redirect", "(", "self", ",", "rule", ",", "method", ",", "values", ",", "query_args", ")", ":", "assert", "self", ".", "map", ".", "redirect_defaults", "for", "r", "in", "self", ".", "map", ".", "_rules_by_endpoint", "[", "rule", ".", "endpoint", "]", ":", "# every rule that comes after this one, including ourself", "# has a lower priority for the defaults. We order the ones", "# with the highest priority up for building.", "if", "r", "is", "rule", ":", "break", "if", "r", ".", "provides_defaults_for", "(", "rule", ")", "and", "r", ".", "suitable_for", "(", "values", ",", "method", ")", ":", "values", ".", "update", "(", "r", ".", "defaults", ")", "domain_part", ",", "path", "=", "r", ".", "build", "(", "values", ")", "return", "self", ".", "make_redirect_url", "(", "path", ",", "query_args", ",", "domain_part", "=", "domain_part", ")" ]
[ 1846, 4 ]
[ 1862, 88 ]
python
en
['en', 'en', 'en']
True
MapAdapter.make_redirect_url
(self, path_info, query_args=None, domain_part=None)
Creates a redirect URL. :internal:
Creates a redirect URL.
def make_redirect_url(self, path_info, query_args=None, domain_part=None): """Creates a redirect URL. :internal: """ suffix = "" if query_args: suffix = "?" + self.encode_query_args(query_args) return str( "%s://%s/%s%s" % ( self.url_scheme or "http", self.get_host(domain_part), posixpath.join( self.script_name[:-1].lstrip("/"), path_info.lstrip("/") ), suffix, ) )
[ "def", "make_redirect_url", "(", "self", ",", "path_info", ",", "query_args", "=", "None", ",", "domain_part", "=", "None", ")", ":", "suffix", "=", "\"\"", "if", "query_args", ":", "suffix", "=", "\"?\"", "+", "self", ".", "encode_query_args", "(", "query_args", ")", "return", "str", "(", "\"%s://%s/%s%s\"", "%", "(", "self", ".", "url_scheme", "or", "\"http\"", ",", "self", ".", "get_host", "(", "domain_part", ")", ",", "posixpath", ".", "join", "(", "self", ".", "script_name", "[", ":", "-", "1", "]", ".", "lstrip", "(", "\"/\"", ")", ",", "path_info", ".", "lstrip", "(", "\"/\"", ")", ")", ",", "suffix", ",", ")", ")" ]
[ 1869, 4 ]
[ 1887, 9 ]
python
en
['en', 'zh', 'en']
True
MapAdapter.make_alias_redirect_url
(self, path, endpoint, values, method, query_args)
Internally called to make an alias redirect URL.
Internally called to make an alias redirect URL.
def make_alias_redirect_url(self, path, endpoint, values, method, query_args): """Internally called to make an alias redirect URL.""" url = self.build( endpoint, values, method, append_unknown=False, force_external=True ) if query_args: url += "?" + self.encode_query_args(query_args) assert url != path, "detected invalid alias setting. No canonical URL found" return url
[ "def", "make_alias_redirect_url", "(", "self", ",", "path", ",", "endpoint", ",", "values", ",", "method", ",", "query_args", ")", ":", "url", "=", "self", ".", "build", "(", "endpoint", ",", "values", ",", "method", ",", "append_unknown", "=", "False", ",", "force_external", "=", "True", ")", "if", "query_args", ":", "url", "+=", "\"?\"", "+", "self", ".", "encode_query_args", "(", "query_args", ")", "assert", "url", "!=", "path", ",", "\"detected invalid alias setting. No canonical URL found\"", "return", "url" ]
[ 1889, 4 ]
[ 1897, 18 ]
python
en
['en', 'en', 'en']
True
MapAdapter._partial_build
(self, endpoint, values, method, append_unknown)
Helper for :meth:`build`. Returns subdomain and path for the rule that accepts this endpoint, values and method. :internal:
Helper for :meth:`build`. Returns subdomain and path for the rule that accepts this endpoint, values and method.
def _partial_build(self, endpoint, values, method, append_unknown): """Helper for :meth:`build`. Returns subdomain and path for the rule that accepts this endpoint, values and method. :internal: """ # in case the method is none, try with the default method first if method is None: rv = self._partial_build( endpoint, values, self.default_method, append_unknown ) if rv is not None: return rv # default method did not match or a specific method is passed, # check all and go with first result. for rule in self.map._rules_by_endpoint.get(endpoint, ()): if rule.suitable_for(values, method): rv = rule.build(values, append_unknown) if rv is not None: return rv
[ "def", "_partial_build", "(", "self", ",", "endpoint", ",", "values", ",", "method", ",", "append_unknown", ")", ":", "# in case the method is none, try with the default method first", "if", "method", "is", "None", ":", "rv", "=", "self", ".", "_partial_build", "(", "endpoint", ",", "values", ",", "self", ".", "default_method", ",", "append_unknown", ")", "if", "rv", "is", "not", "None", ":", "return", "rv", "# default method did not match or a specific method is passed,", "# check all and go with first result.", "for", "rule", "in", "self", ".", "map", ".", "_rules_by_endpoint", ".", "get", "(", "endpoint", ",", "(", ")", ")", ":", "if", "rule", ".", "suitable_for", "(", "values", ",", "method", ")", ":", "rv", "=", "rule", ".", "build", "(", "values", ",", "append_unknown", ")", "if", "rv", "is", "not", "None", ":", "return", "rv" ]
[ 1899, 4 ]
[ 1919, 29 ]
python
en
['en', 'en', 'en']
True
MapAdapter.build
( self, endpoint, values=None, method=None, force_external=False, append_unknown=True, )
Building URLs works pretty much the other way round. Instead of `match` you call `build` and pass it the endpoint and a dict of arguments for the placeholders. The `build` function also accepts an argument called `force_external` which, if you set it to `True` will force external URLs. Per default external URLs (include the server name) will only be used if the target URL is on a different subdomain. >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/<int:id>', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.build("index", {}) '/' >>> urls.build("downloads/show", {'id': 42}) '/downloads/42' >>> urls.build("downloads/show", {'id': 42}, force_external=True) 'http://example.com/downloads/42' Because URLs cannot contain non ASCII data you will always get bytestrings back. Non ASCII characters are urlencoded with the charset defined on the map instance. Additional values are converted to unicode and appended to the URL as URL querystring parameters: >>> urls.build("index", {'q': 'My Searchstring'}) '/?q=My+Searchstring' When processing those additional values, lists are furthermore interpreted as multiple values (as per :py:class:`werkzeug.datastructures.MultiDict`): >>> urls.build("index", {'q': ['a', 'b', 'c']}) '/?q=a&q=b&q=c' Passing a ``MultiDict`` will also add multiple values: >>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b')))) '/?p=z&q=a&q=b' If a rule does not exist when building a `BuildError` exception is raised. The build method accepts an argument called `method` which allows you to specify the method you want to have an URL built for if you have different methods for the same endpoint specified. .. versionadded:: 0.6 the `append_unknown` parameter was added. :param endpoint: the endpoint of the URL to build. :param values: the values for the URL to build. Unhandled values are appended to the URL as query parameters. :param method: the HTTP method for the rule if there are different URLs for different methods on the same endpoint. :param force_external: enforce full canonical external URLs. If the URL scheme is not provided, this will generate a protocol-relative URL. :param append_unknown: unknown parameters are appended to the generated URL as query string argument. Disable this if you want the builder to ignore those.
Building URLs works pretty much the other way round. Instead of `match` you call `build` and pass it the endpoint and a dict of arguments for the placeholders.
def build( self, endpoint, values=None, method=None, force_external=False, append_unknown=True, ): """Building URLs works pretty much the other way round. Instead of `match` you call `build` and pass it the endpoint and a dict of arguments for the placeholders. The `build` function also accepts an argument called `force_external` which, if you set it to `True` will force external URLs. Per default external URLs (include the server name) will only be used if the target URL is on a different subdomain. >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/<int:id>', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.build("index", {}) '/' >>> urls.build("downloads/show", {'id': 42}) '/downloads/42' >>> urls.build("downloads/show", {'id': 42}, force_external=True) 'http://example.com/downloads/42' Because URLs cannot contain non ASCII data you will always get bytestrings back. Non ASCII characters are urlencoded with the charset defined on the map instance. Additional values are converted to unicode and appended to the URL as URL querystring parameters: >>> urls.build("index", {'q': 'My Searchstring'}) '/?q=My+Searchstring' When processing those additional values, lists are furthermore interpreted as multiple values (as per :py:class:`werkzeug.datastructures.MultiDict`): >>> urls.build("index", {'q': ['a', 'b', 'c']}) '/?q=a&q=b&q=c' Passing a ``MultiDict`` will also add multiple values: >>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b')))) '/?p=z&q=a&q=b' If a rule does not exist when building a `BuildError` exception is raised. The build method accepts an argument called `method` which allows you to specify the method you want to have an URL built for if you have different methods for the same endpoint specified. .. versionadded:: 0.6 the `append_unknown` parameter was added. :param endpoint: the endpoint of the URL to build. :param values: the values for the URL to build. Unhandled values are appended to the URL as query parameters. :param method: the HTTP method for the rule if there are different URLs for different methods on the same endpoint. :param force_external: enforce full canonical external URLs. If the URL scheme is not provided, this will generate a protocol-relative URL. :param append_unknown: unknown parameters are appended to the generated URL as query string argument. Disable this if you want the builder to ignore those. """ self.map.update() if values: if isinstance(values, MultiDict): temp_values = {} # iteritems(dict, values) is like `values.lists()` # without the call or `list()` coercion overhead. for key, value in iteritems(dict, values): if not value: continue if len(value) == 1: # flatten single item lists value = value[0] if value is None: # drop None continue temp_values[key] = value values = temp_values else: # drop None values = dict(i for i in iteritems(values) if i[1] is not None) else: values = {} rv = self._partial_build(endpoint, values, method, append_unknown) if rv is None: raise BuildError(endpoint, values, method, self) domain_part, path = rv host = self.get_host(domain_part) # shortcut this. if not force_external and ( (self.map.host_matching and host == self.server_name) or (not self.map.host_matching and domain_part == self.subdomain) ): return "%s/%s" % (self.script_name.rstrip("/"), path.lstrip("/")) return str( "%s//%s%s/%s" % ( self.url_scheme + ":" if self.url_scheme else "", host, self.script_name[:-1], path.lstrip("/"), ) )
[ "def", "build", "(", "self", ",", "endpoint", ",", "values", "=", "None", ",", "method", "=", "None", ",", "force_external", "=", "False", ",", "append_unknown", "=", "True", ",", ")", ":", "self", ".", "map", ".", "update", "(", ")", "if", "values", ":", "if", "isinstance", "(", "values", ",", "MultiDict", ")", ":", "temp_values", "=", "{", "}", "# iteritems(dict, values) is like `values.lists()`", "# without the call or `list()` coercion overhead.", "for", "key", ",", "value", "in", "iteritems", "(", "dict", ",", "values", ")", ":", "if", "not", "value", ":", "continue", "if", "len", "(", "value", ")", "==", "1", ":", "# flatten single item lists", "value", "=", "value", "[", "0", "]", "if", "value", "is", "None", ":", "# drop None", "continue", "temp_values", "[", "key", "]", "=", "value", "values", "=", "temp_values", "else", ":", "# drop None", "values", "=", "dict", "(", "i", "for", "i", "in", "iteritems", "(", "values", ")", "if", "i", "[", "1", "]", "is", "not", "None", ")", "else", ":", "values", "=", "{", "}", "rv", "=", "self", ".", "_partial_build", "(", "endpoint", ",", "values", ",", "method", ",", "append_unknown", ")", "if", "rv", "is", "None", ":", "raise", "BuildError", "(", "endpoint", ",", "values", ",", "method", ",", "self", ")", "domain_part", ",", "path", "=", "rv", "host", "=", "self", ".", "get_host", "(", "domain_part", ")", "# shortcut this.", "if", "not", "force_external", "and", "(", "(", "self", ".", "map", ".", "host_matching", "and", "host", "==", "self", ".", "server_name", ")", "or", "(", "not", "self", ".", "map", ".", "host_matching", "and", "domain_part", "==", "self", ".", "subdomain", ")", ")", ":", "return", "\"%s/%s\"", "%", "(", "self", ".", "script_name", ".", "rstrip", "(", "\"/\"", ")", ",", "path", ".", "lstrip", "(", "\"/\"", ")", ")", "return", "str", "(", "\"%s//%s%s/%s\"", "%", "(", "self", ".", "url_scheme", "+", "\":\"", "if", "self", ".", "url_scheme", "else", "\"\"", ",", "host", ",", "self", ".", "script_name", "[", ":", "-", "1", "]", ",", "path", ".", "lstrip", "(", "\"/\"", ")", ",", ")", ")" ]
[ 1921, 4 ]
[ 2038, 9 ]
python
en
['en', 'en', 'en']
True