code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def artifact_type_schema_to_artifact_list(
name: str,
artifact_type: pipeline_spec_pb2.ArtifactTypeSchema,
task_root: str,
) -> pipeline_spec_pb2.ArtifactList:
"""Constructs an ArtifactList instance for an artifact in ExecutorInput."""
return pipeline_spec_pb2.ArtifactList(artifacts=[
pipeli... | Constructs an ArtifactList instance for an artifact in ExecutorInput. | artifact_type_schema_to_artifact_list | python | kubeflow/pipelines | sdk/python/kfp/local/executor_input_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_input_utils.py | Apache-2.0 |
def dict_to_protobuf_struct(d: Dict[str, Any]) -> struct_pb2.Struct:
"""Converts a Python dictionary to a prototobuf Struct."""
protobuf_struct = struct_pb2.Struct()
protobuf_struct.update(d)
return protobuf_struct | Converts a Python dictionary to a prototobuf Struct. | dict_to_protobuf_struct | python | kubeflow/pipelines | sdk/python/kfp/local/executor_input_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_input_utils.py | Apache-2.0 |
def dsl_artifact_to_artifact_list(
artifact: dsl.Artifact) -> pipeline_spec_pb2.ArtifactList:
"""Converts a single dsl.Aritfact to a protobuf ArtifactList."""
return pipeline_spec_pb2.ArtifactList(artifacts=[
pipeline_spec_pb2.RuntimeArtifact(
name=artifact.name,
type=pip... | Converts a single dsl.Aritfact to a protobuf ArtifactList. | dsl_artifact_to_artifact_list | python | kubeflow/pipelines | sdk/python/kfp/local/executor_input_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_input_utils.py | Apache-2.0 |
def executor_input_to_dict(
executor_input: pipeline_spec_pb2.ExecutorInput,
component_spec: pipeline_spec_pb2.ComponentSpec,
) -> Dict[str, Any]:
"""Converts the executor input to a dictionary.
Since protobuf value represents ints and floats the same way, we
cast ints to their correct type. This s... | Converts the executor input to a dictionary.
Since protobuf value represents ints and floats the same way, we
cast ints to their correct type. This should be called before
replacing placeholders with values.
This is consistent with the remote backend behavior.
| executor_input_to_dict | python | kubeflow/pipelines | sdk/python/kfp/local/executor_input_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_input_utils.py | Apache-2.0 |
def load_executor_output(
executor_output_path: str) -> pipeline_spec_pb2.ExecutorOutput:
"""Loads the ExecutorOutput message from a path."""
executor_output = pipeline_spec_pb2.ExecutorOutput()
if not os.path.isfile(executor_output_path):
return executor_output
with open(executor_outp... | Loads the ExecutorOutput message from a path. | load_executor_output | python | kubeflow/pipelines | sdk/python/kfp/local/executor_output_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_output_utils.py | Apache-2.0 |
def cast_protobuf_numbers(
output_parameters: Dict[str, Any],
output_parameter_types: Dict[
str, pipeline_spec_pb2.ComponentOutputsSpec.ParameterSpec],
) -> Dict[str, Any]:
"""Casts output fields that are typed as NUMBER_INTEGER to a Python int.
This is required, since google.protobuf.struct_pb... | Casts output fields that are typed as NUMBER_INTEGER to a Python int.
This is required, since google.protobuf.struct_pb2.Value uses
number_value to represent both floats and ints. When converting
struct_pb2.Value to a dict/json, int will be upcast to float, even
if the component output specifies int.
... | cast_protobuf_numbers | python | kubeflow/pipelines | sdk/python/kfp/local/executor_output_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_output_utils.py | Apache-2.0 |
def get_outputs_from_executor_output(
executor_output: pipeline_spec_pb2.ExecutorOutput,
executor_input: pipeline_spec_pb2.ExecutorInput,
component_spec: pipeline_spec_pb2.ComponentSpec,
) -> Dict[str, Any]:
"""Obtains a dictionary of output key to output value from several messages
corresponding to... | Obtains a dictionary of output key to output value from several messages
corresponding to the executed a component/task. | get_outputs_from_executor_output | python | kubeflow/pipelines | sdk/python/kfp/local/executor_output_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_output_utils.py | Apache-2.0 |
def special_dsl_outputpath_read(
parameter_name: str,
output_file: str,
dtype: pipeline_spec_pb2.ParameterType.ParameterTypeEnum,
) -> Any:
"""Reads the text in dsl.OutputPath files in the same way as the remote
backend.
In brief: read strings as strings and JSON load everything else.
"""
... | Reads the text in dsl.OutputPath files in the same way as the remote
backend.
In brief: read strings as strings and JSON load everything else.
| special_dsl_outputpath_read | python | kubeflow/pipelines | sdk/python/kfp/local/executor_output_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_output_utils.py | Apache-2.0 |
def merge_dsl_output_file_parameters_to_executor_output(
executor_input: pipeline_spec_pb2.ExecutorInput,
executor_output: pipeline_spec_pb2.ExecutorOutput,
component_spec: pipeline_spec_pb2.ComponentSpec,
) -> pipeline_spec_pb2.ExecutorOutput:
"""Merges and output parameters specified via dsl.OutputPat... | Merges and output parameters specified via dsl.OutputPath with the rest
of the ExecutorOutput message. | merge_dsl_output_file_parameters_to_executor_output | python | kubeflow/pipelines | sdk/python/kfp/local/executor_output_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_output_utils.py | Apache-2.0 |
def pb2_value_to_python(value: struct_pb2.Value) -> Any:
"""Converts protobuf Value to the corresponding Python type."""
if value.HasField('null_value'):
return None
elif value.HasField('number_value'):
return value.number_value
elif value.HasField('string_value'):
return value.s... | Converts protobuf Value to the corresponding Python type. | pb2_value_to_python | python | kubeflow/pipelines | sdk/python/kfp/local/executor_output_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_output_utils.py | Apache-2.0 |
def runtime_artifact_to_dsl_artifact(
runtime_artifact: pipeline_spec_pb2.RuntimeArtifact) -> dsl.Artifact:
"""Converts a single RuntimeArtifact instance to the corresponding
dsl.Artifact instance."""
return executor.create_artifact_instance(
json_format.MessageToDict(runtime_artifact)) | Converts a single RuntimeArtifact instance to the corresponding
dsl.Artifact instance. | runtime_artifact_to_dsl_artifact | python | kubeflow/pipelines | sdk/python/kfp/local/executor_output_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_output_utils.py | Apache-2.0 |
def artifact_list_to_dsl_artifact(
artifact_list: pipeline_spec_pb2.ArtifactList,
is_artifact_list: bool,
) -> Union[dsl.Artifact, List[dsl.Artifact]]:
"""Converts an ArtifactList instance to a single dsl.Artifact or a list of
dsl.Artifacts, depending on whether the ArtifactList is a true list or
si... | Converts an ArtifactList instance to a single dsl.Artifact or a list of
dsl.Artifacts, depending on whether the ArtifactList is a true list or
simply a container for single artifact element. | artifact_list_to_dsl_artifact | python | kubeflow/pipelines | sdk/python/kfp/local/executor_output_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_output_utils.py | Apache-2.0 |
def add_type_to_executor_output(
executor_input: pipeline_spec_pb2.ExecutorInput,
executor_output: pipeline_spec_pb2.ExecutorOutput,
) -> pipeline_spec_pb2.ExecutorOutput:
"""Adds artifact type information (ArtifactTypeSchema) from the
ExecutorInput message to the ExecutorOutput message.
This infor... | Adds artifact type information (ArtifactTypeSchema) from the
ExecutorInput message to the ExecutorOutput message.
This information is not present in the ExecutorOutput message
written by a task, though it is useful to have it for constructing
local outputs. We don't want to change the executor logic an... | add_type_to_executor_output | python | kubeflow/pipelines | sdk/python/kfp/local/executor_output_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_output_utils.py | Apache-2.0 |
def get_outputs_for_task(
executor_input: pipeline_spec_pb2.ExecutorInput,
component_spec: pipeline_spec_pb2.ComponentSpec,
) -> Dict[str, Any]:
"""Gets outputs from a recently executed task, if available, using the
ExecutorInput and ComponentSpec of the task."""
executor_output = load_executor_outp... | Gets outputs from a recently executed task, if available, using the
ExecutorInput and ComponentSpec of the task. | get_outputs_for_task | python | kubeflow/pipelines | sdk/python/kfp/local/executor_output_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/executor_output_utils.py | Apache-2.0 |
def topological_sort_tasks(
tasks: Dict[str, pipeline_spec_pb2.PipelineTaskSpec]) -> List[str]:
"""Given a dictionary of task name to PipelineTaskSpec, obtains a
topologically sorted stack of task names.
Args:
tasks: The tasks in the pipeline.
Returns:
A totally ordered stack o... | Given a dictionary of task name to PipelineTaskSpec, obtains a
topologically sorted stack of task names.
Args:
tasks: The tasks in the pipeline.
Returns:
A totally ordered stack of tasks. Tasks should be executed in the order they are popped off the right side of the stack.
| topological_sort_tasks | python | kubeflow/pipelines | sdk/python/kfp/local/graph_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/graph_utils.py | Apache-2.0 |
def build_dependency_map(
tasks: Dict[str,
pipeline_spec_pb2.PipelineTaskSpec]) -> Dict[str, List[str]]:
"""Builds a dictionary of task name to all upstream task names
(dependencies). This is a data structure simplification step, which allows
for a general topological_sort sort implement... | Builds a dictionary of task name to all upstream task names
(dependencies). This is a data structure simplification step, which allows
for a general topological_sort sort implementation.
Args:
tasks: The tasks in the pipeline.
Returns:
An dictionary of task name to all upstream tasks. ... | build_dependency_map | python | kubeflow/pipelines | sdk/python/kfp/local/graph_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/graph_utils.py | Apache-2.0 |
def topological_sort(dependency_map: Dict[str, List[str]]) -> List[str]:
"""Topologically sorts a dictionary of task names to upstream tasks.
Args:
dependency_map: A dictionary of tasks name to a list of upstream tasks. The key task depends on all value tasks being executed first.
Returns:
... | Topologically sorts a dictionary of task names to upstream tasks.
Args:
dependency_map: A dictionary of tasks name to a list of upstream tasks. The key task depends on all value tasks being executed first.
Returns:
A totally ordered stack of tasks. Tasks should be executed in the order they ar... | topological_sort | python | kubeflow/pipelines | sdk/python/kfp/local/graph_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/graph_utils.py | Apache-2.0 |
def run_importer(
pipeline_resource_name: str,
component_name: str,
component_spec: pipeline_spec_pb2.ComponentSpec,
executor_spec: pipeline_spec_pb2.PipelineDeploymentConfig.ExecutorSpec,
arguments: Dict[str, Any],
pipeline_root: str,
unique_pipeline_id: str,
) -> Tuple[Outputs, status.Stat... | Runs an importer component and returns a two-tuple of (outputs, status).
Args:
pipeline_resource_name: The root pipeline resource name.
component_name: The name of the component.
component_spec: The ComponentSpec of the importer.
executor_spec: The ExecutorSpec of the importer.
... | run_importer | python | kubeflow/pipelines | sdk/python/kfp/local/importer_handler.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/importer_handler.py | Apache-2.0 |
def put_parent_input(
self,
key: str,
value: Any,
) -> None:
"""Persist the value of a parent component (i.e., parent pipeline)
input.
Args:
key: Parent component input name.
value: Value associated with key.
"""
self._parent_i... | Persist the value of a parent component (i.e., parent pipeline)
input.
Args:
key: Parent component input name.
value: Value associated with key.
| put_parent_input | python | kubeflow/pipelines | sdk/python/kfp/local/io.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/io.py | Apache-2.0 |
def get_parent_input(
self,
key: str,
) -> None:
"""Get the value of the parent component (i.e., parent pipeline) input
named key.
Args:
key: Parent component input name.
Returns:
The output value.
"""
if key in self._parent_i... | Get the value of the parent component (i.e., parent pipeline) input
named key.
Args:
key: Parent component input name.
Returns:
The output value.
| get_parent_input | python | kubeflow/pipelines | sdk/python/kfp/local/io.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/io.py | Apache-2.0 |
def put_task_output(
self,
task_name: str,
key: str,
value: Any,
) -> None:
"""Persist the value of an upstream task output.
Args:
task_name: Upstream task name.
key: Output name.
value: Value associated with key.
"""
... | Persist the value of an upstream task output.
Args:
task_name: Upstream task name.
key: Output name.
value: Value associated with key.
| put_task_output | python | kubeflow/pipelines | sdk/python/kfp/local/io.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/io.py | Apache-2.0 |
def get_task_output(
self,
task_name: str,
key: str,
) -> Any:
"""Get the value of an upstream task output.
Args:
task_name: Upstream task name.
key: Output name.
Returns:
The output value.
"""
common_exception_str... | Get the value of an upstream task output.
Args:
task_name: Upstream task name.
key: Output name.
Returns:
The output value.
| get_task_output | python | kubeflow/pipelines | sdk/python/kfp/local/io.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/io.py | Apache-2.0 |
def local_logger_context() -> Generator[None, None, None]:
"""Context manager for creating and reseting the local execution logger."""
logger = logging.getLogger()
original_level = logger.level
original_handlers = logger.handlers[:]
formatter = MillisecondFormatter(
fmt='%(asctime)s - %(lev... | Context manager for creating and reseting the local execution logger. | local_logger_context | python | kubeflow/pipelines | sdk/python/kfp/local/logging_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/logging_utils.py | Apache-2.0 |
def indented_print(num_spaces: int = 4) -> Generator[None, None, None]:
"""Context manager to indent all print statements in its scope by
num_prints.
Useful for visually separating a subprocess logs from the outer
process logs.
"""
original_print = builtins.print
def indented_print_functio... | Context manager to indent all print statements in its scope by
num_prints.
Useful for visually separating a subprocess logs from the outer
process logs.
| indented_print | python | kubeflow/pipelines | sdk/python/kfp/local/logging_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/logging_utils.py | Apache-2.0 |
def make_log_lines_for_artifact(artifact: dsl.Artifact,) -> List[str]:
"""Returns a list of log lines that represent a single artifact output."""
artifact_class_name_and_paren = f'{artifact.__class__.__name__}( '
# name
artifact_lines = [f"{artifact_class_name_and_paren}name='{artifact.name}',"]
new... | Returns a list of log lines that represent a single artifact output. | make_log_lines_for_artifact | python | kubeflow/pipelines | sdk/python/kfp/local/logging_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/logging_utils.py | Apache-2.0 |
def make_log_lines_for_outputs(outputs: Dict[str, Any]) -> List[str]:
"""Returns a list of log lines to repesent the outputs of a task."""
INDENT = ' ' * 4
SEPARATOR = ': '
output_lines = []
for key, value in outputs.items():
key_chars = INDENT + key + SEPARATOR
# present artifacts
... | Returns a list of log lines to repesent the outputs of a task. | make_log_lines_for_outputs | python | kubeflow/pipelines | sdk/python/kfp/local/logging_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/logging_utils.py | Apache-2.0 |
def run_local_pipeline(
pipeline_spec: pipeline_spec_pb2.PipelineSpec,
arguments: Dict[str, Any],
) -> Dict[str, Any]:
"""kfp.local's entrypoint for running a local pipeline.
Args:
pipeline_spec: PipelineSpec to run.
arguments: User-provided arguments.
Returns:
The pipeline... | kfp.local's entrypoint for running a local pipeline.
Args:
pipeline_spec: PipelineSpec to run.
arguments: User-provided arguments.
Returns:
The pipeline outputs.
| run_local_pipeline | python | kubeflow/pipelines | sdk/python/kfp/local/pipeline_orchestrator.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/pipeline_orchestrator.py | Apache-2.0 |
def _run_local_pipeline_implementation(
pipeline_spec: pipeline_spec_pb2.PipelineSpec,
arguments: Dict[str, Any],
raise_on_error: bool,
pipeline_root: str,
runner: config.LocalRunnerType,
) -> Dict[str, Any]:
"""Implementation of run local pipeline.
Args:
pipeline_spec: PipelineSpec... | Implementation of run local pipeline.
Args:
pipeline_spec: PipelineSpec to run.
arguments: User-provided arguments.
raise_on_error: Whether to raise an exception if a task exits with failure.
pipeline_root: The local pipeline root.
runner: The user-specified local runner.
... | _run_local_pipeline_implementation | python | kubeflow/pipelines | sdk/python/kfp/local/pipeline_orchestrator.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/pipeline_orchestrator.py | Apache-2.0 |
def log_and_maybe_raise_for_failure(
pipeline_name: str,
raise_on_error: bool,
fail_stack: List[str],
) -> None:
"""To be called if an inner pipeline task exits with failure status. Either
logs error or throws exception, depending on raise_on_error.
Args:
pipeline_name: The name of the ... | To be called if an inner pipeline task exits with failure status. Either
logs error or throws exception, depending on raise_on_error.
Args:
pipeline_name: The name of the root pipeline.
raise_on_error: Whether to raise on error.
fail_stack: The stack of task failures, if any, starting w... | log_and_maybe_raise_for_failure | python | kubeflow/pipelines | sdk/python/kfp/local/pipeline_orchestrator.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/pipeline_orchestrator.py | Apache-2.0 |
def replace_placeholders(
full_command: List[str],
executor_input_dict: Dict[str, Any],
pipeline_resource_name: str,
task_resource_name: str,
pipeline_root: str,
unique_pipeline_id: str,
) -> List[str]:
"""Iterates over each element in the command and replaces placeholders.
This should ... | Iterates over each element in the command and replaces placeholders.
This should only be called once per each task, since the task's
random ID is created within the scope of the function. Multiple
calls on the same task will result in multiple random IDs per single
task.
| replace_placeholders | python | kubeflow/pipelines | sdk/python/kfp/local/placeholder_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/placeholder_utils.py | Apache-2.0 |
def resolve_self_references_in_executor_input(
executor_input_dict: Dict[str, Any],
pipeline_resource_name: str,
task_resource_name: str,
pipeline_root: str,
pipeline_job_id: str,
pipeline_task_id: str,
) -> Dict[str, Any]:
"""Resolve parameter placeholders that point to other parameter
... | Resolve parameter placeholders that point to other parameter
placeholders in the same ExecutorInput message.
This occurs when passing f-strings to a component. For example:
my_comp(foo=f'bar-{upstream.output}')
May result in the ExecutorInput message:
{'inputs': {'parameterValues': {'pipelinecha... | resolve_self_references_in_executor_input | python | kubeflow/pipelines | sdk/python/kfp/local/placeholder_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/placeholder_utils.py | Apache-2.0 |
def recursively_resolve_json_dict_placeholders(
obj: Any,
executor_input_dict: Dict[str, Any],
pipeline_resource_name: str,
task_resource_name: str,
pipeline_root: str,
pipeline_job_id: str,
pipeline_task_id: str,
) -> Any:
"""Recursively resolves any placeholders in a dictionary represe... | Recursively resolves any placeholders in a dictionary representation of
a JSON object.
These objects are very unlikely to be sufficiently large to exceed
max recursion depth of 1000 and an iterative implementation is much
less readable, so preferring recursive implementation.
| recursively_resolve_json_dict_placeholders | python | kubeflow/pipelines | sdk/python/kfp/local/placeholder_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/placeholder_utils.py | Apache-2.0 |
def flatten_list(l: List[Union[str, list, None]]) -> List[str]:
"""Iteratively flattens arbitrarily deeply nested lists, filtering out
elements that are None."""
result = []
stack = l.copy()
while stack:
element = stack.pop(0)
if isinstance(element, list):
stack = element... | Iteratively flattens arbitrarily deeply nested lists, filtering out
elements that are None. | flatten_list | python | kubeflow/pipelines | sdk/python/kfp/local/placeholder_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/placeholder_utils.py | Apache-2.0 |
def resolve_io_placeholders(
executor_input: Dict[str, Any],
command: str,
) -> str:
"""Resolves placeholders in command using executor_input.
executor_input should not contain any unresolved placeholders.
"""
placeholders = re.findall(r'\{\{\$\.(.*?)\}\}', command)
# e.g., placeholder = "... | Resolves placeholders in command using executor_input.
executor_input should not contain any unresolved placeholders.
| resolve_io_placeholders | python | kubeflow/pipelines | sdk/python/kfp/local/placeholder_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/placeholder_utils.py | Apache-2.0 |
def resolve_struct_placeholders(
placeholder: str,
provided_inputs: List[str],
) -> List[Any]:
"""Resolves IfPresent and Concat placeholders to an arbitrarily deeply
nested list of strings, which may contain None."""
# throughout, filter out None for the case where IfPresent False and no else
d... | Resolves IfPresent and Concat placeholders to an arbitrarily deeply
nested list of strings, which may contain None. | resolve_struct_placeholders | python | kubeflow/pipelines | sdk/python/kfp/local/placeholder_utils.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/placeholder_utils.py | Apache-2.0 |
def run(self) -> status.Status:
"""Runs the local subprocess and returns the status.
Returns:
Status.
"""
with environment(use_venv=self.runner.use_venv) as py_executable:
full_command = replace_python_executable(
self.full_command,
... | Runs the local subprocess and returns the status.
Returns:
Status.
| run | python | kubeflow/pipelines | sdk/python/kfp/local/subprocess_task_handler.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/subprocess_task_handler.py | Apache-2.0 |
def replace_python_executable(full_command: List[str],
new_executable: str) -> List[str]:
"""Replaces the 'python3' string in each element of the full_command with
the new_executable.
Args:
full_command: Commands and args.
new_executable: The Python executable ... | Replaces the 'python3' string in each element of the full_command with
the new_executable.
Args:
full_command: Commands and args.
new_executable: The Python executable to use for local execution.
Returns:
The updated commands and args.
| replace_python_executable | python | kubeflow/pipelines | sdk/python/kfp/local/subprocess_task_handler.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/subprocess_task_handler.py | Apache-2.0 |
def environment(use_venv: bool) -> str:
"""Context manager that handles the environment used for the subprocess.
Args:
use_venv: Whether to use the virtual environment instead of current environment.
Returns:
The Python executable path to use.
"""
if use_venv:
with tempfile... | Context manager that handles the environment used for the subprocess.
Args:
use_venv: Whether to use the virtual environment instead of current environment.
Returns:
The Python executable path to use.
| environment | python | kubeflow/pipelines | sdk/python/kfp/local/subprocess_task_handler.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/subprocess_task_handler.py | Apache-2.0 |
def run_single_task(
pipeline_spec: pipeline_spec_pb2.PipelineSpec,
arguments: Dict[str, Any],
) -> Dict[str, Any]:
"""Runs a single component from its compiled PipelineSpec.
Args:
pipeline_spec: The PipelineSpec of the component to run.
arguments: The runtime arguments.
Returns:
... | Runs a single component from its compiled PipelineSpec.
Args:
pipeline_spec: The PipelineSpec of the component to run.
arguments: The runtime arguments.
Returns:
A LocalTask instance.
| run_single_task | python | kubeflow/pipelines | sdk/python/kfp/local/task_dispatcher.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/task_dispatcher.py | Apache-2.0 |
def run_single_task_implementation(
pipeline_resource_name: str,
component_name: str,
component_spec: pipeline_spec_pb2.ComponentSpec,
executor_spec: pipeline_spec_pb2.PipelineDeploymentConfig.ExecutorSpec,
arguments: Dict[str, Any],
pipeline_root: str,
runner: config.LocalRunnerType,
ra... | The implementation of a single component runner.
Returns a tuple of (outputs, status). If status is FAILURE, outputs
is an empty dictionary.
| run_single_task_implementation | python | kubeflow/pipelines | sdk/python/kfp/local/task_dispatcher.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/task_dispatcher.py | Apache-2.0 |
def compile_and_load_component(
base_component: dsl.base_component.BaseComponent,
) -> dsl.yaml_component.YamlComponent:
"""Compiles a component to PipelineSpec and reloads it as a
YamlComponent."""
return components.load_component_from_text(
json_format.MessageToJson(base_component.pipeline_spe... | Compiles a component to PipelineSpec and reloads it as a
YamlComponent. | compile_and_load_component | python | kubeflow/pipelines | sdk/python/kfp/local/testing_utilities.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/local/testing_utilities.py | Apache-2.0 |
def _request(self,
request_url: str,
request_body: Optional[str] = '',
http_request: Optional[str] = None,
extra_headers: Optional[dict] = None) -> requests.Response:
"""Calls the HTTP request.
Args:
request_url: The addres... | Calls the HTTP request.
Args:
request_url: The address of the API endpoint to send the request to.
request_body: Body of the request.
http_request: Type of HTTP request (post, get, delete etc, defaults to get).
extra_headers: Any extra headers required.
... | _request | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def _is_ar_host(self) -> bool:
"""Checks if the host is on Artifact Registry.
Returns:
Whether the host is on Artifact Registry.
"""
# TODO: Handle multiple known hosts.
return self._known_host_key == 'kfp_pkg_dev' | Checks if the host is on Artifact Registry.
Returns:
Whether the host is on Artifact Registry.
| _is_ar_host | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def _validate_version(self, version: str) -> None:
"""Validates the version.
Args:
version: Version of the package.
"""
if not version.startswith(_VERSION_PREFIX):
raise ValueError('Version should start with \"sha256:\".') | Validates the version.
Args:
version: Version of the package.
| _validate_version | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def _validate_tag(self, tag: str) -> None:
"""Validates the tag.
Args:
tag: Tag attached to the package.
"""
if tag.startswith(_VERSION_PREFIX):
raise ValueError('Tag should not start with \"sha256:\".') | Validates the tag.
Args:
tag: Tag attached to the package.
| _validate_tag | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def _load_auth(
self,
auth: Optional[Union[requests.auth.AuthBase,
credentials.Credentials]] = None,
auth_file: Optional[str] = None
) -> Optional[Union[requests.auth.AuthBase, credentials.Credentials]]:
"""Loads the credentials for authentication.
... | Loads the credentials for authentication.
Args:
auth: Authentication using ``requests.auth.AuthBase`` or ``google.auth.credentials.Credentials``.
auth_file: The location of the local config file that contains the
authentication token. If not specified, defaults to
... | _load_auth | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def _load_config(self, host: Optional[str],
config_file: Optional[str]) -> dict:
"""Loads the config.
Args:
host: The address of the registry host.
config_file: The location of the local config file. If not specified,
defaults to ``'~/.config... | Loads the config.
Args:
host: The address of the registry host.
config_file: The location of the local config file. If not specified,
defaults to ``'~/.config/kfp/context.json'`` (if it exists).
Returns:
The loaded config.
| _load_config | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def _load_context(self,
config_file: str,
config: Optional[dict] = None) -> dict:
"""Loads the context from the given config_file.
Args:
config_file: The location of the config file.
config: An existing config to set as the default con... | Loads the context from the given config_file.
Args:
config_file: The location of the config file.
config: An existing config to set as the default config.
Returns:
The loaded config.
| _load_context | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def _get_auth(
self
) -> Optional[Union[requests.auth.AuthBase, credentials.Credentials]]:
"""Helper function to convert google credentials to AuthBase class if
needed.
Returns:
An instance of the AuthBase class
"""
auth = self._auth
if isinstance... | Helper function to convert google credentials to AuthBase class if
needed.
Returns:
An instance of the AuthBase class
| _get_auth | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def _refresh_creds(self) -> None:
"""Helper function to refresh google credentials if needed."""
if self._is_ar_host() and isinstance(
self._auth, credentials.Credentials) and not self._auth.valid:
self._auth.refresh(google.auth.transport.requests.Request()) | Helper function to refresh google credentials if needed. | _refresh_creds | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def upload_pipeline(
self,
file_name: str,
tags: Optional[Union[str, List[str]]] = None,
extra_headers: Optional[dict] = None) -> Tuple[str, str]:
"""Uploads the pipeline.
Args:
file_name: The name of the file to be uploaded.
tags:... | Uploads the pipeline.
Args:
file_name: The name of the file to be uploaded.
tags: Tags to be attached to the uploaded pipeline.
extra_headers: Any extra headers required.
Returns:
A tuple of the package name and the version.
| upload_pipeline | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def _get_download_url(self,
package_name: str,
version: Optional[str] = None,
tag: Optional[str] = None) -> str:
"""Gets the download url based on version or tag (either one must be
specified).
Args:
packa... | Gets the download url based on version or tag (either one must be
specified).
Args:
package_name: Name of the package.
version: Version of the package.
tag: Tag attached to the package.
Returns:
A url for downloading the package.
| _get_download_url | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def download_pipeline(self,
package_name: str,
version: Optional[str] = None,
tag: Optional[str] = None,
file_name: Optional[str] = None) -> str:
"""Downloads a pipeline. Either version or tag must be specifi... | Downloads a pipeline. Either version or tag must be specified.
Args:
package_name: Name of the package.
version: Version of the package.
tag: Tag attached to the package.
file_name: File name to be saved as. If not specified, the
file name will be... | download_pipeline | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def get_package(self, package_name: str) -> Dict[str, Any]:
"""Gets package metadata.
Args:
package_name: Name of the package.
Returns:
The package metadata.
"""
url = self._config['get_package_url'].format(package_name=package_name)
response = s... | Gets package metadata.
Args:
package_name: Name of the package.
Returns:
The package metadata.
| get_package | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def list_packages(self) -> List[dict]:
"""Lists packages.
Returns:
List of packages in the repository.
"""
url = self._config['list_packages_url']
response = self._request(request_url=url)
response_json = response.json()
return response_json.get('pac... | Lists packages.
Returns:
List of packages in the repository.
| list_packages | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def delete_package(self, package_name: str) -> bool:
"""Deletes a package.
Args:
package_name: Name of the package.
Returns:
Whether the package was deleted successfully.
"""
url = self._config['delete_package_url'].format(
package_name=packa... | Deletes a package.
Args:
package_name: Name of the package.
Returns:
Whether the package was deleted successfully.
| delete_package | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def get_version(self, package_name: str, version: str) -> Dict[str, Any]:
"""Gets package version metadata.
Args:
package_name: Name of the package.
version: Version of the package.
Returns:
The version metadata.
"""
self._validate_version(ve... | Gets package version metadata.
Args:
package_name: Name of the package.
version: Version of the package.
Returns:
The version metadata.
| get_version | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def list_versions(self, package_name: str) -> List[dict]:
"""Lists package versions.
Args:
package_name: Name of the package.
Returns:
List of package versions.
"""
url = self._config['list_versions_url'].format(
package_name=package_name)
... | Lists package versions.
Args:
package_name: Name of the package.
Returns:
List of package versions.
| list_versions | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def delete_version(self, package_name: str, version: str) -> bool:
"""Deletes package version.
Args:
package_name: Name of the package.
version: Version of the package.
Returns:
Whether the version was deleted successfully.
"""
self._validate... | Deletes package version.
Args:
package_name: Name of the package.
version: Version of the package.
Returns:
Whether the version was deleted successfully.
| delete_version | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def create_tag(self, package_name: str, version: str,
tag: str) -> Dict[str, Any]:
"""Creates a tag on a package version.
Args:
package_name: Name of the package.
version: Version of the package.
tag: Tag to be attached to the package version.
... | Creates a tag on a package version.
Args:
package_name: Name of the package.
version: Version of the package.
tag: Tag to be attached to the package version.
Returns:
Metadata for the created tag.
| create_tag | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def get_tag(self, package_name: str, tag: str) -> Dict[str, Any]:
"""Gets tag metadata.
Args:
package_name: Name of the package.
tag: Tag attached to the package version.
Returns:
The metadata for the tag.
"""
self._validate_tag(tag)
... | Gets tag metadata.
Args:
package_name: Name of the package.
tag: Tag attached to the package version.
Returns:
The metadata for the tag.
| get_tag | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def update_tag(self, package_name: str, version: str,
tag: str) -> Dict[str, Any]:
"""Updates a tag to another package version.
Args:
package_name: Name of the package.
version: Version of the package.
tag: Tag to be attached to the new package ver... | Updates a tag to another package version.
Args:
package_name: Name of the package.
version: Version of the package.
tag: Tag to be attached to the new package version.
Returns:
The metadata for the updated tag.
| update_tag | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def list_tags(self, package_name: str) -> List[dict]:
"""Lists package tags.
Args:
package_name: Name of the package.
Returns:
List of tags.
"""
url = self._config['list_tags_url'].format(package_name=package_name)
response = self._request(reques... | Lists package tags.
Args:
package_name: Name of the package.
Returns:
List of tags.
| list_tags | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def delete_tag(self, package_name: str, tag: str) -> Dict[str, Any]:
"""Deletes package tag.
Args:
package_name: Name of the package.
tag: Tag to be deleted.
Returns:
Response from the delete request.
"""
self._validate_tag(tag)
url =... | Deletes package tag.
Args:
package_name: Name of the package.
tag: Tag to be deleted.
Returns:
Response from the delete request.
| delete_tag | python | kubeflow/pipelines | sdk/python/kfp/registry/registry_client.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/kfp/registry/registry_client.py | Apache-2.0 |
def dataset_joiner(
dataset_a: Input[Dataset],
dataset_b: Input[Dataset],
out_dataset: Output[Dataset],
) -> str:
"""Concatenate dataset_a and dataset_b.
Also returns the concatenated string.
Args:
dataset_a: First dataset.
dataset_b: Second dataset.
Returns:
out_d... | Concatenate dataset_a and dataset_b.
Also returns the concatenated string.
Args:
dataset_a: First dataset.
dataset_b: Second dataset.
Returns:
out_dataset: The concatenated dataset.
Output: The concatenated string.
| dataset_joiner | python | kubeflow/pipelines | sdk/python/test_data/components/component_with_metadata_fields.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/test_data/components/component_with_metadata_fields.py | Apache-2.0 |
def create_temporary_google_artifact_package(
temp_dir: tempfile.TemporaryDirectory) -> None:
"""Creates a fake temporary module that can be used as a Vertex SDK mock
for testing purposes."""
import inspect
import os
import textwrap
from kfp import dsl
class VertexModel(dsl.Artifac... | Creates a fake temporary module that can be used as a Vertex SDK mock
for testing purposes. | create_temporary_google_artifact_package | python | kubeflow/pipelines | sdk/python/test_data/pipelines/pipeline_with_google_artifact_type.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/test_data/pipelines/pipeline_with_google_artifact_type.py | Apache-2.0 |
def dataset_concatenator(
string: str,
in_dataset: Input[Dataset],
) -> Dataset:
"""Pipeline to convert string to a Dataset, then concatenate with
in_dataset.
Args:
string: String to concatenate to in_artifact.
in_dataset: Dataset to which to concatenate string.
Returns:
... | Pipeline to convert string to a Dataset, then concatenate with
in_dataset.
Args:
string: String to concatenate to in_artifact.
in_dataset: Dataset to which to concatenate string.
Returns:
Output: The final concatenated dataset.
| dataset_concatenator | python | kubeflow/pipelines | sdk/python/test_data/pipelines/pipeline_with_metadata_fields.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/test_data/pipelines/pipeline_with_metadata_fields.py | Apache-2.0 |
def random_num_op(low, high):
"""Generate a random number between low and high."""
return components.load_component_from_text("""
name: Generate random number
outputs:
- {name: output, type: Integer}
implementation:
container:
image: python:alpine3.9
command:
... | Generate a random number between low and high. | random_num_op | python | kubeflow/pipelines | sdk/python/test_data/pipelines/pipeline_with_nested_conditions_yaml.py | https://github.com/kubeflow/pipelines/blob/master/sdk/python/test_data/pipelines/pipeline_with_nested_conditions_yaml.py | Apache-2.0 |
async def test(test_case: TestCase) -> None:
"""Asynchronously runs all samples and test that they succeed."""
event_loop = asyncio.get_running_loop()
try:
run_url, run_result = run(test_case)
except Exception as e:
raise RuntimeError(
f'Error triggering pipeline {test_case.n... | Asynchronously runs all samples and test that they succeed. | test | python | kubeflow/pipelines | test/kfp-kubernetes-execution-tests/sdk_execution_tests.py | https://github.com/kubeflow/pipelines/blob/master/test/kfp-kubernetes-execution-tests/sdk_execution_tests.py | Apache-2.0 |
def run(self):
""" Run the notebook sample as a python script. """
self._exit_code = str(
subprocess.call(['ipython', '%s.py' % self._testname])) | Run the notebook sample as a python script. | run | python | kubeflow/pipelines | test/sample-test/check_notebook_results.py | https://github.com/kubeflow/pipelines/blob/master/test/sample-test/check_notebook_results.py | Apache-2.0 |
def check(self):
""" Check the pipeline running results of the notebook sample. """
test_cases = []
test_name = self._testname + ' Sample Test'
###### Write the script exit code log ######
utils.add_junit_test(test_cases, 'test script execution',
(se... | Check the pipeline running results of the notebook sample. | check | python | kubeflow/pipelines | test/sample-test/check_notebook_results.py | https://github.com/kubeflow/pipelines/blob/master/test/sample-test/check_notebook_results.py | Apache-2.0 |
def __init__(self,
test_name,
results_gcs_dir,
host='',
target_image_prefix='',
namespace='kubeflow',
expected_result='succeeded'):
"""Launch a KFP sample_test provided its name.
:param test_name: name... | Launch a KFP sample_test provided its name.
:param test_name: name of the corresponding sample test.
:param results_gcs_dir: gs dir to store test result.
:param host: host of KFP API endpoint, default is auto-discovery from inverse-proxy-config.
:param target_image_prefix: prefix of doc... | __init__ | python | kubeflow/pipelines | test/sample-test/sample_test_launcher.py | https://github.com/kubeflow/pipelines/blob/master/test/sample-test/sample_test_launcher.py | Apache-2.0 |
def _injection(self):
"""Sample-specific image injection into yaml file."""
subs = { # Tag can look like 1.0.0-rc.3, so we need both "-" and "." in the regex.
r'gcr\.io/ml-pipeline/ml-pipeline/ml-pipeline-local-confusion-matrix:(\w+|[.-])+':
self._local_confusionmatrix_image... | Sample-specific image injection into yaml file. | _injection | python | kubeflow/pipelines | test/sample-test/sample_test_launcher.py | https://github.com/kubeflow/pipelines/blob/master/test/sample-test/sample_test_launcher.py | Apache-2.0 |
def file_injection(file_in, tmp_file_out, subs):
"""Utility function that substitute several regex within a file by
corresponding string.
:param file_in: input file name.
:param tmp_file_out: tmp output file name.
:param subs: dict, key is the regex expr, value is the substituting string.
"""
with open(f... | Utility function that substitute several regex within a file by
corresponding string.
:param file_in: input file name.
:param tmp_file_out: tmp output file name.
:param subs: dict, key is the regex expr, value is the substituting string.
| file_injection | python | kubeflow/pipelines | test/sample-test/utils.py | https://github.com/kubeflow/pipelines/blob/master/test/sample-test/utils.py | Apache-2.0 |
def __init__(self, in_features, out_features, loss_type='arcface', eps=1e-7, s=None, m=None):
'''
Angular Penalty Softmax Loss
Three 'loss_types' available: ['arcface', 'sphereface', 'cosface']
These losses are described in the following papers:
ArcFace: https://arxiv.... |
Angular Penalty Softmax Loss
Three 'loss_types' available: ['arcface', 'sphereface', 'cosface']
These losses are described in the following papers:
ArcFace: https://arxiv.org/abs/1801.07698
SphereFace: https://arxiv.org/abs/1704.08063
CosFace/Ad Margin: https:... | __init__ | python | cvqluu/Angular-Penalty-Softmax-Losses-Pytorch | loss_functions.py | https://github.com/cvqluu/Angular-Penalty-Softmax-Losses-Pytorch/blob/master/loss_functions.py | MIT |
def bsearch(nums: List[int], target: int) -> int:
"""Binary search of a target in a sorted array
without duplicates. If such a target does not exist,
return -1, othewise, return its index.
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[m... | Binary search of a target in a sorted array
without duplicates. If such a target does not exist,
return -1, othewise, return its index.
| bsearch | python | wangzheng0822/algo | python/15_bsearch/bsearch.py | https://github.com/wangzheng0822/algo/blob/master/python/15_bsearch/bsearch.py | Apache-2.0 |
def bsearch_left(nums: List[int], target: int) -> int:
"""Binary search of the index of the first element
equal to a given target in the ascending sorted array.
If not found, return -1.
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[mid]... | Binary search of the index of the first element
equal to a given target in the ascending sorted array.
If not found, return -1.
| bsearch_left | python | wangzheng0822/algo | python/16_bsearch/bsearch_variants.py | https://github.com/wangzheng0822/algo/blob/master/python/16_bsearch/bsearch_variants.py | Apache-2.0 |
def bsearch_right(nums: List[int], target: int) -> int:
"""Binary search of the index of the last element
equal to a given target in the ascending sorted array.
If not found, return -1.
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[mid]... | Binary search of the index of the last element
equal to a given target in the ascending sorted array.
If not found, return -1.
| bsearch_right | python | wangzheng0822/algo | python/16_bsearch/bsearch_variants.py | https://github.com/wangzheng0822/algo/blob/master/python/16_bsearch/bsearch_variants.py | Apache-2.0 |
def bsearch_left_not_less(nums: List[int], target: int) -> int:
"""Binary search of the index of the first element
not less than a given target in the ascending sorted array.
If not found, return -1.
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
... | Binary search of the index of the first element
not less than a given target in the ascending sorted array.
If not found, return -1.
| bsearch_left_not_less | python | wangzheng0822/algo | python/16_bsearch/bsearch_variants.py | https://github.com/wangzheng0822/algo/blob/master/python/16_bsearch/bsearch_variants.py | Apache-2.0 |
def bsearch_right_not_greater(nums: List[int], target: int) -> int:
"""Binary search of the index of the last element
not greater than a given target in the ascending sorted array.
If not found, return -1.
"""
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
... | Binary search of the index of the last element
not greater than a given target in the ascending sorted array.
If not found, return -1.
| bsearch_right_not_greater | python | wangzheng0822/algo | python/16_bsearch/bsearch_variants.py | https://github.com/wangzheng0822/algo/blob/master/python/16_bsearch/bsearch_variants.py | Apache-2.0 |
def randomLevel(self, p=0.25):
'''
#define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
https://github.com/antirez/redis/blob/unstable/src/t_zset.c
'''
high = 1
for _ in range(self.__MAX_LEVEL - 1):
if random.random() < p:
high += 1
ret... |
#define ZSKIPLIST_P 0.25 /* Skiplist P = 1/4 */
https://github.com/antirez/redis/blob/unstable/src/t_zset.c
| randomLevel | python | wangzheng0822/algo | python/17_skiplist/skip_list_comments.py | https://github.com/wangzheng0822/algo/blob/master/python/17_skiplist/skip_list_comments.py | Apache-2.0 |
def build_heap(cls, a: List[int]) -> None:
"""Data in a needs to start from index 1."""
for i in range((len(a) - 1)//2, 0, -1):
cls._siftdown(a, len(a) - 1, i) | Data in a needs to start from index 1. | build_heap | python | wangzheng0822/algo | python/28_heap/heap.py | https://github.com/wangzheng0822/algo/blob/master/python/28_heap/heap.py | Apache-2.0 |
def bfs(self, s: int, t: int) -> IO[str]:
"""Print out the path from Vertex s to Vertex t
using bfs.
"""
if s == t: return
visited = [False] * self._num_vertices
visited[s] = True
q = deque()
q.append(s)
prev = [None] * self._num_vertices
... | Print out the path from Vertex s to Vertex t
using bfs.
| bfs | python | wangzheng0822/algo | python/31_bfs_dfs/bfs_dfs.py | https://github.com/wangzheng0822/algo/blob/master/python/31_bfs_dfs/bfs_dfs.py | Apache-2.0 |
def dfs(self, s: int, t: int) -> IO[str]:
"""Print out a path from Vertex s to Vertex t
using dfs.
"""
found = False
visited = [False] * self._num_vertices
prev = [None] * self._num_vertices
def _dfs(from_vertex: int) -> None:
nonlocal found
... | Print out a path from Vertex s to Vertex t
using dfs.
| dfs | python | wangzheng0822/algo | python/31_bfs_dfs/bfs_dfs.py | https://github.com/wangzheng0822/algo/blob/master/python/31_bfs_dfs/bfs_dfs.py | Apache-2.0 |
def min_dist(weights: List[List[int]]) -> int:
"""Find the minimum weight path from the weights matrix."""
m, n = len(weights), len(weights[0])
table = [[0] * n for _ in range(m)]
# table[i][j] is the minimum distance (weight) when
# there are i vertical moves and j horizontal moves
# left.
... | Find the minimum weight path from the weights matrix. | min_dist | python | wangzheng0822/algo | python/41_dynamic_programming/min_dist.py | https://github.com/wangzheng0822/algo/blob/master/python/41_dynamic_programming/min_dist.py | Apache-2.0 |
def print_(*args, **kwargs):
"""Wrapper function for py3 to print, with a utf-8 encoded stdout"""
if kwargs.get('file') == sys.stderr:
kwargs['file'] = _py3_utf8_stderr
else:
kwargs['file'] = kwargs.get('file', _py3_utf8_stdout)
_py3_print(*args, **kwargs) | Wrapper function for py3 to print, with a utf-8 encoded stdout | print_ | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def to_utf8(v):
"""Encode value to utf-8 if possible for py2"""
try:
return v.encode('utf8', 'strict')
except AttributeError:
return v | Encode value to utf-8 if possible for py2 | to_utf8 | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def print_(*args, **kwargs):
"""The new-style print function for Python 2.4 and 2.5.
Taken from https://pypi.python.org/pypi/six/
Modified to set encoding to UTF-8 always, and to flush after write
"""
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return... | The new-style print function for Python 2.4 and 2.5.
Taken from https://pypi.python.org/pypi/six/
Modified to set encoding to UTF-8 always, and to flush after write
| print_ | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
source_address=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parame... | Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the... | create_connection | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def _build_connection(connection, source_address, timeout, context=None):
"""Cross Python 2.4 - Python 3 callable to build an ``HTTPConnection`` or
``HTTPSConnection`` with the args we need
Called from ``http(s)_open`` methods of ``SpeedtestHTTPHandler`` or
``SpeedtestHTTPSHandler``
"""
def inn... | Cross Python 2.4 - Python 3 callable to build an ``HTTPConnection`` or
``HTTPSConnection`` with the args we need
Called from ``http(s)_open`` methods of ``SpeedtestHTTPHandler`` or
``SpeedtestHTTPSHandler``
| _build_connection | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def build_opener(source_address=None, timeout=10):
"""Function similar to ``urllib2.build_opener`` that will build
an ``OpenerDirector`` with the explicit handlers we want,
``source_address`` for binding, ``timeout`` and our custom
`User-Agent`
"""
printer('Timeout set to %d' % timeout, debug=T... | Function similar to ``urllib2.build_opener`` that will build
an ``OpenerDirector`` with the explicit handlers we want,
``source_address`` for binding, ``timeout`` and our custom
`User-Agent`
| build_opener | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def distance(origin, destination):
"""Determine distance between 2 sets of [lat,lon] in km"""
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
math.cos(... | Determine distance between 2 sets of [lat,lon] in km | distance | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def build_request(url, data=None, headers=None, bump='0', secure=False):
"""Build a urllib2 request object
This function automatically adds a User-Agent header to all requests
"""
if not headers:
headers = {}
if url[0] == ':':
scheme = ('http', 'https')[bool(secure)]
sche... | Build a urllib2 request object
This function automatically adds a User-Agent header to all requests
| build_request | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def catch_request(request, opener=None):
"""Helper function to catch common exceptions encountered when
establishing a connection with a HTTP/HTTPS request
"""
if opener:
_open = opener.open
else:
_open = urlopen
try:
uh = _open(request)
if request.get_full_url... | Helper function to catch common exceptions encountered when
establishing a connection with a HTTP/HTTPS request
| catch_request | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def get_response_stream(response):
"""Helper function to return either a Gzip reader if
``Content-Encoding`` is ``gzip`` otherwise the response itself
"""
try:
getheader = response.headers.getheader
except AttributeError:
getheader = response.getheader
if getheader('content-en... | Helper function to return either a Gzip reader if
``Content-Encoding`` is ``gzip`` otherwise the response itself
| get_response_stream | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def print_dots(shutdown_event):
"""Built in callback function used by Thread classes for printing
status
"""
def inner(current, total, start=False, end=False):
if event_is_set(shutdown_event):
return
sys.stdout.write('.')
if current + 1 == total and end is True:
... | Built in callback function used by Thread classes for printing
status
| print_dots | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def share(self):
"""POST data to the speedtest.net API to obtain a share results
link
"""
if self._share:
return self._share
download = int(round(self.download / 1000.0, 0))
ping = int(round(self.ping, 0))
upload = int(round(self.upload / 1000.0, 0))... | POST data to the speedtest.net API to obtain a share results
link
| share | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def get_config(self):
"""Download the speedtest.net configuration and return only the data
we are interested in
"""
headers = {}
if gzip:
headers['Accept-Encoding'] = 'gzip'
request = build_request('://www.speedtest.net/speedtest-config.php',
... | Download the speedtest.net configuration and return only the data
we are interested in
| get_config | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def get_servers(self, servers=None, exclude=None):
"""Retrieve a the list of speedtest.net servers, optionally filtered
to servers matching those specified in the ``servers`` argument
"""
if servers is None:
servers = []
if exclude is None:
exclude = []
... | Retrieve a the list of speedtest.net servers, optionally filtered
to servers matching those specified in the ``servers`` argument
| get_servers | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def set_mini_server(self, server):
"""Instead of querying for a list of servers, set a link to a
speedtest mini server
"""
urlparts = urlparse(server)
name, ext = os.path.splitext(urlparts[2])
if ext:
url = os.path.dirname(server)
else:
u... | Instead of querying for a list of servers, set a link to a
speedtest mini server
| set_mini_server | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.