Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
30
32
content
stringlengths
139
2.8k
codereview_new_python_data_157
import shutil import os -FILE_TO_DOWNLOAD = "https://searchfox.org/mozilla-central/source/toolkit/components/passwordmgr/LoginManager.shared.mjs" -REAL_FILE_NAME = "LoginManagerShared.mjs" TEMP_FILE_NAME_APPEND = "TEMP_DOWNLOADED_FILE" GITHUB_ACTIONS_PATH = "./Client/Assets/CC_Script/" TEMP_FILE_PATH = GITHUB_ACTIONS_PATH + TEMP_FILE_NAME_APPEND my bad, I've provided link to searchfox GUI page, not directly to the raw file here is the good link https://hg.mozilla.org/mozilla-central/raw-file/tip/toolkit/components/passwordmgr/LoginManager.shared.mjs import shutil import os +FILE_TO_DOWNLOAD = "https://hg.mozilla.org/mozilla-central/raw-file/tip/toolkit/components/passwordmgr/LoginManager.shared.mjs" +REAL_FILE_NAME = "LoginManager.shared.mjs" TEMP_FILE_NAME_APPEND = "TEMP_DOWNLOADED_FILE" GITHUB_ACTIONS_PATH = "./Client/Assets/CC_Script/" TEMP_FILE_PATH = GITHUB_ACTIONS_PATH + TEMP_FILE_NAME_APPEND
codereview_new_python_data_158
import shutil import os -FILE_TO_DOWNLOAD = "https://searchfox.org/mozilla-central/source/toolkit/components/passwordmgr/LoginManager.shared.mjs" -REAL_FILE_NAME = "LoginManagerShared.mjs" TEMP_FILE_NAME_APPEND = "TEMP_DOWNLOADED_FILE" GITHUB_ACTIONS_PATH = "./Client/Assets/CC_Script/" TEMP_FILE_PATH = GITHUB_ACTIONS_PATH + TEMP_FILE_NAME_APPEND nit: can we keep `.shared.mjs` extension? We may add a bunch of more "shared" files over time and it will be easier if we can keep the pattern across repos import shutil import os +FILE_TO_DOWNLOAD = "https://hg.mozilla.org/mozilla-central/raw-file/tip/toolkit/components/passwordmgr/LoginManager.shared.mjs" +REAL_FILE_NAME = "LoginManager.shared.mjs" TEMP_FILE_NAME_APPEND = "TEMP_DOWNLOADED_FILE" GITHUB_ACTIONS_PATH = "./Client/Assets/CC_Script/" TEMP_FILE_PATH = GITHUB_ACTIONS_PATH + TEMP_FILE_NAME_APPEND
codereview_new_python_data_869
#!/usr/bin/env python -# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. ```suggestion # Copyright 2022 Google LLC ``` #!/usr/bin/env python +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
codereview_new_python_data_870
#!/usr/bin/env python -# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. Is this script product specific? If not, I should look into consolidating these scripts into one script – Perf/Sessions/Crashlytics/etc share the same script in a ProtoSupport directory at the root level #!/usr/bin/env python +# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
codereview_new_python_data_2919
def sign(self, cookie): url = "https://pc.ccava.net/zb_users/plugin/mochu_us/cmd.php?act=qiandao" res = requests.get(url, headers={"Cookie": cookie}).json() if "登录" in res["msg"]: - msg = "cookie 失效" elif "今天" in res["msg"]: - msg = f'重复签到, 剩余 {res["giod"]} 月光币' else: - msg = f'签到成功, 剩余 {res["giod"]} 月光币' - return msg def main(self): msg_all = "" Function `CCAVA.sign` refactored with the following changes: - Lift return into if ([`lift-return-into-if`](https://docs.sourcery.ai/Reference/Built-in-Rules/refactorings/lift-return-into-if/)) def sign(self, cookie): url = "https://pc.ccava.net/zb_users/plugin/mochu_us/cmd.php?act=qiandao" res = requests.get(url, headers={"Cookie": cookie}).json() if "登录" in res["msg"]: + return "cookie 失效" elif "今天" in res["msg"]: + return f'重复签到, 剩余 {res["giod"]} 月光币' else: + return f'签到成功, 剩余 {res["giod"]} 月光币' def main(self): msg_all = ""
codereview_new_python_data_3841
SUPPORTED_FUNCTIONS = [ "abs", "acos", There should be some comments to help people know this file is auto generated. Would be better to mention how it's generated. +###################################################################### +# NOTE: This file is auto-generated by gen_function_list.sh. +# Do not edit this file directly. +###################################################################### SUPPORTED_FUNCTIONS = [ "abs", "acos",
codereview_new_python_data_3843
"avro<=1.11.1", "azure-storage-file-datalake<=12.5.0", "azure-synapse-spark<=0.7.0", # fixing Azure Machine Learning authentication issue per https://stackoverflow.com/a/72262694/3193073 - "aiohttp==3.8.3", # pin to resolve Synapse import issue "azure-identity>=1.8.0", "azure-keyvault-secrets<=4.6.0", # In 1.23.0, azure-core is using ParamSpec which might cause issues in some of the databricks runtime. Can you elaborate a bit more on this? What is the specific issue? "avro<=1.11.1", "azure-storage-file-datalake<=12.5.0", "azure-synapse-spark<=0.7.0", + # Synapse's aiohttp package is old and does not work with Feathr. We pin to a newer version here. + "aiohttp==3.8.3", # fixing Azure Machine Learning authentication issue per https://stackoverflow.com/a/72262694/3193073 "azure-identity>=1.8.0", "azure-keyvault-secrets<=4.6.0", # In 1.23.0, azure-core is using ParamSpec which might cause issues in some of the databricks runtime.
codereview_new_python_data_3844
def __init__(self, config_path:str = "./feathr_config.yaml", local_workspace_dir registry_delimiter = self.envutils.get_environment_variable_with_default('feature_registry', 'purview', 'delimiter') # initialize the registry no matter whether we set purview name or not, given some of the methods are used there. self.registry = _PurviewRegistry(self.project_name, azure_purview_name, registry_delimiter, project_registry_tag, config_path = config_path, credential=credential) - logger.warning("FEATURE_REGISTRY__PURVIEW__PURVIEW_NAME deprecated soon. Please use FEATURE_REGISTRY__API_ENDPOINT instead.") else: # no registry configured logger.info("Feathr registry is not configured. Consider setting the Feathr registry component for richer feature store experience.") deprecated soon => will be deprecated soon def __init__(self, config_path:str = "./feathr_config.yaml", local_workspace_dir registry_delimiter = self.envutils.get_environment_variable_with_default('feature_registry', 'purview', 'delimiter') # initialize the registry no matter whether we set purview name or not, given some of the methods are used there. self.registry = _PurviewRegistry(self.project_name, azure_purview_name, registry_delimiter, project_registry_tag, config_path = config_path, credential=credential) + logger.warning("FEATURE_REGISTRY__PURVIEW__PURVIEW_NAME will be deprecated soon. Please use FEATURE_REGISTRY__API_ENDPOINT instead.") else: # no registry configured logger.info("Feathr registry is not configured. Consider setting the Feathr registry component for richer feature store experience.")
codereview_new_python_data_3845
def add_new_dropoff_and_fare_amount_column(df: DataFrame): client.build_features(anchor_list=[agg_anchor, request_anchor], derived_feature_list=derived_feature_list) return client -def registry_test_setup_update(config_path: str, project_name: str): now = datetime.now() os.environ["project_config__project_name"] = project_name suggest change registry_test_setup_update to registry_test_setup_for_409 def add_new_dropoff_and_fare_amount_column(df: DataFrame): client.build_features(anchor_list=[agg_anchor, request_anchor], derived_feature_list=derived_feature_list) return client +def registry_test_setup_for_409(config_path: str, project_name: str): now = datetime.now() os.environ["project_config__project_name"] = project_name
codereview_new_python_data_3846
def _upload_single_entity(self, entity:AtlasEntity): else: raise ConflictError("The requested entity %s conflicts with the existing entity in PurView" % j["attributes"]["qualifiedName"]) except AtlasException as e: - print("XXXXXX", e) pass entity.lastModifiedTS="0" Should clean up this? def _upload_single_entity(self, entity:AtlasEntity): else: raise ConflictError("The requested entity %s conflicts with the existing entity in PurView" % j["attributes"]["qualifiedName"]) except AtlasException as e: pass entity.lastModifiedTS="0"
codereview_new_python_data_3847
def get_result_df(client: FeathrClient, format: str = None, res_url: str = None, def copy_files(client: FeathrClient, source_url: str, target_url: str = None): source_url: str = source_url or client.get_job_result_uri(block=True, timeout_sec=1200) - if source_url is None or target_url is None: raise RuntimeError("source_url None. Please make sure either you provide a source_url or make sure the job finished in FeathrClient has a valid result URI.") client.feathr_spark_launcher.copy_files(source_url, target_url) -def dir_exsits(client: FeathrClient, dir_path: str) -> bool: - return client.feathr_spark_launcher.dir_exists(dir_path) \ No newline at end of file \ No newline at end of file One of source_url or target_url is None. Please make sure either you provide a source_url or make sure the job finished in FeathrClient has a valid result URI. def get_result_df(client: FeathrClient, format: str = None, res_url: str = None, def copy_files(client: FeathrClient, source_url: str, target_url: str = None): source_url: str = source_url or client.get_job_result_uri(block=True, timeout_sec=1200) + if source_url is None: raise RuntimeError("source_url None. Please make sure either you provide a source_url or make sure the job finished in FeathrClient has a valid result URI.") + if target_url is None: + raise RuntimeError("target_url None. Please make sure you provide a target_url.") client.feathr_spark_launcher.copy_files(source_url, target_url) \ No newline at end of file +def cloud_dir_exsits(client: FeathrClient, dir_path: str) -> bool: + return client.feathr_spark_launcher.cloud_dir_exists(dir_path) \ No newline at end of file
codereview_new_python_data_3848
class MaterializationSettings: sinks: sinks where the materialized features should be written to feature_names: list of feature names to be materialized backfill_time: time range and frequency for the materialization. Default to now(). """ def __init__(self, name: str, sinks: List[Sink], feature_names: List[str], backfill_time: Optional[BackfillTime] = None, resolution: str = "DAILY"): if resolution not in ["DAILY", "HOURLY"]: add docstring for resolution here class MaterializationSettings: sinks: sinks where the materialized features should be written to feature_names: list of feature names to be materialized backfill_time: time range and frequency for the materialization. Default to now(). + resolution: time interval for output directories. Only support 'DAILY' and 'HOURLY' for now (DAILY by default). + If 'DAILY', output paths should be: yyyy/MM/dd; + Otherwise would be: yyyy/MM/dd/HH """ def __init__(self, name: str, sinks: List[Sink], feature_names: List[str], backfill_time: Optional[BackfillTime] = None, resolution: str = "DAILY"): if resolution not in ["DAILY", "HOURLY"]:
codereview_new_python_data_3849
def wait_for_completion(self, timeout_seconds: Optional[float]) -> bool: logger.error("Feathr job has failed.") error_msg = self._api.get_driver_log(self.current_job_info.id).decode('utf-8') logger.error(error_msg) - logger.error("The size of the whole error log is: {}. It can be larger than size limit of log. If you cannot see the whole log, you may either extend setting for size limit, or follow the link above to check it.", len(error_msg)) return False else: time.sleep(30) logger.error("The size of the whole error log is: {}. The logs might be truncated in some cases (such as in Visual Studio Code) so only the top a few lines of the error message is displayed. If you cannot see the whole log, you may want to extend the setting for output size limit.", len(error_msg)) def wait_for_completion(self, timeout_seconds: Optional[float]) -> bool: logger.error("Feathr job has failed.") error_msg = self._api.get_driver_log(self.current_job_info.id).decode('utf-8') logger.error(error_msg) + logger.error("The size of the whole error log is: {}. The logs might be truncated in some cases (such as in Visual Studio Code) so only the top a few lines of the error message is displayed. If you cannot see the whole log, you may want to extend the setting for output size limit.", len(error_msg)) return False else: time.sleep(30)
codereview_new_python_data_3850
def delete_entity(entity: str): downstream_entities = registry.get_dependent_entities(entity_id) if len(downstream_entities) > 0: raise HTTPException( - status_code=500, detail=f"""Entity cannot be deleted as it has downstream/dependent entities. Entities: {list([e.qualified_name for e in downstream_entities])}""" ) registry.delete_entity(entity_id) Better to use a status code other than 500, my recommendation is "412 precondition failed". def delete_entity(entity: str): downstream_entities = registry.get_dependent_entities(entity_id) if len(downstream_entities) > 0: raise HTTPException( + status_code=412, detail=f"""Entity cannot be deleted as it has downstream/dependent entities. Entities: {list([e.qualified_name for e in downstream_entities])}""" ) registry.delete_entity(entity_id)
codereview_new_python_data_3851
def delete_entity(entity: str): downstream_entities = registry.get_dependent_entities(entity_id) if len(downstream_entities) > 0: raise HTTPException( - status_code=500, detail=f"""Entity cannot be deleted as it has downstream/dependent entities. Entities: {list([e.qualified_name for e in downstream_entities])}""" ) registry.delete_entity(entity_id) Better to use a status code other than 500, my recommendation is "412 precondition failed". def delete_entity(entity: str): downstream_entities = registry.get_dependent_entities(entity_id) if len(downstream_entities) > 0: raise HTTPException( + status_code=412, detail=f"""Entity cannot be deleted as it has downstream/dependent entities. Entities: {list([e.qualified_name for e in downstream_entities])}""" ) registry.delete_entity(entity_id)
codereview_new_python_data_3852
def get_version(): # Decouple Feathr MAVEN Version from Feathr Python SDK Version import os -def get_maven_artifact(): - maven_version = os.environ.get("FEATHR_MAVEN_VERSION", __version__) - return f"com.linkedin.feathr:feathr_2.12:{maven_version}" \ No newline at end of file \ No newline at end of file Might be better if we call this `get_maven_artifact_version`? def get_version(): # Decouple Feathr MAVEN Version from Feathr Python SDK Version import os \ No newline at end of file +def get_maven_artifact_fullname(): + maven_artifact_version = os.environ.get("MAVEN_ARTIFACT_VERSION", __version__) + return f"com.linkedin.feathr:feathr_2.12:{maven_artifact_version}" \ No newline at end of file
codereview_new_python_data_3853
def get_version(): # Decouple Feathr MAVEN Version from Feathr Python SDK Version import os -def get_maven_artifact(): - maven_version = os.environ.get("FEATHR_MAVEN_VERSION", __version__) - return f"com.linkedin.feathr:feathr_2.12:{maven_version}" \ No newline at end of file \ No newline at end of file Suggest following name change to make code more readable - maven_version => maven_artifact_version - get_maven_artifact => get_maven_artifact_fullname - FEATHR_MAVEN_VERSION => MAVEN_ARTIFACT_VERSION def get_version(): # Decouple Feathr MAVEN Version from Feathr Python SDK Version import os \ No newline at end of file +def get_maven_artifact_fullname(): + maven_artifact_version = os.environ.get("MAVEN_ARTIFACT_VERSION", __version__) + return f"com.linkedin.feathr:feathr_2.12:{maven_artifact_version}" \ No newline at end of file
codereview_new_python_data_3854
def to_feature_config(self) -> str: {% if source.sql is defined %} sql: "{{source.sql}}" {% elif source.table is defined %} - sql: "{{source.table}}" {% endif %} } {% if source.event_timestamp_column is defined %} should `sql` be `table` here? def to_feature_config(self) -> str: {% if source.sql is defined %} sql: "{{source.sql}}" {% elif source.table is defined %} + table: "{{source.table}}" {% endif %} } {% if source.event_timestamp_column is defined %}
codereview_new_python_data_3855
# it brings a different version of msrest(0.7.0) which is incompatible with azure-core==1.22.1. Hence we need to pin it. # See this for more details: https://github.com/Azure/azure-sdk-for-python/issues/24765 "msrest<=0.6.21", - "typing_extensions>=4.2.0", - "aws-requests-auth>=0.4.3" ], tests_require=[ # TODO: This has been depricated "pytest", "aws-requests-auth>=0.4.3" is this required? # it brings a different version of msrest(0.7.0) which is incompatible with azure-core==1.22.1. Hence we need to pin it. # See this for more details: https://github.com/Azure/azure-sdk-for-python/issues/24765 "msrest<=0.6.21", + "typing_extensions>=4.2.0" ], tests_require=[ # TODO: This has been depricated "pytest",
codereview_new_python_data_3856
def save_to_feature_config_from_context(self, anchor_list, derived_feature_list, def default_registry_client(project_name: str, config_path:str = "./feathr_config.yaml", project_registry_tag: Dict[str, str]=None, credential = None) -> FeathrRegistry: from feathr.registry._feathr_registry_client import _FeatureRegistry from feathr.registry._feature_registry_purview import _PurviewRegistry - from feathr.registry._feathr_registry_client_aws import _FeatureRegistryAWS - from aws_requests_auth.aws_auth import AWSRequestsAuth - envutils = _EnvVaraibleUtil(config_path) registry_endpoint = envutils.get_environment_variable_with_default("feature_registry", "api_endpoint") - if registry_endpoint and isinstance(credential, AWSRequestsAuth): - return _FeatureRegistryAWS(project_name, endpoint=registry_endpoint, project_tags=project_registry_tag, credential=credential) - elif registry_endpoint: return _FeatureRegistry(project_name, endpoint=registry_endpoint, project_tags=project_registry_tag, credential=credential) else: registry_delimiter = envutils.get_environment_variable_with_default('feature_registry', 'purview', 'delimiter') Sounds like this part is irrelevant for this PR, maybe we have a seperate PR for this? def save_to_feature_config_from_context(self, anchor_list, derived_feature_list, def default_registry_client(project_name: str, config_path:str = "./feathr_config.yaml", project_registry_tag: Dict[str, str]=None, credential = None) -> FeathrRegistry: from feathr.registry._feathr_registry_client import _FeatureRegistry from feathr.registry._feature_registry_purview import _PurviewRegistry + envutils = _EnvVaraibleUtil(config_path) registry_endpoint = envutils.get_environment_variable_with_default("feature_registry", "api_endpoint") + if registry_endpoint: return _FeatureRegistry(project_name, endpoint=registry_endpoint, project_tags=project_registry_tag, credential=credential) else: registry_delimiter = envutils.get_environment_variable_with_default('feature_registry', 'purview', 'delimiter')
codereview_new_python_data_3857
def test_feathr_online_store_agg_features(): if client.spark_runtime == 'databricks': output_path = ''.join(['dbfs:/feathrazure_cijob','_', str(now.minute), '_', str(now.second), ".avro"]) else: - output_path = ''.join(['abfss://feathrazuretest3fs@xchfeathrtest4sto.dfs.core.windows.net/demo_data/output','_', str(now.minute), '_', str(now.second), ".avro"]) client.get_offline_features(observation_settings=settings, xchfeathrtest4sto - should this also be changed? def test_feathr_online_store_agg_features(): if client.spark_runtime == 'databricks': output_path = ''.join(['dbfs:/feathrazure_cijob','_', str(now.minute), '_', str(now.second), ".avro"]) else: + output_path = ''.join(['abfss://feathrazuretest3fs@feathrazuretest3storage.dfs.core.windows.net/demo_data/output','_', str(now.minute), '_', str(now.second), ".avro"]) client.get_offline_features(observation_settings=settings,
codereview_new_python_data_3858
class FeathrModel(BaseModel): """ displayName: str # name of the entity showed on UI typeName: str # type of entity in str format, will be displayed in UI - # Represents zero, one or multiple keyPlaceholderRefs which are used as the - # identifiers to reference KeyPlaceholders of the FeatureSource - keyPlaceholderRefs: List[str] = [] Do we need this as a common field? Feels like this should be a more specific field to some entity class FeathrModel(BaseModel): """ displayName: str # name of the entity showed on UI typeName: str # type of entity in str format, will be displayed in UI
codereview_new_python_data_3859
class SlidingWindowEmbeddingAggregationType(Enum): class WindowTimeUnit(Enum): """ - Represents a unit of time. """ DAY = "day" HOUR = "hour" nit: fix spacing class SlidingWindowEmbeddingAggregationType(Enum): class WindowTimeUnit(Enum): """ + Represents a unit of time. """ DAY = "day" HOUR = "hour"
codereview_new_python_data_3860
import pandas as pd from pyspark.sql import DataFrame, SparkSession from feathr.datasets.utils import maybe_download from feathr.utils.platform import is_databricks -NYC_TAXI_SMALL_URL = ( - "https://azurefeathrstorage.blob.core.windows.net/public/sample_data/green_tripdata_2020-04_with_index.csv" -) - - def get_pandas_df( local_cache_path: str = None, ) -> pd.DataFrame: Shall we move it to `constants.py` or new a `datasets/constants.py`? It will be useful if we extend to more datasets. import pandas as pd from pyspark.sql import DataFrame, SparkSession +from feathr.datasets import NYC_TAXI_SMALL_URL from feathr.datasets.utils import maybe_download from feathr.utils.platform import is_databricks def get_pandas_df( local_cache_path: str = None, ) -> pd.DataFrame:
codereview_new_python_data_3862
def _parse_function_str_for_name(fn_str: str) -> str: return None tree = ast.parse(fn_str) if len(tree.body) != 1 or not isinstance(tree.body[0], ast.FunctionDef): raise ValueError("provided code fragment is not a single function") return tree.body[0].name Thanks! Maybe add a bit explanation in the PR or in the comment on how tree.body[] works? def _parse_function_str_for_name(fn_str: str) -> str: return None tree = ast.parse(fn_str) + + # tree.body contains a list of function definition objects parsed from the input string. + # Currently, we only accept a single function. if len(tree.body) != 1 or not isinstance(tree.body[0], ast.FunctionDef): raise ValueError("provided code fragment is not a single function") + # Get the function name from the function definition. return tree.body[0].name
codereview_new_python_data_3866
class HdfsSource(Source): registry_tags: A dict of (str, str) that you can pass to feature registry for better organization. For example, you can use {"deprecated": "true"} to indicate this source is deprecated, etc. time_partition_pattern(Optional[str]): Format of the time partitioned feature data. e.g. yyyy/MM/DD. All formats supported in dateTimeFormatter. - HOCON config: timeSnapshotHdfsSource: { location: Let's not talk about HOCON here since this is not exposed to customers class HdfsSource(Source): registry_tags: A dict of (str, str) that you can pass to feature registry for better organization. For example, you can use {"deprecated": "true"} to indicate this source is deprecated, etc. time_partition_pattern(Optional[str]): Format of the time partitioned feature data. e.g. yyyy/MM/DD. All formats supported in dateTimeFormatter. + config: timeSnapshotHdfsSource: { location:
codereview_new_python_data_3867
class HdfsSink(Sink): """Offline Hadoop HDFS-compatible(HDFS, delta lake, Azure blog storage etc) sink that is used to store feature data. The result is in AVRO format. - Incremental aggregation is enabled by default when using HdfsSink. Use incremental aggregation will significantly expedite the SWA feature calculation. For example, aggregation sum of a feature F within a 180-day window at day T can be expressed as: F(T) = F(T - 1)+DirectAgg(T-1)-DirectAgg(T - 181). Once a SNAPSHOT of the first day is generated, the calculation for the following days can leverage it. SWA should be WindowAggTransformation to unify the name. class HdfsSink(Sink): """Offline Hadoop HDFS-compatible(HDFS, delta lake, Azure blog storage etc) sink that is used to store feature data. The result is in AVRO format. + Incremental aggregation is enabled by default when using HdfsSink. Use incremental aggregation will significantly expedite the WindowAggTransformation feature calculation. For example, aggregation sum of a feature F within a 180-day window at day T can be expressed as: F(T) = F(T - 1)+DirectAgg(T-1)-DirectAgg(T - 181). Once a SNAPSHOT of the first day is generated, the calculation for the following days can leverage it.
codereview_new_python_data_3868
"confluent-kafka<=1.9.2", "databricks-cli<=0.17.3", "avro<=1.11.1", - "azure-storage-file-datalake>=12.5.0", "azure-synapse-spark<=0.7.0", # fixing Azure Machine Learning authentication issue per https://stackoverflow.com/a/72262694/3193073 "azure-identity>=1.8.0", I tried 12.8.0 but it doesn't seem to work, maybe we need a more strict constraint here. "confluent-kafka<=1.9.2", "databricks-cli<=0.17.3", "avro<=1.11.1", + "azure-storage-file-datalake<=12.5.0", "azure-synapse-spark<=0.7.0", # fixing Azure Machine Learning authentication issue per https://stackoverflow.com/a/72262694/3193073 "azure-identity>=1.8.0",
codereview_new_python_data_3869
def test_feathr_register_features_e2e(self): config_paths = [ "feathr_config_registry_purview.yaml", "feathr_config_registry_sql.yaml", - "feathr_config_registry_sql_rbac.yaml" ] for config_path in config_paths: Should we have 4 tests? i.e. sql sql+rbac purview purview+rbac def test_feathr_register_features_e2e(self): config_paths = [ "feathr_config_registry_purview.yaml", + "feathr_config_registry_purview_rbac.yaml", "feathr_config_registry_sql.yaml", + "feathr_config_registry_sql_rbac.yaml", ] for config_path in config_paths:
codereview_new_python_data_3871
Purpose of this is to decouple backend data models from API specific data models. For each feature registry provider/implementation, they will extend this abstract data models and backend API. -Diagram of the data models: """ Just one suggestion, possible we use mermaid for this flowchart? [Mermaid is officially supported in github](https://github.blog/2022-02-14-include-diagrams-markdown-files-mermaid/). This will make furhter maintain easiler. Purpose of this is to decouple backend data models from API specific data models. For each feature registry provider/implementation, they will extend this abstract data models and backend API. +Diagram of the data models: ./data-model-diagram.md """
codereview_new_python_data_3872
def parse_avro_result(output_path): vertical_concat_df = pd.concat(dataframe_list, axis=0) return vertical_concat_df - -if __name__ == "__main__": - test_local_spark_get_offline_features() - remove this for e2e testing? def parse_avro_result(output_path): vertical_concat_df = pd.concat(dataframe_list, axis=0) return vertical_concat_df
codereview_new_python_data_3877
class RelationshipType(Enum): Consumes = 3 Produces = 4 - - def __str__(self): - return { - RelationshipType.Contains: "Contains", - RelationshipType.BelongsTo: "BelongsTo", - RelationshipType.Consumes: "Consumes", - RelationshipType.Produces: "Produces", - }[self] - - class ToDict(ABC): """ This ABC is used to convert object to dict, then JSON. This actually already exists as `Enum.name` property. class RelationshipType(Enum): Consumes = 3 Produces = 4 class ToDict(ABC): """ This ABC is used to convert object to dict, then JSON.
codereview_new_python_data_3878
import json from typing import Dict, List, Optional from jinja2 import Template -from pymysql import paramstyle from feathr.definition.feathrconfig import HoconConvertible Remove pymysql as current code does not use it import json from typing import Dict, List, Optional from jinja2 import Template from feathr.definition.feathrconfig import HoconConvertible
codereview_new_python_data_3879
class BackfillTime: - """Time range to materialize/backfill feature data. Please refer to https://github.com/linkedin/feathr/blob/main/docs/concepts/materializing-features.md#feature-backfill for a more detailed explanation. Attributes: start: start time of the backfill, inclusive. https://linkedin.github.io/feathr/concepts/materializing-features.html#feature-backfill class BackfillTime: + """Time range to materialize/backfill feature data. Please refer to https://linkedin.github.io/feathr/concepts/materializing-features.html#feature-backfill for a more detailed explanation. Attributes: start: start time of the backfill, inclusive.
codereview_new_python_data_3880
def _register_feathr_feature_types(self): superTypes=["DataSet"], ) new_entitydefs = [type_feathr_anchor_features, type_feathr_anchors, type_feathr_derived_features, type_feathr_sources, type_feathr_project] new_entitydefs_names = [entity.name for entity in new_entitydefs] Could we add a comment here, so reader can know this is skip if exists def _register_feathr_feature_types(self): superTypes=["DataSet"], ) + # Check if any of these type definitiones are already registered. + # If so this registration will be skipped. new_entitydefs = [type_feathr_anchor_features, type_feathr_anchors, type_feathr_derived_features, type_feathr_sources, type_feathr_project] new_entitydefs_names = [entity.name for entity in new_entitydefs]
codereview_new_python_data_3881
class WindowAggTransformation(Transformation): agg_func: aggregation function. Available values: `SUM`, `COUNT`, `MAX`, `MIN`, `AVG`, `MAX_POOLING`, `MIN_POOLING`, `AVG_POOLING`, `LATEST` window: Time window length to apply the aggregation. support 4 type of units: d(day), h(hour), m(minute), s(second). The example value are "7d' or "5h" or "3m" or "1s" group_by: Feathr expressions applied after the `agg_expr` transformation as groupby field, before aggregation, same as 'group by' in SQL - filter: Feathr expression applied to each row as a filter before aggregation. This should be a string and should be a valid Spark SQL Expression. For example: filter = 'age > 3'. This is similar to PySpark filter operation and more details can be learned here: https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.filter.html """ def __init__(self, agg_expr: str, agg_func: str, window: str, group_by: Optional[str] = None, filter: Optional[str] = None, limit: Optional[int] = None) -> None: super().__init__() `should be` used twice in one sentence. class WindowAggTransformation(Transformation): agg_func: aggregation function. Available values: `SUM`, `COUNT`, `MAX`, `MIN`, `AVG`, `MAX_POOLING`, `MIN_POOLING`, `AVG_POOLING`, `LATEST` window: Time window length to apply the aggregation. support 4 type of units: d(day), h(hour), m(minute), s(second). The example value are "7d' or "5h" or "3m" or "1s" group_by: Feathr expressions applied after the `agg_expr` transformation as groupby field, before aggregation, same as 'group by' in SQL + filter: Feathr expression applied to each row as a filter before aggregation. This should be a string and a valid Spark SQL Expression. For example: filter = 'age > 3'. This is similar to PySpark filter operation and more details can be learned here: https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.filter.html """ def __init__(self, agg_expr: str, agg_func: str, window: str, group_by: Optional[str] = None, filter: Optional[str] = None, limit: Optional[int] = None) -> None: super().__init__()
codereview_new_python_data_3882
def _get_user_from_token(decoded_token: Mapping) -> User: except Exception as e: raise InvalidAuthorization(detail=f'Unable to extract subject as unique id from token, {e}') - print(decoded_token) - aad_user_key = "preferred_username" aad_app_key = "appid" common_user_key = "email" >decoded_token [](http://example.com/codeflow?start=14&length=13) token is sensitive, should not print/log def _get_user_from_token(decoded_token: Mapping) -> User: except Exception as e: raise InvalidAuthorization(detail=f'Unable to extract subject as unique id from token, {e}') aad_user_key = "preferred_username" aad_app_key = "appid" common_user_key = "email"
codereview_new_python_data_3883
def __init__(self, def validate_feature(self): """Validate the derived feature is valid""" - # Validate key alias input_feature_key_alias = [] for feature in self.input_features: - input_feature_key_alias.extend(feature.key_alias) for key_alias in self.key_alias: assert key_alias in input_feature_key_alias, "key alias {} in derived feature {} must come from " \ "its input features key alias list {}".format(key_alias, self.name, input_feature_key_alias) - def to_feature_config(self) -> str: tm = Template(""" {{derived_feature.name}}: { Any particular reason we are skipping this? def __init__(self, def validate_feature(self): """Validate the derived feature is valid""" + input_feature_key_alias = [] for feature in self.input_features: + input_feature_key_alias.extend([x['keyColumnAlias'] for x in feature['attributes']['key']] if isinstance(feature,dict) else feature.key_alias) for key_alias in self.key_alias: assert key_alias in input_feature_key_alias, "key alias {} in derived feature {} must come from " \ "its input features key alias list {}".format(key_alias, self.name, input_feature_key_alias) def to_feature_config(self) -> str: tm = Template(""" {{derived_feature.name}}: {
codereview_new_python_data_3884
env_file = os.path.join("registry", "access_control", ".env") config = Config(os.path.abspath(env_file)) -def _get_config(key:str, default:str = "", config:Config = config): - return os.environ.get(key) or config.get(key, default=default) # API Settings -RBAC_API_BASE: str = _get_config("RBAC_API_BASE", default="/api/v1") # Authentication -RBAC_API_CLIENT_ID: str = _get_config("RBAC_API_CLIENT_ID", default="db8dc4b0-202e-450c-b38d-7396ad9631a5") -RBAC_AAD_TENANT_ID: str = _get_config("RBAC_AAD_TENANT_ID", default="common") -RBAC_AAD_INSTANCE: str = _get_config("RBAC_AAD_INSTANCE", default="https://login.microsoftonline.com") -RBAC_API_AUDIENCE: str = _get_config("RBAC_API_AUDIENCE", default=RBAC_API_CLIENT_ID) # SQL Database -RBAC_CONNECTION_STR: str = _get_config("RBAC_CONNECTION_STR", default= "") # Downstream API Endpoint -RBAC_REGISTRY_URL: str = _get_config("RBAC_REGISTRY_URL", default= "https://feathr-sql-registry.azurewebsites.net/api/v1") >default [](http://example.com/codeflow?start=60&length=7) I suggest we do not make these as default in code base, otherwise when customer build production images, these config will be included. I think UI has similar issues, I will take care of UI. Move .env to .env.development as .env.development is by default excluded when build prod via webpack. env_file = os.path.join("registry", "access_control", ".env") config = Config(os.path.abspath(env_file)) +def _get_config(key:str, config:Config = config): + return os.environ.get(key) or config.get(key) # API Settings +RBAC_API_BASE: str = _get_config("RBAC_API_BASE") # Authentication +RBAC_API_CLIENT_ID: str = _get_config("RBAC_API_CLIENT_ID") +RBAC_AAD_TENANT_ID: str = _get_config("RBAC_AAD_TENANT_ID") +RBAC_AAD_INSTANCE: str = _get_config("RBAC_AAD_INSTANCE") +RBAC_API_AUDIENCE: str = _get_config("RBAC_API_AUDIENCE") # SQL Database +RBAC_CONNECTION_STR: str = _get_config("RBAC_CONNECTION_STR") # Downstream API Endpoint +RBAC_REGISTRY_URL: str = _get_config("RBAC_REGISTRY_URL")
codereview_new_python_data_3885
def get_result_df(client: FeathrClient, format: str = None, res_url: str = None, format: format override, could be "parquet", "delta", etc. res_url: output URL to download files. Note that this will not block the job so you need to make sure the job is finished and result URL contains actual data. """ res_url: str = res_url or client.get_job_result_uri(block=True, timeout_sec=1200) format: str = format or client.get_job_tags().get(OUTPUT_FORMAT, "") # if local_folder params is not provided then create a temporary folder if local_folder is not None: - local_dir_path = os.getcwd() + local_folder else: tmp_dir = tempfile.TemporaryDirectory() local_dir_path = tmp_dir.name Add the pydoc string for local_folder def get_result_df(client: FeathrClient, format: str = None, res_url: str = None, format: format override, could be "parquet", "delta", etc. res_url: output URL to download files. Note that this will not block the job so you need to make sure the job is finished and result URL contains actual data. + local_folder: optional parameter to specify the absolute download path. if the user does not provide this, function will create a temporary directory and delete it after reading the dataframe. """ res_url: str = res_url or client.get_job_result_uri(block=True, timeout_sec=1200) format: str = format or client.get_job_tags().get(OUTPUT_FORMAT, "") # if local_folder params is not provided then create a temporary folder if local_folder is not None: + local_dir_path = local_folder else: tmp_dir = tempfile.TemporaryDirectory() local_dir_path = tmp_dir.name
codereview_new_python_data_3886
def get_result_df(client: FeathrClient, format: str = None, res_url: str = None, format: format override, could be "parquet", "delta", etc. res_url: output URL to download files. Note that this will not block the job so you need to make sure the job is finished and result URL contains actual data. """ res_url: str = res_url or client.get_job_result_uri(block=True, timeout_sec=1200) format: str = format or client.get_job_tags().get(OUTPUT_FORMAT, "") # if local_folder params is not provided then create a temporary folder if local_folder is not None: - local_dir_path = os.getcwd() + local_folder else: tmp_dir = tempfile.TemporaryDirectory() local_dir_path = tmp_dir.name Maybe we just use absolute path rather than a local_folder under `os.getcwd()`? def get_result_df(client: FeathrClient, format: str = None, res_url: str = None, format: format override, could be "parquet", "delta", etc. res_url: output URL to download files. Note that this will not block the job so you need to make sure the job is finished and result URL contains actual data. + local_folder: optional parameter to specify the absolute download path. if the user does not provide this, function will create a temporary directory and delete it after reading the dataframe. """ res_url: str = res_url or client.get_job_result_uri(block=True, timeout_sec=1200) format: str = format or client.get_job_tags().get(OUTPUT_FORMAT, "") # if local_folder params is not provided then create a temporary folder if local_folder is not None: + local_dir_path = local_folder else: tmp_dir = tempfile.TemporaryDirectory() local_dir_path = tmp_dir.name
codereview_new_python_data_3887
def get_result_df(client: FeathrClient, format: str = None, res_url: str = None, tmp_dir = tempfile.TemporaryDirectory() local_dir_path = tmp_dir.name - client.feathr_spark_laucher.download_result(result_path=res_url, local_folder=local_dir_path) dataframe_list = [] # by default the result are in avro format if format: client.feathr_spark_launcher.download_result def get_result_df(client: FeathrClient, format: str = None, res_url: str = None, tmp_dir = tempfile.TemporaryDirectory() local_dir_path = tmp_dir.name + client.feathr_spark_launcher.download_result(result_path=res_url, local_folder=local_dir_path) dataframe_list = [] # by default the result are in avro format if format:
codereview_new_python_data_3888
def submit_feathr_job(self, job_name: str, main_jar_path: str, main_class_name: submission_params['new_cluster']['spark_conf'] = configuration submission_params['new_cluster']['custom_tags'] = job_tags # the feathr main jar file is anyway needed regardless it's pyspark or scala spark - if main_jar_path is None or main_jar_path=="": - logger.info("Main JAR file is not set, using default package from Maven") submission_params['libraries'][0]['maven'] = { "coordinates": FEATHR_MAVEN_ARTIFACT } else: submission_params['libraries'][0]['jar'] = self.upload_or_get_cloud_path(main_jar_path) Also print maven version (FEATHR_MAVEN_ARTIFACT)? def submit_feathr_job(self, job_name: str, main_jar_path: str, main_class_name: submission_params['new_cluster']['spark_conf'] = configuration submission_params['new_cluster']['custom_tags'] = job_tags # the feathr main jar file is anyway needed regardless it's pyspark or scala spark + if not main_jar_path: + logger.info(f"Main JAR file is not set, using default package '{FEATHR_MAVEN_ARTIFACT}' from Maven") submission_params['libraries'][0]['maven'] = { "coordinates": FEATHR_MAVEN_ARTIFACT } else: submission_params['libraries'][0]['jar'] = self.upload_or_get_cloud_path(main_jar_path)
codereview_new_python_data_3889
def search_entity(self, project: Optional[Union[str, UUID]] = None) -> list[EntityRef]: pass - -if __name__ == '__main__': - print("foo bar") -else: - print("spam") remove this part def search_entity(self, project: Optional[Union[str, UUID]] = None) -> list[EntityRef]: pass
codereview_new_python_data_3896
def _parse_anchors(self, anchor_list: List[FeatureAnchor]) -> List[AtlasEntity]: anchors_batch.append(anchor_entity) return anchors_batch - def _merge_anchor(self,original_anchor:dict, new_anchor:dict)->dict[str,any]: - print('gua?') ''' Merge the new anchors defined locally with the anchors that is defined in the centralized registry. ''' delete this print def _parse_anchors(self, anchor_list: List[FeatureAnchor]) -> List[AtlasEntity]: anchors_batch.append(anchor_entity) return anchors_batch + def _merge_anchor(self,original_anchor:Dict, new_anchor:Dict)->Dict[str,any]: ''' Merge the new anchors defined locally with the anchors that is defined in the centralized registry. '''
codereview_new_python_data_3899
def to_feature_config(self) -> str: return msg -class OfflineSink(Sink): """Offline Hadoop HDFS-compatible(HDFS, delta lake, Azure blog storage etc) sink that is used to store feature data. The result is in AVRO format. Should we call it HDFSSink instead? Since we might also need to sink it to SQL or other offline stores (maybe in the future depending on user feedback) def to_feature_config(self) -> str: return msg +class HdfsSink(Sink): """Offline Hadoop HDFS-compatible(HDFS, delta lake, Azure blog storage etc) sink that is used to store feature data. The result is in AVRO format.
codereview_new_python_data_3900
from .lookup_feature import LookupFeature from .aggregation import Aggregation from .feathr_configurations import SparkExecutionConfiguration -from feathr.api.app.core.feathr_api_exception import * \ No newline at end of file \ No newline at end of file I made the call that the exceptions in [feathr.api.app.core.fathr_api_exception.py](https://github.com/linkedin/feathr/blob/main/feathr_project/feathr/api/app/core/feathr_api_exception.py) should be exported by default as part of the public API. Happy to roll this back if reviewers feel otherwise. from .lookup_feature import LookupFeature from .aggregation import Aggregation from .feathr_configurations import SparkExecutionConfiguration \ No newline at end of file +from .api.app.core.feathr_api_exception import * \ No newline at end of file
codereview_new_python_data_3901
from urllib.parse import urlparse from os.path import basename from enum import Enum -from azure.identity import DefaultAzureCredential - from azure.identity import (ChainedTokenCredential, DefaultAzureCredential, DeviceCodeCredential, EnvironmentCredential, ManagedIdentityCredential) duplicate with line 12? from urllib.parse import urlparse from os.path import basename from enum import Enum from azure.identity import (ChainedTokenCredential, DefaultAzureCredential, DeviceCodeCredential, EnvironmentCredential, ManagedIdentityCredential)
codereview_new_python_data_3902
from pathlib import Path from typing import Dict, List, Optional, Union from pprint import pprint -from xmlrpc.client import Boolean import redis from azure.identity import DefaultAzureCredential this seems wrong wrong? from pathlib import Path from typing import Dict, List, Optional, Union from pprint import pprint import redis from azure.identity import DefaultAzureCredential
codereview_new_python_data_3903
def get_offline_features(self, else: raise RuntimeError("Please call FeathrClient.build_features() first in order to get offline features") - # Pretty print anchor list and derived_feature_list if verbose: - if self.anchor_list: - FeaturePrinter.pretty_print(self.anchor_list) - if self.derived_feature_list: - FeaturePrinter.pretty_print(self.derived_feature_list) write_to_file(content=config, full_file_name=config_file_path) return self._get_offline_features_with_config(config_file_path, execution_configuratons, udf_files=udf_files) we should only print feature_query. Feature anchor is a super set of feature_query. For example, i have an anchor and it contains f1, f2, f3. But I only want f1 and f2. Then my feature_query = f1, f2. Giving out whole anchors is confusing. def get_offline_features(self, else: raise RuntimeError("Please call FeathrClient.build_features() first in order to get offline features") + # Pretty print feature query if verbose: + FeaturePrinter.pretty_print_feature_query(feature_query) write_to_file(content=config, full_file_name=config_file_path) return self._get_offline_features_with_config(config_file_path, execution_configuratons, udf_files=udf_files)
codereview_new_python_data_3904
from pathlib import Path from pyspark.sql.functions import col,sum,avg,max from feathr.utils.job_utils import get_result_df -from feathr.feature_definition.anchor import FeatureAnchor -from feathr.feature_definition.dtype import STRING, BOOLEAN, FLOAT, INT32, ValueType -from feathr.feature_definition.feature import Feature -from feathr.feature_definition.query_feature_list import FeatureQuery -from feathr.feature_definition.settings import ObservationSettings -from feathr.feature_definition.source import INPUT_CONTEXT, HdfsSource -from feathr.feature_definition.typed_key import TypedKey -from feathr.feature_definition.transformation import WindowAggTransformation from pyspark.sql import SparkSession, DataFrame from test_fixture import basic_test_setup, snowflake_test_setup from feathr import (BackfillTime, MaterializationSettings) the convention is not to use underscore. definition should be enough. this changes the docs. I am not sure how we can show that users only need to import feathr.xyz in the readthedocs. from pathlib import Path from pyspark.sql.functions import col,sum,avg,max from feathr.utils.job_utils import get_result_df +from feathr.definition.anchor import FeatureAnchor +from feathr.definition.dtype import STRING, BOOLEAN, FLOAT, INT32, ValueType +from feathr.definition.feature import Feature +from feathr.definition.query_feature_list import FeatureQuery +from feathr.definition.settings import ObservationSettings +from feathr.definition.source import INPUT_CONTEXT, HdfsSource +from feathr.definition.typed_key import TypedKey +from feathr.definition.transformation import WindowAggTransformation from pyspark.sql import SparkSession, DataFrame from test_fixture import basic_test_setup, snowflake_test_setup from feathr import (BackfillTime, MaterializationSettings)
codereview_new_python_data_3905
def wait_for_completion(self, timeout_seconds: Optional[int] = 600) -> bool: elif status in {'INTERNAL_ERROR', 'FAILED', 'TIMEDOUT', 'CANCELED'}: result = RunsApi(self.api_client).get_run_output(self.res_job_id) # See here for the returned fields: https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/2.0/jobs#--response-structure-8 - # print out logs and stack trace if the job is failed - logger.error("Feathr job is failed. Please visit this page to view error message: {}", self.job_url) if "error" in result: logger.error("Error Code: {}", result["error"]) if "error_trace" in result: has failed def wait_for_completion(self, timeout_seconds: Optional[int] = 600) -> bool: elif status in {'INTERNAL_ERROR', 'FAILED', 'TIMEDOUT', 'CANCELED'}: result = RunsApi(self.api_client).get_run_output(self.res_job_id) # See here for the returned fields: https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/2.0/jobs#--response-structure-8 + # print out logs and stack trace if the job has failed + logger.error("Feathr job has failed. Please visit this page to view error message: {}", self.job_url) if "error" in result: logger.error("Error Code: {}", result["error"]) if "error_trace" in result:
codereview_new_python_data_3906
def wait_for_completion(self, timeout_seconds: Optional[int] = 600) -> bool: elif status in {'INTERNAL_ERROR', 'FAILED', 'TIMEDOUT', 'CANCELED'}: result = RunsApi(self.api_client).get_run_output(self.res_job_id) # See here for the returned fields: https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/2.0/jobs#--response-structure-8 - # print out logs and stack trace if the job is failed - logger.error("Feathr job is failed. Please visit this page to view error message: {}", self.job_url) if "error" in result: logger.error("Error Code: {}", result["error"]) if "error_trace" in result: if result["error"]? def wait_for_completion(self, timeout_seconds: Optional[int] = 600) -> bool: elif status in {'INTERNAL_ERROR', 'FAILED', 'TIMEDOUT', 'CANCELED'}: result = RunsApi(self.api_client).get_run_output(self.res_job_id) # See here for the returned fields: https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/2.0/jobs#--response-structure-8 + # print out logs and stack trace if the job has failed + logger.error("Feathr job has failed. Please visit this page to view error message: {}", self.job_url) if "error" in result: logger.error("Error Code: {}", result["error"]) if "error_trace" in result:
codereview_new_python_data_3907
def wait_for_completion(self, timeout_seconds: Optional[int] = 600) -> bool: elif status in {'INTERNAL_ERROR', 'FAILED', 'TIMEDOUT', 'CANCELED'}: result = RunsApi(self.api_client).get_run_output(self.res_job_id) # See here for the returned fields: https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/2.0/jobs#--response-structure-8 - # print out logs and stack trace if the job is failed - logger.error("Feathr job is failed. Please visit this page to view error message: {}", self.job_url) if "error" in result: logger.error("Error Code: {}", result["error"]) if "error_trace" in result: if result["error_trace"] def wait_for_completion(self, timeout_seconds: Optional[int] = 600) -> bool: elif status in {'INTERNAL_ERROR', 'FAILED', 'TIMEDOUT', 'CANCELED'}: result = RunsApi(self.api_client).get_run_output(self.res_job_id) # See here for the returned fields: https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/2.0/jobs#--response-structure-8 + # print out logs and stack trace if the job has failed + logger.error("Feathr job has failed. Please visit this page to view error message: {}", self.job_url) if "error" in result: logger.error("Error Code: {}", result["error"]) if "error_trace" in result:
codereview_new_python_data_3908
# The short X.Y version version = '0.4' # The full version, including alpha/beta/rc tags -release = '0.4_azure_alpha' # -- General configuration --------------------------------------------------- should we just say 0.4? # The short X.Y version version = '0.4' # The full version, including alpha/beta/rc tags +release = '0.4' # -- General configuration ---------------------------------------------------
codereview_new_python_data_3909
'pytest', ], extras_require={ - 'pyspark': ["pyspark>=3.1.2",], }, entry_points={ 'console_scripts': ['feathr=feathrcli.cli:cli'] we shoud name it something as full_dependency or full instead of pyspark as we may have more heavy depdencies in the future that goes into this part. 'pytest', ], extras_require={ + 'all': ["pyspark>=3.1.2"] }, entry_points={ 'console_scripts': ['feathr=feathrcli.cli:cli']
codereview_new_python_data_3910
def add_new_dropoff_and_fare_amount_column(df: DataFrame): def get_online_test_table_name(table_name: str): # use different time for testing to avoid write conflicts now = datetime.now() - return ''.join([table_name,'_', str(now.minute), '_', str(now.second)]) \ No newline at end of file \ No newline at end of file '_'.join([table_name, str(now.minute), str(now.second)]) def add_new_dropoff_and_fare_amount_column(df: DataFrame): def get_online_test_table_name(table_name: str): # use different time for testing to avoid write conflicts now = datetime.now() \ No newline at end of file + return '_'.join([table_name, str(now.minute), str(now.second)]) \ No newline at end of file
codereview_new_python_data_3911
from loguru import logger from azure.core.exceptions import ResourceNotFoundError -class akvClient: def __init__(self, akv_name: str): self.akv_name = akv_name self.secret_client = None [nitpick] - Suggest changing it to more descriptive name AzureKeyVaultClient, the way we have for PurviewClient etc. from loguru import logger from azure.core.exceptions import ResourceNotFoundError +class AzureKeyVaultClient: def __init__(self, akv_name: str): self.akv_name = akv_name self.secret_client = None
codereview_new_python_data_3912
def snowflake_test_setup(config_path: str): def registry_test_setup(config_path: str): - # use a new project name every time to make sure if all features are registered correctly no now = datetime.now() os.environ["project_config__project_name"] = ''.join(['feathr_ci','_', str(now.minute), '_', str(now.second), '_', str(now.microsecond)]) nit: typo? 'correctly no' def snowflake_test_setup(config_path: str): def registry_test_setup(config_path: str): + # use a new project name every time to make sure all features are registered correctly now = datetime.now() os.environ["project_config__project_name"] = ''.join(['feathr_ci','_', str(now.minute), '_', str(now.second), '_', str(now.microsecond)])
codereview_new_python_data_3913
def __str__(self): class KafkaConfig: def __init__(self, brokers: List[str], topics: List[str], schema: SourceSchema): self.brokers = brokers self.topics = topics doc def __str__(self): class KafkaConfig: + """Kafka config for a streaming source + Attributes: + brokers: broker/server address + topics: Kafka topics + schema: Kafka message schema + """ def __init__(self, brokers: List[str], topics: List[str], schema: SourceSchema): self.brokers = brokers self.topics = topics
codereview_new_python_data_3914
def __init__(self, config_path:str = "./feathr_config.yaml", local_workspace_dir # Kafka configs self.kafka_endpoint = envutils.get_environment_variable_with_default( - 'offline_store', 'kafka', 'kafka_endpoint') # spark configs self.output_num_parts = envutils.get_environment_variable_with_default( Should it be just "streaming" source and "kafka"? I don't think we should have "offline" here def __init__(self, config_path:str = "./feathr_config.yaml", local_workspace_dir # Kafka configs self.kafka_endpoint = envutils.get_environment_variable_with_default( + 'streaming', 'kafka', 'kafka_endpoint') # spark configs self.output_num_parts = envutils.get_environment_variable_with_default(
codereview_new_python_data_3918
def validate_features(self): if self.source != INPUT_CONTEXT: for feature in self.features: if feature.key == [DUMMY_KEY]: - raise RuntimeError(f"For Non INPUT_CONTEXT(PASSTHROUGH) anchors, key of feature {feature.name} " - f"should be explicitly specified and DUMMY_KEY should not be used.") for feature in self.features: assert feature.key_alias == self.features[0].key_alias If input source is not INPUT_CONTEXT, key of feature {feature.name} should be explicitly specified and not left blank. Maybe something like above? Since we don't talk about DUMMY KEY or PASSTHROUGH def validate_features(self): if self.source != INPUT_CONTEXT: for feature in self.features: if feature.key == [DUMMY_KEY]: + raise RuntimeError(f"For anchors of non-INPUT_CONTEXT source, key of feature {feature.name} " + f"should be explicitly specified and not left blank.") for feature in self.features: assert feature.key_alias == self.features[0].key_alias
codereview_new_python_data_3919
def submit_spark_job(feature_names_funcs): print(scala_dataframe) # Need to convert java DataFrame into python DataFrame py_df = DataFrame(scala_dataframe, sql_ctx) - print("Corresponding py_df: ") - print(py_df) - py_df.show(10) # Preprocess the DataFrame via UDF user_func = feature_names_funcs[feature_names] preprocessed_udf = user_func(py_df) - preprocessed_udf.show(10) new_preprocessed_df_map[feature_names] = preprocessed_udf._jdf print("submit_spark_job: running Feature job with preprocessed DataFrames:") delete def submit_spark_job(feature_names_funcs): print(scala_dataframe) # Need to convert java DataFrame into python DataFrame py_df = DataFrame(scala_dataframe, sql_ctx) # Preprocess the DataFrame via UDF user_func = feature_names_funcs[feature_names] preprocessed_udf = user_func(py_df) new_preprocessed_df_map[feature_names] = preprocessed_udf._jdf print("submit_spark_job: running Feature job with preprocessed DataFrames:")
codereview_new_python_data_3920
def submit_spark_job(feature_names_funcs): print(scala_dataframe) # Need to convert java DataFrame into python DataFrame py_df = DataFrame(scala_dataframe, sql_ctx) - print("Corresponding py_df: ") - print(py_df) - py_df.show(10) # Preprocess the DataFrame via UDF user_func = feature_names_funcs[feature_names] preprocessed_udf = user_func(py_df) - preprocessed_udf.show(10) new_preprocessed_df_map[feature_names] = preprocessed_udf._jdf print("submit_spark_job: running Feature job with preprocessed DataFrames:") delete or hide within debug switch def submit_spark_job(feature_names_funcs): print(scala_dataframe) # Need to convert java DataFrame into python DataFrame py_df = DataFrame(scala_dataframe, sql_ctx) # Preprocess the DataFrame via UDF user_func = feature_names_funcs[feature_names] preprocessed_udf = user_func(py_df) new_preprocessed_df_map[feature_names] = preprocessed_udf._jdf print("submit_spark_job: running Feature job with preprocessed DataFrames:")
codereview_new_python_data_3921
def submit_spark_job(feature_names_funcs): print(scala_dataframe) # Need to convert java DataFrame into python DataFrame py_df = DataFrame(scala_dataframe, sql_ctx) - print("Corresponding py_df: ") - print(py_df) - py_df.show(10) # Preprocess the DataFrame via UDF user_func = feature_names_funcs[feature_names] preprocessed_udf = user_func(py_df) - preprocessed_udf.show(10) new_preprocessed_df_map[feature_names] = preprocessed_udf._jdf print("submit_spark_job: running Feature job with preprocessed DataFrames:") Delete? def submit_spark_job(feature_names_funcs): print(scala_dataframe) # Need to convert java DataFrame into python DataFrame py_df = DataFrame(scala_dataframe, sql_ctx) # Preprocess the DataFrame via UDF user_func = feature_names_funcs[feature_names] preprocessed_udf = user_func(py_df) new_preprocessed_df_map[feature_names] = preprocessed_udf._jdf print("submit_spark_job: running Feature job with preprocessed DataFrames:")
codereview_new_python_data_3923
"google>=3.0.0", "graphlib_backport", "google-api-python-client>=2.41.0", ], tests_require=[ 'pytest', The license seems not compatible with Apache 2? "google>=3.0.0", "graphlib_backport", "google-api-python-client>=2.41.0", + "azure-keyvault-secrets", ], tests_require=[ 'pytest',
codereview_new_python_data_3924
class FeatureAnchor: name: Unique name of the anchor. source: data source that the features are anchored to. Should be either of `INPUT_CONTEXT` or `feathr.source.Source` features: list of features within this anchor. - registry_tags: A dict of (str, str) that you can pass to feature registry for customization. For example, you can use `registry_tags` to indicate anchor description, whether this anchor is deprecated or not, etc. """ def __init__(self, name: str, For example, you can use `registry_tags` to indicate whether this anchor is deprecated or not. class FeatureAnchor: name: Unique name of the anchor. source: data source that the features are anchored to. Should be either of `INPUT_CONTEXT` or `feathr.source.Source` features: list of features within this anchor. + registry_tags: A dict of (str, str) that you can pass to feature registry for customization. For example, you can use `registry_tags` to indicate whether this anchor is deprecated or not, etc. """ def __init__(self, name: str,
codereview_new_python_data_3925
def add_new_dropoff_and_fare_amount_column(df: DataFrame): derived_feature_list = [ f_trip_time_distance, f_trip_time_rounded, f_trip_time_rounded_plus] - random.shuffle(derived_feature_list) # shuffule the order to make sure they can be parsed correctly client.build_features(anchor_list=[agg_anchor, request_anchor], derived_feature_list=derived_feature_list) return client it's still hard to understand why shuffle is here > Those input derived features can be in arbitrary order, but in order to parse the right dependencies, we need to reorder them internally in a certain order. This test is to make sure that each time we have random shuffle for the input and make sure the internal sorting algorithm works (we are using topological sort). I have updated the comments to reflect this. def add_new_dropoff_and_fare_amount_column(df: DataFrame): derived_feature_list = [ f_trip_time_distance, f_trip_time_rounded, f_trip_time_rounded_plus] + # shuffule the order to make sure they can be parsed correctly + # Those input derived features can be in arbitrary order, but in order to parse the right dependencies, we need to reorder them internally in a certain order. + # This shuffle is to make sure that each time we have random shuffle for the input and make sure the internal sorting algorithm works (we are using topological sort). + random.shuffle(derived_feature_list) client.build_features(anchor_list=[agg_anchor, request_anchor], derived_feature_list=derived_feature_list) return client
codereview_new_python_data_3926
class FeatureAnchor: name: Unique name of the anchor. source: data source that the features are anchored to. Should be either of `INPUT_CONTEXT` or `feathr.source.Source` features: list of features within this anchor. - registry_tags: A dict of (str, str) that you can pass to feature registry for customization. For example, you can use `registry_tags` to indicate whether this anchor is deprecated or not, etc. """ def __init__(self, name: str, why is it A dict of (str, str)? Provide example class FeatureAnchor: name: Unique name of the anchor. source: data source that the features are anchored to. Should be either of `INPUT_CONTEXT` or `feathr.source.Source` features: list of features within this anchor. + registry_tags: A dict of (str, str) that you can pass to feature registry for better organization. For example, you can use {"deprecated": "true"} to indicate this anchor is deprecated, etc. """ def __init__(self, name: str,
codereview_new_python_data_3927
class DerivedFeature(FeatureBase): key: All features with corresponding keys that this derived feature depends on input_features: features that this derived features depends on transform: transformation that produces the derived feature value, based on the input_features - registry_tags: A dict of (str, str) that you can pass to feature registry for customization. For example, you can use `registry_tags` to indicate feature description, whether this feature is deprecated or not, last refreshed time, etc. """ def __init__(self, it's better to have a class for registry_tags so you don't have to keep repeating the documenation. and also can provide some methods for registry tags. class DerivedFeature(FeatureBase): key: All features with corresponding keys that this derived feature depends on input_features: features that this derived features depends on transform: transformation that produces the derived feature value, based on the input_features + registry_tags: A dict of (str, str) that you can pass to feature registry for better organization. For example, you can For example, you can use {"deprecated": "true"} to indicate this feature is deprecated, etc. """ def __init__(self,
codereview_new_python_data_3938
def __init__(self, self.timestamp_format = timestamp_format self.observation_path = observation_path if observation_path.startswith("http"): - logger.warning("Your observation_path starts with http, which might not work in Spark. Consider using paths starting with wasb[s]/abfs[s]/s3.") def to_config(self) -> str: tm = Template(""" spark is impl details that users should not know. Let's just say Http is not supported. def __init__(self, self.timestamp_format = timestamp_format self.observation_path = observation_path if observation_path.startswith("http"): + logger.warning("Your observation_path {} starts with http, which is not supported. Consider using paths starting with wasb[s]/abfs[s]/s3.", observation_path) def to_config(self) -> str: tm = Template("""
codereview_new_python_data_3939
def upload_file(self, src_file_path)-> str: def download_file(self, target_adls_directory: str, local_dir_cache: str): """ - Download file to a local cache. Supporting download a folder and the content in its subfolder Args: target_adls_directory (str): target ADLS directory adding all its subfolders recursively (to be more precise) def upload_file(self, src_file_path)-> str: def download_file(self, target_adls_directory: str, local_dir_cache: str): """ + Download file to a local cache. Supporting download a folder and the content in its subfolder. + Note that the code will just download the content in the root folder, and the folder in the next level (rather than recursively for all layers of folders) Args: target_adls_directory (str): target ADLS directory
codereview_new_python_data_3944
REDIS_PASSWORD = 'REDIS_PASSWORD' # 1MB = 1024*1024 -DATABRICKS_MB_BYTES = 1048576 \ No newline at end of file \ No newline at end of file this isn't databrics specific so no need to say databricks. REDIS_PASSWORD = 'REDIS_PASSWORD' # 1MB = 1024*1024 \ No newline at end of file +MB_BYTES = 1048576 \ No newline at end of file
codereview_new_python_data_3945
def download_result(self, result_path: str, local_folder: str): """ Supports downloading files from the result folder. Only support paths starts with `dbfs:/` and only support downloading files in one folder (per Spark's design, everything will be in the result folder in a flat manner) """ - print(result_path,result_path.startswith('dfbs')) if not result_path.startswith('dfbs'): RuntimeError('Currently only paths starting with dbfs is supported for downloading results from a databricks cluster. The path should start with \"dbfs:\" .') add a test for this? def download_result(self, result_path: str, local_folder: str): """ Supports downloading files from the result folder. Only support paths starts with `dbfs:/` and only support downloading files in one folder (per Spark's design, everything will be in the result folder in a flat manner) """ if not result_path.startswith('dfbs'): RuntimeError('Currently only paths starting with dbfs is supported for downloading results from a databricks cluster. The path should start with \"dbfs:\" .')
codereview_new_python_data_3946
from enum import Enum class Aggregation(Enum): NOP = 0 AVG = 1 MAX = 2 MIN = 3 SUM = 4 UNION = 5 ELEMENTWISE_AVG = 6 ELEMENTWISE_MIN = 7 ELEMENTWISE_MAX = 8 ELEMENTWISE_SUM = 9 LATEST = 10 \ No newline at end of file explain what does each aggregation do from enum import Enum + class Aggregation(Enum): + """ + The built-in aggregation functions for LookupFeature + """ + # No operation NOP = 0 + # Average AVG = 1 MAX = 2 MIN = 3 SUM = 4 UNION = 5 + # Element-wise average, typically used in array type value, i.e. 1d dense tensor ELEMENTWISE_AVG = 6 ELEMENTWISE_MIN = 7 ELEMENTWISE_MAX = 8 ELEMENTWISE_SUM = 9 + # Pick the latest value according to its timestamp LATEST = 10 \ No newline at end of file
codereview_new_python_data_3947
-from feathr.feature import Feature -from feathr.lookup_feature import LookupFeature -from feathr.dtype import FLOAT, FLOAT_VECTOR, ValueType, INT32_VECTOR -from feathr.typed_key import TypedKey - -from feathr.aggregation import Aggregation def assert_config_equals(one, another): assert one.translate(str.maketrans('', '', ' \n\t\r')) == another.translate(str.maketrans('', '', ' \n\t\r')) use the simplified from feathr import ... +from feathr import Aggregation +from feathr import Feature +from feathr import LookupFeature +from feathr import FLOAT, FLOAT_VECTOR, ValueType, INT32_VECTOR +from feathr import TypedKey def assert_config_equals(one, another): assert one.translate(str.maketrans('', '', ' \n\t\r')) == another.translate(str.maketrans('', '', ' \n\t\r'))
codereview_new_python_data_3948
def _get_sql_config_str(self): return config_str def _get_snowflake_config_str(self): - """Construct the Snowflake config string for jdbc. The dbtable (query), user, password and other parameters can be set via - environment variables.""" sf_url = self.envutils.get_environment_variable_with_default('offline_store', 'snowflake', 'url') sf_user = self.envutils.get_environment_variable_with_default('offline_store', 'snowflake', 'user') sf_role = self.envutils.get_environment_variable_with_default('offline_store', 'snowflake', 'role') update the doc. Seems only url, user and role are set via yaml. Password is set through env. def _get_sql_config_str(self): return config_str def _get_snowflake_config_str(self): + """Construct the Snowflake config string for jdbc. The url, user, role and other parameters can be set via + yaml config. Password can be set via environment variables.""" sf_url = self.envutils.get_environment_variable_with_default('offline_store', 'snowflake', 'url') sf_user = self.envutils.get_environment_variable_with_default('offline_store', 'snowflake', 'user') sf_role = self.envutils.get_environment_variable_with_default('offline_store', 'snowflake', 'role')
codereview_new_python_data_3949
"pandas", "redis", "requests", - "scikit-learn", "pyapacheatlas", "pyhocon", "pandavro", "python-snappy", "pyyaml", "Jinja2", "google", "google-api-python-client" ], entry_points={ 'console_scripts': ['feathr=feathrcli.cli:cli'] You might want to put some versioning here (like larger than a certain version) to make the maintenance easier. "pandas", "redis", "requests", "pyapacheatlas", "pyhocon", "pandavro", "python-snappy", "pyyaml", "Jinja2", "google", +<<<<<<< HEAD "google-api-python-client" +======= + "google-api-python-client", + "pytest" +>>>>>>> 37b3d6b2bc8e09ae336f4c965de4077f866afbde ], entry_points={ 'console_scripts': ['feathr=feathrcli.cli:cli']
codereview_new_python_data_3955
def _get_sql_config_str(self): """.format(JDBC_TABLE=table, JDBC_USER=user, JDBC_PASSWORD=password) return config_str - def sync_features(self, project_name): """ Sync features from the registry given a project name """ self.registry.sync_features_from_registry(project_name, os.path.abspath("./")) \ No newline at end of file Should we say something like "get_features_from_registry" so that it's clear on the direction? def _get_sql_config_str(self): """.format(JDBC_TABLE=table, JDBC_USER=user, JDBC_PASSWORD=password) return config_str + def get_features_from_registry(self, project_name): """ Sync features from the registry given a project name """ self.registry.sync_features_from_registry(project_name, os.path.abspath("./")) \ No newline at end of file
codereview_new_python_data_3956
def list_registered_features(self, project_name: str = None) -> List[str]: return feature_list - def sync_features_from_registry(self, project_name: str, workspace_path: str): """[Sync Features from registry to local workspace, given a project_name, will write project's features from registry to to user's local workspace] Args: project_name (str): project name. Should we say something like "get_features_from_registry" so that it's clear on the direction? def list_registered_features(self, project_name: str = None) -> List[str]: return feature_list + def get_features_from_registry(self, project_name: str, workspace_path: str): """[Sync Features from registry to local workspace, given a project_name, will write project's features from registry to to user's local workspace] Args: project_name (str): project name.
codereview_new_python_data_3957
def _get_sql_config_str(self): return config_str def get_features_from_registry(self, project_name): - """ Sync features from the registry given a project name """ self.registry.get_features_from_registry(project_name, os.path.abspath("./")) \ No newline at end of file Is this by design that specify workspace path is not exposed to user? They can only achieve so, by execute code under certain workspace folder. def _get_sql_config_str(self): return config_str def get_features_from_registry(self, project_name): + """ Sync features from the registry given a project name """ + # TODO - Add support for customized workspace path self.registry.get_features_from_registry(project_name, os.path.abspath("./")) \ No newline at end of file
codereview_new_python_data_4000
def run(self): # in DynamicRequirements and optionally define a custom complete method def custom_complete(complete_fn): # example: Data() stores all outputs in the same directory, so avoid doing len(data) fs - # calls but rather check the only the first, and compare basenames for the rest # (complete_fn defaults to "lambda task: task.complete()" but can also include caching) if not complete_fn(data_dependent_deps[0]): return False perhaps typo? should this read `...but rather check only the first,...`? (too many `the`s) def run(self): # in DynamicRequirements and optionally define a custom complete method def custom_complete(complete_fn): # example: Data() stores all outputs in the same directory, so avoid doing len(data) fs + # calls but rather check only the first, and compare basenames for the rest # (complete_fn defaults to "lambda task: task.complete()" but can also include caching) if not complete_fn(data_dependent_deps[0]): return False
codereview_new_python_data_4002
def contents(self): # # @param self A file object. - def length(self): return vine_file_length(self._file) ## Suggest the more pythonic `def __len__(self)`. Code then calls `len(File(...))` def contents(self): # # @param self A file object. + def __len__(self): return vine_file_length(self._file) ##
codereview_new_python_data_4003
class FileBuffer(File): # @param buffer The contents of the buffer, or None for an empty output buffer. def __init__(self, buffer=None): - if buffer is None: - self._file = vine_file_buffer(None,0); else: - buffer = str(buffer) self._file = vine_file_buffer(buffer, len(buffer)) ## `if not buffer:` class FileBuffer(File): # @param buffer The contents of the buffer, or None for an empty output buffer. def __init__(self, buffer=None): + if not buffer: + self._file = vine_file_buffer(None,0) else: + buffer = bytes(buffer,"ascii") self._file = vine_file_buffer(buffer, len(buffer)) ##
codereview_new_python_data_4004
class FileBuffer(File): # @param buffer The contents of the buffer, or None for an empty output buffer. def __init__(self, buffer=None): - if buffer is None: - self._file = vine_file_buffer(None,0); else: - buffer = str(buffer) self._file = vine_file_buffer(buffer, len(buffer)) ## I don't think you want str, as that calls a method on buffer which may not give you what you want. Suggest for now: ``` buffer = bytes(buffer, "ascii") ``` In the future we may want to use memory views: https://stackoverflow.com/questions/16998686/expose-a-vector-as-a-memoryview-using-swig class FileBuffer(File): # @param buffer The contents of the buffer, or None for an empty output buffer. def __init__(self, buffer=None): + if not buffer: + self._file = vine_file_buffer(None,0) else: + buffer = bytes(buffer,"ascii") self._file = vine_file_buffer(buffer, len(buffer)) ##
codereview_new_python_data_4005
sys.exit(1) print("listening on port", m.port) - m.enable_debug_log("manager.log") - temp_files = [] for i in range(0, 36): temp_files.append(vine.FileTemp()) enable_debug_log not there anymore. Logs always in `vine-run-info/%Y-%m-%dT%H:%M:%S` (see https://cctools.readthedocs.io/en/latest/taskvine/#logging-facilities) sys.exit(1) print("listening on port", m.port) temp_files = [] for i in range(0, 36): temp_files.append(vine.FileTemp())
codereview_new_python_data_4012
def remote_wrapper(event, q=None): def send_configuration(config): config_string = json.dumps(config) - print(len(config_string) + 1, "\\n", config_string + "\\n", flush=True) def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) The print is sending itself a newline, is this intended? Let's be more explicit about this protocol, e.g.: ```python conf_cmd = r"{}\n{}\n\n".format(len(config_string)+1, config_string) sys.stdout.write(conf_cmd) sys.stdout.flush() ``` or something like that. def remote_wrapper(event, q=None): def send_configuration(config): config_string = json.dumps(config) + config_cmd = f"{len(config_string) + 1}\\n{config_string}\\n" + sys.stdout.write(config_cmd) + sys.stdout.flush() def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
codereview_new_python_data_4016
def _clear_widgets(self): self.keystring, self.prog, self.clock, *self._text_widgets]: assert isinstance(widget, QWidget) if widget in [self.prog, self.backforward]: - widget.enabled=False widget.hide() self._hbox.removeWidget(widget) self._text_widgets.clear() For the mypy error probably just slap a `# type: ignore[attr-defined]` on the end of the line. I think the whole statusbar/ folder is a bit beyond consistent typing and polymorphism at this point an needs a good refactor. def _clear_widgets(self): self.keystring, self.prog, self.clock, *self._text_widgets]: assert isinstance(widget, QWidget) if widget in [self.prog, self.backforward]: + widget.enabled = False # type: ignore[attr-defined] widget.hide() self._hbox.removeWidget(widget) self._text_widgets.clear()
codereview_new_python_data_4140
def main(): - for project in ('.', 'op-wheel'): print(f'Updating {project}...') update_mod(project) Note that `indexer/go.mod` also references op-geth but wasn't previously included in the list to update. Should it be added here? def main(): + for project in ('.', 'op-wheel', 'indexer'): print(f'Updating {project}...') update_mod(project)
codereview_new_python_data_4191
class DumpDetResults(DumpResults): segmentation masks into RLE format. Args: - keep_gt (bool): Whether dumped `gt_instances` simultaneously. It should be True if offline VOCMetric is used. Defaults to False. keep_gt_ignore (bool): Whether dumped `ignored_instances` simultaneously. It should be True if offline VOCMetric is used. ```suggestion keep_gt (bool): Whether to dump `gt_instances` simultaneously. It ``` class DumpDetResults(DumpResults): segmentation masks into RLE format. Args: + keep_gt (bool): Whether to dump `gt_instances` simultaneously. It should be True if offline VOCMetric is used. Defaults to False. keep_gt_ignore (bool): Whether dumped `ignored_instances` simultaneously. It should be True if offline VOCMetric is used.
codereview_new_python_data_4192
def _forward(self, mask_outs = self.mask_head.forward(x) else: mask_outs = self.mask_head.forward(x, positive_infos) - outs = outs + (mask_outs[0], ) return outs def loss(self, batch_inputs: Tensor, batch_data_samples: SampleList, Can we add some comments above this line to explain? I do not quite understand mask_outs[0] def _forward(self, mask_outs = self.mask_head.forward(x) else: mask_outs = self.mask_head.forward(x, positive_infos) + # YOLACT segmentation branch, + # if not training will not process the forward function. + if hasattr(self.mask_head, 'segm_branch') and not self.training: + outs = outs + (mask_outs[0], ) + else: + outs = outs + (mask_outs, ) return outs def loss(self, batch_inputs: Tensor, batch_data_samples: SampleList,
codereview_new_python_data_4193
def forward(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_img_metas=batch_img_metas, batch_gt_instances=batch_gt_instances) bbox_results.pop('loss_bbox') bbox_results.pop('results_list') bbox_res = bbox_results.copy() bbox_res.pop('sampling_results') May add comments to indicate why def forward(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_img_metas=batch_img_metas, batch_gt_instances=batch_gt_instances) bbox_results.pop('loss_bbox') + # JIT don't support type NoneType bbox_results.pop('results_list') bbox_res = bbox_results.copy() bbox_res.pop('sampling_results')
codereview_new_python_data_4194
def _forward(self, mask_outs = self.mask_head.forward(x) else: mask_outs = self.mask_head.forward(x, positive_infos) - # YOLACT segmentation branch, - # if not training will not process the forward function. - if hasattr(self.mask_head, 'segm_branch') and not self.training: - outs = outs + (mask_outs[0], ) - else: - outs = outs + (mask_outs, ) return outs def loss(self, batch_inputs: Tensor, batch_data_samples: SampleList, If the child's logic is different from the parent, you should overwrite this method in the child instead of modify the parent. def _forward(self, mask_outs = self.mask_head.forward(x) else: mask_outs = self.mask_head.forward(x, positive_infos) + outs = outs + (mask_outs, ) return outs def loss(self, batch_inputs: Tensor, batch_data_samples: SampleList,
codereview_new_python_data_4195
def forward(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_img_metas=batch_img_metas, batch_gt_instances=batch_gt_instances) bbox_results.pop('loss_bbox') - # JIT don't support type SamplingResult bbox_results.pop('results_list') bbox_res = bbox_results.copy() bbox_res.pop('sampling_results') xxx.jit does not support obj:``SamplingResult`` def forward(self, x: Tuple[Tensor], rpn_results_list: InstanceList, batch_img_metas=batch_img_metas, batch_gt_instances=batch_gt_instances) bbox_results.pop('loss_bbox') + # torch.jit does not support obj:SamplingResult bbox_results.pop('results_list') bbox_res = bbox_results.copy() bbox_res.pop('sampling_results')
codereview_new_python_data_4196
def main(args): logger.info(f'Processing: {model_name}') - http_prefix = 'https://download.openmmlab.com/mmclassification/' if args.checkpoint_root is not None: root = args.checkpoint_root if 's3://' in args.checkpoint_root: mmcls or mmdet? def main(args): logger.info(f'Processing: {model_name}') + http_prefix = 'https://download.openmmlab.com/mmdetection/' if args.checkpoint_root is not None: root = args.checkpoint_root if 's3://' in args.checkpoint_root:
codereview_new_python_data_4197
def inference(args, logger): # 2. load a picture from the dataset # In two stage detectors, _forward need batch_samples to get # rpn_results_list, then use rpn_results_list to compute flops, - # so only support use the second way. try: model = MODELS.build(cfg.model) if torch.cuda.is_available(): so only the second way is supported def inference(args, logger): # 2. load a picture from the dataset # In two stage detectors, _forward need batch_samples to get # rpn_results_list, then use rpn_results_list to compute flops, + # so only the second way is supported try: model = MODELS.build(cfg.model) if torch.cuda.is_available():
codereview_new_python_data_4198
class DetDataPreprocessor(ImgDataPreprocessor): boxtype2tensor (bool): Whether to keep the ``BaseBoxes`` type of bboxes data or not. Defaults to True. non_blocking (bool): Whether block current process - when transferring data to device. New in version v0.3.0. - Defaults to False. batch_augments (list[dict], optional): Batch-level augmentations """ It would be better to enable non_blocking and pin_memory in the base config. class DetDataPreprocessor(ImgDataPreprocessor): boxtype2tensor (bool): Whether to keep the ``BaseBoxes`` type of bboxes data or not. Defaults to True. non_blocking (bool): Whether block current process + when transferring data to device. Defaults to False. batch_augments (list[dict], optional): Batch-level augmentations """
codereview_new_python_data_4199
class DumpDetResults(DumpResults): """Dump model predictions to a pickle file for offline evaluation. Args: out_file_path (str): Path of the dumped file. Must end with '.pkl' or '.pickle'. Might indicate what is the difference between it and the DumpResults. class DumpDetResults(DumpResults): """Dump model predictions to a pickle file for offline evaluation. + Different from `DumpResults` in MMEngine, it compresses instance + segmentation masks into RLE format. + Args: out_file_path (str): Path of the dumped file. Must end with '.pkl' or '.pickle'.
codereview_new_python_data_4200
train_pipeline = [ dict( type='LoadImageFromFile', - file_client_args={{_base_.file_client_args}}, imdecode_backend=backend), dict(type='LoadAnnotations', with_bbox=True, with_mask=False), dict(type='RandomFlip', prob=0.5), ```suggestion file_client_args=_base_.file_client_args, ``` train_pipeline = [ dict( type='LoadImageFromFile', + file_client_args=_base_.file_client_args, imdecode_backend=backend), dict(type='LoadAnnotations', with_bbox=True, with_mask=False), dict(type='RandomFlip', prob=0.5),
codereview_new_python_data_4201
train_pipeline = [ dict( type='LoadImageFromFile', - file_client_args={{_base_.file_client_args}}, imdecode_backend=backend), dict(type='LoadAnnotations', with_bbox=True, with_mask=False), dict(type='RandomFlip', prob=0.5), ```suggestion dict(type='LoadAnnotations', with_bbox=True), ``` train_pipeline = [ dict( type='LoadImageFromFile', + file_client_args=_base_.file_client_args, imdecode_backend=backend), dict(type='LoadAnnotations', with_bbox=True, with_mask=False), dict(type='RandomFlip', prob=0.5),
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1