index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20,533 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/command_center/models.py | 497,499 | 482,505 | load_from_file_path | CommandCenterSettings | 499,501 | 499,501 | @dataclass
class CommandCenterSettings(CommandCenterBaseClass):
cache: CacheSettings = None
history: HistorySettings = field(default_factory=lambda: dict(
pages=dict(size=5),
picks=dict(size=100),
searches=dict(size=12),
))
interface: InterfaceSettings = None
def __post_init... | @dataclass
class CommandCenterSettings(CommandCenterBaseClass):
cache: CacheSettings = None
history: HistorySettings = field(default_factory=lambda: dict(
pages=dict(size=5),
picks=dict(size=100),
searches=dict(size=12),
))
interface: InterfaceSettings = None
def __post_init... | return self.load(**(load_settings(full_path=file_path) or {}))
| return self.load(**(load_settings(full_path=file_path) or {}))
| 4 | 226 | 27 | 253 | from dataclasses import dataclass, field
from typing import Dict, List, Union
from mage_ai.api.operations.constants import OperationType
from mage_ai.command_center.constants import (
ApplicationExpansionUUID,
ApplicationType,
ButtonActionType,
InteractionType,
ItemTagEnum,
ItemType,
ModeTy... | from dataclasses import dataclass, field
from typing import Dict, List, Union
from mage_ai.api.operations.constants import OperationType
from mage_ai.command_center.constants import (
ApplicationExpansionUUID,
ApplicationType,
ButtonActionType,
InteractionType,
ItemTagEnum,
ItemType,
ModeTy... |
20,534 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/command_center/pipeline_runs/utils.py | 82,89 | 1,142 | build_and_score | 89,142 | 89,142 | from typing import Dict, List
from mage_ai.api.operations.constants import OperationType
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.orchestration.db.models.schedules import PipelineRun, PipelineSchedule
def add_application_ac... | from typing import Dict, List
from mage_ai.api.operations.constants import OperationType
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.orchestration.db.models.schedules import PipelineRun, PipelineSchedule
def add_application_ac... | description = str(model.status)
if model.completed_at:
description = f'{description} on {model.completed_at.isoformat()}'
elif model.started_at:
description = f'{description} after starting on {model.started_at.isoformat()}'
elif model.execution_partition:
description = f'{descr... | description = str(model.status)
if model.completed_at:
description = f'{description} on {model.completed_at.isoformat()}'
elif model.started_at:
description = f'{description} after starting on {model.started_at.isoformat()}'
elif model.execution_partition:
description = f'{descr... | 101 | 653 | 640 | 1,293 | from typing import Dict, List
from mage_ai.api.operations.constants import OperationType
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.orchestration.db.models.schedules import PipelineRun, PipelineSchedule
def add_application_ac... | from typing import Dict, List
from mage_ai.api.operations.constants import OperationType
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.orchestration.db.models.schedules import PipelineRun, PipelineSchedule
def add_application_ac... | |
20,535 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/command_center/pipelines/utils.py | 14,15 | 1,121 | add_application_actions | 15,67 | 15,67 | import urllib.parse
from typing import Dict, List, Tuple
from mage_ai.api.operations.constants import OperationType
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.data_preparation.models.constants import PIPELINE_TYPE_DISPLAY_NAME_... | import urllib.parse
from typing import Dict, List, Tuple
from mage_ai.api.operations.constants import OperationType
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.data_preparation.models.constants import PIPELINE_TYPE_DISPLAY_NAME_... | metadata = (item_dict.get('metadata') or {}).get('pipeline') or {}
uuid = metadata.get('uuid')
application_action = dict(
request=dict(
operation=OperationType.DETAIL,
resource='pipelines',
resource_id=urllib.parse.quote_plus(uuid or ''),
response_res... | metadata = (item_dict.get('metadata') or {}).get('pipeline') or {}
uuid = metadata.get('uuid')
application_action = dict(
request=dict(
operation=OperationType.DETAIL,
resource='pipelines',
resource_id=urllib.parse.quote_plus(uuid or ''),
response_res... | 62 | 634 | 425 | 1,059 | import urllib.parse
from typing import Dict, List, Tuple
from mage_ai.api.operations.constants import OperationType
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.data_preparation.models.constants import PIPELINE_TYPE_DISPLAY_NAME_... | import urllib.parse
from typing import Dict, List, Tuple
from mage_ai.api.operations.constants import OperationType
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.data_preparation.models.constants import PIPELINE_TYPE_DISPLAY_NAME_... | |
20,536 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/command_center/presenters/text.py | 4,5 | 1,10 | application_title | 5,10 | 5,10 | from mage_ai.command_center.constants import ApplicationExpansionUUID
def application_title(uuid: ApplicationExpansionUUID) -> str:
FILL_FUNC_BODY | from mage_ai.command_center.constants import ApplicationExpansionUUID
def application_title(uuid: ApplicationExpansionUUID) -> str:
FILL_FUNC_BODY | if ApplicationExpansionUUID.VersionControlFileDiffs == uuid:
return 'version control file diffs'
if ApplicationExpansionUUID.ArcaneLibrary == uuid:
return 'the Text Editor'
return f'the {uuid} application'
| if ApplicationExpansionUUID.VersionControlFileDiffs == uuid:
return 'version control file diffs'
if ApplicationExpansionUUID.ArcaneLibrary == uuid:
return 'the Text Editor'
return f'the {uuid} application'
| 21 | 47 | 66 | 113 | from mage_ai.command_center.constants import ApplicationExpansionUUID
def application_title(uuid: ApplicationExpansionUUID) -> str:
FILL_FUNC_BODY | from mage_ai.command_center.constants import ApplicationExpansionUUID
def application_title(uuid: ApplicationExpansionUUID) -> str:
FILL_FUNC_BODY | |
20,537 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/command_center/service.py | 24,25 | 1,26 | search_items | 25,26 | 25,26 | from typing import List
from mage_ai.command_center.applications.factory import ApplicationFactory
from mage_ai.command_center.blocks.factory import BlockFactory
from mage_ai.command_center.factory import BaseFactory
from mage_ai.command_center.files.factory import FileFactory
from mage_ai.command_center.models import... | from typing import List
from mage_ai.command_center.applications.factory import ApplicationFactory
from mage_ai.command_center.blocks.factory import BlockFactory
from mage_ai.command_center.factory import BaseFactory
from mage_ai.command_center.files.factory import FileFactory
from mage_ai.command_center.models import... | return await BaseFactory.create_items(FACTORIES_OR_ITEMS, **kwargs)
| return await BaseFactory.create_items(FACTORIES_OR_ITEMS, **kwargs)
| 4 | 258 | 25 | 283 | from typing import List
from mage_ai.command_center.applications.factory import ApplicationFactory
from mage_ai.command_center.blocks.factory import BlockFactory
from mage_ai.command_center.factory import BaseFactory
from mage_ai.command_center.files.factory import FileFactory
from mage_ai.command_center.models import... | from typing import List
from mage_ai.command_center.applications.factory import ApplicationFactory
from mage_ai.command_center.blocks.factory import BlockFactory
from mage_ai.command_center.factory import BaseFactory
from mage_ai.command_center.files.factory import FileFactory
from mage_ai.command_center.models import... | |
20,539 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/command_center/utils.py | 6,7 | 1,31 | shorten_directory | 7,31 | 7,31 | import os
from pathlib import Path
from typing import Dict
def shorten_directory(full_path: str) -> Dict:
FILL_FUNC_BODY | import os
from pathlib import Path
from typing import Dict
def shorten_directory(full_path: str) -> Dict:
FILL_FUNC_BODY | parts = Path(os.path.dirname(full_path)).parts
parts_count = len(parts)
dir_name = ''
if parts_count >= 1:
os.path.join(*parts[max([0, parts_count - 3]):])
if parts_count >= 4:
if parts_count >= 5:
dir_name = os.path.join('.', dir_name)
else:
dir_name... | parts = Path(os.path.dirname(full_path)).parts
parts_count = len(parts)
dir_name = ''
if parts_count >= 1:
os.path.join(*parts[max([0, parts_count - 3]):])
if parts_count >= 4:
if parts_count >= 5:
dir_name = os.path.join('.', dir_name)
else:
dir_name... | 62 | 45 | 248 | 293 | import os
from pathlib import Path
from typing import Dict
def shorten_directory(full_path: str) -> Dict:
FILL_FUNC_BODY | import os
from pathlib import Path
from typing import Dict
def shorten_directory(full_path: str) -> Dict:
FILL_FUNC_BODY | |
20,541 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/command_center/version_control/constants.py | 37,38 | 1,120 | build_reset_authentication_github | 38,78 | 38,78 | import urllib.parse
from typing import Dict
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.resources.OauthResource import OauthResource
from mage_ai.authentication.oauth.constants import ProviderName
from mage_ai.command_center.constants import (
ItemType,
ModeType,
ObjectType,... | import urllib.parse
from typing import Dict
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.resources.OauthResource import OauthResource
from mage_ai.authentication.oauth.constants import ProviderName
from mage_ai.command_center.constants import (
ItemType,
ModeType,
ObjectType,... | expires_on = oauth_resource.expires
if expires_on:
expires_on = expires_on.strftime('%b %-d, %y')
return dict(
uuid=f'reset_authentication_github_version_control_{user.id if user else "user"}',
item_type=ItemType.DELETE,
object_type=ObjectType.AUTHENTICATION,
title='G... | expires_on = oauth_resource.expires
if expires_on:
expires_on = expires_on.strftime('%b %-d, %y')
return dict(
uuid=f'reset_authentication_github_version_control_{user.id if user else "user"}',
item_type=ItemType.DELETE,
object_type=ObjectType.AUTHENTICATION,
title='G... | 58 | 711 | 404 | 1,115 | import urllib.parse
from typing import Dict
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.resources.OauthResource import OauthResource
from mage_ai.authentication.oauth.constants import ProviderName
from mage_ai.command_center.constants import (
ItemType,
ModeType,
ObjectType,... | import urllib.parse
from typing import Dict
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.resources.OauthResource import OauthResource
from mage_ai.authentication.oauth.constants import ProviderName
from mage_ai.command_center.constants import (
ItemType,
ModeType,
ObjectType,... | |
20,543 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/command_center/version_control/projects/constants.py | 14,15 | 1,103 | build_create_project | 15,103 | 15,103 | from typing import Dict
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.policies.FilePolicy import FilePolicy
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.presenters.interactions.constants import Inter... | from typing import Dict
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.policies.FilePolicy import FilePolicy
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.presenters.interactions.constants import Inter... | return dict(
item_type=ItemType.CREATE,
object_type=ObjectType.PROJECT,
title='New Git project',
description='Initialize Git in a folder to start pulling or pushing code.',
display_settings_by_attribute=dict(
icon=dict(
icon_uuid='Categories',
... | return dict(
item_type=ItemType.CREATE,
object_type=ObjectType.PROJECT,
title='New Git project',
description='Initialize Git in a folder to start pulling or pushing code.',
display_settings_by_attribute=dict(
icon=dict(
icon_uuid='Categories',
... | 122 | 125 | 777 | 902 | from typing import Dict
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.policies.FilePolicy import FilePolicy
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.presenters.interactions.constants import Inter... | from typing import Dict
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.policies.FilePolicy import FilePolicy
from mage_ai.command_center.constants import (
ApplicationType,
ButtonActionType,
ItemType,
ObjectType,
)
from mage_ai.presenters.interactions.constants import Inter... | |
20,545 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/command_center/version_control/shared/utils.py | 6,7 | 1,28 | add_validate_output_error_fatal | 7,28 | 7,28 | from typing import Dict
from mage_ai.command_center.constants import ValidationType
def add_validate_output_error_fatal(item_dict: Dict) -> Dict:
FILL_FUNC_BODY | from typing import Dict
from mage_ai.command_center.constants import ValidationType
def add_validate_output_error_fatal(item_dict: Dict) -> Dict:
FILL_FUNC_BODY | action_uuid = item_dict['actions'][0]['uuid']
item_dict['actions'][1]['validations'] = [ValidationType.CUSTOM_VALIDATION_PARSERS]
item_dict['actions'][1]['validation_parsers'] = [
dict(
positional_argument_names=[
'item',
'action',
'applic... | action_uuid = item_dict['actions'][0]['uuid']
item_dict['actions'][1]['validations'] = [ValidationType.CUSTOM_VALIDATION_PARSERS]
item_dict['actions'][1]['validation_parsers'] = [
dict(
positional_argument_names=[
'item',
'action',
'applic... | 32 | 61 | 222 | 283 | from typing import Dict
from mage_ai.command_center.constants import ValidationType
def add_validate_output_error_fatal(item_dict: Dict) -> Dict:
FILL_FUNC_BODY | from typing import Dict
from mage_ai.command_center.constants import ValidationType
def add_validate_output_error_fatal(item_dict: Dict) -> Dict:
FILL_FUNC_BODY | |
20,546 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/analysis/calculator.py | 50,51 | 32,185 | __process | AnalysisCalculator | 51,103 | 51,103 | class AnalysisCalculator:
def __init__(
self,
df,
column_types,
statistics,
verbose=False,
**kwargs,
):
self.df = df
self.column_types = column_types
self.features = [{'uuid': col, 'column_type': column_types.get(col)} for col in df.columns... | class AnalysisCalculator:
def __init__(
self,
df,
column_types,
statistics,
verbose=False,
**kwargs,
):
self.df = df
self.column_types = column_types
self.features = [{'uuid': col, 'column_type': column_types.get(col)} for col in df.columns... | increment(f'{DD_KEY}.process.start', self.tags)
df_columns = df.columns
features_to_use = self.features
datetime_features_to_use = [f for f in self.datetime_features if f['uuid'] in df_columns]
numeric_features_to_use = self.numeric_features
if not is_clean:
... | increment(f'{DD_KEY}.process.start', self.tags)
df_columns = df.columns
features_to_use = self.features
datetime_features_to_use = [f for f in self.datetime_features if f['uuid'] in df_columns]
numeric_features_to_use = self.numeric_features
if not is_clean:
... | 118 | 956 | 584 | 1,540 | from mage_ai.data_cleaner.analysis import charts
from mage_ai.data_cleaner.analysis.constants import (
DATA_KEY_CHARTS,
DATA_KEY_CORRELATION,
DATA_KEY_TIME_SERIES,
)
from mage_ai.data_cleaner.column_types.constants import ColumnType
from mage_ai.data_cleaner.shared.utils import clean_dataframe, is_numeric_d... | from mage_ai.data_cleaner.analysis import charts
from mage_ai.data_cleaner.analysis.constants import (
DATA_KEY_CHARTS,
DATA_KEY_CORRELATION,
DATA_KEY_TIME_SERIES,
)
from mage_ai.data_cleaner.column_types.constants import ColumnType
from mage_ai.data_cleaner.shared.utils import clean_dataframe, is_numeric_d... |
20,547 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/base.py | 17,18 | 7,66 | _filter_numeric_types | BaseRule | 18,29 | 18,29 | class BaseRule:
default_config = dict()
def __init__(self, df, column_types, statistics, custom_config={}):
self.df = df
self.df_columns = df.columns.tolist()
self.column_types = column_types
self.statistics = statistics
self.custom_config = custom_config
def _filte... | class BaseRule:
default_config = dict()
def __init__(self, df, column_types, statistics, custom_config={}):
self.df = df
self.df_columns = df.columns.tolist()
self.column_types = column_types
self.statistics = statistics
self.custom_config = custom_config
def _filte... | numeric_columns = []
numeric_df = self.df.copy()
for column in self.df_columns:
if self.column_types[column] in NUMBER_TYPES:
numeric_df.loc[:, column] = numeric_df.loc[:, column].astype(float)
numeric_columns.append(column)
else:
... | numeric_columns = []
numeric_df = self.df.copy()
for column in self.df_columns:
if self.column_types[column] in NUMBER_TYPES:
numeric_df.loc[:, column] = numeric_df.loc[:, column].astype(float)
numeric_columns.append(column)
else:
... | 30 | 380 | 158 | 538 | from mage_ai.data_cleaner.column_types.constants import NUMBER_TYPES
STATUS_NOT_APPLIED = 'not_applied'
STATUS_COMPLETED = 'completed'
class BaseRule:
default_config = dict()
def __init__(self, df, column_types, statistics, custom_config={}):
self.df = df
self.df_columns = df.columns.tolist(... | from mage_ai.data_cleaner.column_types.constants import NUMBER_TYPES
STATUS_NOT_APPLIED = 'not_applied'
STATUS_COMPLETED = 'completed'
class BaseRule:
default_config = dict()
def __init__(self, df, column_types, statistics, custom_config={}):
self.df = df
self.df_columns = df.columns.tolist(... |
20,548 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/clean_column_names.py | 22,23 | 7,47 | evaluate | CleanColumnNames | 32,47 | 23,47 | class CleanColumnNames(BaseRule):
def is_dirty(self, name):
if NameConventionPatterns.NON_ALNUM.search(name):
return True
if REGEX_NUMBER.match(name) is not None:
return True
if iskeyword(name):
return True
if NameConventionPatterns.SNAKE.match(na... | class CleanColumnNames(BaseRule):
def is_dirty(self, name):
if NameConventionPatterns.NON_ALNUM.search(name):
return True
if REGEX_NUMBER.match(name) is not None:
return True
if iskeyword(name):
return True
if NameConventionPatterns.SNAKE.match(na... | matches = list(filter(self.is_dirty, self.df_columns))
suggestions = []
if len(matches) != 0:
suggestions.append(
self._build_transformer_action_suggestion(
'Clean dirty column names',
'Format these column names as lowercase and... | """
Rule:
1. If column name contains an nonalphanumeric character (except _),
suggest cleaning (remove all characters)
2. If the column name is a number, suggest cleaning (prefix with 'number_')
3. If the column name is a reseved keyword, suggest cleaning (postfix with... | 38 | 263 | 154 | 417 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.column_type_detector import REGEX_NUMBER
from mage_ai.data_cleaner.transformer_actions.constants import ActionType, NameConventionPatterns
from keyword import iskeyword
class CleanColumnNames(BaseRule):
def is_dir... | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.column_type_detector import REGEX_NUMBER
from mage_ai.data_cleaner.transformer_actions.constants import ActionType, NameConventionPatterns
from keyword import iskeyword
class CleanColumnNames(BaseRule):
def is_dir... |
20,549 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/fix_syntax_errors.py | 10,11 | 9,31 | evaluate | FixSyntaxErrors | 11,31 | 11,31 | class FixSyntaxErrors(BaseRule):
def evaluate(self):
FILL_FUNC_BODY | class FixSyntaxErrors(BaseRule):
def evaluate(self):
FILL_FUNC_BODY | columns_with_syntax_errors = []
for column in self.df_columns:
if self.statistics[f'{column}/invalid_value_rate'] > 0:
columns_with_syntax_errors.append(column)
suggestions = []
if len(columns_with_syntax_errors):
suggestions.append(
... | columns_with_syntax_errors = []
for column in self.df_columns:
if self.statistics[f'{column}/invalid_value_rate'] > 0:
columns_with_syntax_errors.append(column)
suggestions = []
if len(columns_with_syntax_errors):
suggestions.append(
... | 46 | 26 | 241 | 267 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.transformer_actions.constants import (
ActionType,
Axis,
)
from mage_ai.data_cleaner.transformer_actions.utils import build_action_variables
class FixSyntaxErrors(BaseRule):
def evaluate(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.transformer_actions.constants import (
ActionType,
Axis,
)
from mage_ai.data_cleaner.transformer_actions.utils import build_action_variables
class FixSyntaxErrors(BaseRule):
def evaluate(self):
FILL_FUNC_BODY |
20,550 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/impute_values.py | 100,101 | 92,125 | evaluate | CategoricalImputeSubRule | 110,125 | 101,125 | class CategoricalImputeSubRule(TypeImputeSubRule):
ACCEPTED_DTYPES = CATEGORICAL_TYPES
RAND_EMPTY_UB = 0.3
MODE_PROP_LB = 0.4
def accepted_dtypes(self):
return self.ACCEPTED_DTYPES
def evaluate(self, column):
FILL_FUNC_BODY | class CategoricalImputeSubRule(TypeImputeSubRule):
ACCEPTED_DTYPES = CATEGORICAL_TYPES
RAND_EMPTY_UB = 0.3
MODE_PROP_LB = 0.4
def accepted_dtypes(self):
return self.ACCEPTED_DTYPES
def evaluate(self, column):
"""
Rule:
1. If there are no null entries, no suggestion
... | if self.statistics[f'{column}/null_value_rate'] == 0:
return ImputationStrategy.NOOP
elif (
self.is_timeseries
and self.statistics[f'{column}/max_null_seq'] <= self.MAX_NULL_SEQ_LENGTH
and self.df[column].notna().iloc[0]
):
return Imput... | """
Rule:
1. If there are no null entries, no suggestion
2. If the dataset was identified as timeseries, suggest sequential imputation
3. Else, if more than MODE_PROP_LB of nonnull entries are a single value, use
imputation with mode
4. Else, if less than RAND_... | 32 | 230 | 212 | 442 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... |
20,551 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/impute_values.py | 131,132 | 125,149 | evaluate | DateTimeImputeSubRule | 138,149 | 132,149 | class DateTimeImputeSubRule(TypeImputeSubRule):
ACCEPTED_DTYPES = frozenset((ColumnType.DATETIME,))
def accepted_dtypes(self):
return self.ACCEPTED_DTYPES
def evaluate(self, column):
FILL_FUNC_BODY | class DateTimeImputeSubRule(TypeImputeSubRule):
ACCEPTED_DTYPES = frozenset((ColumnType.DATETIME,))
def accepted_dtypes(self):
return self.ACCEPTED_DTYPES
def evaluate(self, column):
"""
Rule:
1. If there are no null entries, no suggestion
2. If the dataset was iden... | if self.statistics[f'{column}/null_value_rate'] == 0:
return ImputationStrategy.NOOP
elif (
self.is_timeseries
and self.statistics[f'{column}/max_null_seq'] <= self.MAX_NULL_SEQ_LENGTH
and self.df[column].notna().iloc[0]
):
return Imput... | """
Rule:
1. If there are no null entries, no suggestion
2. If the dataset was identified as timeseries, suggest sequential imputation
3. Else suggest no imputation (no good fit)
"""
if self.statistics[f'{column}/null_value_rate'] == 0:
return Imputati... | 20 | 142 | 130 | 272 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... |
20,553 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/impute_values.py | 157,158 | 149,182 | evaluate | ListImputeSubRule | 167,182 | 158,182 | class ListImputeSubRule(TypeImputeSubRule):
ACCEPTED_DTYPES = frozenset((ColumnType.LIST,))
RAND_EMPTY_UB = 0.3
MODE_PROP_LB = 0.4
def accepted_dtypes(self):
return self.ACCEPTED_DTYPES
def evaluate(self, column):
FILL_FUNC_BODY | class ListImputeSubRule(TypeImputeSubRule):
ACCEPTED_DTYPES = frozenset((ColumnType.LIST,))
RAND_EMPTY_UB = 0.3
MODE_PROP_LB = 0.4
def accepted_dtypes(self):
return self.ACCEPTED_DTYPES
def evaluate(self, column):
"""
Rule:
1. If there are no null entries, no sugges... | if self.statistics[f'{column}/null_value_rate'] == 0:
return ImputationStrategy.NOOP
elif (
self.is_timeseries
and self.statistics[f'{column}/max_null_seq'] <= self.MAX_NULL_SEQ_LENGTH
and self.df[column].notna().iloc[0]
):
return Imput... | """
Rule:
1. If there are no null entries, no suggestion
2. If the dataset was identified as timeseries, suggest sequential imputation
3. Else, if more than MODE_PROP_LB of nonnull entries are a single value, use
imputation with mode
4. Else, if less than RAND_... | 32 | 229 | 212 | 441 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... |
20,554 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/impute_values.py | 59,60 | 51,92 | evaluate | NumericalImputeSubRule | 71,92 | 60,92 | class NumericalImputeSubRule(TypeImputeSubRule):
ACCEPTED_DTYPES = NUMBER_TYPES
SKEW_UB = 0.7
AVG_OR_MED_EMPTY_UB = {'small': 0.3, 'large': 0.5}
def accepted_dtypes(self):
return self.ACCEPTED_DTYPES
def evaluate(self, column):
FILL_FUNC_BODY | class NumericalImputeSubRule(TypeImputeSubRule):
ACCEPTED_DTYPES = NUMBER_TYPES
SKEW_UB = 0.7
AVG_OR_MED_EMPTY_UB = {'small': 0.3, 'large': 0.5}
def accepted_dtypes(self):
return self.ACCEPTED_DTYPES
def evaluate(self, column):
"""
Rule:
1. If there are no null entr... | if self.statistics[f'{column}/null_value_rate'] == 0:
return ImputationStrategy.NOOP
elif (
self.is_timeseries
and self.statistics[f'{column}/max_null_seq'] <= self.MAX_NULL_SEQ_LENGTH
and self.df[column].notna().iloc[0]
):
return Imput... | """
Rule:
1. If there are no null entries, no suggestion
2. If the dataset was identified as timeseries, suggest sequential imputation
3. If the number of nonnull entries is sell than DATA_SM_UB, use the
small dataset bound; else use the large dataset bound
3a.... | 45 | 304 | 315 | 619 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... |
20,555 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/impute_values.py | 191,192 | 182,216 | evaluate | StringImputeSubRule | 201,216 | 192,216 | class StringImputeSubRule(TypeImputeSubRule):
# TODO: Give list type its own imputation strategy
ACCEPTED_DTYPES = STRING_TYPES
RAND_EMPTY_UB = 0.3
MODE_PROP_LB = 0.4
def accepted_dtypes(self):
return self.ACCEPTED_DTYPES
def evaluate(self, column):
FILL_FUNC_BODY | class StringImputeSubRule(TypeImputeSubRule):
# TODO: Give list type its own imputation strategy
ACCEPTED_DTYPES = STRING_TYPES
RAND_EMPTY_UB = 0.3
MODE_PROP_LB = 0.4
def accepted_dtypes(self):
return self.ACCEPTED_DTYPES
def evaluate(self, column):
"""
Rule:
1.... | if self.statistics[f'{column}/null_value_rate'] == 0:
return ImputationStrategy.NOOP
if (
self.is_timeseries
and self.statistics[f'{column}/max_null_seq'] <= self.MAX_NULL_SEQ_LENGTH
and self.df[column].notna().iloc[0]
):
return Imputat... | """
Rule:
1. If there are no null entries, no suggestion
2. If the dataset was identified as timeseries, suggest sequential imputation
3. Else, if more than MODE_PROP_LB of nonnull entries are a single value, use
imputation with mode
4. Else, if less than RAND_... | 32 | 239 | 212 | 451 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... |
20,556 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/impute_values.py | 36,37 | 17,51 | accepted_dtypes | TypeImputeSubRule | 40,44 | 37,44 | class TypeImputeSubRule:
DATA_SM_UB = 100
MAX_NULL_SEQ_LENGTH = 4
def __init__(self, df, column_types, statistics, is_timeseries=False):
"""
Assumptions of TypeImputeSubRule
1. df will not contain any empty strings - all empty strings are converted to null types.
This is han... | class TypeImputeSubRule:
DATA_SM_UB = 100
MAX_NULL_SEQ_LENGTH = 4
def __init__(self, df, column_types, statistics, is_timeseries=False):
"""
Assumptions of TypeImputeSubRule
1. df will not contain any empty strings - all empty strings are converted to null types.
This is han... | raise NotImplementedError(
'Children of TypeImputeSubRule must override \'accepted_dtypes()\''
)
| """
Gets the list of dtypes this subrule accepts and checks
"""
raise NotImplementedError(
'Children of TypeImputeSubRule must override \'accepted_dtypes()\''
)
| 9 | 310 | 40 | 350 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.column_types.constants import (
CATEGORICAL_TYPES,
NUMBER_TYPES,
STRING_TYPES,
ColumnType,
)
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants impo... |
20,557 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/remove_columns_with_high_empty_rate.py | 13,14 | 8,46 | evaluate | RemoveColumnsWithHighEmptyRate | 14,46 | 14,46 | class RemoveColumnsWithHighEmptyRate(BaseRule):
default_config = dict(
missing_rate_threshold=0.8,
)
def evaluate(self):
FILL_FUNC_BODY | class RemoveColumnsWithHighEmptyRate(BaseRule):
default_config = dict(
missing_rate_threshold=0.8,
)
def evaluate(self):
FILL_FUNC_BODY | columns_with_missing_values = []
columns_with_no_values = []
for c in self.df_columns:
if self.statistics.get(f'{c}/count') == 0:
columns_with_no_values.append(c)
elif f'{c}/null_value_rate' in self.statistics:
null_value_rate = self.statis... | columns_with_missing_values = []
columns_with_no_values = []
for c in self.df_columns:
if self.statistics.get(f'{c}/count') == 0:
columns_with_no_values.append(c)
elif f'{c}/null_value_rate' in self.statistics:
null_value_rate = self.statis... | 84 | 54 | 391 | 445 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.transformer_actions.constants import (
ActionType,
Axis,
)
class RemoveColumnsWithHighEmptyRate(BaseRule):
default_config = dict(
missing_rate_threshold=0.8,
)
def evaluate(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.transformer_actions.constants import (
ActionType,
Axis,
)
class RemoveColumnsWithHighEmptyRate(BaseRule):
default_config = dict(
missing_rate_threshold=0.8,
)
def evaluate(self):
FILL_FUNC_BODY |
20,558 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/remove_columns_with_single_value.py | 11,12 | 8,32 | evaluate | RemoveColumnsWithSingleValue | 12,32 | 12,32 | class RemoveColumnsWithSingleValue(BaseRule):
# Check statistic [feature_uuid]/count_distinct
def evaluate(self):
FILL_FUNC_BODY | class RemoveColumnsWithSingleValue(BaseRule):
# Check statistic [feature_uuid]/count_distinct
def evaluate(self):
FILL_FUNC_BODY | columns_with_single_value = []
for c in self.df_columns:
if f'{c}/count_distinct' not in self.statistics:
continue
feature_count_distinct = self.statistics[f'{c}/count_distinct']
if feature_count_distinct == 1:
columns_with_single_value... | columns_with_single_value = []
for c in self.df_columns:
if f'{c}/count_distinct' not in self.statistics:
continue
feature_count_distinct = self.statistics[f'{c}/count_distinct']
if feature_count_distinct == 1:
columns_with_single_value... | 57 | 45 | 234 | 279 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.transformer_actions.constants import (
ActionType,
Axis,
)
class RemoveColumnsWithSingleValue(BaseRule):
# Check statistic [feature_uuid]/count_distinct
def evaluate(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.transformer_actions.constants import (
ActionType,
Axis,
)
class RemoveColumnsWithSingleValue(BaseRule):
# Check statistic [feature_uuid]/count_distinct
def evaluate(self):
FILL_FUNC_BODY |
20,559 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/remove_duplicate_rows.py | 9,10 | 8,25 | evaluate | RemoveDuplicateRows | 10,25 | 10,25 | class RemoveDuplicateRows(BaseRule):
def evaluate(self):
FILL_FUNC_BODY | class RemoveDuplicateRows(BaseRule):
def evaluate(self):
FILL_FUNC_BODY | df_dedupe = self.df.drop_duplicates()
duplicate_row_count = self.df.shape[0] - df_dedupe.shape[0]
suggestions = []
if duplicate_row_count > 0:
suggestions.append(
self._build_transformer_action_suggestion(
'Remove duplicate rows',
... | df_dedupe = self.df.drop_duplicates()
duplicate_row_count = self.df.shape[0] - df_dedupe.shape[0]
suggestions = []
if duplicate_row_count > 0:
suggestions.append(
self._build_transformer_action_suggestion(
'Remove duplicate rows',
... | 39 | 27 | 176 | 203 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.transformer_actions.constants import (
ActionType,
Axis,
)
class RemoveDuplicateRows(BaseRule):
def evaluate(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.transformer_actions.constants import (
ActionType,
Axis,
)
class RemoveDuplicateRows(BaseRule):
def evaluate(self):
FILL_FUNC_BODY |
20,560 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/cleaning_rules/remove_outliers.py | 53,54 | 12,60 | evaluate | RemoveOutliers | 54,60 | 54,60 | class RemoveOutliers(BaseRule):
default_config = dict(
max_z_score=3,
)
"""
Checks dataframe for the existence of potential outliers, and generates a cleaning suggestion
to remove these outliers
"""
def one_dim_outlier_check(self, column: str) -> Union[Dict, None]:
"""
... | class RemoveOutliers(BaseRule):
default_config = dict(
max_z_score=3,
)
"""
Checks dataframe for the existence of potential outliers, and generates a cleaning suggestion
to remove these outliers
"""
def one_dim_outlier_check(self, column: str) -> Union[Dict, None]:
"""
... | suggestions = []
for col in self.df_columns:
suggestion = self.one_dim_outlier_check(col)
if suggestion:
suggestions.append(suggestion)
return suggestions
| suggestions = []
for col in self.df_columns:
suggestion = self.one_dim_outlier_check(col)
if suggestion:
suggestions.append(suggestion)
return suggestions
| 15 | 453 | 57 | 510 | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants import (
ActionType,
Axis,
)
from typing import Union, Dict
REMOVE_OUTLIERS_TITLE = 'Remove outliers'
class RemoveOutliers(BaseR... | from mage_ai.data_cleaner.cleaning_rules.base import BaseRule
from mage_ai.data_cleaner.shared.utils import wrap_column_name
from mage_ai.data_cleaner.transformer_actions.constants import (
ActionType,
Axis,
)
from typing import Union, Dict
REMOVE_OUTLIERS_TITLE = 'Remove outliers'
class RemoveOutliers(BaseR... |
20,561 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/data_cleaner.py | 10,11 | 1,108 | analyze | 11,15 | 11,15 | from mage_ai.data_cleaner.analysis.calculator import AnalysisCalculator
from mage_ai.data_cleaner.column_types import column_type_detector
from mage_ai.data_cleaner.pipelines.base import DEFAULT_RULES, BasePipeline
from mage_ai.data_cleaner.shared.utils import clean_dataframe
from mage_ai.data_cleaner.statistics.calcul... | from mage_ai.data_cleaner.analysis.calculator import AnalysisCalculator
from mage_ai.data_cleaner.column_types import column_type_detector
from mage_ai.data_cleaner.pipelines.base import DEFAULT_RULES, BasePipeline
from mage_ai.data_cleaner.shared.utils import clean_dataframe
from mage_ai.data_cleaner.statistics.calcul... | cleaner = DataCleaner()
return cleaner.analyze(df)
| cleaner = DataCleaner()
return cleaner.analyze(df)
| 5 | 1,059 | 24 | 1,083 | from mage_ai.data_cleaner.analysis.calculator import AnalysisCalculator
from mage_ai.data_cleaner.column_types import column_type_detector
from mage_ai.data_cleaner.pipelines.base import DEFAULT_RULES, BasePipeline
from mage_ai.data_cleaner.shared.utils import clean_dataframe
from mage_ai.data_cleaner.statistics.calcul... | from mage_ai.data_cleaner.analysis.calculator import AnalysisCalculator
from mage_ai.data_cleaner.column_types import column_type_detector
from mage_ai.data_cleaner.pipelines.base import DEFAULT_RULES, BasePipeline
from mage_ai.data_cleaner.shared.utils import clean_dataframe
from mage_ai.data_cleaner.statistics.calcul... | |
20,562 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/data_cleaner.py | 71,80 | 35,108 | clean | DataCleaner | 80,108 | 80,108 | class DataCleaner:
def __init__(self, verbose=False):
self.verbose = verbose
def analyze(self, df, column_types={}, df_original=None):
"""Analyze a dataframe
1. Detect column types
2. Calculate statisitics
3. Calculate analysis
"""
with timer('data_cleane... | class DataCleaner:
def __init__(self, verbose=False):
self.verbose = verbose
def analyze(self, df, column_types={}, df_original=None):
"""Analyze a dataframe
1. Detect column types
2. Calculate statisitics
3. Calculate analysis
"""
with timer('data_cleane... | df_stats = self.analyze(df, column_types=column_types, df_original=df_original)
df = df_stats['cleaned_df']
pipeline = BasePipeline(rules=rules, verbose=self.verbose)
if df_stats['statistics']['is_timeseries']:
df = df.sort_values(by=df_stats['statistics']['timeseries_index']... | df_stats = self.analyze(df, column_types=column_types, df_original=df_original)
df = df_stats['cleaned_df']
pipeline = BasePipeline(rules=rules, verbose=self.verbose)
if df_stats['statistics']['is_timeseries']:
df = df.sort_values(by=df_stats['statistics']['timeseries_index']... | 64 | 455 | 350 | 805 | from mage_ai.data_cleaner.analysis.calculator import AnalysisCalculator
from mage_ai.data_cleaner.column_types import column_type_detector
from mage_ai.data_cleaner.pipelines.base import DEFAULT_RULES, BasePipeline
from mage_ai.data_cleaner.shared.utils import clean_dataframe
from mage_ai.data_cleaner.statistics.calcul... | from mage_ai.data_cleaner.analysis.calculator import AnalysisCalculator
from mage_ai.data_cleaner.column_types import column_type_detector
from mage_ai.data_cleaner.pipelines.base import DEFAULT_RULES, BasePipeline
from mage_ai.data_cleaner.shared.utils import clean_dataframe
from mage_ai.data_cleaner.statistics.calcul... |
20,563 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/action_code.py | 24,25 | 1,115 | __query_mutate_null_type | 25,45 | 25,45 | from mage_ai.data_cleaner.transformer_actions.constants import Operator
import re
ACTION_CODE_NAME = r'(?:([^\s()"\']+|[\'\"][^"\']+[\'\"]))'
ACTION_CODE_PATTERN = re.compile(
rf'{ACTION_CODE_NAME} ([!=<>]+|(?:contains)|(?:not contains)) {ACTION_CODE_NAME}'
)
ORIGINAL_COLUMN_PREFIX = 'orig_'
QUOTES = '\"\''
TRANSF... | from mage_ai.data_cleaner.transformer_actions.constants import Operator
import re
ACTION_CODE_NAME = r'(?:([^\s()"\']+|[\'\"][^"\']+[\'\"]))'
ACTION_CODE_PATTERN = re.compile(
rf'{ACTION_CODE_NAME} ([!=<>]+|(?:contains)|(?:not contains)) {ACTION_CODE_NAME}'
)
ORIGINAL_COLUMN_PREFIX = 'orig_'
QUOTES = '\"\''
TRANSF... | condition = ['']
column_name, operator, _ = match.groups()
column_name = append_prefix(column_name, ORIGINAL_COLUMN_PREFIX)
if operator == '==':
condition.append(f'({column_name}.isna()')
if dtype == bool:
condition.append(f' | {column_name} == \'\'')
elif dtype == st... | condition = ['']
column_name, operator, _ = match.groups()
column_name = append_prefix(column_name, ORIGINAL_COLUMN_PREFIX)
if operator == '==':
condition.append(f'({column_name}.isna()')
if dtype == bool:
condition.append(f' | {column_name} == \'\'')
elif dtype == st... | 59 | 1,318 | 252 | 1,570 | from mage_ai.data_cleaner.transformer_actions.constants import Operator
import re
ACTION_CODE_NAME = r'(?:([^\s()"\']+|[\'\"][^"\']+[\'\"]))'
ACTION_CODE_PATTERN = re.compile(
rf'{ACTION_CODE_NAME} ([!=<>]+|(?:contains)|(?:not contains)) {ACTION_CODE_NAME}'
)
ORIGINAL_COLUMN_PREFIX = 'orig_'
QUOTES = '\"\''
TRANSF... | from mage_ai.data_cleaner.transformer_actions.constants import Operator
import re
ACTION_CODE_NAME = r'(?:([^\s()"\']+|[\'\"][^"\']+[\'\"]))'
ACTION_CODE_PATTERN = re.compile(
rf'{ACTION_CODE_NAME} ([!=<>]+|(?:contains)|(?:not contains)) {ACTION_CODE_NAME}'
)
ORIGINAL_COLUMN_PREFIX = 'orig_'
QUOTES = '\"\''
TRANSF... | |
20,564 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/base.py | 189,190 | 65,234 | join | BaseAction | 190,217 | 190,217 | class BaseAction:
def __init__(self, action):
self.action = action
self.columns_by_type = {}
for variable_data in self.action.get('action_variables', {}).values():
if not variable_data:
continue
feature = variable_data.get(VariableType.FEATURE)
... | class BaseAction:
def __init__(self, action):
self.action = action
self.columns_by_type = {}
for variable_data in self.action.get('action_variables', {}).values():
if not variable_data:
continue
feature = variable_data.get(VariableType.FEATURE)
... | action_options = action['action_options']
left_on = action_options['left_on']
right_on = action_options['right_on']
for i in range(len(left_on)):
col1, col2 = left_on[i], right_on[i]
if df[col1].dtype != df_to_join[col2].dtype:
df[col1] = drop_na(... | action_options = action['action_options']
left_on = action_options['left_on']
right_on = action_options['right_on']
for i in range(len(left_on)):
col1, col2 = left_on[i], right_on[i]
if df[col1].dtype != df_to_join[col2].dtype:
df[col1] = drop_na(... | 83 | 1,371 | 444 | 1,815 | from mage_ai.data_cleaner.shared.utils import is_spark_dataframe
from mage_ai.data_cleaner.transformer_actions import column, row
from mage_ai.data_cleaner.transformer_actions.constants import ActionType, Axis, VariableType
from mage_ai.data_cleaner.transformer_actions.dependency_resolution import (
default_resolut... | from mage_ai.data_cleaner.shared.utils import is_spark_dataframe
from mage_ai.data_cleaner.transformer_actions import column, row
from mage_ai.data_cleaner.transformer_actions.constants import ActionType, Axis, VariableType
from mage_ai.data_cleaner.transformer_actions.dependency_resolution import (
default_resolut... |
20,565 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/custom_action.py | 12,13 | 1,49 | execute_custom_action | 41,49 | 13,49 | from collections import deque
def build_custom_action_decorator(action_list):
def custom_action(function):
action_list.append(function)
return function
return custom_action
def execute_custom_action(df, action, **kwargs):
FILL_FUNC_BODY | from collections import deque
def build_custom_action_decorator(action_list):
def custom_action(function):
action_list.append(function)
return function
return custom_action
def execute_custom_action(df, action, **kwargs):
"""
Handles custom action generation and execution. Custom ac... | custom_actions = deque()
transformer_action = build_custom_action_decorator(custom_actions)
action_code = action['action_code']
action_code = action_code.replace('\t', ' ' * 4)
exec(action_code, {'df': df, 'transformer_action': transformer_action})
while len(custom_actions) != 0:
df = cu... | """
Handles custom action generation and execution. Custom actions are currently supported in two
different ways:
- `transformer_action` decorator: any function decorated with `@transformer_action` will be
executed afterwards as a custom action. All functions must accept a Pandas dataframe and
r... | 30 | 373 | 124 | 497 | from collections import deque
def build_custom_action_decorator(action_list):
def custom_action(function):
action_list.append(function)
return function
return custom_action
def execute_custom_action(df, action, **kwargs):
FILL_FUNC_BODY | from collections import deque
def build_custom_action_decorator(action_list):
def custom_action(function):
action_list.append(function)
return function
return custom_action
def execute_custom_action(df, action, **kwargs):
"""
Handles custom action generation and execution. Custom ac... | |
20,566 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/udf/base.py | 16,17 | 1,22 | execute_udf | 17,22 | 17,22 | import importlib
class BaseUDF():
def __init__(self, df, arguments=[], code=None, options={}, kwargs={}):
self.df = df
self.arguments = arguments
self.code = code
self.options = options
self.kwargs = kwargs
def execute(self):
pass
def execute_udf(udf_name, df... | import importlib
class BaseUDF():
def __init__(self, df, arguments=[], code=None, options={}, kwargs={}):
self.df = df
self.arguments = arguments
self.code = code
self.options = options
self.kwargs = kwargs
def execute(self):
pass
def execute_udf(udf_name, df... | udf_class = getattr(
importlib.import_module(f'mage_ai.data_cleaner.transformer_actions.udf.{udf_name}'),
udf_name.title().replace('_', ''),
)
return udf_class(df, arguments, code, options, kwargs).execute()
| udf_class = getattr(
importlib.import_module(f'mage_ai.data_cleaner.transformer_actions.udf.{udf_name}'),
udf_name.title().replace('_', ''),
)
return udf_class(df, arguments, code, options, kwargs).execute()
| 13 | 125 | 94 | 219 | import importlib
class BaseUDF():
def __init__(self, df, arguments=[], code=None, options={}, kwargs={}):
self.df = df
self.arguments = arguments
self.code = code
self.options = options
self.kwargs = kwargs
def execute(self):
pass
def execute_udf(udf_name, df... | import importlib
class BaseUDF():
def __init__(self, df, arguments=[], code=None, options={}, kwargs={}):
self.df = df
self.arguments = arguments
self.code = code
self.options = options
self.kwargs = kwargs
def execute(self):
pass
def execute_udf(udf_name, df... | |
20,567 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/udf/constant.py | 5,6 | 4,7 | execute | Constant | 6,7 | 6,7 | class Constant(BaseUDF):
def execute(self):
FILL_FUNC_BODY | class Constant(BaseUDF):
def execute(self):
FILL_FUNC_BODY | return self.arguments[0]
| return self.arguments[0]
| 2 | 25 | 10 | 35 | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class Constant(BaseUDF):
def execute(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class Constant(BaseUDF):
def execute(self):
FILL_FUNC_BODY |
20,568 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/udf/divide.py | 5,6 | 4,13 | execute | Divide | 6,13 | 6,13 | class Divide(BaseUDF):
def execute(self):
FILL_FUNC_BODY | class Divide(BaseUDF):
def execute(self):
FILL_FUNC_BODY | col1 = self.arguments[0]
if len(self.arguments) > 1:
col2 = self.arguments[1]
return self.df[col1].astype(float) / self.df[col2].astype(float)
elif self.options.get('value') is not None:
return self.df[col1] / float(self.options['value'])
raise Excepti... | col1 = self.arguments[0]
if len(self.arguments) > 1:
col2 = self.arguments[1]
return self.df[col1].astype(float) / self.df[col2].astype(float)
elif self.options.get('value') is not None:
return self.df[col1] / float(self.options['value'])
raise Excepti... | 32 | 26 | 118 | 144 | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class Divide(BaseUDF):
def execute(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class Divide(BaseUDF):
def execute(self):
FILL_FUNC_BODY |
20,569 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/udf/if_else.py | 6,7 | 5,20 | execute | IfElse | 7,20 | 7,20 | class IfElse(BaseUDF):
def execute(self):
FILL_FUNC_BODY | class IfElse(BaseUDF):
def execute(self):
FILL_FUNC_BODY | df_copy = self.df.copy()
true_index = query_with_action_code(df_copy, self.code, self.kwargs).index
arg1_type = self.options.get('arg1_type', 'value')
arg2_type = self.options.get('arg2_type', 'value')
arg1 = self.arguments[0]
if arg1_type == 'column':
arg1 = ... | df_copy = self.df.copy()
true_index = query_with_action_code(df_copy, self.code, self.kwargs).index
arg1_type = self.options.get('arg1_type', 'value')
arg2_type = self.options.get('arg2_type', 'value')
arg1 = self.arguments[0]
if arg1_type == 'column':
arg1 = ... | 45 | 27 | 210 | 237 | from mage_ai.data_cleaner.transformer_actions.action_code import query_with_action_code
from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class IfElse(BaseUDF):
def execute(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.transformer_actions.action_code import query_with_action_code
from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class IfElse(BaseUDF):
def execute(self):
FILL_FUNC_BODY |
20,570 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/udf/multiply.py | 5,6 | 4,13 | execute | Multiply | 6,13 | 6,13 | class Multiply(BaseUDF):
def execute(self):
FILL_FUNC_BODY | class Multiply(BaseUDF):
def execute(self):
FILL_FUNC_BODY | col1 = self.arguments[0]
if len(self.arguments) > 1:
col2 = self.arguments[1]
return self.df[col1].astype(float) * self.df[col2].astype(float)
elif self.options.get('value') is not None:
return self.df[col1] * float(self.options['value'])
raise Excepti... | col1 = self.arguments[0]
if len(self.arguments) > 1:
col2 = self.arguments[1]
return self.df[col1].astype(float) * self.df[col2].astype(float)
elif self.options.get('value') is not None:
return self.df[col1] * float(self.options['value'])
raise Excepti... | 32 | 27 | 119 | 146 | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class Multiply(BaseUDF):
def execute(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class Multiply(BaseUDF):
def execute(self):
FILL_FUNC_BODY |
20,571 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/udf/string_replace.py | 5,6 | 4,11 | execute | StringReplace | 6,11 | 6,11 | class StringReplace(BaseUDF):
def execute(self):
FILL_FUNC_BODY | class StringReplace(BaseUDF):
def execute(self):
FILL_FUNC_BODY | pattern = self.options.get('pattern')
replacement = self.options.get('replacement')
if not pattern and not replacement:
raise Exception('Require both `pattern` and `replacement` parameters.')
return self.df[self.arguments[0]].str.replace(pattern, replacement)
| pattern = self.options.get('pattern')
replacement = self.options.get('replacement')
if not pattern and not replacement:
raise Exception('Require both `pattern` and `replacement` parameters.')
return self.df[self.arguments[0]].str.replace(pattern, replacement)
| 22 | 26 | 79 | 105 | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class StringReplace(BaseUDF):
def execute(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class StringReplace(BaseUDF):
def execute(self):
FILL_FUNC_BODY |
20,572 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/udf/string_split.py | 5,6 | 4,11 | execute | StringSplit | 6,11 | 6,11 | class StringSplit(BaseUDF):
def execute(self):
FILL_FUNC_BODY | class StringSplit(BaseUDF):
def execute(self):
FILL_FUNC_BODY | separator = self.options.get('separator')
part_index = self.options.get('part_index')
if separator is None or part_index is None:
raise Exception('Require both `separator` and `part_index` parameters.')
return self.df[self.arguments[0]].str.split(separator).str[part_index].st... | separator = self.options.get('separator')
part_index = self.options.get('part_index')
if separator is None or part_index is None:
raise Exception('Require both `separator` and `part_index` parameters.')
return self.df[self.arguments[0]].str.split(separator).str[part_index].st... | 23 | 26 | 100 | 126 | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class StringSplit(BaseUDF):
def execute(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class StringSplit(BaseUDF):
def execute(self):
FILL_FUNC_BODY |
20,573 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/udf/substring.py | 5,6 | 4,11 | execute | Substring | 6,11 | 6,11 | class Substring(BaseUDF):
def execute(self):
FILL_FUNC_BODY | class Substring(BaseUDF):
def execute(self):
FILL_FUNC_BODY | start = self.options.get('start')
stop = self.options.get('stop')
if start is None and stop is None:
raise Exception('Require at least one of `start` and `stop` parameters.')
return self.df[self.arguments[0]].str.slice(start=start, stop=stop)
| start = self.options.get('start')
stop = self.options.get('stop')
if start is None and stop is None:
raise Exception('Require at least one of `start` and `stop` parameters.')
return self.df[self.arguments[0]].str.slice(start=start, stop=stop)
| 27 | 26 | 86 | 112 | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class Substring(BaseUDF):
def execute(self):
FILL_FUNC_BODY | from mage_ai.data_cleaner.transformer_actions.udf.base import BaseUDF
class Substring(BaseUDF):
def execute(self):
FILL_FUNC_BODY |
20,574 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_cleaner/transformer_actions/variable_replacer.py | 5,6 | 1,41 | interpolate | 14,32 | 6,32 | from mage_ai.data_cleaner.transformer_actions.constants import VariableType
import re
def interpolate(text, key, variable_data):
FILL_FUNC_BODYdef replace_true_false(action_code):
regex_pattern_true = re.compile(' true')
regex_pattern_false = re.compile(' false')
return re.sub(
regex_pattern_true... | from mage_ai.data_cleaner.transformer_actions.constants import VariableType
import re
def interpolate(text, key, variable_data):
"""
text:
string to operate on
key:
key to search within text
variable_data:
dictionary containing data used to interpolate
"""
FILL_FUNC_BODYdef... |
regex_replacement = key
if variable_data['type'] == VariableType.FEATURE:
regex_replacement = variable_data[VariableType.FEATURE]['uuid']
elif variable_data['type'] == VariableType.FEATURE_SET_VERSION:
regex_replacement = \
variable_data[VariableType.FEATURE_SET_VERSION][Variabl... | """
text:
string to operate on
key:
key to search within text
variable_data:
dictionary containing data used to interpolate
"""
regex_replacement = key
if variable_data['type'] == VariableType.FEATURE:
regex_replacement = variable_data[VariableType.FEATURE]['... | 32 | 176 | 224 | 400 | from mage_ai.data_cleaner.transformer_actions.constants import VariableType
import re
def interpolate(text, key, variable_data):
FILL_FUNC_BODYdef replace_true_false(action_code):
regex_pattern_true = re.compile(' true')
regex_pattern_false = re.compile(' false')
return re.sub(
regex_pattern_true... | from mage_ai.data_cleaner.transformer_actions.constants import VariableType
import re
def interpolate(text, key, variable_data):
"""
text:
string to operate on
key:
key to search within text
variable_data:
dictionary containing data used to interpolate
"""
FILL_FUNC_BODYdef... | |
20,575 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_integrations/utils/settings.py | 4,5 | 1,9 | get_uuid | 5,9 | 5,9 | from typing import Dict
def get_uuid(option: Dict) -> str:
FILL_FUNC_BODY | from typing import Dict
def get_uuid(option: Dict) -> str:
FILL_FUNC_BODY | if option.get('uuid'):
return option.get('uuid')
return option['name'].lower().replace(' ', '_')
| if option.get('uuid'):
return option.get('uuid')
return option['name'].lower().replace(' ', '_')
| 8 | 33 | 38 | 71 | from typing import Dict
def get_uuid(option: Dict) -> str:
FILL_FUNC_BODY | from typing import Dict
def get_uuid(option: Dict) -> str:
FILL_FUNC_BODY | |
20,576 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/decorators.py | 112,113 | 1,121 | collect_decorated_objs | 116,121 | 113,121 | """Static definition of block decorators.
These decorators definitions are added to avoid python compilation errors.
The actual definitions of the decorators are generated at runtime dynamically in
execute_block method of mage_ai/data_preparation/models/block.py file.
"""
def callback(function):
return function
... | """Static definition of block decorators.
These decorators definitions are added to avoid python compilation errors.
The actual definitions of the decorators are generated at runtime dynamically in
execute_block method of mage_ai/data_preparation/models/block.py file.
"""
def callback(function):
return function
... | def custom_code(obj):
decorated_objs.append(obj)
return obj
return custom_code
| """
Method to collect the decorated objects (function or class)
"""
def custom_code(obj):
decorated_objs.append(obj)
return obj
return custom_code
| 7 | 478 | 36 | 514 | """Static definition of block decorators.
These decorators definitions are added to avoid python compilation errors.
The actual definitions of the decorators are generated at runtime dynamically in
execute_block method of mage_ai/data_preparation/models/block.py file.
"""
def callback(function):
return function
... | """Static definition of block decorators.
These decorators definitions are added to avoid python compilation errors.
The actual definitions of the decorators are generated at runtime dynamically in
execute_block method of mage_ai/data_preparation/models/block.py file.
"""
def callback(function):
return function
... | |
20,577 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/executors/azure_container_instance_executor.py | 17,23 | 8,33 | execute | AzureContainerInstanceExecutor | 23,33 | 23,33 | class AzureContainerInstanceExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pipeline, block_uuid: str, execution_partition: str = None, **kwargs):
super().__init__(pipeline, block_uuid, execution_partition=execution_partition)
self.executor_config = self.pipeline.repo_config.azure... | class AzureContainerInstanceExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pipeline, block_uuid: str, execution_partition: str = None, **kwargs):
super().__init__(pipeline, block_uuid, execution_partition=execution_partition)
self.executor_config = self.pipeline.repo_config.azure... | cmd = self._run_commands(
block_run_id=block_run_id,
global_vars=global_vars,
**kwargs,
)
container_instance.run_job(
' '.join(cmd),
f'mage-data-prep-block-{block_run_id}',
self.executor_config,
)
| cmd = self._run_commands(
block_run_id=block_run_id,
global_vars=global_vars,
**kwargs,
)
container_instance.run_job(
' '.join(cmd),
f'mage-data-prep-block-{block_run_id}',
self.executor_config,
)
| 13 | 197 | 104 | 301 | from typing import Dict
from mage_ai.data_preparation.executors.block_executor import BlockExecutor
from mage_ai.services.azure.container_instance import container_instance
from mage_ai.shared.hash import merge_dict
class AzureContainerInstanceExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pi... | from typing import Dict
from mage_ai.data_preparation.executors.block_executor import BlockExecutor
from mage_ai.services.azure.container_instance import container_instance
from mage_ai.shared.hash import merge_dict
class AzureContainerInstanceExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pi... |
20,578 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/executors/ecs_block_executor.py | 17,23 | 8,29 | _execute | EcsBlockExecutor | 23,29 | 23,29 | class EcsBlockExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pipeline, block_uuid: str, execution_partition: str = None, **kwargs):
super().__init__(pipeline, block_uuid, execution_partition=execution_partition)
self.executor_config = self.pipeline.repo_config.ecs_config or dict(... | class EcsBlockExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pipeline, block_uuid: str, execution_partition: str = None, **kwargs):
super().__init__(pipeline, block_uuid, execution_partition=execution_partition)
self.executor_config = self.pipeline.repo_config.ecs_config or dict(... | cmd = self._run_commands(
block_run_id=block_run_id,
global_vars=global_vars,
**kwargs,
)
ecs.run_task(cmd, ecs_config=self.executor_config)
| cmd = self._run_commands(
block_run_id=block_run_id,
global_vars=global_vars,
**kwargs,
)
ecs.run_task(cmd, ecs_config=self.executor_config)
| 9 | 194 | 72 | 266 | from typing import Dict
from mage_ai.data_preparation.executors.block_executor import BlockExecutor
from mage_ai.services.aws.ecs import ecs
from mage_ai.shared.hash import merge_dict
class EcsBlockExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pipeline, block_uuid: str, execution_partition: ... | from typing import Dict
from mage_ai.data_preparation.executors.block_executor import BlockExecutor
from mage_ai.services.aws.ecs import ecs
from mage_ai.shared.hash import merge_dict
class EcsBlockExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pipeline, block_uuid: str, execution_partition: ... |
20,579 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/executors/ecs_pipeline_executor.py | 15,21 | 8,27 | execute | EcsPipelineExecutor | 21,27 | 21,27 | class EcsPipelineExecutor(PipelineExecutor):
def __init__(self, pipeline, execution_partition: str = None):
super().__init__(pipeline, execution_partition=execution_partition)
self.executor_config = self.pipeline.repo_config.ecs_config or dict()
if self.pipeline.executor_config is not None:
... | class EcsPipelineExecutor(PipelineExecutor):
def __init__(self, pipeline, execution_partition: str = None):
super().__init__(pipeline, execution_partition=execution_partition)
self.executor_config = self.pipeline.repo_config.ecs_config or dict()
if self.pipeline.executor_config is not None:
... | cmd = self._run_commands(
global_vars=global_vars,
pipeline_run_id=pipeline_run_id,
**kwargs
)
ecs.run_task(' '.join(cmd), ecs_config=self.executor_config)
| cmd = self._run_commands(
global_vars=global_vars,
pipeline_run_id=pipeline_run_id,
**kwargs
)
ecs.run_task(' '.join(cmd), ecs_config=self.executor_config)
| 10 | 174 | 75 | 249 | from typing import Dict
from mage_ai.data_preparation.executors.pipeline_executor import PipelineExecutor
from mage_ai.services.aws.ecs import ecs
from mage_ai.shared.hash import merge_dict
class EcsPipelineExecutor(PipelineExecutor):
def __init__(self, pipeline, execution_partition: str = None):
super()... | from typing import Dict
from mage_ai.data_preparation.executors.pipeline_executor import PipelineExecutor
from mage_ai.services.aws.ecs import ecs
from mage_ai.shared.hash import merge_dict
class EcsPipelineExecutor(PipelineExecutor):
def __init__(self, pipeline, execution_partition: str = None):
super()... |
20,580 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/executors/executor_factory.py | 39,46 | 15,168 | get_pipeline_executor | ExecutorFactory | 66,94 | 46,94 | class ExecutorFactory:
@classmethod
def get_default_executor_type(self):
executor_type = os.getenv('DEFAULT_EXECUTOR_TYPE', ExecutorType.LOCAL_PYTHON)
if ExecutorType.is_valid_type(executor_type):
return executor_type
return ExecutorType.LOCAL_PYTHON
@classmethod
def... | class ExecutorFactory:
@classmethod
def get_default_executor_type(self):
executor_type = os.getenv('DEFAULT_EXECUTOR_TYPE', ExecutorType.LOCAL_PYTHON)
if ExecutorType.is_valid_type(executor_type):
return executor_type
return ExecutorType.LOCAL_PYTHON
@classmethod
def... |
executor_type = self.get_pipeline_executor_type(pipeline, executor_type=executor_type)
if executor_type == ExecutorType.PYSPARK:
from mage_ai.data_preparation.executors.pyspark_pipeline_executor import (
PySparkPipelineExecutor,
)
# Run pipeline on E... | """Get the pipeline executor based on pipeline type or pipeline executor_type.
If the executor_type is not specified in the method. Infer the executor_type with the
following rules:
1. If the pipeline type is PYSPARK, then use PYSPARK executor.
2. If the pipeline executor_type is... | 71 | 1,623 | 402 | 2,025 | import os
from typing import Union
from mage_ai.data_preparation.executors.block_executor import BlockExecutor
from mage_ai.data_preparation.executors.pipeline_executor import PipelineExecutor
from mage_ai.data_preparation.models.constants import (
BlockType,
ExecutorType,
PipelineType,
)
from mage_ai.data... | import os
from typing import Union
from mage_ai.data_preparation.executors.block_executor import BlockExecutor
from mage_ai.data_preparation.executors.pipeline_executor import PipelineExecutor
from mage_ai.data_preparation.models.constants import (
BlockType,
ExecutorType,
PipelineType,
)
from mage_ai.data... |
20,581 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/executors/gcp_cloud_run_block_executor.py | 22,28 | 9,38 | execute | GcpCloudRunBlockExecutor | 28,38 | 28,38 | class GcpCloudRunBlockExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pipeline, block_uuid: str, execution_partition: str = None, **kwargs):
super().__init__(pipeline, block_uuid, execution_partition=execution_partition)
self.executor_config = self.pipeline.repo_config.gcp_cloud_r... | class GcpCloudRunBlockExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pipeline, block_uuid: str, execution_partition: str = None, **kwargs):
super().__init__(pipeline, block_uuid, execution_partition=execution_partition)
self.executor_config = self.pipeline.repo_config.gcp_cloud_r... | cmd = self._run_commands(
block_run_id=block_run_id,
global_vars=global_vars,
**kwargs,
)
cloud_run.run_job(
cmd,
f'mage-data-prep-block-{block_run_id}',
cloud_run_config=self.executor_config,
)
| cmd = self._run_commands(
block_run_id=block_run_id,
global_vars=global_vars,
**kwargs,
)
cloud_run.run_job(
cmd,
f'mage-data-prep-block-{block_run_id}',
cloud_run_config=self.executor_config,
)
| 12 | 279 | 106 | 385 | import os
from typing import Dict
from mage_ai.data_preparation.executors.block_executor import BlockExecutor
from mage_ai.services.gcp.cloud_run import cloud_run
from mage_ai.shared.hash import merge_dict
class GcpCloudRunBlockExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pipeline, block_uu... | import os
from typing import Dict
from mage_ai.data_preparation.executors.block_executor import BlockExecutor
from mage_ai.services.gcp.cloud_run import cloud_run
from mage_ai.shared.hash import merge_dict
class GcpCloudRunBlockExecutor(BlockExecutor):
RETRYABLE = False
def __init__(self, pipeline, block_uu... |
20,582 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/executors/pyspark_block_executor.py | 68,69 | 16,98 | upload_block_execution_script | PySparkBlockExecutor | 69,84 | 69,84 | class PySparkBlockExecutor(BlockExecutor):
def __init__(
self,
pipeline: Pipeline,
block_uuid: str,
execution_partition: str = None,
**kwargs,
):
super().__init__(pipeline, block_uuid, execution_partition=execution_partition)
self.resource_manager = EmrRes... | class PySparkBlockExecutor(BlockExecutor):
def __init__(
self,
pipeline: Pipeline,
block_uuid: str,
execution_partition: str = None,
**kwargs,
):
super().__init__(pipeline, block_uuid, execution_partition=execution_partition)
self.resource_manager = EmrRes... | execution_script_code = template_env.get_template(
'pipeline_execution/spark_script.jinja',
).render(
block_uuid=f'\'{self.block_uuid}\'',
execution_partition_str=f'\'{self.execution_partition}\''
if self.execution_partition is not ... | execution_script_code = template_env.get_template(
'pipeline_execution/spark_script.jinja',
).render(
block_uuid=f'\'{self.block_uuid}\'',
execution_partition_str=f'\'{self.execution_partition}\''
if self.execution_partition is not ... | 22 | 805 | 227 | 1,032 | import posixpath
from contextlib import redirect_stdout
from typing import Dict
from mage_ai.data_preparation.executors.block_executor import BlockExecutor
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.shared.stream import StreamToLogger
from mage_ai.data_preparation.templ... | import posixpath
from contextlib import redirect_stdout
from typing import Dict
from mage_ai.data_preparation.executors.block_executor import BlockExecutor
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.shared.stream import StreamToLogger
from mage_ai.data_preparation.templ... |
20,583 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/executors/pyspark_pipeline_executor.py | 50,52 | 14,86 | spark_script_path | PySparkPipelineExecutor | 52,54 | 52,54 | class PySparkPipelineExecutor(PipelineExecutor):
def __init__(self, pipeline: Pipeline, **kwargs):
super().__init__(pipeline, **kwargs)
self.emr_config = self.pipeline.repo_config.emr_config or dict()
if self.pipeline.executor_config is not None:
self.emr_config = merge_dict(se... | class PySparkPipelineExecutor(PipelineExecutor):
def __init__(self, pipeline: Pipeline, **kwargs):
super().__init__(pipeline, **kwargs)
self.emr_config = self.pipeline.repo_config.emr_config or dict()
if self.pipeline.executor_config is not None:
self.emr_config = merge_dict(se... | return posixpath.join('s3://', self.s3_bucket, self.spark_script_path_key)
| return posixpath.join('s3://', self.s3_bucket, self.spark_script_path_key)
| 4 | 859 | 35 | 894 | import posixpath
from typing import Dict
from mage_ai.data_preparation.executors.pipeline_executor import PipelineExecutor
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.templates.utils import template_env
from mage_ai.services.aws.emr import emr
from mage_ai.services.aws.e... | import posixpath
from typing import Dict
from mage_ai.data_preparation.executors.pipeline_executor import PipelineExecutor
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.templates.utils import template_env
from mage_ai.services.aws.emr import emr
from mage_ai.services.aws.e... |
20,584 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/git/clients/base.py | 10,12 | 6,59 | get_client_for_provider | Client | 12,37 | 12,37 | class Client(ABC):
def __init__(self, access_token: str):
self.access_token = access_token
@classmethod
def get_client_for_provider(cls, provider: str):
FILL_FUNC_BODY @abstractmethod
def get_user(self):
raise NotImplementedError()
@abstractmethod
def get_branches(self, repo... | class Client(ABC):
def __init__(self, access_token: str):
self.access_token = access_token
@classmethod
def get_client_for_provider(cls, provider: str):
FILL_FUNC_BODY @abstractmethod
def get_user(self):
raise NotImplementedError()
@abstractmethod
def get_branches(self, repo... | if not provider or provider == ProviderName.GITHUB:
from mage_ai.data_preparation.git.clients.github import GitHubClient
return GitHubClient
elif provider == ProviderName.BITBUCKET:
from mage_ai.data_preparation.git.clients.bitbucket import BitbucketClient
... | if not provider or provider == ProviderName.GITHUB:
from mage_ai.data_preparation.git.clients.github import GitHubClient
return GitHubClient
elif provider == ProviderName.BITBUCKET:
from mage_ai.data_preparation.git.clients.bitbucket import BitbucketClient
... | 58 | 225 | 286 | 511 | from abc import ABC, abstractmethod
from mage_ai.authentication.oauth.constants import ProviderName
class Client(ABC):
def __init__(self, access_token: str):
self.access_token = access_token
@classmethod
def get_client_for_provider(cls, provider: str):
FILL_FUNC_BODY @abstractmethod
def g... | from abc import ABC, abstractmethod
from mage_ai.authentication.oauth.constants import ProviderName
class Client(ABC):
def __init__(self, access_token: str):
self.access_token = access_token
@classmethod
def get_client_for_provider(cls, provider: str):
FILL_FUNC_BODY @abstractmethod
def g... |
20,587 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/logging/logger_manager_factory.py | 7,13 | 6,23 | get_logger_manager | LoggerManagerFactory | 13,23 | 13,23 | class LoggerManagerFactory:
@classmethod
def get_logger_manager(
self,
repo_config: RepoConfig = None,
**kwargs,
):
FILL_FUNC_BODY | class LoggerManagerFactory:
@classmethod
def get_logger_manager(
self,
repo_config: RepoConfig = None,
**kwargs,
):
FILL_FUNC_BODY | if repo_config is not None and repo_config.logging_config is not None:
logger_type = repo_config.logging_config.get('type')
if logger_type == LoggerType.S3:
from mage_ai.data_preparation.logging.s3_logger_manager import S3LoggerManager
return S3LoggerManag... | if repo_config is not None and repo_config.logging_config is not None:
logger_type = repo_config.logging_config.get('type')
if logger_type == LoggerType.S3:
from mage_ai.data_preparation.logging.s3_logger_manager import S3LoggerManager
return S3LoggerManag... | 38 | 56 | 188 | 244 | from mage_ai.data_preparation.logging import LoggerType
from mage_ai.data_preparation.logging.logger_manager import LoggerManager
from mage_ai.data_preparation.repo_manager import RepoConfig
class LoggerManagerFactory:
@classmethod
def get_logger_manager(
self,
repo_config: RepoConfig = None,
... | from mage_ai.data_preparation.logging import LoggerType
from mage_ai.data_preparation.logging.logger_manager import LoggerManager
from mage_ai.data_preparation.repo_manager import RepoConfig
class LoggerManagerFactory:
@classmethod
def get_logger_manager(
self,
repo_config: RepoConfig = None,
... |
20,588 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/block_factory.py | 26,28 | 25,78 | block_class_from_type | BlockFactory | 28,51 | 28,51 | class BlockFactory:
@classmethod
def block_class_from_type(self, block_type: str, language=None, pipeline=None) -> 'Block':
FILL_FUNC_BODY @classmethod
def get_block(
self,
name,
uuid,
block_type,
configuration=None,
content=None,
language=None,
... | class BlockFactory:
@classmethod
def block_class_from_type(self, block_type: str, language=None, pipeline=None) -> 'Block':
FILL_FUNC_BODY @classmethod
def get_block(
self,
name,
uuid,
block_type,
configuration=None,
content=None,
language=None,
... | if BlockType.CHART == block_type:
return Widget
elif BlockType.DBT == block_type:
if language == BlockLanguage.YAML:
return DBTBlockYAML
return DBTBlockSQL
elif pipeline and PipelineType.INTEGRATION == pipeline.type:
if BlockType.CA... | if BlockType.CHART == block_type:
return Widget
elif BlockType.DBT == block_type:
if language == BlockLanguage.YAML:
return DBTBlockYAML
return DBTBlockSQL
elif pipeline and PipelineType.INTEGRATION == pipeline.type:
if BlockType.CA... | 65 | 226 | 242 | 468 | from mage_ai.data_preparation.models.block import Block, CallbackBlock, ConditionalBlock
from mage_ai.data_preparation.models.block.constants import BLOCK_TYPE_TO_CLASS
from mage_ai.data_preparation.models.block.integration import (
DestinationBlock,
SourceBlock,
TransformerBlock,
)
from mage_ai.data_prepar... | from mage_ai.data_preparation.models.block import Block, CallbackBlock, ConditionalBlock
from mage_ai.data_preparation.models.block.constants import BLOCK_TYPE_TO_CLASS
from mage_ai.data_preparation.models.block.integration import (
DestinationBlock,
SourceBlock,
TransformerBlock,
)
from mage_ai.data_prepar... |
20,589 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/dbt/utils.py | 1,2 | 1,7 | get_source_name | 2,5 | 2,5 | def get_source_name(dbt_project_name: str) -> str:
FILL_FUNC_BODYdef get_source_table_name_for_block(block) -> str:
return f'{block.pipeline.uuid}_{block.uuid}'
| def get_source_name(dbt_project_name: str) -> str:
FILL_FUNC_BODYdef get_source_table_name_for_block(block) -> str:
return f'{block.pipeline.uuid}_{block.uuid}'
| return f'mage_{dbt_project_name}'
| return f'mage_{dbt_project_name}'
| 2 | 68 | 20 | 88 | def get_source_name(dbt_project_name: str) -> str:
FILL_FUNC_BODYdef get_source_table_name_for_block(block) -> str:
return f'{block.pipeline.uuid}_{block.uuid}'
| def get_source_name(dbt_project_name: str) -> str:
FILL_FUNC_BODYdef get_source_table_name_for_block(block) -> str:
return f'{block.pipeline.uuid}_{block.uuid}'
| |
20,590 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/extension/block.py | 14,15 | 10,79 | _block_decorator | ExtensionBlock | 15,79 | 15,79 | class ExtensionBlock(Block):
def post_process_output(self, output: Dict) -> List:
return output
def _block_decorator(self, decorated_functions: List[Callable]):
FILL_FUNC_BODY | class ExtensionBlock(Block):
def post_process_output(self, output: Dict) -> List:
return output
def _block_decorator(self, decorated_functions: List[Callable]):
FILL_FUNC_BODY | def custom_code(
extension_name: str,
expectations: List[Dict] = None,
*args,
**kwargs,
):
if not extension_name or type(extension_name) is not str:
raise Exception(
'No @extension decorator found with a vali... | def custom_code(
extension_name: str,
expectations: List[Dict] = None,
*args,
**kwargs,
):
if not extension_name or type(extension_name) is not str:
raise Exception(
'No @extension decorator found with a vali... | 154 | 63 | 607 | 670 | from typing import Callable, Dict, List
from mage_ai.data_preparation.models.block import Block
from mage_ai.extensions.constants import (
EXTENSION_UUID_GREAT_EXPECTATIONS,
EXTENSION_UUIDS,
)
class ExtensionBlock(Block):
def post_process_output(self, output: Dict) -> List:
return output
def... | from typing import Callable, Dict, List
from mage_ai.data_preparation.models.block import Block
from mage_ai.extensions.constants import (
EXTENSION_UUID_GREAT_EXPECTATIONS,
EXTENSION_UUIDS,
)
class ExtensionBlock(Block):
def post_process_output(self, output: Dict) -> List:
return output
def... |
20,591 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/extension/utils.py | 10,21 | 1,50 | handle_run_tests | 21,50 | 21,50 | from logging import Logger
from typing import Dict, List
from mage_ai.extensions.great_expectations.constants import (
EXTENSION_UUID as EXTENSION_UUID_GREAT_EXPECTATIONS,
)
from mage_ai.shared.hash import index_by
def handle_run_tests(
block,
dynamic_block_index: int = None,
dynamic_block_indexes: D... | from logging import Logger
from typing import Dict, List
from mage_ai.extensions.great_expectations.constants import (
EXTENSION_UUID as EXTENSION_UUID_GREAT_EXPECTATIONS,
)
from mage_ai.shared.hash import index_by
def handle_run_tests(
block,
dynamic_block_index: int = None,
dynamic_block_indexes: D... | if not block.pipeline:
return
extensions = block.pipeline.extensions
if EXTENSION_UUID_GREAT_EXPECTATIONS not in extensions:
return
extension = extensions[EXTENSION_UUID_GREAT_EXPECTATIONS]
blocks_by_uuid = extension.get('blocks_by_uuid', {})
extension_blocks = []
for exte... | if not block.pipeline:
return
extensions = block.pipeline.extensions
if EXTENSION_UUID_GREAT_EXPECTATIONS not in extensions:
return
extension = extensions[EXTENSION_UUID_GREAT_EXPECTATIONS]
blocks_by_uuid = extension.get('blocks_by_uuid', {})
extension_blocks = []
for exte... | 56 | 198 | 350 | 548 | from logging import Logger
from typing import Dict, List
from mage_ai.extensions.great_expectations.constants import (
EXTENSION_UUID as EXTENSION_UUID_GREAT_EXPECTATIONS,
)
from mage_ai.shared.hash import index_by
def handle_run_tests(
block,
dynamic_block_index: int = None,
dynamic_block_indexes: D... | from logging import Logger
from typing import Dict, List
from mage_ai.extensions.great_expectations.constants import (
EXTENSION_UUID as EXTENSION_UUID_GREAT_EXPECTATIONS,
)
from mage_ai.shared.hash import index_by
def handle_run_tests(
block,
dynamic_block_index: int = None,
dynamic_block_indexes: D... | |
20,592 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/hook/block.py | 8,9 | 7,42 | _execute_block | HookBlock | 9,40 | 9,40 | class HookBlock(Block):
def _execute_block(self, *args, **kwargs) -> List:
FILL_FUNC_BODY def run_tests(self, *args, **kwargs) -> None:
pass
| class HookBlock(Block):
def _execute_block(self, *args, **kwargs) -> List:
FILL_FUNC_BODY def run_tests(self, *args, **kwargs) -> None:
pass
| global_vars = kwargs.get('global_vars') or {}
self.hook.run(
check_status=True,
error_on_failure=True,
poll_interval=10,
strategies=[HookStrategy.RAISE],
with_trigger=True,
**(global_vars or {}),
)
output = None
... | global_vars = kwargs.get('global_vars') or {}
self.hook.run(
check_status=True,
error_on_failure=True,
poll_interval=10,
strategies=[HookStrategy.RAISE],
with_trigger=True,
**(global_vars or {}),
)
output = None
... | 59 | 60 | 294 | 354 | from typing import List
from mage_ai.data_preparation.models.block import Block
from mage_ai.data_preparation.models.global_hooks.models import HookStrategy
class HookBlock(Block):
def _execute_block(self, *args, **kwargs) -> List:
FILL_FUNC_BODY def run_tests(self, *args, **kwargs) -> None:
pass
| from typing import List
from mage_ai.data_preparation.models.block import Block
from mage_ai.data_preparation.models.global_hooks.models import HookStrategy
class HookBlock(Block):
def _execute_block(self, *args, **kwargs) -> List:
FILL_FUNC_BODY def run_tests(self, *args, **kwargs) -> None:
pass
|
20,593 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/platform/utils.py | 34,39 | 1,108 | get_selected_directory_from_file_path | 39,108 | 39,108 | import os
from pathlib import Path
from typing import Callable
from mage_ai.settings.platform import (
get_repo_paths_for_file_path,
project_platform_activated,
)
from mage_ai.settings.repo import get_repo_path
from mage_ai.shared.files import find_directory
from mage_ai.shared.path_fixer import get_path_parts... | import os
from pathlib import Path
from typing import Callable
from mage_ai.settings.platform import (
get_repo_paths_for_file_path,
project_platform_activated,
)
from mage_ai.settings.repo import get_repo_path
from mage_ai.shared.files import find_directory
from mage_ai.shared.path_fixer import get_path_parts... | # /home/src/default_repo/default_platform/tons_of_dbt_projects/diff_name/models/example/
# my_second_dbt_model.sql
full_path_of_file_path = find_directory(
get_repo_path(root_project=True),
lambda fn: str(fn).endswith(str(file_path)),
)
if not full_path_of_file_path:
full_pa... | # /home/src/default_repo/default_platform/tons_of_dbt_projects/diff_name/models/example/
# my_second_dbt_model.sql
full_path_of_file_path = find_directory(
get_repo_path(root_project=True),
lambda fn: str(fn).endswith(str(file_path)),
)
if not full_path_of_file_path:
full_pa... | 122 | 405 | 835 | 1,240 | import os
from pathlib import Path
from typing import Callable
from mage_ai.settings.platform import (
get_repo_paths_for_file_path,
project_platform_activated,
)
from mage_ai.settings.repo import get_repo_path
from mage_ai.shared.files import find_directory
from mage_ai.shared.path_fixer import get_path_parts... | import os
from pathlib import Path
from typing import Callable
from mage_ai.settings.platform import (
get_repo_paths_for_file_path,
project_platform_activated,
)
from mage_ai.settings.repo import get_repo_path
from mage_ai.shared.files import find_directory
from mage_ai.shared.path_fixer import get_path_parts... | |
20,594 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/remote/models.py | 18,20 | 7,59 | pipeline | RemoteBlock | 20,35 | 20,35 | @dataclass
class RemoteBlock(BaseDataClass):
block_uuid: str
execution_partition: str = None
pipeline_uuid: str = None
repo_path: str = None
def __post_init__(self):
self._block = None
self._pipeline = None
@property
def pipeline(self):
FILL_FUNC_BODY @property
def b... | @dataclass
class RemoteBlock(BaseDataClass):
block_uuid: str
execution_partition: str = None
pipeline_uuid: str = None
repo_path: str = None
def __post_init__(self):
self._block = None
self._pipeline = None
@property
def pipeline(self):
FILL_FUNC_BODY @property
def b... | from mage_ai.data_preparation.models.pipeline import Pipeline
if self._pipeline:
return self._pipeline
self._pipeline = Pipeline.get(
self.pipeline_uuid,
all_projects=True,
check_if_exists=False,
repo_path=self.repo_path,
... | from mage_ai.data_preparation.models.pipeline import Pipeline
if self._pipeline:
return self._pipeline
self._pipeline = Pipeline.get(
self.pipeline_uuid,
all_projects=True,
check_if_exists=False,
repo_path=self.repo_path,
... | 23 | 280 | 135 | 415 | from dataclasses import dataclass
from typing import Any, List
from mage_ai.shared.models import BaseDataClass
@dataclass
class RemoteBlock(BaseDataClass):
block_uuid: str
execution_partition: str = None
pipeline_uuid: str = None
repo_path: str = None
def __post_init__(self):
self._block... | from dataclasses import dataclass
from typing import Any, List
from mage_ai.shared.models import BaseDataClass
@dataclass
class RemoteBlock(BaseDataClass):
block_uuid: str
execution_partition: str = None
pipeline_uuid: str = None
repo_path: str = None
def __post_init__(self):
self._block... |
20,595 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/sql/clickhouse.py | 9,21 | 1,57 | create_upstream_block_tables | 21,44 | 21,44 | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | configuration = configuration if configuration else block.configuration
database = configuration.get('data_provider_database') or loader.default_database()
create_upstream_block_tables_orig(
loader,
block,
cascade_on_drop,
configuration,
execution_partition,
c... | configuration = configuration if configuration else block.configuration
database = configuration.get('data_provider_database') or loader.default_database()
create_upstream_block_tables_orig(
loader,
block,
cascade_on_drop,
configuration,
execution_partition,
c... | 31 | 326 | 224 | 550 | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | |
20,596 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/sql/druid.py | 10,22 | 1,57 | create_upstream_block_tables | 22,44 | 22,44 | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | create_upstream_block_tables_orig(
loader,
block,
cascade_on_drop,
configuration,
execution_partition,
cache_upstream_dbt_models,
cache_keys=[
ConfigKey.DRUID_HOST,
ConfigKey.DRUID_PASSWORD,
ConfigKey.DRUID_PATH,
... | create_upstream_block_tables_orig(
loader,
block,
cascade_on_drop,
configuration,
execution_partition,
cache_upstream_dbt_models,
cache_keys=[
ConfigKey.DRUID_HOST,
ConfigKey.DRUID_PASSWORD,
ConfigKey.DRUID_PATH,
... | 20 | 347 | 203 | 550 | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | |
20,597 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/sql/duckdb.py | 10,22 | 1,54 | create_upstream_block_tables | 22,41 | 22,41 | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | create_upstream_block_tables_orig(
loader,
block,
cascade_on_drop,
configuration,
execution_partition,
cache_upstream_dbt_models,
cache_keys=[
ConfigKey.DUCKDB_DATABASE,
ConfigKey.DUCKDB_SCHEMA,
],
no_schema=True,
... | create_upstream_block_tables_orig(
loader,
block,
cascade_on_drop,
configuration,
execution_partition,
cache_upstream_dbt_models,
cache_keys=[
ConfigKey.DUCKDB_DATABASE,
ConfigKey.DUCKDB_SCHEMA,
],
no_schema=True,
... | 17 | 347 | 169 | 516 | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | |
20,598 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/sql/mssql.py | 64,71 | 1,100 | execute_raw_sql | 71,100 | 71,100 | from typing import Any, Dict, List
from mage_ai.data_preparation.models.block import Block
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import (
has_create_or... | from typing import Any, Dict, List
from mage_ai.data_preparation.models.block import Block
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import (
has_create_or... | if configuration is None:
configuration = {}
queries = []
fetch_query_at_indexes = []
has_create_or_insert = has_create_or_insert_statement(query_string)
for query in split_query_string(query_string):
if has_create_or_insert:
queries.append(query)
fetch_quer... | if configuration is None:
configuration = {}
queries = []
fetch_query_at_indexes = []
has_create_or_insert = has_create_or_insert_statement(query_string)
for query in split_query_string(query_string):
if has_create_or_insert:
queries.append(query)
fetch_quer... | 50 | 633 | 291 | 924 | from typing import Any, Dict, List
from mage_ai.data_preparation.models.block import Block
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import (
has_create_or... | from typing import Any, Dict, List
from mage_ai.data_preparation.models.block import Block
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import (
has_create_or... | |
20,599 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/sql/mysql.py | 9,21 | 1,54 | create_upstream_block_tables | 21,41 | 21,41 | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | create_upstream_block_tables_orig(
loader,
block,
cascade_on_drop,
configuration,
execution_partition,
cache_upstream_dbt_models,
cache_keys=[
ConfigKey.MYSQL_DATABASE,
ConfigKey.MYSQL_HOST,
ConfigKey.MYSQL_PORT,
],
... | create_upstream_block_tables_orig(
loader,
block,
cascade_on_drop,
configuration,
execution_partition,
cache_upstream_dbt_models,
cache_keys=[
ConfigKey.MYSQL_DATABASE,
ConfigKey.MYSQL_HOST,
ConfigKey.MYSQL_PORT,
],
... | 18 | 326 | 177 | 503 | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | |
20,600 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/sql/postgres.py | 43,50 | 1,58 | interpolate_input_data | 50,58 | 50,58 | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | return interpolate_input(
block,
query,
get_database=lambda opts: f'"{loader.default_database()}"',
get_schema=lambda opts: loader.default_schema(),
dynamic_block_index=dynamic_block_index,
dynamic_upstream_block_uuids=dynamic_upstream_block_uuids,
)
| return interpolate_input(
block,
query,
get_database=lambda opts: f'"{loader.default_database()}"',
get_schema=lambda opts: loader.default_schema(),
dynamic_block_index=dynamic_block_index,
dynamic_upstream_block_uuids=dynamic_upstream_block_uuids,
)
| 13 | 459 | 98 | 557 | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | from typing import Dict, List
from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
)
from mage_ai.data_preparation.models.block.sql.utils.shared import interpolate_input
from mage_ai.io.config import ConfigKey
def create_upstream_... | |
20,601 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/sql/redshift.py | 43,50 | 1,58 | interpolate_input_data | 50,58 | 50,58 | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | return interpolate_input(
block,
query,
get_database=lambda opts: loader.default_database(),
get_schema=lambda opts: loader.default_schema(),
dynamic_block_index=dynamic_block_index,
dynamic_upstream_block_uuids=dynamic_upstream_block_uuids,
)
| return interpolate_input(
block,
query,
get_database=lambda opts: loader.default_database(),
get_schema=lambda opts: loader.default_schema(),
dynamic_block_index=dynamic_block_index,
dynamic_upstream_block_uuids=dynamic_upstream_block_uuids,
)
| 13 | 457 | 93 | 550 | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict, List
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool ... | |
20,602 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/block/sql/spark.py | 37,38 | 1,43 | interpolate_input_data | 38,43 | 38,43 | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool = Fals... | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool = Fals... | return interpolate_input(
block,
query,
lambda db, schema, tn: tn,
)
| return interpolate_input(
block,
query,
lambda db, schema, tn: tn,
)
| 10 | 309 | 38 | 347 | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool = Fals... | from mage_ai.data_preparation.models.block.sql.utils.shared import (
create_upstream_block_tables as create_upstream_block_tables_orig,
interpolate_input,
)
from mage_ai.io.config import ConfigKey
from typing import Dict
def create_upstream_block_tables(
loader,
block,
cascade_on_drop: bool = Fals... | |
20,603 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/constants.py | 92,94 | 82,97 | is_valid_type | ExecutorType | 94,97 | 94,97 | class ExecutorType(str, Enum):
AZURE_CONTAINER_INSTANCE = 'azure_container_instance'
ECS = 'ecs'
GCP_CLOUD_RUN = 'gcp_cloud_run'
K8S = 'k8s'
LOCAL_PYTHON = 'local_python'
# Force using local python when default executor is set
LOCAL_PYTHON_FORCE = 'local_python_force'
PYSPARK = 'pyspark'... | class ExecutorType(str, Enum):
AZURE_CONTAINER_INSTANCE = 'azure_container_instance'
ECS = 'ecs'
GCP_CLOUD_RUN = 'gcp_cloud_run'
K8S = 'k8s'
LOCAL_PYTHON = 'local_python'
# Force using local python when default executor is set
LOCAL_PYTHON_FORCE = 'local_python_force'
PYSPARK = 'pyspark'... | return executor_type.upper() in cls.__members__
| return executor_type.upper() in cls.__members__
| 4 | 169 | 21 | 190 | import os
from enum import Enum
DATA_INTEGRATION_CATALOG_FILE = 'data_integration_catalog.json'
DATAFRAME_ANALYSIS_KEYS = frozenset(
[
'metadata',
'statistics',
'insights',
'suggestions',
]
)
DATAFRAME_ANALYSIS_MAX_COLUMNS = 100
DATAFRAME_ANALYSIS_MAX_ROWS = 100_000
DATAFRAME_SA... | import os
from enum import Enum
DATA_INTEGRATION_CATALOG_FILE = 'data_integration_catalog.json'
DATAFRAME_ANALYSIS_KEYS = frozenset(
[
'metadata',
'statistics',
'insights',
'suggestions',
]
)
DATAFRAME_ANALYSIS_MAX_COLUMNS = 100
DATAFRAME_ANALYSIS_MAX_ROWS = 100_000
DATAFRAME_SA... |
20,604 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/custom_templates/utils.py | 55,59 | 1,79 | group_and_hydrate_files | 59,79 | 59,79 | import os
from typing import Dict, List
from mage_ai.data_preparation.models.custom_templates.constants import (
CUSTOM_TEMPLATES_DIRECTORY,
CUSTOM_TEMPLATES_DIRECTORY_ENVIRONMENT_VARIABLE,
)
from mage_ai.data_preparation.models.file import File
from mage_ai.settings.repo import get_repo_path
from mage_ai.shar... | import os
from typing import Dict, List
from mage_ai.data_preparation.models.custom_templates.constants import (
CUSTOM_TEMPLATES_DIRECTORY,
CUSTOM_TEMPLATES_DIRECTORY_ENVIRONMENT_VARIABLE,
)
from mage_ai.data_preparation.models.file import File
from mage_ai.settings.repo import get_repo_path
from mage_ai.shar... | def _func(x):
arr = ['']
if x:
parent_names = x.get('parent_names', []) or []
if parent_names and len(parent_names) >= 1:
arr = [str(parent_name) for parent_name in parent_names]
return os.path.join(*arr)
groups = group_by(_func, file_dicts)
... | def _func(x):
arr = ['']
if x:
parent_names = x.get('parent_names', []) or []
if parent_names and len(parent_names) >= 1:
arr = [str(parent_name) for parent_name in parent_names]
return os.path.join(*arr)
groups = group_by(_func, file_dicts)
... | 49 | 537 | 201 | 738 | import os
from typing import Dict, List
from mage_ai.data_preparation.models.custom_templates.constants import (
CUSTOM_TEMPLATES_DIRECTORY,
CUSTOM_TEMPLATES_DIRECTORY_ENVIRONMENT_VARIABLE,
)
from mage_ai.data_preparation.models.file import File
from mage_ai.settings.repo import get_repo_path
from mage_ai.shar... | import os
from typing import Dict, List
from mage_ai.data_preparation.models.custom_templates.constants import (
CUSTOM_TEMPLATES_DIRECTORY,
CUSTOM_TEMPLATES_DIRECTORY_ENVIRONMENT_VARIABLE,
)
from mage_ai.data_preparation.models.file import File
from mage_ai.settings.repo import get_repo_path
from mage_ai.shar... | |
20,605 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/global_hooks/pipelines.py | 15,20 | 1,97 | attach_global_hook_execution | 20,97 | 20,97 | from typing import Dict, List, Tuple
from mage_ai.authentication.permissions.constants import EntityName
from mage_ai.data_preparation.models.global_hooks.models import (
GlobalHooks,
HookOperation,
HookStage,
)
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.mod... | from typing import Dict, List, Tuple
from mage_ai.authentication.permissions.constants import EntityName
from mage_ai.data_preparation.models.global_hooks.models import (
GlobalHooks,
HookOperation,
HookStage,
)
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.mod... | if not Project.is_feature_enabled_in_root_or_active_project(FeatureUUID.GLOBAL_HOOKS):
return block_uuids_and_create_options
global_hooks = GlobalHooks.load_from_file()
hook_variables = dict(
operation_resource=pipeline_run.to_dict(),
payload=dict(
block_runs=block_uuids... | if not Project.is_feature_enabled_in_root_or_active_project(FeatureUUID.GLOBAL_HOOKS):
return block_uuids_and_create_options
global_hooks = GlobalHooks.load_from_file()
hook_variables = dict(
operation_resource=pipeline_run.to_dict(),
payload=dict(
block_runs=block_uuids... | 133 | 223 | 794 | 1,017 | from typing import Dict, List, Tuple
from mage_ai.authentication.permissions.constants import EntityName
from mage_ai.data_preparation.models.global_hooks.models import (
GlobalHooks,
HookOperation,
HookStage,
)
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.mod... | from typing import Dict, List, Tuple
from mage_ai.authentication.permissions.constants import EntityName
from mage_ai.data_preparation.models.global_hooks.models import (
GlobalHooks,
HookOperation,
HookStage,
)
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.mod... | |
20,606 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/global_hooks/utils.py | 14,19 | 1,34 | extract_valid_data | 19,34 | 19,34 | from typing import Dict
from mage_ai.authentication.permissions.constants import EntityName
from mage_ai.data_preparation.models.global_hooks.constants import (
DISABLED_RESOURCE_TYPES,
RESTRICTED_RESOURCE_TYPES,
VALID_KEYS_FOR_INPUT_OUTPUT_DATA_ALL,
VALID_KEYS_FOR_INPUT_OUTPUT_DATA_UNRESTRICTED,
H... | from typing import Dict
from mage_ai.authentication.permissions.constants import EntityName
from mage_ai.data_preparation.models.global_hooks.constants import (
DISABLED_RESOURCE_TYPES,
RESTRICTED_RESOURCE_TYPES,
VALID_KEYS_FOR_INPUT_OUTPUT_DATA_ALL,
VALID_KEYS_FOR_INPUT_OUTPUT_DATA_UNRESTRICTED,
H... | data = {}
limited_types = DISABLED_RESOURCE_TYPES + RESTRICTED_RESOURCE_TYPES
if not resource_type or resource_type in limited_types:
data = extract(input_data or {}, VALID_KEYS_FOR_INPUT_OUTPUT_DATA_UNRESTRICTED)
else:
data = extract(
input_data or {},
VALID_KEY... | data = {}
limited_types = DISABLED_RESOURCE_TYPES + RESTRICTED_RESOURCE_TYPES
if not resource_type or resource_type in limited_types:
data = extract(input_data or {}, VALID_KEYS_FOR_INPUT_OUTPUT_DATA_UNRESTRICTED)
else:
data = extract(
input_data or {},
VALID_KEY... | 43 | 210 | 192 | 402 | from typing import Dict
from mage_ai.authentication.permissions.constants import EntityName
from mage_ai.data_preparation.models.global_hooks.constants import (
DISABLED_RESOURCE_TYPES,
RESTRICTED_RESOURCE_TYPES,
VALID_KEYS_FOR_INPUT_OUTPUT_DATA_ALL,
VALID_KEYS_FOR_INPUT_OUTPUT_DATA_UNRESTRICTED,
H... | from typing import Dict
from mage_ai.authentication.permissions.constants import EntityName
from mage_ai.data_preparation.models.global_hooks.constants import (
DISABLED_RESOURCE_TYPES,
RESTRICTED_RESOURCE_TYPES,
VALID_KEYS_FOR_INPUT_OUTPUT_DATA_ALL,
VALID_KEYS_FOR_INPUT_OUTPUT_DATA_UNRESTRICTED,
H... | |
20,607 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/pipelines/seed.py | 68,74 | 1,158 | __process | 74,158 | 74,158 | from datetime import datetime
from typing import List
from mage_ai.data_preparation.models.block import Block
from mage_ai.data_preparation.models.constants import BlockType
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import (
ScheduleInterval,
Sc... | from datetime import datetime
from typing import List
from mage_ai.data_preparation.models.block import Block
from mage_ai.data_preparation.models.constants import BlockType
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import (
ScheduleInterval,
Sc... | pipelines_count = len(pipelines)
pipeline_schedules_models = []
if pipeline_schedules is None:
pipeline_schedules_models = PipelineSchedule.query.all()
else:
for i in range(pipeline_schedules):
pipeline = pipelines[i % pipelines_count]
model = PipelineSchedule(
... | pipelines_count = len(pipelines)
pipeline_schedules_models = []
if pipeline_schedules is None:
pipeline_schedules_models = PipelineSchedule.query.all()
else:
for i in range(pipeline_schedules):
pipeline = pipelines[i % pipelines_count]
model = PipelineSchedule(
... | 179 | 761 | 991 | 1,752 | from datetime import datetime
from typing import List
from mage_ai.data_preparation.models.block import Block
from mage_ai.data_preparation.models.constants import BlockType
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import (
ScheduleInterval,
Sc... | from datetime import datetime
from typing import List
from mage_ai.data_preparation.models.block import Block
from mage_ai.data_preparation.models.constants import BlockType
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import (
ScheduleInterval,
Sc... | |
20,608 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/models/pipelines/utils.py | 20,21 | 1,29 | get_all_pipeline_uuids | 21,29 | 21,29 | import os
from pathlib import Path
from mage_ai.data_preparation.models.constants import PIPELINES_FOLDER
from mage_ai.settings.repo import get_repo_path
def number_string(version: int, number_of_numbers: int = 20) -> str:
version_string = str(version)
for _i in range(number_of_numbers - len(version_string))... | import os
from pathlib import Path
from mage_ai.data_preparation.models.constants import PIPELINES_FOLDER
from mage_ai.settings.repo import get_repo_path
def number_string(version: int, number_of_numbers: int = 20) -> str:
version_string = str(version)
for _i in range(number_of_numbers - len(version_string))... | base_dirname = os.path.join(get_repo_path(), PIPELINES_FOLDER)
arr = []
for path in Path(base_dirname).rglob('*'):
if path.name.endswith('metadata.yaml') or path.name.endswith('metadata.yml'):
arr.append(get_uuid(path, base_dirname))
return sorted(arr)
| base_dirname = os.path.join(get_repo_path(), PIPELINES_FOLDER)
arr = []
for path in Path(base_dirname).rglob('*'):
if path.name.endswith('metadata.yaml') or path.name.endswith('metadata.yml'):
arr.append(get_uuid(path, base_dirname))
return sorted(arr)
| 19 | 200 | 117 | 317 | import os
from pathlib import Path
from mage_ai.data_preparation.models.constants import PIPELINES_FOLDER
from mage_ai.settings.repo import get_repo_path
def number_string(version: int, number_of_numbers: int = 20) -> str:
version_string = str(version)
for _i in range(number_of_numbers - len(version_string))... | import os
from pathlib import Path
from mage_ai.data_preparation.models.constants import PIPELINES_FOLDER
from mage_ai.settings.repo import get_repo_path
def number_string(version: int, number_of_numbers: int = 20) -> str:
version_string = str(version)
for _i in range(number_of_numbers - len(version_string))... | |
20,609 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/shared/stream.py | 20,21 | 6,26 | write | StreamToLogger | 21,24 | 21,24 | class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
"""
def __init__(self, logger, log_level=logging.INFO, logging_tags: Dict = dict()):
self.logger = logger
self.log_level = log_level
self.logging_tags = logging_tags or dict... | class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
"""
def __init__(self, logger, log_level=logging.INFO, logging_tags: Dict = dict()):
self.logger = logger
self.log_level = log_level
self.logging_tags = logging_tags or dict... | for line in buf.rstrip().splitlines():
self.logger.log(self.log_level, line.rstrip(), **self.logging_tags)
| for line in buf.rstrip().splitlines():
self.logger.log(self.log_level, line.rstrip(), **self.logging_tags)
| 7 | 164 | 43 | 207 | from typing import Dict
import logging
import sys
class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
"""
def __init__(self, logger, log_level=logging.INFO, logging_tags: Dict = dict()):
self.logger = logger
self.log_level = log_le... | from typing import Dict
import logging
import sys
class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
"""
def __init__(self, logger, log_level=logging.INFO, logging_tags: Dict = dict()):
self.logger = logger
self.log_level = log_le... |
20,610 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/shared/utils.py | 7,8 | 1,38 | get_template_vars | 8,16 | 8,16 | import os
from typing import Callable, Dict
from mage_ai.shared.hash import get_json_value, merge_dict
def get_template_vars(include_python_libraries: Dict = None) -> Dict[str, Callable]:
FILL_FUNC_BODYdef get_template_vars_no_db(include_python_libraries: Dict = None) -> Dict[str, Callable]:
kwargs = dict(
... | import os
from typing import Callable, Dict
from mage_ai.shared.hash import get_json_value, merge_dict
def get_template_vars(include_python_libraries: Dict = None) -> Dict[str, Callable]:
FILL_FUNC_BODYdef get_template_vars_no_db(include_python_libraries: Dict = None) -> Dict[str, Callable]:
kwargs = dict(
... | from mage_ai.data_preparation.shared.secrets import get_secret_value
no_db_kwargs = get_template_vars_no_db(include_python_libraries=include_python_libraries)
kwargs = dict(mage_secret_var=get_secret_value)
return merge_dict(no_db_kwargs, kwargs)
| from mage_ai.data_preparation.shared.secrets import get_secret_value
no_db_kwargs = get_template_vars_no_db(include_python_libraries=include_python_libraries)
kwargs = dict(mage_secret_var=get_secret_value)
return merge_dict(no_db_kwargs, kwargs)
| 13 | 288 | 107 | 395 | import os
from typing import Callable, Dict
from mage_ai.shared.hash import get_json_value, merge_dict
def get_template_vars(include_python_libraries: Dict = None) -> Dict[str, Callable]:
FILL_FUNC_BODYdef get_template_vars_no_db(include_python_libraries: Dict = None) -> Dict[str, Callable]:
kwargs = dict(
... | import os
from typing import Callable, Dict
from mage_ai.shared.hash import get_json_value, merge_dict
def get_template_vars(include_python_libraries: Dict = None) -> Dict[str, Callable]:
FILL_FUNC_BODYdef get_template_vars_no_db(include_python_libraries: Dict = None) -> Dict[str, Callable]:
kwargs = dict(
... | |
20,611 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/sync/git_sync.py | 53,54 | 1,60 | get_sync_config | 54,60 | 54,60 | import os
from typing import Union
from mage_ai.data_preparation.git import Git
from mage_ai.data_preparation.preferences import get_preferences
from mage_ai.data_preparation.sync import GitConfig
from mage_ai.data_preparation.sync.base_sync import BaseSync
from mage_ai.shared.logger import VerboseFunctionExec
class... | import os
from typing import Union
from mage_ai.data_preparation.git import Git
from mage_ai.data_preparation.preferences import get_preferences
from mage_ai.data_preparation.sync import GitConfig
from mage_ai.data_preparation.sync.base_sync import BaseSync
from mage_ai.shared.logger import VerboseFunctionExec
class... | sync_config = None
preferences = get_preferences()
if preferences.sync_config:
sync_config = GitConfig.load(config=preferences.sync_config)
return sync_config
| sync_config = None
preferences = get_preferences()
if preferences.sync_config:
sync_config = GitConfig.load(config=preferences.sync_config)
return sync_config
| 13 | 602 | 58 | 660 | import os
from typing import Union
from mage_ai.data_preparation.git import Git
from mage_ai.data_preparation.preferences import get_preferences
from mage_ai.data_preparation.sync import GitConfig
from mage_ai.data_preparation.sync.base_sync import BaseSync
from mage_ai.shared.logger import VerboseFunctionExec
class... | import os
from typing import Union
from mage_ai.data_preparation.git import Git
from mage_ai.data_preparation.preferences import get_preferences
from mage_ai.data_preparation.sync import GitConfig
from mage_ai.data_preparation.sync.base_sync import BaseSync
from mage_ai.shared.logger import VerboseFunctionExec
class... | |
20,612 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/sync/git_sync.py | 38,39 | 27,53 | sync_data | GitSync | 39,45 | 39,45 | class GitSync(BaseSync):
def __init__(self, sync_config: GitConfig, setup_repo: bool = False):
self.sync_submodules = sync_config.sync_submodules
self.branch = sync_config.branch or 'main'
self.remote_repo_link = sync_config.remote_repo_link
self.git_manager = Git(
auth_t... | class GitSync(BaseSync):
def __init__(self, sync_config: GitConfig, setup_repo: bool = False):
self.sync_submodules = sync_config.sync_submodules
self.branch = sync_config.branch or 'main'
self.remote_repo_link = sync_config.remote_repo_link
self.git_manager = Git(
auth_t... | with PreserveGitConfig():
self.git_manager.reset_hard(branch=self.branch)
if self.sync_submodules:
self.git_manager.submodules_update()
# Reset git sync by cloning the remote repo
| with PreserveGitConfig():
self.git_manager.reset_hard(branch=self.branch)
if self.sync_submodules:
self.git_manager.submodules_update()
# Reset git sync by cloning the remote repo
| 15 | 228 | 70 | 298 | import os
from typing import Union
from mage_ai.data_preparation.git import Git
from mage_ai.data_preparation.preferences import get_preferences
from mage_ai.data_preparation.sync import GitConfig
from mage_ai.data_preparation.sync.base_sync import BaseSync
from mage_ai.shared.logger import VerboseFunctionExec
class... | import os
from typing import Union
from mage_ai.data_preparation.git import Git
from mage_ai.data_preparation.preferences import get_preferences
from mage_ai.data_preparation.sync import GitConfig
from mage_ai.data_preparation.sync.base_sync import BaseSync
from mage_ai.shared.logger import VerboseFunctionExec
class... |
20,613 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/templates/data_integrations/utils.py | 22,23 | 1,127 | get_templates | 23,69 | 23,69 | from typing import Dict, List, Mapping, Union
from mage_ai.data_integrations.destinations.constants import DESTINATIONS
from mage_ai.data_integrations.sources.constants import SOURCES
from mage_ai.data_integrations.utils.settings import get_uuid
from mage_ai.data_preparation.models.constants import (
BLOCK_LANGUAG... | from typing import Dict, List, Mapping, Union
from mage_ai.data_integrations.destinations.constants import DESTINATIONS
from mage_ai.data_integrations.sources.constants import SOURCES
from mage_ai.data_integrations.utils.settings import get_uuid
from mage_ai.data_preparation.models.constants import (
BLOCK_LANGUAG... | arr = []
mapping = {}
for items, block_type, di_type in [
(SOURCES, BlockType.DATA_LOADER, DATA_INTEGRATION_TYPE_SOURCES),
(DESTINATIONS, BlockType.DATA_EXPORTER, DATA_INTEGRATION_TYPE_DESTINATIONS),
]:
for data_dict in items:
display_name = data_dict.get('name')
... | arr = []
mapping = {}
for items, block_type, di_type in [
(SOURCES, BlockType.DATA_LOADER, DATA_INTEGRATION_TYPE_SOURCES),
(DESTINATIONS, BlockType.DATA_EXPORTER, DATA_INTEGRATION_TYPE_DESTINATIONS),
]:
for data_dict in items:
display_name = data_dict.get('name')
... | 87 | 948 | 462 | 1,410 | from typing import Dict, List, Mapping, Union
from mage_ai.data_integrations.destinations.constants import DESTINATIONS
from mage_ai.data_integrations.sources.constants import SOURCES
from mage_ai.data_integrations.utils.settings import get_uuid
from mage_ai.data_preparation.models.constants import (
BLOCK_LANGUAG... | from typing import Dict, List, Mapping, Union
from mage_ai.data_integrations.destinations.constants import DESTINATIONS
from mage_ai.data_integrations.sources.constants import SOURCES
from mage_ai.data_integrations.utils.settings import get_uuid
from mage_ai.data_preparation.models.constants import (
BLOCK_LANGUAG... | |
20,615 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/data_preparation/utils/block/convert_content.py | 6,7 | 1,87 | convert_to_block | 7,87 | 7,87 | from mage_ai.autocomplete.utils import extract_all_imports
from mage_ai.data_preparation.models.constants import BlockType
import re
def convert_to_block(block, content):
FILL_FUNC_BODY | from mage_ai.autocomplete.utils import extract_all_imports
from mage_ai.data_preparation.models.constants import BlockType
import re
def convert_to_block(block, content):
FILL_FUNC_BODY | block_template_content = block.content
content_imports = extract_all_imports(content, ignore_nesting=True)
block_template_imports = extract_all_imports(block_template_content, ignore_nesting=True)
for i in content_imports:
content = content.replace(i, '')
for i in block_template_imports:
... | block_template_content = block.content
content_imports = extract_all_imports(content, ignore_nesting=True)
block_template_imports = extract_all_imports(block_template_content, ignore_nesting=True)
for i in content_imports:
content = content.replace(i, '')
for i in block_template_imports:
... | 183 | 67 | 910 | 977 | from mage_ai.autocomplete.utils import extract_all_imports
from mage_ai.data_preparation.models.constants import BlockType
import re
def convert_to_block(block, content):
FILL_FUNC_BODY | from mage_ai.autocomplete.utils import extract_all_imports
from mage_ai.data_preparation.models.constants import BlockType
import re
def convert_to_block(block, content):
FILL_FUNC_BODY | |
20,616 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/airflow.py | 83,91 | 1,109 | create_dags | 91,109 | 91,109 | from datetime import datetime
from typing import Any, Dict, List
import mage_ai
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import ScheduleInterval
from mage_ai.shared.hash import ignore_keys, merge_dict
def create_dag(
project_path: str,
pipeli... | from datetime import datetime
from typing import Any, Dict, List
import mage_ai
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import ScheduleInterval
from mage_ai.shared.hash import ignore_keys, merge_dict
def create_dag(
project_path: str,
pipeli... | if blacklist_pipelines is None:
blacklist_pipelines = []
if dag_settings is None:
dag_settings = dict()
if globals_dict is None:
globals_dict = dict()
all_pipeline_uuids = Pipeline.get_all_pipelines(project_path)
for pipeline_uuid in all_pipeline_uuids:
if pipeline_u... | if blacklist_pipelines is None:
blacklist_pipelines = []
if dag_settings is None:
dag_settings = dict()
if globals_dict is None:
globals_dict = dict()
all_pipeline_uuids = Pipeline.get_all_pipelines(project_path)
for pipeline_uuid in all_pipeline_uuids:
if pipeline_u... | 41 | 820 | 180 | 1,000 | from datetime import datetime
from typing import Any, Dict, List
import mage_ai
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import ScheduleInterval
from mage_ai.shared.hash import ignore_keys, merge_dict
def create_dag(
project_path: str,
pipeli... | from datetime import datetime
from typing import Any, Dict, List
import mage_ai
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import ScheduleInterval
from mage_ai.shared.hash import ignore_keys, merge_dict
def create_dag(
project_path: str,
pipeli... | |
20,617 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/db/errors.py | 14,15 | 9,19 | to_dict | ValidationError | 15,19 | 15,19 | class ValidationError(MageBaseException):
def __init__(self, error: str, metadata: Dict):
self.error = error
self.metadata = metadata
def to_dict(self):
FILL_FUNC_BODY | class ValidationError(MageBaseException):
def __init__(self, error: str, metadata: Dict):
self.error = error
self.metadata = metadata
def to_dict(self):
FILL_FUNC_BODY | return dict(
error=self.error,
metadata=self.metadata,
)
| return dict(
error=self.error,
metadata=self.metadata,
)
| 5 | 62 | 28 | 90 | from mage_ai.errors.base import MageBaseException
from typing import Dict
class DoesNotExistError(MageBaseException):
pass
class ValidationError(MageBaseException):
def __init__(self, error: str, metadata: Dict):
self.error = error
self.metadata = metadata
def to_dict(self):
FILL_FUNC_B... | from mage_ai.errors.base import MageBaseException
from typing import Dict
class DoesNotExistError(MageBaseException):
pass
class ValidationError(MageBaseException):
def __init__(self, error: str, metadata: Dict):
self.error = error
self.metadata = metadata
def to_dict(self):
FILL_FUNC_B... |
20,618 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/db/models/utils.py | 37,39 | 1,65 | activate_project_for_user | 39,65 | 39,65 | from mage_ai.orchestration.db import db_connection, safe_db_query
@safe_db_query
def transfer_related_models_for_pipeline(old_uuid: str, new_uuid: str):
from mage_ai.orchestration.db.models.schedules import (
Backfill,
PipelineRun,
PipelineSchedule,
)
# Migrate pipeline schedules
... | from mage_ai.orchestration.db import db_connection, safe_db_query
@safe_db_query
def transfer_related_models_for_pipeline(old_uuid: str, new_uuid: str):
from mage_ai.orchestration.db.models.schedules import (
Backfill,
PipelineRun,
PipelineSchedule,
)
# Migrate pipeline schedules
... | from mage_ai.orchestration.db.models.projects import UserProject
projects = UserProject.query.filter(
UserProject.user_id == user.id,
UserProject.root_project_uuid == root_project_uuid,
)
projects.update({
UserProject.active: False
}, synchronize_session=False)
project_... | from mage_ai.orchestration.db.models.projects import UserProject
projects = UserProject.query.filter(
UserProject.user_id == user.id,
UserProject.root_project_uuid == root_project_uuid,
)
projects.update({
UserProject.active: False
}, synchronize_session=False)
project_... | 46 | 458 | 242 | 700 | from mage_ai.orchestration.db import db_connection, safe_db_query
@safe_db_query
def transfer_related_models_for_pipeline(old_uuid: str, new_uuid: str):
from mage_ai.orchestration.db.models.schedules import (
Backfill,
PipelineRun,
PipelineSchedule,
)
# Migrate pipeline schedules
... | from mage_ai.orchestration.db import db_connection, safe_db_query
@safe_db_query
def transfer_related_models_for_pipeline(old_uuid: str, new_uuid: str):
from mage_ai.orchestration.db.models.schedules import (
Backfill,
PipelineRun,
PipelineSchedule,
)
# Migrate pipeline schedules
... | |
20,619 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/db/setup.py | 18,19 | 1,48 | get_postgres_connection_url | 19,48 | 19,48 | import json
import os
from typing import Optional
from mage_ai.orchestration.constants import (
AWS_DB_SECRETS_NAME,
PG_DB_HOST,
PG_DB_NAME,
PG_DB_PASS,
PG_DB_PORT,
PG_DB_USER,
)
DEFAULT_POSTGRES_HOST = '127.0.0.1'
DEFAULT_POSTGRES_PORT = '5432'
def get_postgres_connection_url() -> Optional[... | import json
import os
from typing import Optional
from mage_ai.orchestration.constants import (
AWS_DB_SECRETS_NAME,
PG_DB_HOST,
PG_DB_NAME,
PG_DB_PASS,
PG_DB_PORT,
PG_DB_USER,
)
DEFAULT_POSTGRES_HOST = '127.0.0.1'
DEFAULT_POSTGRES_PORT = '5432'
def get_postgres_connection_url() -> Optional[... | db_user = None
db_pass = None
db_name = None
db_host = None
db_port = None
if os.getenv(AWS_DB_SECRETS_NAME):
try:
from mage_ai.services.aws.secrets_manager.secrets_manager import get_secret
response = get_secret(os.getenv(AWS_DB_SECRETS_NAME))
secrets... | db_user = None
db_pass = None
db_name = None
db_host = None
db_port = None
if os.getenv(AWS_DB_SECRETS_NAME):
try:
from mage_ai.services.aws.secrets_manager.secrets_manager import get_secret
response = get_secret(os.getenv(AWS_DB_SECRETS_NAME))
secrets... | 94 | 154 | 440 | 594 | import json
import os
from typing import Optional
from mage_ai.orchestration.constants import (
AWS_DB_SECRETS_NAME,
PG_DB_HOST,
PG_DB_NAME,
PG_DB_PASS,
PG_DB_PORT,
PG_DB_USER,
)
DEFAULT_POSTGRES_HOST = '127.0.0.1'
DEFAULT_POSTGRES_PORT = '5432'
def get_postgres_connection_url() -> Optional[... | import json
import os
from typing import Optional
from mage_ai.orchestration.constants import (
AWS_DB_SECRETS_NAME,
PG_DB_HOST,
PG_DB_NAME,
PG_DB_PASS,
PG_DB_PORT,
PG_DB_USER,
)
DEFAULT_POSTGRES_HOST = '127.0.0.1'
DEFAULT_POSTGRES_PORT = '5432'
def get_postgres_connection_url() -> Optional[... | |
20,620 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/db/utils.py | 4,7 | 1,24 | get_user_info_from_db_connection_url | 18,24 | 7,24 | from typing import Optional, Tuple
def get_user_info_from_db_connection_url(
url: str,
) -> Tuple[Optional[str], Optional[str]]:
FILL_FUNC_BODY | from typing import Optional, Tuple
def get_user_info_from_db_connection_url(
url: str,
) -> Tuple[Optional[str], Optional[str]]:
"""
Attempt to parse db connection url to get username and password. urllib.parse
does not work for all cases.
Args:
url (str): db connection url usually in the... | try:
prefix = '@'.join(url.split('@')[0:-1])
user_info = prefix.split('://', 1)[1]
return user_info.split(':', 1)
except Exception:
return None, None
| """
Attempt to parse db connection url to get username and password. urllib.parse
does not work for all cases.
Args:
url (str): db connection url usually in the form of
"scheme://username:password@host:port/dbname?options"
Returns:
Tuple[str, str]: tuple of username, pa... | 16 | 150 | 72 | 222 | from typing import Optional, Tuple
def get_user_info_from_db_connection_url(
url: str,
) -> Tuple[Optional[str], Optional[str]]:
FILL_FUNC_BODY | from typing import Optional, Tuple
def get_user_info_from_db_connection_url(
url: str,
) -> Tuple[Optional[str], Optional[str]]:
"""
Attempt to parse db connection url to get username and password. urllib.parse
does not work for all cases.
Args:
url (str): db connection url usually in the... | |
20,621 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/execution_process_manager.py | 49,50 | 5,89 | terminate_block_process | ExecutionProcessManager | 50,53 | 50,53 | class ExecutionProcessManager:
def __init__(self):
self.block_processes = dict()
self.pipeline_processes = dict()
def has_pipeline_process(self, pipeline_run_id: int):
return (
pipeline_run_id in self.pipeline_processes
and self.pipeline_processes[pipeline_run_id... | class ExecutionProcessManager:
def __init__(self):
self.block_processes = dict()
self.pipeline_processes = dict()
def has_pipeline_process(self, pipeline_run_id: int):
return (
pipeline_run_id in self.pipeline_processes
and self.pipeline_processes[pipeline_run_id... | if self.has_block_process(pipeline_run_id, block_run_id):
self.block_processes[pipeline_run_id][block_run_id].terminate()
| if self.has_block_process(pipeline_run_id, block_run_id):
self.block_processes[pipeline_run_id][block_run_id].terminate()
| 4 | 1,079 | 53 | 1,132 | from mage_ai.orchestration.db.models.schedules import PipelineRun
import multiprocessing
class ExecutionProcessManager:
def __init__(self):
self.block_processes = dict()
self.pipeline_processes = dict()
def has_pipeline_process(self, pipeline_run_id: int):
return (
pipelin... | from mage_ai.orchestration.db.models.schedules import PipelineRun
import multiprocessing
class ExecutionProcessManager:
def __init__(self):
self.block_processes = dict()
self.pipeline_processes = dict()
def has_pipeline_process(self, pipeline_run_id: int):
return (
pipelin... |
20,622 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/job_manager.py | 18,26 | 14,99 | add_job | JobManager | 26,30 | 26,30 | class JobManager:
def __init__(self):
self.queue = QueueFactory.get_queue()
def add_job(
self,
job_type: JobType,
uid: Union[str, int],
target: Callable,
*args,
**kwargs
):
FILL_FUNC_BODY def clean_up_jobs(self):
self.queue.clean_up_jobs()
... | class JobManager:
def __init__(self):
self.queue = QueueFactory.get_queue()
def add_job(
self,
job_type: JobType,
uid: Union[str, int],
target: Callable,
*args,
**kwargs
):
FILL_FUNC_BODY def clean_up_jobs(self):
self.queue.clean_up_jobs()
... | job_id = self.__job_id(job_type, uid)
self.queue.enqueue(job_id, target, *args, **kwargs)
| job_id = self.__job_id(job_type, uid)
self.queue.enqueue(job_id, target, *args, **kwargs)
| 8 | 802 | 46 | 848 | import traceback
from enum import Enum
from typing import Callable, Dict, Union
from mage_ai.orchestration.queue.queue_factory import QueueFactory
class JobType(str, Enum):
BLOCK_RUN = 'block_run'
PIPELINE_RUN = 'pipeline_run'
INTEGRATION_STREAM = 'integration_stream'
class JobManager:
def __init__... | import traceback
from enum import Enum
from typing import Callable, Dict, Union
from mage_ai.orchestration.queue.queue_factory import QueueFactory
class JobType(str, Enum):
BLOCK_RUN = 'block_run'
PIPELINE_RUN = 'pipeline_run'
INTEGRATION_STREAM = 'integration_stream'
class JobManager:
def __init__... |
20,625 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/queue/celery_queue.py | 26,27 | 7,37 | has_job | CeleryQueue | 27,29 | 27,29 | class CeleryQueue(Queue):
"""
TODO: implement this class.
"""
def __init__(self, queue_config: QueueConfig):
# self.celery_app = Celery(
# 'mypackage',
# broker='amqp://guest@localhost//',
# backend='amqp://guest@localhost//',
# )
pass
de... | class CeleryQueue(Queue):
"""
TODO: implement this class.
"""
def __init__(self, queue_config: QueueConfig):
# self.celery_app = Celery(
# 'mypackage',
# broker='amqp://guest@localhost//',
# backend='amqp://guest@localhost//',
# )
pass
de... | return False
| return False
| 2 | 214 | 7 | 221 | from typing import Callable
from mage_ai.orchestration.queue.config import QueueConfig
from mage_ai.orchestration.queue.queue import Queue
class CeleryQueue(Queue):
"""
TODO: implement this class.
"""
def __init__(self, queue_config: QueueConfig):
# self.celery_app = Celery(
# 'm... | from typing import Callable
from mage_ai.orchestration.queue.config import QueueConfig
from mage_ai.orchestration.queue.queue import Queue
class CeleryQueue(Queue):
"""
TODO: implement this class.
"""
def __init__(self, queue_config: QueueConfig):
# self.celery_app = Celery(
# 'm... |
20,626 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/queue/queue.py | 30,31 | 5,32 | _print | Queue | 31,32 | 31,32 | class Queue(ABC):
@abstractmethod
def clean_up_jobs(self):
pass
@abstractmethod
def enqueue(self, job_id: str, target: Callable, *args, **kwargs):
pass
@abstractmethod
def has_job(self, job_id: str, logger=None):
pass
@abstractmethod
def kill_job(self, job_id: ... | class Queue(ABC):
@abstractmethod
def clean_up_jobs(self):
pass
@abstractmethod
def enqueue(self, job_id: str, target: Callable, *args, **kwargs):
pass
@abstractmethod
def has_job(self, job_id: str, logger=None):
pass
@abstractmethod
def kill_job(self, job_id: ... | print(f'[{self.__class__.__name__}] {msg}')
| print(f'[{self.__class__.__name__}] {msg}')
| 2 | 173 | 21 | 194 | from abc import ABC, abstractmethod
from typing import Callable
class Queue(ABC):
@abstractmethod
def clean_up_jobs(self):
pass
@abstractmethod
def enqueue(self, job_id: str, target: Callable, *args, **kwargs):
pass
@abstractmethod
def has_job(self, job_id: str, logger=None):... | from abc import ABC, abstractmethod
from typing import Callable
class Queue(ABC):
@abstractmethod
def clean_up_jobs(self):
pass
@abstractmethod
def enqueue(self, job_id: str, target: Callable, *args, **kwargs):
pass
@abstractmethod
def has_job(self, job_id: str, logger=None):... |
20,627 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/queue/queue_factory.py | 8,10 | 5,21 | get_queue | QueueFactory | 10,21 | 10,21 | class QueueFactory:
queue = None
@classmethod
def get_queue(self):
FILL_FUNC_BODY | class QueueFactory:
queue = None
@classmethod
def get_queue(self):
FILL_FUNC_BODY | if self.queue is not None:
return self.queue
queue_config = QueueConfig.load(config=get_repo_config().queue_config or dict())
if queue_config.queue_type == QueueType.CELERY:
from mage_ai.orchestration.queue.celery_queue import CeleryQueue
self.queue = CeleryQ... | if self.queue is not None:
return self.queue
queue_config = QueueConfig.load(config=get_repo_config().queue_config or dict())
if queue_config.queue_type == QueueType.CELERY:
from mage_ai.orchestration.queue.celery_queue import CeleryQueue
self.queue = CeleryQ... | 33 | 36 | 154 | 190 | from mage_ai.data_preparation.repo_manager import get_repo_config
from mage_ai.orchestration.queue.config import QueueConfig, QueueType
class QueueFactory:
queue = None
@classmethod
def get_queue(self):
FILL_FUNC_BODY | from mage_ai.data_preparation.repo_manager import get_repo_config
from mage_ai.orchestration.queue.config import QueueConfig, QueueType
class QueueFactory:
queue = None
@classmethod
def get_queue(self):
FILL_FUNC_BODY |
20,628 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/run_status_checker.py | 24,31 | 1,82 | check_status | 31,67 | 31,67 | from datetime import datetime, timedelta, timezone
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.utils import warn_for_repo_path
from mage_ai.orchestration.db.models.schedules import (
BlockRun,
PipelineRun,
PipelineSchedule,
)
from mage_ai.settings.repo... | from datetime import datetime, timedelta, timezone
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.utils import warn_for_repo_path
from mage_ai.orchestration.db.models.schedules import (
BlockRun,
PipelineRun,
PipelineSchedule,
)
from mage_ai.settings.repo... | __validate_pipeline_and_block(pipeline_uuid, block_uuid, repo_path=repo_path)
execution_date = execution_date.replace(tzinfo=timezone.utc)
pipeline_run = (
PipelineRun
.query
.join(PipelineRun.pipeline_schedule)
.filter(PipelineSchedule.pipeline_uuid == pipeline_uuid)
... | __validate_pipeline_and_block(pipeline_uuid, block_uuid, repo_path=repo_path)
execution_date = execution_date.replace(tzinfo=timezone.utc)
pipeline_run = (
PipelineRun
.query
.join(PipelineRun.pipeline_schedule)
.filter(PipelineSchedule.pipeline_uuid == pipeline_uuid)
... | 86 | 469 | 418 | 887 | from datetime import datetime, timedelta, timezone
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.utils import warn_for_repo_path
from mage_ai.orchestration.db.models.schedules import (
BlockRun,
PipelineRun,
PipelineSchedule,
)
from mage_ai.settings.repo... | from datetime import datetime, timedelta, timezone
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.utils import warn_for_repo_path
from mage_ai.orchestration.db.models.schedules import (
BlockRun,
PipelineRun,
PipelineSchedule,
)
from mage_ai.settings.repo... | |
20,629 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/triggers/api.py | 95,99 | 1,125 | __fetch_or_create_pipeline_schedule | 99,125 | 99,125 | from datetime import datetime
from typing import Dict, List, Optional, Union
from mage_ai.api.resources.PipelineScheduleResource import PipelineScheduleResource
from mage_ai.data_preparation.models.block.remote.models import RemoteBlock
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_pr... | from datetime import datetime
from typing import Dict, List, Optional, Union
from mage_ai.api.resources.PipelineScheduleResource import PipelineScheduleResource
from mage_ai.data_preparation.models.block.remote.models import RemoteBlock
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_pr... | if schedule_name is None:
schedule_name = TRIGGER_NAME_FOR_TRIGGER_CREATED_FROM_CODE
pipeline_uuid = pipeline.uuid
schedule_type = ScheduleType.API
pipeline_schedule = PipelineSchedule.repo_query.filter(
PipelineSchedule.name == schedule_name,
PipelineSchedule.pipeline_uuid == ... | if schedule_name is None:
schedule_name = TRIGGER_NAME_FOR_TRIGGER_CREATED_FROM_CODE
pipeline_uuid = pipeline.uuid
schedule_type = ScheduleType.API
pipeline_schedule = PipelineSchedule.repo_query.filter(
PipelineSchedule.name == schedule_name,
PipelineSchedule.pipeline_uuid == ... | 46 | 1,005 | 255 | 1,260 | from datetime import datetime
from typing import Dict, List, Optional, Union
from mage_ai.api.resources.PipelineScheduleResource import PipelineScheduleResource
from mage_ai.data_preparation.models.block.remote.models import RemoteBlock
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_pr... | from datetime import datetime
from typing import Dict, List, Optional, Union
from mage_ai.api.resources.PipelineScheduleResource import PipelineScheduleResource
from mage_ai.data_preparation.models.block.remote.models import RemoteBlock
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_pr... | |
20,630 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/triggers/event_trigger.py | 5,6 | 4,8 | run | EventTrigger | 6,8 | 6,8 | class EventTrigger:
def run(self, event) -> None:
FILL_FUNC_BODY | class EventTrigger:
def run(self, event) -> None:
FILL_FUNC_BODY | print(f'Trigger by event: {event}')
schedule_with_event(event)
| print(f'Trigger by event: {event}')
schedule_with_event(event)
| 5 | 29 | 27 | 56 | from mage_ai.orchestration.pipeline_scheduler import schedule_with_event
class EventTrigger:
def run(self, event) -> None:
FILL_FUNC_BODY | from mage_ai.orchestration.pipeline_scheduler import schedule_with_event
class EventTrigger:
def run(self, event) -> None:
FILL_FUNC_BODY |
20,631 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/triggers/loop_time_trigger.py | 11,12 | 7,19 | start | LoopTimeTrigger | 12,19 | 12,19 | class LoopTimeTrigger(TimeTrigger):
def __init__(self, trigger_interval=SCHEDULER_TRIGGER_INTERVAL) -> None:
super().__init__(trigger_interval)
def start(self) -> None:
FILL_FUNC_BODY | class LoopTimeTrigger(TimeTrigger):
def __init__(self, trigger_interval=SCHEDULER_TRIGGER_INTERVAL) -> None:
super().__init__(trigger_interval)
def start(self) -> None:
FILL_FUNC_BODY | while True:
self.last_run_time = int(time.time())
self.run()
current_time = int(time.time())
sleep_time = self.trigger_interval - (current_time - self.last_run_time)
if sleep_time > 0:
time.sleep(sleep_time)
| while True:
self.last_run_time = int(time.time())
self.run()
current_time = int(time.time())
sleep_time = self.trigger_interval - (current_time - self.last_run_time)
if sleep_time > 0:
time.sleep(sleep_time)
| 21 | 74 | 90 | 164 | import time
from mage_ai.orchestration.triggers.time_trigger import TimeTrigger
from mage_ai.settings import SCHEDULER_TRIGGER_INTERVAL
class LoopTimeTrigger(TimeTrigger):
def __init__(self, trigger_interval=SCHEDULER_TRIGGER_INTERVAL) -> None:
super().__init__(trigger_interval)
def start(self) -> N... | import time
from mage_ai.orchestration.triggers.time_trigger import TimeTrigger
from mage_ai.settings import SCHEDULER_TRIGGER_INTERVAL
class LoopTimeTrigger(TimeTrigger):
def __init__(self, trigger_interval=SCHEDULER_TRIGGER_INTERVAL) -> None:
super().__init__(trigger_interval)
def start(self) -> N... |
20,632 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/triggers/time_trigger.py | 10,11 | 6,17 | run | TimeTrigger | 11,14 | 11,14 | class TimeTrigger(ABC):
def __init__(self, trigger_interval: int = 10) -> None:
self.trigger_interval = trigger_interval
def run(self) -> None:
FILL_FUNC_BODY @abstractmethod
def start(self) -> None:
pass
| class TimeTrigger(ABC):
def __init__(self, trigger_interval: int = 10) -> None:
self.trigger_interval = trigger_interval
def run(self) -> None:
FILL_FUNC_BODY @abstractmethod
def start(self) -> None:
pass
| schedule_all()
check_sla()
| schedule_all()
check_sla()
| 2 | 83 | 17 | 100 | from abc import ABC, abstractmethod
from mage_ai.orchestration.pipeline_scheduler import check_sla, schedule_all
class TimeTrigger(ABC):
def __init__(self, trigger_interval: int = 10) -> None:
self.trigger_interval = trigger_interval
def run(self) -> None:
FILL_FUNC_BODY @abstractmethod
def s... | from abc import ABC, abstractmethod
from mage_ai.orchestration.pipeline_scheduler import check_sla, schedule_all
class TimeTrigger(ABC):
def __init__(self, trigger_interval: int = 10) -> None:
self.trigger_interval = trigger_interval
def run(self) -> None:
FILL_FUNC_BODY @abstractmethod
def s... |
20,633 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/triggers/utils.py | 82,90 | 1,137 | create_and_start_pipeline_run | 90,137 | 90,137 | from datetime import datetime, timedelta
from time import sleep
from typing import Dict, List, Optional, Union
from mage_ai.data_preparation.models.block.remote.models import RemoteBlock
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import ScheduleStatus
fr... | from datetime import datetime, timedelta
from time import sleep
from typing import Dict, List, Optional, Union
from mage_ai.data_preparation.models.block.remote.models import RemoteBlock
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import ScheduleStatus
fr... | if payload is None:
payload = {}
configured_payload, is_integration = configure_pipeline_run_payload(
pipeline_schedule,
pipeline.type,
payload,
)
if remote_blocks:
variables = configured_payload.get('variables', {})
if variables.get('remote_blocks'):
... | if payload is None:
payload = {}
configured_payload, is_integration = configure_pipeline_run_payload(
pipeline_schedule,
pipeline.type,
payload,
)
if remote_blocks:
variables = configured_payload.get('variables', {})
if variables.get('remote_blocks'):
... | 106 | 924 | 484 | 1,408 | from datetime import datetime, timedelta
from time import sleep
from typing import Dict, List, Optional, Union
from mage_ai.data_preparation.models.block.remote.models import RemoteBlock
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import ScheduleStatus
fr... | from datetime import datetime, timedelta
from time import sleep
from typing import Dict, List, Optional, Union
from mage_ai.data_preparation.models.block.remote.models import RemoteBlock
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.data_preparation.models.triggers import ScheduleStatus
fr... | |
20,634 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/utils/distributed_lock.py | 18,19 | 5,34 | try_acquire_lock | DistributedLock | 19,30 | 19,30 | class DistributedLock:
def __init__(
self,
lock_key_prefix='LOCK_KEY',
lock_timeout=30,
):
self.lock_key_prefix = lock_key_prefix
self.lock_timeout = lock_timeout
self.redis_client = init_redis_client(REDIS_URL)
def __lock_key(self, key) -> str:
retur... | class DistributedLock:
def __init__(
self,
lock_key_prefix='LOCK_KEY',
lock_timeout=30,
):
self.lock_key_prefix = lock_key_prefix
self.lock_timeout = lock_timeout
self.redis_client = init_redis_client(REDIS_URL)
def __lock_key(self, key) -> str:
retur... | if not self.redis_client:
return True
# Try to acquire the lock by setting the lock key with a value and an expiration time
acquired = self.redis_client.set(
self.__lock_key(key),
'1',
nx=True,
ex=timeout or self.lock_timeout,
)... | if not self.redis_client:
return True
# Try to acquire the lock by setting the lock key with a value and an expiration time
acquired = self.redis_client.set(
self.__lock_key(key),
'1',
nx=True,
ex=timeout or self.lock_timeout,
)... | 37 | 208 | 104 | 312 | from mage_ai.services.redis.redis import init_redis_client
from mage_ai.settings import REDIS_URL
class DistributedLock:
def __init__(
self,
lock_key_prefix='LOCK_KEY',
lock_timeout=30,
):
self.lock_key_prefix = lock_key_prefix
self.lock_timeout = lock_timeout
s... | from mage_ai.services.redis.redis import init_redis_client
from mage_ai.settings import REDIS_URL
class DistributedLock:
def __init__(
self,
lock_key_prefix='LOCK_KEY',
lock_timeout=30,
):
self.lock_key_prefix = lock_key_prefix
self.lock_timeout = lock_timeout
s... |
20,635 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/orchestration/utils/git.py | 43,44 | 1,62 | log_git_sync | 44,62 | 44,62 | from typing import Dict
from mage_ai.data_preparation.logging.logger import DictLogger
from mage_ai.data_preparation.preferences import get_preferences
from mage_ai.data_preparation.sync import GitConfig
from mage_ai.data_preparation.sync.git_sync import GitSync
from mage_ai.orchestration.utils.distributed_lock import... | from typing import Dict
from mage_ai.data_preparation.logging.logger import DictLogger
from mage_ai.data_preparation.preferences import get_preferences
from mage_ai.data_preparation.sync import GitConfig
from mage_ai.data_preparation.sync.git_sync import GitSync
from mage_ai.orchestration.utils.distributed_lock import... | if result is None:
return
if tags is None:
tags = dict()
git_sync_status = result.get('status')
if git_sync_status == 'success':
logger.info(
'Successfully synced data from git repo: '
f'{result.get("remote_repo_link")}, branch: {result.get("branch")}',
... | if result is None:
return
if tags is None:
tags = dict()
git_sync_status = result.get('status')
if git_sync_status == 'success':
logger.info(
'Successfully synced data from git repo: '
f'{result.get("remote_repo_link")}, branch: {result.get("branch")}',
... | 55 | 443 | 201 | 644 | from typing import Dict
from mage_ai.data_preparation.logging.logger import DictLogger
from mage_ai.data_preparation.preferences import get_preferences
from mage_ai.data_preparation.sync import GitConfig
from mage_ai.data_preparation.sync.git_sync import GitSync
from mage_ai.orchestration.utils.distributed_lock import... | from typing import Dict
from mage_ai.data_preparation.logging.logger import DictLogger
from mage_ai.data_preparation.preferences import get_preferences
from mage_ai.data_preparation.sync import GitConfig
from mage_ai.data_preparation.sync.git_sync import GitSync
from mage_ai.orchestration.utils.distributed_lock import... | |
20,637 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/presenters/charts/data_sources/base.py | 19,21 | 7,29 | pipeline | ChartDataSourceBase | 21,26 | 21,26 | class ChartDataSourceBase(ABC):
def __init__(
self,
block_uuid: str = None,
pipeline_schedule_id: int = None,
pipeline_uuid: str = None,
):
self._pipeline = None
self.block_uuid = block_uuid
self.pipeline_schedule_id = pipeline_schedule_id
self.pip... | class ChartDataSourceBase(ABC):
def __init__(
self,
block_uuid: str = None,
pipeline_schedule_id: int = None,
pipeline_uuid: str = None,
):
self._pipeline = None
self.block_uuid = block_uuid
self.pipeline_schedule_id = pipeline_schedule_id
self.pip... | if self.pipeline_uuid and not self._pipeline:
self._pipeline = Pipeline.get(self.pipeline_uuid, repo_path=get_repo_path())
return self._pipeline
| if self.pipeline_uuid and not self._pipeline:
self._pipeline = Pipeline.get(self.pipeline_uuid, repo_path=get_repo_path())
return self._pipeline
| 11 | 149 | 59 | 208 | from abc import ABC, abstractmethod
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.settings.repo import get_repo_path
class ChartDataSourceBase(ABC):
def __init__(
self,
block_uuid: str = None,
pipeline_schedule_id: int = None,
pipeline_uuid: str = None... | from abc import ABC, abstractmethod
from mage_ai.data_preparation.models.pipeline import Pipeline
from mage_ai.settings.repo import get_repo_path
class ChartDataSourceBase(ABC):
def __init__(
self,
block_uuid: str = None,
pipeline_schedule_id: int = None,
pipeline_uuid: str = None... |
20,638 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/presenters/charts/data_sources/block.py | 11,17 | 10,72 | load_data | ChartDataSourceBlock | 17,72 | 17,72 | class ChartDataSourceBlock(ChartDataSourceBase):
def load_data(
self,
partitions: Union[int, List[str]] = None,
variables: Dict = None,
**kwargs,
) -> List:
FILL_FUNC_BODY | class ChartDataSourceBlock(ChartDataSourceBase):
def load_data(
self,
partitions: Union[int, List[str]] = None,
variables: Dict = None,
**kwargs,
) -> List:
FILL_FUNC_BODY | block = self.pipeline.get_block(self.block_uuid)
arr = []
if partitions is not None and (not is_number(partitions) or partitions != 0):
execution_partitions = []
if isinstance(partitions, List):
execution_partitions += partitions
elif is_num... | block = self.pipeline.get_block(self.block_uuid)
arr = []
if partitions is not None and (not is_number(partitions) or partitions != 0):
execution_partitions = []
if isinstance(partitions, List):
execution_partitions += partitions
elif is_num... | 109 | 69 | 569 | 638 | from typing import Dict, List, Union
from mage_ai.data_preparation.variable_manager import get_global_variables
from mage_ai.orchestration.db.models.schedules import PipelineRun
from mage_ai.presenters.charts.data_sources.base import ChartDataSourceBase
from mage_ai.shared.hash import merge_dict
from mage_ai.shared.st... | from typing import Dict, List, Union
from mage_ai.data_preparation.variable_manager import get_global_variables
from mage_ai.orchestration.db.models.schedules import PipelineRun
from mage_ai.presenters.charts.data_sources.base import ChartDataSourceBase
from mage_ai.shared.hash import merge_dict
from mage_ai.shared.st... |
20,639 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/presenters/pages/constants.py | 18,19 | 1,29 | _combine | 19,23 | 19,23 | from functools import reduce
from typing import Dict
from mage_ai.presenters.pages.models.client_pages.pipeline_schedules import (
CreatePage as PipelineSchedulesCreatePage,
)
from mage_ai.presenters.pages.models.client_pages.pipeline_schedules import (
ListPage as PipelineSchedulesListPage,
)
from mage_ai.pre... | from functools import reduce
from typing import Dict
from mage_ai.presenters.pages.models.client_pages.pipeline_schedules import (
CreatePage as PipelineSchedulesCreatePage,
)
from mage_ai.presenters.pages.models.client_pages.pipeline_schedules import (
ListPage as PipelineSchedulesListPage,
)
from mage_ai.pre... | acc[model.get_uuid()] = model
return acc
| acc[model.get_uuid()] = model
return acc
| 5 | 242 | 23 | 265 | from functools import reduce
from typing import Dict
from mage_ai.presenters.pages.models.client_pages.pipeline_schedules import (
CreatePage as PipelineSchedulesCreatePage,
)
from mage_ai.presenters.pages.models.client_pages.pipeline_schedules import (
ListPage as PipelineSchedulesListPage,
)
from mage_ai.pre... | from functools import reduce
from typing import Dict
from mage_ai.presenters.pages.models.client_pages.pipeline_schedules import (
CreatePage as PipelineSchedulesCreatePage,
)
from mage_ai.presenters.pages.models.client_pages.pipeline_schedules import (
ListPage as PipelineSchedulesListPage,
)
from mage_ai.pre... | |
20,640 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/presenters/pages/loaders/pipeline_schedules.py | 8,15 | 7,24 | load | Loader | 15,24 | 15,24 | class Loader(BaseLoader):
@classmethod
async def load(
self,
ids: List[Union[int, str]],
query: Dict = None,
**kwargs,
) -> List[PipelineSchedule]:
FILL_FUNC_BODY | class Loader(BaseLoader):
@classmethod
async def load(
self,
ids: List[Union[int, str]],
query: Dict = None,
**kwargs,
) -> List[PipelineSchedule]:
FILL_FUNC_BODY | if ids:
ids = list(filter(lambda x: x, ids))
if ids:
return PipelineSchedule.query.filter(
PipelineSchedule.id.in_(ids),
).all()
return []
| if ids:
ids = list(filter(lambda x: x, ids))
if ids:
return PipelineSchedule.query.filter(
PipelineSchedule.id.in_(ids),
).all()
return []
| 16 | 74 | 74 | 148 | from typing import Dict, List, Union
from mage_ai.orchestration.db.models.schedules import PipelineSchedule
from mage_ai.presenters.pages.loaders.base import BaseLoader
class Loader(BaseLoader):
@classmethod
async def load(
self,
ids: List[Union[int, str]],
query: Dict = None,
... | from typing import Dict, List, Union
from mage_ai.orchestration.db.models.schedules import PipelineSchedule
from mage_ai.presenters.pages.loaders.base import BaseLoader
class Loader(BaseLoader):
@classmethod
async def load(
self,
ids: List[Union[int, str]],
query: Dict = None,
... |
20,641 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/presenters/pages/loaders/utils.py | 5,6 | 1,17 | load_resources | 6,17 | 6,17 | import importlib
from typing import Dict
async def load_resources(query: Dict) -> Dict:
FILL_FUNC_BODY | import importlib
from typing import Dict
async def load_resources(query: Dict) -> Dict:
FILL_FUNC_BODY | mapping = {}
for query_parameter_name, ids in query.items():
resource_name = query_parameter_name.replace('[]', '')
loader = importlib.import_module(
f'mage_ai.presenters.pages.loaders.{resource_name}',
).Loader
mapping[resource_name] = await loader.load(ids, query)... | mapping = {}
for query_parameter_name, ids in query.items():
resource_name = query_parameter_name.replace('[]', '')
loader = importlib.import_module(
f'mage_ai.presenters.pages.loaders.{resource_name}',
).Loader
mapping[resource_name] = await loader.load(ids, query)... | 24 | 39 | 113 | 152 | import importlib
from typing import Dict
async def load_resources(query: Dict) -> Dict:
FILL_FUNC_BODY | import importlib
from typing import Dict
async def load_resources(query: Dict) -> Dict:
FILL_FUNC_BODY | |
20,642 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/presenters/pages/models/client_pages/pipeline_schedules.py | 38,40 | 28,51 | disabled | CreatePage | 40,51 | 40,51 | class CreatePage(BasePage):
operation = OperationType.CREATE
@classmethod
async def components(self, **kwargs) -> List[PageComponent]:
return [
CreateWithInteractionsComponent,
EditComponent,
]
@classmethod
async def disabled(self, current_user: User = None,... | class CreatePage(BasePage):
operation = OperationType.CREATE
@classmethod
async def components(self, **kwargs) -> List[PageComponent]:
return [
CreateWithInteractionsComponent,
EditComponent,
]
@classmethod
async def disabled(self, current_user: User = None,... | pipelines = kwargs.get('pipelines') or []
for pipeline in [p for p in pipelines if p]:
pipeline_schedule = PipelineScheduleResource.model_class(pipeline_uuid=pipeline.uuid)
resource = PipelineScheduleResource(pipeline_schedule, current_user)
policy = resource.policy_c... | pipelines = kwargs.get('pipelines') or []
for pipeline in [p for p in pipelines if p]:
pipeline_schedule = PipelineScheduleResource.model_class(pipeline_uuid=pipeline.uuid)
resource = PipelineScheduleResource(pipeline_schedule, current_user)
policy = resource.policy_c... | 35 | 99 | 141 | 240 | from typing import List
from mage_ai.api.errors import ApiError
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.resources.PipelineScheduleResource import PipelineScheduleResource
from mage_ai.orchestration.db.models.oauth import User
from mage_ai.presenters.pages.models.base import ClientPa... | from typing import List
from mage_ai.api.errors import ApiError
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.resources.PipelineScheduleResource import PipelineScheduleResource
from mage_ai.orchestration.db.models.oauth import User
from mage_ai.presenters.pages.models.base import ClientPa... |
20,643 | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai | /home/hieuvd/dung_repo/raw/stars_01/mage-ai_mage-ai/mage-ai/mage_ai/presenters/pages/models/page_components/pipeline_schedules.py | 27,29 | 22,52 | enabled | CreateWithInteractionsComponent | 29,52 | 29,52 | class CreateWithInteractionsComponent(BaseComponent):
category = ComponentCategory.BUTTON
operation = OperationType.CREATE
uuid_from_name = True
@classmethod
async def enabled(self, current_user: User = None, **kwargs) -> bool:
FILL_FUNC_BODY | class CreateWithInteractionsComponent(BaseComponent):
category = ComponentCategory.BUTTON
operation = OperationType.CREATE
uuid_from_name = True
@classmethod
async def enabled(self, current_user: User = None, **kwargs) -> bool:
FILL_FUNC_BODY | async def __validate_pipeline_interactions_permissions(
pipeline: Pipeline,
current_user=current_user,
) -> bool:
return await PipelineInteractions(pipeline).filter_for_permissions(current_user)
pipelines = kwargs.get('pipelines') or []
if pipelines ... | async def __validate_pipeline_interactions_permissions(
pipeline: Pipeline,
current_user=current_user,
) -> bool:
return await PipelineInteractions(pipeline).filter_for_permissions(current_user)
pipelines = kwargs.get('pipelines') or []
if pipelines ... | 48 | 78 | 221 | 299 | import asyncio
from typing import List
from mage_ai.api.constants import AttributeOperationType
from mage_ai.api.errors import ApiError
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.resources.PipelineScheduleResource import PipelineScheduleResource
from mage_ai.data_preparation.models.pip... | import asyncio
from typing import List
from mage_ai.api.constants import AttributeOperationType
from mage_ai.api.errors import ApiError
from mage_ai.api.operations.constants import OperationType
from mage_ai.api.resources.PipelineScheduleResource import PipelineScheduleResource
from mage_ai.data_preparation.models.pip... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.