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,752 | /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_integrations/mage_integrations/sources/chargebee/streams/promotional_credits.py | 18,19 | 4,20 | get_url | PromotionalCreditsStream | 19,20 | 19,20 | class PromotionalCreditsStream(BaseChargebeeStream):
TABLE = 'promotional_credits'
ENTITY = 'promotional_credit'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'created_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['created_at']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEY... | class PromotionalCreditsStream(BaseChargebeeStream):
TABLE = 'promotional_credits'
ENTITY = 'promotional_credit'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'created_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['created_at']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEY... | return 'https://{}.chargebee.com/api/v2/promotional_credits'.format(self.config.get('site'))
| return 'https://{}.chargebee.com/api/v2/promotional_credits'.format(self.config.get('site'))
| 2 | 185 | 36 | 221 | from mage_integrations.sources.chargebee.streams.base import BaseChargebeeStream
class PromotionalCreditsStream(BaseChargebeeStream):
TABLE = 'promotional_credits'
ENTITY = 'promotional_credit'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'created_at'
KEY_PROPERTIES = ['id']
BOOKMARK_P... | from mage_integrations.sources.chargebee.streams.base import BaseChargebeeStream
class PromotionalCreditsStream(BaseChargebeeStream):
TABLE = 'promotional_credits'
ENTITY = 'promotional_credit'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'created_at'
KEY_PROPERTIES = ['id']
BOOKMARK_P... |
20,753 | /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_integrations/mage_integrations/sources/chargebee/streams/quotes.py | 18,19 | 4,20 | get_url | QuotesStream | 19,20 | 19,20 | class QuotesStream(BaseChargebeeStream):
TABLE = 'quotes'
ENTITY = 'quote'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['updated_at']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEYS = ['updated_at']
INCLUSION = 'av... | class QuotesStream(BaseChargebeeStream):
TABLE = 'quotes'
ENTITY = 'quote'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['updated_at']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEYS = ['updated_at']
INCLUSION = 'av... | return 'https://{}.chargebee.com/api/v2/quotes'.format(self.config.get('site'))
| return 'https://{}.chargebee.com/api/v2/quotes'.format(self.config.get('site'))
| 2 | 171 | 32 | 203 | from mage_integrations.sources.chargebee.streams.base import BaseChargebeeStream
class QuotesStream(BaseChargebeeStream):
TABLE = 'quotes'
ENTITY = 'quote'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['updated_at']
SELECTE... | from mage_integrations.sources.chargebee.streams.base import BaseChargebeeStream
class QuotesStream(BaseChargebeeStream):
TABLE = 'quotes'
ENTITY = 'quote'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['updated_at']
SELECTE... |
20,754 | /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_integrations/mage_integrations/sources/chargebee/streams/subscriptions.py | 23,24 | 4,25 | get_url | SubscriptionsStream | 24,25 | 24,25 | class SubscriptionsStream(BaseChargebeeStream):
TABLE = 'subscriptions'
ENTITY = 'subscription'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['updated_at']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEYS = ['updated_at'... | class SubscriptionsStream(BaseChargebeeStream):
TABLE = 'subscriptions'
ENTITY = 'subscription'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['updated_at']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEYS = ['updated_at'... | return 'https://{}.chargebee.com/api/v2/subscriptions'.format(self.config.get('site'))
| return 'https://{}.chargebee.com/api/v2/subscriptions'.format(self.config.get('site'))
| 2 | 251 | 32 | 283 | from mage_integrations.sources.chargebee.streams.base import BaseChargebeeStream
class SubscriptionsStream(BaseChargebeeStream):
TABLE = 'subscriptions'
ENTITY = 'subscription'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['upd... | from mage_integrations.sources.chargebee.streams.base import BaseChargebeeStream
class SubscriptionsStream(BaseChargebeeStream):
TABLE = 'subscriptions'
ENTITY = 'subscription'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['upd... |
20,755 | /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_integrations/mage_integrations/sources/chargebee/streams/transactions.py | 18,19 | 4,20 | get_url | TransactionsStream | 19,20 | 19,20 | class TransactionsStream(BaseChargebeeStream):
TABLE = 'transactions'
ENTITY = 'transaction'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['updated_at']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEYS = ['updated_at']
... | class TransactionsStream(BaseChargebeeStream):
TABLE = 'transactions'
ENTITY = 'transaction'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['updated_at']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEYS = ['updated_at']
... | return 'https://{}.chargebee.com/api/v2/transactions'.format(self.config.get('site'))
| return 'https://{}.chargebee.com/api/v2/transactions'.format(self.config.get('site'))
| 2 | 173 | 32 | 205 | from mage_integrations.sources.chargebee.streams.base import BaseChargebeeStream
class TransactionsStream(BaseChargebeeStream):
TABLE = 'transactions'
ENTITY = 'transaction'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['update... | from mage_integrations.sources.chargebee.streams.base import BaseChargebeeStream
class TransactionsStream(BaseChargebeeStream):
TABLE = 'transactions'
ENTITY = 'transaction'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['update... |
20,756 | /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_integrations/mage_integrations/sources/chargebee/streams/virtual_bank_accounts.py | 18,19 | 4,20 | get_url | VirtualBankAccountsStream | 19,20 | 19,20 | class VirtualBankAccountsStream(BaseChargebeeStream):
TABLE = 'virtual_bank_accounts'
ENTITY = 'virtual_bank_account'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['updated_at']
SELECTED_BY_DEFAULT = True
VALID_REPLICATIO... | class VirtualBankAccountsStream(BaseChargebeeStream):
TABLE = 'virtual_bank_accounts'
ENTITY = 'virtual_bank_account'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['updated_at']
SELECTED_BY_DEFAULT = True
VALID_REPLICATIO... | return 'https://{}.chargebee.com/api/v2/virtual_bank_accounts'.format(self.config.get('site'))
| return 'https://{}.chargebee.com/api/v2/virtual_bank_accounts'.format(self.config.get('site'))
| 2 | 184 | 36 | 220 | from mage_integrations.sources.chargebee.streams.base import BaseChargebeeStream
class VirtualBankAccountsStream(BaseChargebeeStream):
TABLE = 'virtual_bank_accounts'
ENTITY = 'virtual_bank_account'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKM... | from mage_integrations.sources.chargebee.streams.base import BaseChargebeeStream
class VirtualBankAccountsStream(BaseChargebeeStream):
TABLE = 'virtual_bank_accounts'
ENTITY = 'virtual_bank_account'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'updated_at'
KEY_PROPERTIES = ['id']
BOOKM... |
20,757 | /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_integrations/mage_integrations/sources/commercetools/streams/base.py | 15,16 | 4,31 | load_data | BaseStream | 16,31 | 16,31 | class BaseStream():
KEY_PROPERTIES = []
URL_PATH = None
def __init__(self, client, config, stream, logger):
self.client = client
self.config = config
self.stream = stream
self.logger = logger
def load_data(self, bookmarks: Dict = None) -> Generator[List[Dict], None, No... | class BaseStream():
KEY_PROPERTIES = []
URL_PATH = None
def __init__(self, client, config, stream, logger):
self.client = client
self.config = config
self.stream = stream
self.logger = logger
def load_data(self, bookmarks: Dict = None) -> Generator[List[Dict], None, No... | if self.URL_PATH is None:
return
offset = 0
kwargs = dict(path=self.URL_PATH)
while True:
kwargs['params'] = dict(offset=offset)
data = self.client.request(**kwargs)
results = data['results']
if not results:
brea... | if self.URL_PATH is None:
return
offset = 0
kwargs = dict(path=self.URL_PATH)
while True:
kwargs['params'] = dict(offset=offset)
data = self.client.request(**kwargs)
results = data['results']
if not results:
brea... | 37 | 109 | 140 | 249 | from typing import Dict, Generator, List
class BaseStream():
KEY_PROPERTIES = []
URL_PATH = None
def __init__(self, client, config, stream, logger):
self.client = client
self.config = config
self.stream = stream
self.logger = logger
def load_data(self, bookmarks: Dic... | from typing import Dict, Generator, List
class BaseStream():
KEY_PROPERTIES = []
URL_PATH = None
def __init__(self, client, config, stream, logger):
self.client = client
self.config = config
self.stream = stream
self.logger = logger
def load_data(self, bookmarks: Dic... |
20,758 | /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_integrations/mage_integrations/sources/couchbase/utils.py | 12,20 | 1,59 | build_comparison_statement | 20,43 | 20,43 | from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NULL,
COLUMN_TYPE_NUMBER,
)
from mage_integrations.utils.array import find
from typing import Any, Callable, Dict
def build_comparison_statement(
col: str,
val: A... | from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NULL,
COLUMN_TYPE_NUMBER,
)
from mage_integrations.utils.array import find
from typing import Any, Callable, Dict
def build_comparison_statement(
col: str,
val: A... | column_properties = properties.get(col)
if not column_properties:
raise Exception(
f'There are no properties in the schema for column {col}.')
column_type = find(
lambda x: COLUMN_TYPE_NULL != x,
column_properties['type']
)
column_format = column_properties.get('... | column_properties = properties.get(col)
if not column_properties:
raise Exception(
f'There are no properties in the schema for column {col}.')
column_type = find(
lambda x: COLUMN_TYPE_NULL != x,
column_properties['type']
)
column_format = column_properties.get('... | 58 | 316 | 220 | 536 | from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NULL,
COLUMN_TYPE_NUMBER,
)
from mage_integrations.utils.array import find
from typing import Any, Callable, Dict
def build_comparison_statement(
col: str,
val: A... | from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NULL,
COLUMN_TYPE_NUMBER,
)
from mage_integrations.utils.array import find
from typing import Any, Callable, Dict
def build_comparison_statement(
col: str,
val: A... | |
20,759 | /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_integrations/mage_integrations/sources/datadog/client.py | 12,13 | 4,19 | get_headers | DatadogClient | 13,19 | 13,19 | class DatadogClient(Client):
def __init__(self, config, logger=None, api_result_limit=100):
super().__init__(
config,
logger=logger,
api_result_limit=api_result_limit,
)
def get_headers(self):
FILL_FUNC_BODY | class DatadogClient(Client):
def __init__(self, config, logger=None, api_result_limit=100):
super().__init__(
config,
logger=logger,
api_result_limit=api_result_limit,
)
def get_headers(self):
FILL_FUNC_BODY | return {
"Accept": "application/json",
"Content-Type": "application/json",
"DD-API-KEY": self.config.get('api_key'),
"DD-APPLICATION-KEY": self.config.get('application_key')
}
| return {
"Accept": "application/json",
"Content-Type": "application/json",
"DD-API-KEY": self.config.get('api_key'),
"DD-APPLICATION-KEY": self.config.get('application_key')
}
| 11 | 87 | 75 | 162 | from mage_integrations.sources.http.client import Client
class DatadogClient(Client):
def __init__(self, config, logger=None, api_result_limit=100):
super().__init__(
config,
logger=logger,
api_result_limit=api_result_limit,
)
def get_headers(self):
FILL_FU... | from mage_integrations.sources.http.client import Client
class DatadogClient(Client):
def __init__(self, config, logger=None, api_result_limit=100):
super().__init__(
config,
logger=logger,
api_result_limit=api_result_limit,
)
def get_headers(self):
FILL_FU... |
20,760 | /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_integrations/mage_integrations/sources/dremio/utils.py | 17,18 | 1,29 | mssql_column_type_mapping | 18,23 | 18,23 | from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_FORMAT_UUID,
COLUMN_TYPE_INTEGER,
)
from mage_integrations.sources.sql.base import column_type_mapping
def postgres_column_type_mapping(column_type: str, column_format: str = None) -> str:
if COLUMN_FORMAT_DATETIME == col... | from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_FORMAT_UUID,
COLUMN_TYPE_INTEGER,
)
from mage_integrations.sources.sql.base import column_type_mapping
def postgres_column_type_mapping(column_type: str, column_format: str = None) -> str:
if COLUMN_FORMAT_DATETIME == col... | if COLUMN_FORMAT_DATETIME == column_format:
return 'DATETIME'
return column_type_mapping(column_type, column_format)
| if COLUMN_FORMAT_DATETIME == column_format:
return 'DATETIME'
return column_type_mapping(column_type, column_format)
| 9 | 304 | 51 | 355 | from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_FORMAT_UUID,
COLUMN_TYPE_INTEGER,
)
from mage_integrations.sources.sql.base import column_type_mapping
def postgres_column_type_mapping(column_type: str, column_format: str = None) -> str:
if COLUMN_FORMAT_DATETIME == col... | from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_FORMAT_UUID,
COLUMN_TYPE_INTEGER,
)
from mage_integrations.sources.sql.base import column_type_mapping
def postgres_column_type_mapping(column_type: str, column_format: str = None) -> str:
if COLUMN_FORMAT_DATETIME == col... | |
20,761 | /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_integrations/mage_integrations/sources/facebook_ads/tap_facebook/process_output.py | 55,56 | 1,115 | p_nabd | 56,59 | 56,59 | #!/usr/bin/env python3
from operator import itemgetter
import json
import sys
import csv
def translate_breakdown(breakdown):
if breakdown is None:
return ''
if breakdown == ['age', 'gender']:
return 'ag'
if breakdown == ['country']:
return 'c'
if breakdown == ['placement', 'im... | #!/usr/bin/env python3
from operator import itemgetter
import json
import sys
import csv
def translate_breakdown(breakdown):
if breakdown is None:
return ''
if breakdown == ['age', 'gender']:
return 'ag'
if breakdown == ['country']:
return 'c'
if breakdown == ['placement', 'im... | return proportion(lambda r: r['nabd'] == nabd, recs)
| return proportion(lambda r: r['nabd'] == nabd, recs)
| 7 | 1,100 | 27 | 1,127 | #!/usr/bin/env python3
from operator import itemgetter
import json
import sys
import csv
def translate_breakdown(breakdown):
if breakdown is None:
return ''
if breakdown == ['age', 'gender']:
return 'ag'
if breakdown == ['country']:
return 'c'
if breakdown == ['placement', 'im... | #!/usr/bin/env python3
from operator import itemgetter
import json
import sys
import csv
def translate_breakdown(breakdown):
if breakdown is None:
return ''
if breakdown == ['age', 'gender']:
return 'ag'
if breakdown == ['country']:
return 'c'
if breakdown == ['placement', 'im... | |
20,762 | /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_integrations/mage_integrations/sources/freshdesk/tap_freshdesk/utils.py | 59,60 | 1,94 | update_state | 60,73 | 60,73 | import argparse
import collections
import datetime
import functools
import json
import os
import time
DATETIME_FMT = "%Y-%m-%dT%H:%M:%SZ"
def strptime(dt):
return datetime.datetime.strptime(dt, DATETIME_FMT)
def strftime(dt):
return dt.strftime(DATETIME_FMT)
def ratelimit(limit, every):
def limitdeco... | import argparse
import collections
import datetime
import functools
import json
import os
import time
DATETIME_FMT = "%Y-%m-%dT%H:%M:%SZ"
def strptime(dt):
return datetime.datetime.strptime(dt, DATETIME_FMT)
def strftime(dt):
return dt.strftime(DATETIME_FMT)
def ratelimit(limit, every):
def limitdeco... | if dt is None:
return
if isinstance(dt, datetime.datetime):
dt = strftime(dt)
if entity not in state:
state[entity] = dt
if dt >= state[entity]:
state[entity] = dt
| if dt is None:
return
if isinstance(dt, datetime.datetime):
dt = strftime(dt)
if entity not in state:
state[entity] = dt
if dt >= state[entity]:
state[entity] = dt
| 26 | 621 | 83 | 704 | import argparse
import collections
import datetime
import functools
import json
import os
import time
DATETIME_FMT = "%Y-%m-%dT%H:%M:%SZ"
def strptime(dt):
return datetime.datetime.strptime(dt, DATETIME_FMT)
def strftime(dt):
return dt.strftime(DATETIME_FMT)
def ratelimit(limit, every):
def limitdeco... | import argparse
import collections
import datetime
import functools
import json
import os
import time
DATETIME_FMT = "%Y-%m-%dT%H:%M:%SZ"
def strptime(dt):
return datetime.datetime.strptime(dt, DATETIME_FMT)
def strftime(dt):
return dt.strftime(DATETIME_FMT)
def ratelimit(limit, every):
def limitdeco... | |
20,763 | /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_integrations/mage_integrations/sources/front/streams/base.py | 15,16 | 4,30 | load_data | BaseStream | 16,30 | 16,30 | class BaseStream():
KEY_PROPERTIES = []
URL_PATH = None
def __init__(self, client, config, stream, logger):
self.client = client
self.config = config
self.stream = stream
self.logger = logger
def load_data(self, bookmarks: Dict = None) -> Generator[List[Dict], None, No... | class BaseStream():
KEY_PROPERTIES = []
URL_PATH = None
def __init__(self, client, config, stream, logger):
self.client = client
self.config = config
self.stream = stream
self.logger = logger
def load_data(self, bookmarks: Dict = None) -> Generator[List[Dict], None, No... | if self.URL_PATH is None:
return
kwargs = dict(path=self.URL_PATH)
while True:
data = self.client.get(**kwargs)
results = data['_results']
yield results
pagination_next_url = data.get('_pagination', dict()).get('next')
if n... | if self.URL_PATH is None:
return
kwargs = dict(path=self.URL_PATH)
while True:
data = self.client.get(**kwargs)
results = data['_results']
yield results
pagination_next_url = data.get('_pagination', dict()).get('next')
if n... | 35 | 109 | 157 | 266 | from typing import Dict, Generator, List
class BaseStream():
KEY_PROPERTIES = []
URL_PATH = None
def __init__(self, client, config, stream, logger):
self.client = client
self.config = config
self.stream = stream
self.logger = logger
def load_data(self, bookmarks: Dic... | from typing import Dict, Generator, List
class BaseStream():
KEY_PROPERTIES = []
URL_PATH = None
def __init__(self, client, config, stream, logger):
self.client = client
self.config = config
self.stream = stream
self.logger = logger
def load_data(self, bookmarks: Dic... |
20,764 | /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_integrations/mage_integrations/sources/monday/client.py | 14,16 | 5,36 | base_url | Client | 16,18 | 16,18 | class Client(BaseClient):
"""
Authentication: https://developer.monday.com/api-reference/docs/authentication
"""
def __init__(self, config: Dict, logger):
super().__init__(config)
self.logger = logger
@property
def base_url(self):
FILL_FUNC_BODY def get_headers(self):
... | class Client(BaseClient):
"""
Authentication: https://developer.monday.com/api-reference/docs/authentication
"""
def __init__(self, config: Dict, logger):
super().__init__(config)
self.logger = logger
@property
def base_url(self):
FILL_FUNC_BODY def get_headers(self):
... | return 'https://api.monday.com/v2'
| return 'https://api.monday.com/v2'
| 2 | 225 | 19 | 244 | from mage_integrations.sources.http.client import Client as BaseClient
from typing import Dict
class Client(BaseClient):
"""
Authentication: https://developer.monday.com/api-reference/docs/authentication
"""
def __init__(self, config: Dict, logger):
super().__init__(config)
self.logge... | from mage_integrations.sources.http.client import Client as BaseClient
from typing import Dict
class Client(BaseClient):
"""
Authentication: https://developer.monday.com/api-reference/docs/authentication
"""
def __init__(self, config: Dict, logger):
super().__init__(config)
self.logge... |
20,765 | /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_integrations/mage_integrations/sources/paystack/client.py | 8,9 | 4,15 | get_headers | PaystackClient | 9,15 | 9,15 | class PaystackClient(Client):
def __init__(self, config, api_result_limit=100):
super().__init__(config, api_result_limit=api_result_limit)
def get_headers(self):
FILL_FUNC_BODY | class PaystackClient(Client):
def __init__(self, config, api_result_limit=100):
super().__init__(config, api_result_limit=api_result_limit)
def get_headers(self):
FILL_FUNC_BODY | headers = {}
if self.config.get('secret_key'):
headers['authorization'] = f"Bearer {self.config.get('secret_key')}"
return headers
| headers = {}
if self.config.get('secret_key'):
headers['authorization'] = f"Bearer {self.config.get('secret_key')}"
return headers
| 11 | 69 | 56 | 125 | from mage_integrations.sources.http.client import Client
class PaystackClient(Client):
def __init__(self, config, api_result_limit=100):
super().__init__(config, api_result_limit=api_result_limit)
def get_headers(self):
FILL_FUNC_BODY | from mage_integrations.sources.http.client import Client
class PaystackClient(Client):
def __init__(self, config, api_result_limit=100):
super().__init__(config, api_result_limit=api_result_limit)
def get_headers(self):
FILL_FUNC_BODY |
20,766 | /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_integrations/mage_integrations/sources/paystack/streams/customers.py | 17,18 | 4,19 | get_url | CustomersStream | 18,19 | 18,19 | class CustomersStream(BasePaystackStream):
TABLE = 'customers'
ENTITY = 'customer'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'createdAt'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['createdAt']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEYS = ['createdAt']
INCLUSION ... | class CustomersStream(BasePaystackStream):
TABLE = 'customers'
ENTITY = 'customer'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'createdAt'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['createdAt']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEYS = ['createdAt']
INCLUSION ... | return 'https://api.paystack.co/customer'
| return 'https://api.paystack.co/customer'
| 2 | 155 | 16 | 171 | from mage_integrations.sources.paystack.streams.base import BasePaystackStream
class CustomersStream(BasePaystackStream):
TABLE = 'customers'
ENTITY = 'customer'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'createdAt'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['createdAt']
SEL... | from mage_integrations.sources.paystack.streams.base import BasePaystackStream
class CustomersStream(BasePaystackStream):
TABLE = 'customers'
ENTITY = 'customer'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'createdAt'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['createdAt']
SEL... |
20,767 | /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_integrations/mage_integrations/sources/paystack/streams/transactions.py | 17,18 | 4,19 | get_url | TransactionsStream | 18,19 | 18,19 | class TransactionsStream(BasePaystackStream):
TABLE = 'transactions'
ENTITY = 'transaction'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'createdAt'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['createdAt']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEYS = ['createdAt']
I... | class TransactionsStream(BasePaystackStream):
TABLE = 'transactions'
ENTITY = 'transaction'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'createdAt'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['createdAt']
SELECTED_BY_DEFAULT = True
VALID_REPLICATION_KEYS = ['createdAt']
I... | return 'https://api.paystack.co/transaction'
| return 'https://api.paystack.co/transaction'
| 2 | 155 | 16 | 171 | from mage_integrations.sources.paystack.streams.base import BasePaystackStream
class TransactionsStream(BasePaystackStream):
TABLE = 'transactions'
ENTITY = 'transaction'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'createdAt'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['createdAt'... | from mage_integrations.sources.paystack.streams.base import BasePaystackStream
class TransactionsStream(BasePaystackStream):
TABLE = 'transactions'
ENTITY = 'transaction'
REPLICATION_METHOD = 'INCREMENTAL'
REPLICATION_KEY = 'createdAt'
KEY_PROPERTIES = ['id']
BOOKMARK_PROPERTIES = ['createdAt'... |
20,768 | /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_integrations/mage_integrations/sources/pipedrive/tap_pipedrive/streams/recents/users.py | 14,15 | 6,22 | process_row | RecentUsersStream | 15,22 | 15,22 | class RecentUsersStream(RecentsStream):
items = 'user'
schema = 'users'
key_properties = ['id', ]
# temporary disabled due current Pipedrive API limitations
# state_field = 'modified'
replication_method = 'FULL_TABLE'
def process_row(self, row):
FILL_FUNC_BODY | class RecentUsersStream(RecentsStream):
items = 'user'
schema = 'users'
key_properties = ['id', ]
# temporary disabled due current Pipedrive API limitations
# state_field = 'modified'
replication_method = 'FULL_TABLE'
def process_row(self, row):
FILL_FUNC_BODY | # NB> Temporary split here in response to unintended change made with this changelog
# - https://developers.pipedrive.com/changelog/post/improvements-to-permissionsets-api-and-users-api
# - This used to be a list, but turned into an object with this changelog entry's effective date.
if i... | # NB> Temporary split here in response to unintended change made with this changelog
# - https://developers.pipedrive.com/changelog/post/improvements-to-permissionsets-api-and-users-api
# - This used to be a list, but turned into an object with this changelog entry's effective date.
if i... | 44 | 93 | 128 | 221 | from mage_integrations.sources.pipedrive.tap_pipedrive.streams.recents import (
RecentsStream,
)
class RecentUsersStream(RecentsStream):
items = 'user'
schema = 'users'
key_properties = ['id', ]
# temporary disabled due current Pipedrive API limitations
# state_field = 'modified'
replicati... | from mage_integrations.sources.pipedrive.tap_pipedrive.streams.recents import (
RecentsStream,
)
class RecentUsersStream(RecentsStream):
items = 'user'
schema = 'users'
key_properties = ['id', ]
# temporary disabled due current Pipedrive API limitations
# state_field = 'modified'
replicati... |
20,770 | /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_integrations/mage_integrations/sources/postgresql/decoders.py | 137,138 | 123,150 | decode_buffer | Begin | 138,145 | 138,145 | class Begin(PgoutputMessage):
"""
https://pgpedia.info/x/xlogrecptr.html
https://www.postgresql.org/docs/14/datatype-pg-lsn.html
byte1 Byte1('B') Identifies the message as a begin message.
final_tx_lsn Int64 The final LSN of the transaction.
commit_tx_ts Int64 Commit timestamp of the transaction... | class Begin(PgoutputMessage):
"""
https://pgpedia.info/x/xlogrecptr.html
https://www.postgresql.org/docs/14/datatype-pg-lsn.html
byte1 Byte1('B') Identifies the message as a begin message.
final_tx_lsn Int64 The final LSN of the transaction.
commit_tx_ts Int64 Commit timestamp of the transaction... | if self.byte1 != 'B':
raise Exception('first byte in buffer does not match Begin message')
self.final_tx_lsn = self.read_int64()
self.commit_tx_ts = self.read_timestamp()
self.tx_xid = self.read_int64()
return self
| if self.byte1 != 'B':
raise Exception('first byte in buffer does not match Begin message')
self.final_tx_lsn = self.read_int64()
self.commit_tx_ts = self.read_timestamp()
self.tx_xid = self.read_int64()
return self
| 25 | 302 | 91 | 393 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... |
20,771 | /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_integrations/mage_integrations/sources/postgresql/decoders.py | 164,165 | 150,178 | decode_buffer | Commit | 165,173 | 165,173 | class Commit(PgoutputMessage):
"""
byte1: Byte1('C') Identifies the message as a commit message.
flags: Int8 Flags; currently unused (must be 0).
lsn_commit: Int64 The LSN of the commit.
final_tx_lsn: Int64 The end LSN of the transaction.
Int64 Commit timestamp of the transaction. The value is i... | class Commit(PgoutputMessage):
"""
byte1: Byte1('C') Identifies the message as a commit message.
flags: Int8 Flags; currently unused (must be 0).
lsn_commit: Int64 The LSN of the commit.
final_tx_lsn: Int64 The end LSN of the transaction.
Int64 Commit timestamp of the transaction. The value is i... | if self.byte1 != 'C':
raise Exception('first byte in buffer does not match Commit message')
self.flags = self.read_utf8()
self.lsn_commit = self.read_int64()
self.final_tx_lsn = self.read_int64()
self.commit_tx_ts = self.read_timestamp()
return self
| if self.byte1 != 'C':
raise Exception('first byte in buffer does not match Commit message')
self.flags = self.read_utf8()
self.lsn_commit = self.read_int64()
self.final_tx_lsn = self.read_int64()
self.commit_tx_ts = self.read_timestamp()
return self
| 28 | 293 | 105 | 398 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... |
20,772 | /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_integrations/mage_integrations/sources/postgresql/decoders.py | 335,336 | 321,350 | decode_buffer | Delete | 336,345 | 336,345 | class Delete(PgoutputMessage):
"""
Byte1('D') Identifies the message as a delete message.
Int32 ID of the relation corresponding to the ID in the relation message.
Byte1('K') Identifies the following TupleData submessage as a key. This field is present if the table in which the delet... | class Delete(PgoutputMessage):
"""
Byte1('D') Identifies the message as a delete message.
Int32 ID of the relation corresponding to the ID in the relation message.
Byte1('K') Identifies the following TupleData submessage as a key. This field is present if the table in which the delet... | if self.byte1 != 'D':
raise Exception(f"first byte in buffer does not match Delete message (expected 'D', got '{self.byte1}'")
self.relation_id = self.read_int32()
self.message_type = self.read_utf8()
if self.message_type not in ['K','O']:
raise Exception(f"messa... | if self.byte1 != 'D':
raise Exception(f"first byte in buffer does not match Delete message (expected 'D', got '{self.byte1}'")
self.relation_id = self.read_int32()
self.message_type = self.read_utf8()
if self.message_type not in ['K','O']:
raise Exception(f"messa... | 46 | 340 | 152 | 492 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... |
20,773 | /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_integrations/mage_integrations/sources/postgresql/decoders.py | 264,265 | 252,277 | decode_buffer | Insert | 265,272 | 265,272 | class Insert(PgoutputMessage):
"""
Byte1('I') Identifies the message as an insert message.
Int32 ID of the relation corresponding to the ID in the relation message.
Byte1('N') Identifies the following TupleData message as a new tuple.
TupleData TupleData message part representing the contents of ne... | class Insert(PgoutputMessage):
"""
Byte1('I') Identifies the message as an insert message.
Int32 ID of the relation corresponding to the ID in the relation message.
Byte1('N') Identifies the following TupleData message as a new tuple.
TupleData TupleData message part representing the contents of ne... | if self.byte1 != 'I':
raise Exception(f"first byte in buffer does not match Insert message (expected 'I', got '{self.byte1}'")
self.relation_id = self.read_int32()
self.new_tuple_byte = self.read_utf8()
self.new_tuple = self.read_tuple_data()
return self
| if self.byte1 != 'I':
raise Exception(f"first byte in buffer does not match Insert message (expected 'I', got '{self.byte1}'")
self.relation_id = self.read_int32()
self.new_tuple_byte = self.read_utf8()
self.new_tuple = self.read_tuple_data()
return self
| 29 | 238 | 107 | 345 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... |
20,774 | /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_integrations/mage_integrations/sources/postgresql/decoders.py | 74,75 | 45,123 | read_timestamp | PgoutputMessage | 75,78 | 75,78 | class PgoutputMessage(ABC):
def __init__(self, buffer: bytes):
self.buffer: io.BytesIO = io.BytesIO(buffer)
self.byte1: str = self.read_utf8(1)
self.decode_buffer()
@abstractmethod
def decode_buffer(self):
pass
@abstractmethod
def __repr__(self):
pass
d... | class PgoutputMessage(ABC):
def __init__(self, buffer: bytes):
self.buffer: io.BytesIO = io.BytesIO(buffer)
self.byte1: str = self.read_utf8(1)
self.decode_buffer()
@abstractmethod
def decode_buffer(self):
pass
@abstractmethod
def __repr__(self):
pass
d... | # 8 chars -> int64 -> timestamp
return convert_pg_ts(_ts_in_microseconds=self.read_int64())
| # 8 chars -> int64 -> timestamp
return convert_pg_ts(_ts_in_microseconds=self.read_int64())
| 9 | 881 | 43 | 924 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... |
20,775 | /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_integrations/mage_integrations/sources/postgresql/decoders.py | 215,216 | 189,241 | decode_buffer | Relation | 216,234 | 216,234 | class Relation(PgoutputMessage):
"""
Byte1('R') Identifies the message as a relation message.
Int32 ID of the relation.
String Namespace (empty string for pg_catalog).
String Relation name.
Int8 Replica identity setting for the relation (same as relreplident in pg_class).
# select relre... | class Relation(PgoutputMessage):
"""
Byte1('R') Identifies the message as a relation message.
Int32 ID of the relation.
String Namespace (empty string for pg_catalog).
String Relation name.
Int8 Replica identity setting for the relation (same as relreplident in pg_class).
# select relre... | if self.byte1 != 'R':
raise Exception('first byte in buffer does not match Relation message')
self.relation_id = self.read_int32()
self.namespace = self.read_string()
self.relation_name = self.read_string()
self.replica_identity_setting = self.read_utf8()
self... | if self.byte1 != 'R':
raise Exception('first byte in buffer does not match Relation message')
self.relation_id = self.read_int32()
self.namespace = self.read_string()
self.relation_name = self.read_string()
self.replica_identity_setting = self.read_utf8()
self... | 78 | 512 | 279 | 791 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... |
20,776 | /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_integrations/mage_integrations/sources/postgresql/decoders.py | 362,363 | 350,376 | decode_buffer | Truncate | 363,371 | 363,371 | class Truncate(PgoutputMessage):
"""
Byte1('T') Identifies the message as a truncate message.
Int32 Number of relations
Int8 Option bits for TRUNCATE: 1 for CASCADE, 2 for RESTART IDENTITY
Int32 ID of the relation corresponding to the ID in the relation message. T... | class Truncate(PgoutputMessage):
"""
Byte1('T') Identifies the message as a truncate message.
Int32 Number of relations
Int8 Option bits for TRUNCATE: 1 for CASCADE, 2 for RESTART IDENTITY
Int32 ID of the relation corresponding to the ID in the relation message. T... | if self.byte1 != 'T':
raise Exception(f"first byte in buffer does not match Truncate message (expected 'T', got '{self.byte1}'")
self.number_of_relations = self.read_int32()
self.option_bits = self.read_int8()
self.relation_ids = []
for relation in range(self.number_o... | if self.byte1 != 'T':
raise Exception(f"first byte in buffer does not match Truncate message (expected 'T', got '{self.byte1}'")
self.number_of_relations = self.read_int32()
self.option_bits = self.read_int8()
self.relation_ids = []
for relation in range(self.number_o... | 32 | 238 | 128 | 366 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... |
20,777 | /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_integrations/mage_integrations/sources/postgresql/decoders.py | 296,297 | 277,321 | decode_buffer | Update | 297,315 | 297,315 | class Update(PgoutputMessage):
"""
Byte1('U') Identifies the message as an update message.
Int32 ID of the relation corresponding to the ID in the relation message.
Byte1('K') Identifies the following TupleData submessage as a key. This field is optional and is only present if the up... | class Update(PgoutputMessage):
"""
Byte1('U') Identifies the message as an update message.
Int32 ID of the relation corresponding to the ID in the relation message.
Byte1('K') Identifies the following TupleData submessage as a key. This field is optional and is only present if the up... | self.optional_tuple_identifier = None
self.old_tuple = None
if self.byte1 != 'U':
raise Exception(f"first byte in buffer does not match Update message (expected 'U', got '{self.byte1}'")
self.relation_id = self.read_int32()
# TODO test update to PK, test update with R... | self.optional_tuple_identifier = None
self.old_tuple = None
if self.byte1 != 'U':
raise Exception(f"first byte in buffer does not match Update message (expected 'U', got '{self.byte1}'")
self.relation_id = self.read_int32()
# TODO test update to PK, test update with R... | 91 | 507 | 330 | 837 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... | from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
import io
from typing import Tuple, Union, Optional, List
# integer byte lengths
INT8 = 1
INT16 = 2
INT32 = 4
INT64 = 8
def convert_pg_ts(_ts_in_microseconds: int) -> datetime:
ts = datetime(... |
20,778 | /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_integrations/mage_integrations/sources/postmark/tap_postmark/tools.py | 36,37 | 1,88 | retrieve_bookmark_with_path | 55,64 | 37,64 | """Tools."""
# -*- coding: utf-8 -*-
from datetime import date, datetime, timedelta
from functools import reduce
from typing import Optional
def clear_currently_syncing(state: dict) -> dict:
"""Clear the currently syncing from the state.
Arguments:
state (dict) -- State file
Returns:
dic... | """Tools."""
# -*- coding: utf-8 -*-
from datetime import date, datetime, timedelta
from functools import reduce
from typing import Optional
def clear_currently_syncing(state: dict) -> dict:
"""Clear the currently syncing from the state.
Arguments:
state (dict) -- State file
Returns:
dic... | # If the path has a dot, then parse it as key and subkeys
if '.' in path:
return str(reduce(dict.get, path.split('.'), row)) # type: ignore
# Else if the path is just a key, parse it as a normal key
elif path:
return row[path]
return None
| """Bookmark exists in the row of data which is an dictionary.
The bookmark can either be a key such as row[key] but also a subkey such as
row[key][subkey]. In the streams definition file, the key can be saved as
a string, but [key][subkey] cannot. Therefore, in the streams file, if we
want to use a... | 46 | 709 | 97 | 806 | """Tools."""
# -*- coding: utf-8 -*-
from datetime import date, datetime, timedelta
from functools import reduce
from typing import Optional
def clear_currently_syncing(state: dict) -> dict:
"""Clear the currently syncing from the state.
Arguments:
state (dict) -- State file
Returns:
dic... | """Tools."""
# -*- coding: utf-8 -*-
from datetime import date, datetime, timedelta
from functools import reduce
from typing import Optional
def clear_currently_syncing(state: dict) -> dict:
"""Clear the currently syncing from the state.
Arguments:
state (dict) -- State file
Returns:
dic... | |
20,779 | /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_integrations/mage_integrations/sources/query.py | 14,15 | 1,24 | get_execution_date | 15,18 | 15,18 | from mage_integrations.utils.dictionary import extract
from typing import Dict
SYSTEM_QUERY_END_DATE = '_end_date'
SYSTEM_QUERY_EXECUTION_DATE = '_execution_date'
SYSTEM_QUERY_EXECUTION_PARTITION = '_execution_partition'
SYSTEM_QUERY_START_DATE = '_start_date'
def get_end_date(query: Dict) -> Dict:
return query.... | from mage_integrations.utils.dictionary import extract
from typing import Dict
SYSTEM_QUERY_END_DATE = '_end_date'
SYSTEM_QUERY_EXECUTION_DATE = '_execution_date'
SYSTEM_QUERY_EXECUTION_PARTITION = '_execution_partition'
SYSTEM_QUERY_START_DATE = '_start_date'
def get_end_date(query: Dict) -> Dict:
return query.... | return query.get(SYSTEM_QUERY_EXECUTION_DATE)
| return query.get(SYSTEM_QUERY_EXECUTION_DATE)
| 2 | 235 | 25 | 260 | from mage_integrations.utils.dictionary import extract
from typing import Dict
SYSTEM_QUERY_END_DATE = '_end_date'
SYSTEM_QUERY_EXECUTION_DATE = '_execution_date'
SYSTEM_QUERY_EXECUTION_PARTITION = '_execution_partition'
SYSTEM_QUERY_START_DATE = '_start_date'
def get_end_date(query: Dict) -> Dict:
return query.... | from mage_integrations.utils.dictionary import extract
from typing import Dict
SYSTEM_QUERY_END_DATE = '_end_date'
SYSTEM_QUERY_EXECUTION_DATE = '_execution_date'
SYSTEM_QUERY_EXECUTION_PARTITION = '_execution_partition'
SYSTEM_QUERY_START_DATE = '_start_date'
def get_end_date(query: Dict) -> Dict:
return query.... | |
20,780 | /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_integrations/mage_integrations/sources/redshift/utils.py | 16,17 | 1,27 | column_type_mapping | 17,27 | 17,27 | from mage_integrations.sources.constants import (
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NUMBER,
COLUMN_TYPE_OBJECT,
)
from mage_integrations.sources.redshift.constants import (
DATA_TYPE_BOOLEAN,
DATA_TYPE_BIGINT,
DATA_TYPE_DOUBLE_PRECISION,
DATA_TYPE_TEXT,
DATA_TYPE_... | from mage_integrations.sources.constants import (
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NUMBER,
COLUMN_TYPE_OBJECT,
)
from mage_integrations.sources.redshift.constants import (
DATA_TYPE_BOOLEAN,
DATA_TYPE_BIGINT,
DATA_TYPE_DOUBLE_PRECISION,
DATA_TYPE_TEXT,
DATA_TYPE_... | if COLUMN_TYPE_BOOLEAN == column_type:
return DATA_TYPE_BOOLEAN
elif COLUMN_TYPE_INTEGER == column_type:
return DATA_TYPE_BIGINT
elif COLUMN_TYPE_NUMBER == column_type:
return DATA_TYPE_DOUBLE_PRECISION
elif COLUMN_TYPE_OBJECT == column_type:
return DATA_TYPE_TEXT
re... | if COLUMN_TYPE_BOOLEAN == column_type:
return DATA_TYPE_BOOLEAN
elif COLUMN_TYPE_INTEGER == column_type:
return DATA_TYPE_BIGINT
elif COLUMN_TYPE_NUMBER == column_type:
return DATA_TYPE_DOUBLE_PRECISION
elif COLUMN_TYPE_OBJECT == column_type:
return DATA_TYPE_TEXT
re... | 26 | 178 | 136 | 314 | from mage_integrations.sources.constants import (
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NUMBER,
COLUMN_TYPE_OBJECT,
)
from mage_integrations.sources.redshift.constants import (
DATA_TYPE_BOOLEAN,
DATA_TYPE_BIGINT,
DATA_TYPE_DOUBLE_PRECISION,
DATA_TYPE_TEXT,
DATA_TYPE_... | from mage_integrations.sources.constants import (
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NUMBER,
COLUMN_TYPE_OBJECT,
)
from mage_integrations.sources.redshift.constants import (
DATA_TYPE_BOOLEAN,
DATA_TYPE_BIGINT,
DATA_TYPE_DOUBLE_PRECISION,
DATA_TYPE_TEXT,
DATA_TYPE_... | |
20,781 | /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_integrations/mage_integrations/sources/sftp/tap_sftp/singer_encodings/compression.py | 5,6 | 1,21 | infer | 8,21 | 6,21 | import gzip
import zipfile
def infer(iterable, file_name):
FILL_FUNC_BODY | import gzip
import zipfile
def infer(iterable, file_name):
"""Uses the incoming file_name and checks the end of the string
for supported compression types"""
FILL_FUNC_BODY | if not file_name:
raise Exception("Need file name")
if file_name.endswith('.tar.gz'):
raise NotImplementedError("tar.gz not supported")
elif file_name.endswith('.gz'):
yield gzip.GzipFile(fileobj=iterable)
elif file_name.endswith('.zip'):
with zipfile.ZipFile(iterable) a... | """Uses the incoming file_name and checks the end of the string
for supported compression types"""
if not file_name:
raise Exception("Need file name")
if file_name.endswith('.tar.gz'):
raise NotImplementedError("tar.gz not supported")
elif file_name.endswith('.gz'):
yield gz... | 32 | 55 | 151 | 206 | import gzip
import zipfile
def infer(iterable, file_name):
FILL_FUNC_BODY | import gzip
import zipfile
def infer(iterable, file_name):
"""Uses the incoming file_name and checks the end of the string
for supported compression types"""
FILL_FUNC_BODY | |
20,782 | /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_integrations/mage_integrations/sources/sftp/tap_sftp/singer_encodings/json_schema.py | 33,34 | 1,205 | sample_file | 34,79 | 34,79 |
from mage_integrations.sources.sftp.tap_sftp.aws_ssm import AWS_SSM
from . import csv_handler
SDC_SOURCE_FILE_COLUMN = "_sdc_source_file"
SDC_SOURCE_LINENO_COLUMN = "_sdc_source_lineno"
SDC_SOURCE_LAST_MODIFIED = "_sdc_source_last_modified"
def get_schema_for_table(conn, table_spec, config):
files = conn.get_f... |
from mage_integrations.sources.sftp.tap_sftp.aws_ssm import AWS_SSM
from . import csv_handler
SDC_SOURCE_FILE_COLUMN = "_sdc_source_file"
SDC_SOURCE_LINENO_COLUMN = "_sdc_source_lineno"
SDC_SOURCE_LAST_MODIFIED = "_sdc_source_last_modified"
def get_schema_for_table(conn, table_spec, config):
files = conn.get_f... | samples = []
decryption_configs = config.get('decryption_configs')
if decryption_configs:
decryption_configs['key'] = AWS_SSM.get_decryption_key(
decryption_configs.get('SSM_key_name'))
file_handle, decrypted_name = conn.get_file_handle(f,
... | samples = []
decryption_configs = config.get('decryption_configs')
if decryption_configs:
decryption_configs['key'] = AWS_SSM.get_decryption_key(
decryption_configs.get('SSM_key_name'))
file_handle, decrypted_name = conn.get_file_handle(f,
... | 130 | 1,380 | 577 | 1,957 |
from mage_integrations.sources.sftp.tap_sftp.aws_ssm import AWS_SSM
from . import csv_handler
SDC_SOURCE_FILE_COLUMN = "_sdc_source_file"
SDC_SOURCE_LINENO_COLUMN = "_sdc_source_lineno"
SDC_SOURCE_LAST_MODIFIED = "_sdc_source_last_modified"
def get_schema_for_table(conn, table_spec, config):
files = conn.get_f... |
from mage_integrations.sources.sftp.tap_sftp.aws_ssm import AWS_SSM
from . import csv_handler
SDC_SOURCE_FILE_COLUMN = "_sdc_source_file"
SDC_SOURCE_LINENO_COLUMN = "_sdc_source_lineno"
SDC_SOURCE_LAST_MODIFIED = "_sdc_source_last_modified"
def get_schema_for_table(conn, table_spec, config):
files = conn.get_f... | |
20,783 | /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_integrations/mage_integrations/sources/sftp/tap_sftp/stats.py | 21,22 | 1,45 | add_file_data | 22,38 | 22,38 | STATS = {}
# example = {
# '<table_name>': {
# 'search_prefix': 'folder1',
# 'search_pattern': 'file.*.csv'
# 'files': {
# '<filepath>': {
# 'row_count': 100,
# 'last_modified': '10-03-2018T5:00:00'
# },
# 'folder1/file_1.c... | STATS = {}
# example = {
# '<table_name>': {
# 'search_prefix': 'folder1',
# 'search_pattern': 'file.*.csv'
# 'files': {
# '<filepath>': {
# 'row_count': 100,
# 'last_modified': '10-03-2018T5:00:00'
# },
# 'folder1/file_1.c... | table_name = table_spec['table_name']
global STATS
if STATS.get(table_name):
STATS[table_name]['files'][filepath] = {
'last_modified': last_modified,
'row_count': row_count
}
else:
initialize_table_stats(table_spec)
STATS[table_name]['files'][file... | table_name = table_spec['table_name']
global STATS
if STATS.get(table_name):
STATS[table_name]['files'][filepath] = {
'last_modified': last_modified,
'row_count': row_count
}
else:
initialize_table_stats(table_spec)
STATS[table_name]['files'][file... | 25 | 289 | 154 | 443 | STATS = {}
# example = {
# '<table_name>': {
# 'search_prefix': 'folder1',
# 'search_pattern': 'file.*.csv'
# 'files': {
# '<filepath>': {
# 'row_count': 100,
# 'last_modified': '10-03-2018T5:00:00'
# },
# 'folder1/file_1.c... | STATS = {}
# example = {
# '<table_name>': {
# 'search_prefix': 'folder1',
# 'search_pattern': 'file.*.csv'
# 'files': {
# '<filepath>': {
# 'row_count': 100,
# 'last_modified': '10-03-2018T5:00:00'
# },
# 'folder1/file_1.c... | |
20,784 | /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_integrations/mage_integrations/sources/sql/utils.py | 15,24 | 1,78 | build_comparison_statement | 24,42 | 24,42 | from typing import Any, Callable, Dict, Union
from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NULL,
COLUMN_TYPE_NUMBER,
COLUMN_TYPE_OBJECT,
)
from mage_integrations.sources.sql.constants import PredicateOperator
fro... | from typing import Any, Callable, Dict, Union
from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NULL,
COLUMN_TYPE_NUMBER,
COLUMN_TYPE_OBJECT,
)
from mage_integrations.sources.sql.constants import PredicateOperator
fro... | column_properties = properties.get(col)
if not column_properties:
raise Exception(f'There are no properties in the schema for column {col}.')
column_type = find(lambda x: COLUMN_TYPE_NULL != x, column_properties['type'])
column_format = column_properties.get('format')
col_type = column_type... | column_properties = properties.get(col)
if not column_properties:
raise Exception(f'There are no properties in the schema for column {col}.')
column_type = find(lambda x: COLUMN_TYPE_NULL != x, column_properties['type'])
column_format = column_properties.get('format')
col_type = column_type... | 63 | 590 | 235 | 825 | from typing import Any, Callable, Dict, Union
from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NULL,
COLUMN_TYPE_NUMBER,
COLUMN_TYPE_OBJECT,
)
from mage_integrations.sources.sql.constants import PredicateOperator
fro... | from typing import Any, Callable, Dict, Union
from mage_integrations.sources.constants import (
COLUMN_FORMAT_DATETIME,
COLUMN_TYPE_BOOLEAN,
COLUMN_TYPE_INTEGER,
COLUMN_TYPE_NULL,
COLUMN_TYPE_NUMBER,
COLUMN_TYPE_OBJECT,
)
from mage_integrations.sources.sql.constants import PredicateOperator
fro... | |
20,785 | /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_integrations/mage_integrations/utils/array.py | 4,5 | 1,41 | batch | 5,10 | 5,10 | import random
def batch(iterable, n=1):
FILL_FUNC_BODYdef difference(li1, li2):
li1_lookup = set(li1)
li2_lookup = set(li2)
return [i for i in li1 + li2 if i not in li1_lookup or i not in li2_lookup]
def flatten(arr):
return [item for sublist in arr for item in sublist]
def find(condition, arr, ma... | import random
def batch(iterable, n=1):
FILL_FUNC_BODYdef difference(li1, li2):
li1_lookup = set(li1)
li2_lookup = set(li2)
return [i for i in li1 + li2 if i not in li1_lookup or i not in li2_lookup]
def flatten(arr):
return [item for sublist in arr for item in sublist]
def find(condition, arr, ma... | l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)]
| l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)]
| 14 | 281 | 48 | 329 | import random
def batch(iterable, n=1):
FILL_FUNC_BODYdef difference(li1, li2):
li1_lookup = set(li1)
li2_lookup = set(li2)
return [i for i in li1 + li2 if i not in li1_lookup or i not in li2_lookup]
def flatten(arr):
return [item for sublist in arr for item in sublist]
def find(condition, arr, ma... | import random
def batch(iterable, n=1):
FILL_FUNC_BODYdef difference(li1, li2):
li1_lookup = set(li1)
li2_lookup = set(li2)
return [i for i in li1 + li2 if i not in li1_lookup or i not in li2_lookup]
def flatten(arr):
return [item for sublist in arr for item in sublist]
def find(condition, arr, ma... | |
20,786 | /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_integrations/mage_integrations/utils/dates.py | 4,5 | 1,36 | date_intervals | 5,36 | 5,36 | import datetime
import math
def date_intervals(start_date, end_date, timedelta):
FILL_FUNC_BODY | import datetime
import math
def date_intervals(start_date, end_date, timedelta):
FILL_FUNC_BODY | tzinfos = list(filter(lambda x: x, [end_date.tzinfo, start_date.tzinfo]))
if len(tzinfos) == 1:
tzinfo = tzinfos[0]
if not end_date.tzinfo:
end_date = end_date.replace(tzinfo=tzinfo)
if not start_date.tzinfo:
start_date = start_date.replace(tzinfo=tzinfo)
tot... | tzinfos = list(filter(lambda x: x, [end_date.tzinfo, start_date.tzinfo]))
if len(tzinfos) == 1:
tzinfo = tzinfos[0]
if not end_date.tzinfo:
end_date = end_date.replace(tzinfo=tzinfo)
if not start_date.tzinfo:
start_date = start_date.replace(tzinfo=tzinfo)
tot... | 88 | 36 | 398 | 434 | import datetime
import math
def date_intervals(start_date, end_date, timedelta):
FILL_FUNC_BODY | import datetime
import math
def date_intervals(start_date, end_date, timedelta):
FILL_FUNC_BODY | |
20,787 | /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_integrations/mage_integrations/utils/dictionary.py | 79,80 | 1,109 | group_by | 80,89 | 80,89 | import math
import re
from functools import reduce
def dig(obj_arg, arr_or_string):
if type(arr_or_string) is str:
arr_or_string = arr_or_string.split('.')
arr = list(map(str.strip, arr_or_string))
def _build(obj, key):
tup = re.split(r'\[(\d+)\]$', key)
if len(tup) >= 2:
... | import math
import re
from functools import reduce
def dig(obj_arg, arr_or_string):
if type(arr_or_string) is str:
arr_or_string = arr_or_string.split('.')
arr = list(map(str.strip, arr_or_string))
def _build(obj, key):
tup = re.split(r'\[(\d+)\]$', key)
if len(tup) >= 2:
... | def _build(obj, item):
val = func(item)
if not obj.get(val):
obj[val] = []
obj[val].append(item)
return obj
return reduce(_build, arr, {})
| def _build(obj, item):
val = func(item)
if not obj.get(val):
obj[val] = []
obj[val].append(item)
return obj
return reduce(_build, arr, {})
| 19 | 769 | 72 | 841 | import math
import re
from functools import reduce
def dig(obj_arg, arr_or_string):
if type(arr_or_string) is str:
arr_or_string = arr_or_string.split('.')
arr = list(map(str.strip, arr_or_string))
def _build(obj, key):
tup = re.split(r'\[(\d+)\]$', key)
if len(tup) >= 2:
... | import math
import re
from functools import reduce
def dig(obj_arg, arr_or_string):
if type(arr_or_string) is str:
arr_or_string = arr_or_string.split('.')
arr = list(map(str.strip, arr_or_string))
def _build(obj, key):
tup = re.split(r'\[(\d+)\]$', key)
if len(tup) >= 2:
... | |
20,788 | /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_integrations/mage_integrations/utils/files.py | 4,5 | 1,6 | get_abs_path | 5,6 | 5,6 | import os
def get_abs_path(path):
FILL_FUNC_BODY | import os
def get_abs_path(path):
FILL_FUNC_BODY | return os.path.join(os.path.dirname(os.path.realpath(__file__)), path)
| return os.path.join(os.path.dirname(os.path.realpath(__file__)), path)
| 3 | 25 | 29 | 54 | import os
def get_abs_path(path):
FILL_FUNC_BODY | import os
def get_abs_path(path):
FILL_FUNC_BODY | |
20,789 | /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_integrations/mage_integrations/utils/parsers.py | 5,6 | 1,17 | encode_complex | 6,17 | 6,17 | import uuid
from datetime import datetime, timedelta
def encode_complex(obj):
FILL_FUNC_BODY | import uuid
from datetime import datetime, timedelta
def encode_complex(obj):
FILL_FUNC_BODY | if hasattr(obj, 'isoformat') and 'method' in type(obj.isoformat).__name__:
return obj.isoformat()
elif isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, timedelta):
# Used to encode the TIME type from the source DB
return str(obj)
elif type(obj) is uu... | if hasattr(obj, 'isoformat') and 'method' in type(obj.isoformat).__name__:
return obj.isoformat()
elif isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, timedelta):
# Used to encode the TIME type from the source DB
return str(obj)
elif type(obj) is uu... | 38 | 33 | 123 | 156 | import uuid
from datetime import datetime, timedelta
def encode_complex(obj):
FILL_FUNC_BODY | import uuid
from datetime import datetime, timedelta
def encode_complex(obj):
FILL_FUNC_BODY | |
20,790 | /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_integrations/mage_integrations/utils/schema_helpers.py | 29,30 | 1,38 | filter_columns | 30,38 | 30,38 | from mage_integrations.sources.constants import (
INCLUSION_AUTOMATIC,
INCLUSION_UNSUPPORTED,
METADATA_KEY_INCLUSION,
METADATA_KEY_SELECTED,
)
from typing import Dict, List
def extract_selected_columns(metadata_array: List[dict]) -> List[str]:
columns = []
for d in metadata_array:
bre... | from mage_integrations.sources.constants import (
INCLUSION_AUTOMATIC,
INCLUSION_UNSUPPORTED,
METADATA_KEY_INCLUSION,
METADATA_KEY_SELECTED,
)
from typing import Dict, List
def extract_selected_columns(metadata_array: List[dict]) -> List[str]:
columns = []
for d in metadata_array:
bre... | filtered_columns = []
for col in columns:
if col not in properties:
continue
types = properties[col]['type']
if any(t in column_types for t in types):
filtered_columns.append(col)
return filtered_columns
| filtered_columns = []
for col in columns:
if col not in properties:
continue
types = properties[col]['type']
if any(t in column_types for t in types):
filtered_columns.append(col)
return filtered_columns
| 27 | 262 | 75 | 337 | from mage_integrations.sources.constants import (
INCLUSION_AUTOMATIC,
INCLUSION_UNSUPPORTED,
METADATA_KEY_INCLUSION,
METADATA_KEY_SELECTED,
)
from typing import Dict, List
def extract_selected_columns(metadata_array: List[dict]) -> List[str]:
columns = []
for d in metadata_array:
bre... | from mage_integrations.sources.constants import (
INCLUSION_AUTOMATIC,
INCLUSION_UNSUPPORTED,
METADATA_KEY_INCLUSION,
METADATA_KEY_SELECTED,
)
from typing import Dict, List
def extract_selected_columns(metadata_array: List[dict]) -> List[str]:
columns = []
for d in metadata_array:
bre... | |
20,791 | /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_integrations/mage_integrations/utils/strings.py | 1,2 | 1,7 | is_number | 2,7 | 2,7 | def is_number(s):
FILL_FUNC_BODY | def is_number(s):
FILL_FUNC_BODY | try:
float(s)
return True
except ValueError:
return False
| try:
float(s)
return True
except ValueError:
return False
| 8 | 18 | 29 | 47 | def is_number(s):
FILL_FUNC_BODY | def is_number(s):
FILL_FUNC_BODY | |
20,792 | /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_integrations/setup.py | 4,5 | 1,38 | readme | 5,10 | 5,10 | import setuptools
def readme():
FILL_FUNC_BODYrequirements = []
with open('requirements.txt') as f:
for line in f.read().splitlines():
if line.startswith('# extras'):
break
requirements.append(line)
setuptools.setup(
name='mage-integrations',
version='0.0.0',
author='Mage'... | import setuptools
def readme():
FILL_FUNC_BODYrequirements = []
with open('requirements.txt') as f:
for line in f.read().splitlines():
if line.startswith('# extras'):
break
requirements.append(line)
setuptools.setup(
name='mage-integrations',
version='0.0.0',
author='Mage'... | with open('README.md', encoding='utf8') as f:
README = f.read()
return README
| with open('README.md', encoding='utf8') as f:
README = f.read()
return README
| 10 | 286 | 40 | 326 | import setuptools
def readme():
FILL_FUNC_BODYrequirements = []
with open('requirements.txt') as f:
for line in f.read().splitlines():
if line.startswith('# extras'):
break
requirements.append(line)
setuptools.setup(
name='mage-integrations',
version='0.0.0',
author='Mage'... | import setuptools
def readme():
FILL_FUNC_BODYrequirements = []
with open('requirements.txt') as f:
for line in f.read().splitlines():
if line.startswith('# extras'):
break
requirements.append(line)
setuptools.setup(
name='mage-integrations',
version='0.0.0',
author='Mage'... | |
20,797 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/install_hooks.py | 4,5 | 1,18 | symlink_develop | 5,18 | 5,18 | import os
import sys
def symlink_develop(config):
FILL_FUNC_BODY | import os
import sys
def symlink_develop(config):
FILL_FUNC_BODY | if 'develop' in sys.argv:
share_path = os.path.join(sys.prefix, 'share')
if not os.path.exists(share_path):
os.makedirs(share_path)
os.symlink(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'shared-data'
),
... | if 'develop' in sys.argv:
share_path = os.path.join(sys.prefix, 'share')
if not os.path.exists(share_path):
os.makedirs(share_path)
os.symlink(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'shared-data'
),
... | 21 | 26 | 139 | 165 | import os
import sys
def symlink_develop(config):
FILL_FUNC_BODY | import os
import sys
def symlink_develop(config):
FILL_FUNC_BODY | |
20,798 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/__main__.py | 5,6 | 1,11 | main | 6,9 | 6,9 | import sys
from mailpile.app import Main
def main():
FILL_FUNC_BODYif __name__ == "__main__":
main()
| import sys
from mailpile.app import Main
def main():
FILL_FUNC_BODYif __name__ == "__main__":
main()
| Main(sys.argv[1:])
| Main(sys.argv[1:])
| 1 | 43 | 17 | 60 | import sys
from mailpile.app import Main
def main():
FILL_FUNC_BODYif __name__ == "__main__":
main()
| import sys
from mailpile.app import Main
def main():
FILL_FUNC_BODYif __name__ == "__main__":
main()
| |
20,799 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/config/paths.py | 31,32 | 1,91 | DEFAULT_WORKDIR | 32,51 | 32,51 | import os
import sys
import mailpile.platforms
try:
from appdirs import AppDirs
except ImportError:
AppDirs = None
def _ensure_exists(path, mode=0o700):
if not os.path.exists(path):
head, tail = os.path.split(path)
_ensure_exists(head)
os.mkdir(path, mode)
return path
def L... | import os
import sys
import mailpile.platforms
try:
from appdirs import AppDirs
except ImportError:
AppDirs = None
def _ensure_exists(path, mode=0o700):
if not os.path.exists(path):
head, tail = os.path.split(path)
_ensure_exists(head)
os.mkdir(path, mode)
return path
def L... | # The Mailpile environment variable trumps everything
workdir = os.getenv('MAILPILE_HOME')
if workdir:
return _ensure_exists(workdir)
# Which profile?
profile = os.getenv('MAILPILE_PROFILE', 'default')
# Check if we have a legacy setup we need to preserve
workdir = LEGACY_DEFAULT_W... | # The Mailpile environment variable trumps everything
workdir = os.getenv('MAILPILE_HOME')
if workdir:
return _ensure_exists(workdir)
# Which profile?
profile = os.getenv('MAILPILE_PROFILE', 'default')
# Check if we have a legacy setup we need to preserve
workdir = LEGACY_DEFAULT_W... | 60 | 775 | 239 | 1,014 | import os
import sys
import mailpile.platforms
try:
from appdirs import AppDirs
except ImportError:
AppDirs = None
def _ensure_exists(path, mode=0o700):
if not os.path.exists(path):
head, tail = os.path.split(path)
_ensure_exists(head)
os.mkdir(path, mode)
return path
def L... | import os
import sys
import mailpile.platforms
try:
from appdirs import AppDirs
except ImportError:
AppDirs = None
def _ensure_exists(path, mode=0o700):
if not os.path.exists(path):
head, tail = os.path.split(path)
_ensure_exists(head)
os.mkdir(path, mode)
return path
def L... | |
20,801 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/crypto/autocrypt.py | 457,458 | 426,469 | set_recommendation | AutocryptRecommendation | 458,466 | 458,466 | class AutocryptRecommendation(object):
DISABLE = "disable"
DISCOURAGE = "discourage"
ENABLE = "enable"
ENCRYPT = "encrypt"
ORDERED_POLICIES = (DISABLE, DISCOURAGE, ENABLE, ENCRYPT)
def __init__(self, policy, key_sig=None):
self.key_sig = self._policy = None
self.set_r... | class AutocryptRecommendation(object):
DISABLE = "disable"
DISCOURAGE = "discourage"
ENABLE = "enable"
ENCRYPT = "encrypt"
ORDERED_POLICIES = (DISABLE, DISCOURAGE, ENABLE, ENCRYPT)
def __init__(self, policy, key_sig=None):
self.key_sig = self._policy = None
self.set_r... | if policy not in self.ORDERED_POLICIES:
raise ValueError('Invalid Autocrypt policy: %s' % policy)
if policy != self.DISABLE and key_sig is None and self.key_sig is None:
raise ValueError('Policy %s requires a key' % policy)
self._policy = policy
if key_sig is not ... | if policy not in self.ORDERED_POLICIES:
raise ValueError('Invalid Autocrypt policy: %s' % policy)
if policy != self.DISABLE and key_sig is None and self.key_sig is None:
raise ValueError('Policy %s requires a key' % policy)
self._policy = policy
if key_sig is not ... | 43 | 375 | 112 | 487 | from __future__ import print_function
# Copyright (C) 2018 Jack Dodds & Mailpile ehf.
# This code is part of Mailpile and is hereby released under the
# Gnu Affero Public Licence v.3 - see ../../COPYING and ../../AGPLv3.txt.
#
"""
This file contains low-level Autocrypt code: constants, parsing, etc.
The higher level a... | from __future__ import print_function
# Copyright (C) 2018 Jack Dodds & Mailpile ehf.
# This code is part of Mailpile and is hereby released under the
# Gnu Affero Public Licence v.3 - see ../../COPYING and ../../AGPLv3.txt.
#
"""
This file contains low-level Autocrypt code: constants, parsing, etc.
The higher level a... |
20,802 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/index/search.py | 51,52 | 37,65 | set_results | CachedSearchResultSet | 52,58 | 52,58 | class CachedSearchResultSet(SearchResultSet):
"""
Cached search result.
"""
def __init__(self, idx, terms):
global SEARCH_RESULT_CACHE
self.terms = set(terms)
self._index = idx
self._results = SEARCH_RESULT_CACHE.get(self._skey(), {})
self._results['_last_used'] =... | class CachedSearchResultSet(SearchResultSet):
"""
Cached search result.
"""
def __init__(self, idx, terms):
global SEARCH_RESULT_CACHE
self.terms = set(terms)
self._index = idx
self._results = SEARCH_RESULT_CACHE.get(self._skey(), {})
self._results['_last_used'] =... | global SEARCH_RESULT_CACHE
SearchResultSet.set_results(self, *args)
SEARCH_RESULT_CACHE[self._skey()] = self._results
self._results['_last_used'] = time.time()
return self
| global SEARCH_RESULT_CACHE
SearchResultSet.set_results(self, *args)
SEARCH_RESULT_CACHE[self._skey()] = self._results
self._results['_last_used'] = time.time()
return self
| 12 | 211 | 74 | 285 | from __future__ import print_function
import time
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
class SearchResultSet:
"""
Search results!
"""
def __init__(self, idx, terms, results, exclude):
self.terms = set(terms)
self._index = idx
self.set... | from __future__ import print_function
import time
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
class SearchResultSet:
"""
Search results!
"""
def __init__(self, idx, terms, results, exclude):
self.terms = set(terms)
self._index = idx
self.set... |
20,803 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/index/search.py | 17,18 | 8,34 | set_results | SearchResultSet | 18,24 | 18,24 | class SearchResultSet:
"""
Search results!
"""
def __init__(self, idx, terms, results, exclude):
self.terms = set(terms)
self._index = idx
self.set_results(results, exclude)
def set_results(self, results, exclude):
FILL_FUNC_BODY def __len__(self):
return len(self... | class SearchResultSet:
"""
Search results!
"""
def __init__(self, idx, terms, results, exclude):
self.terms = set(terms)
self._index = idx
self.set_results(results, exclude)
def set_results(self, results, exclude):
FILL_FUNC_BODY def __len__(self):
return len(self... | self._results = {
'raw': set(results),
'excluded': set(exclude) & set(results)
}
return self
| self._results = {
'raw': set(results),
'excluded': set(exclude) & set(results)
}
return self
| 12 | 162 | 46 | 208 | from __future__ import print_function
import time
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
class SearchResultSet:
"""
Search results!
"""
def __init__(self, idx, terms, results, exclude):
self.terms = set(terms)
self._index = idx
self.set... | from __future__ import print_function
import time
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
class SearchResultSet:
"""
Search results!
"""
def __init__(self, idx, terms, results, exclude):
self.terms = set(terms)
self._index = idx
self.set... |
20,804 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/mail_source/imap_starttls.py | 19,20 | 10,33 | readline | IMAP4 | 21,26 | 20,26 | class IMAP4(imaplib.IMAP4, object):
# This is a bugfix for imaplib's default readline method. It is
# identical except it raises abort() instead of error() as the
# internal state will certainly be broken.
#
# Note: This would be the function to change if we want to do away
# with the lin... | class IMAP4(imaplib.IMAP4, object):
# This is a bugfix for imaplib's default readline method. It is
# identical except it raises abort() instead of error() as the
# internal state will certainly be broken.
#
# Note: This would be the function to change if we want to do away
# with the lin... | line = self.file.readline(imaplib._MAXLINE + 1)
if len(line) > imaplib._MAXLINE:
raise self.abort("got more than %d bytes" % imaplib._MAXLINE)
return line
| """Read line from remote."""
line = self.file.readline(imaplib._MAXLINE + 1)
if len(line) > imaplib._MAXLINE:
raise self.abort("got more than %d bytes" % imaplib._MAXLINE)
return line
| 19 | 229 | 68 | 297 | import imaplib
import ssl
Commands = {
'STARTTLS': ('NONAUTH')
}
imaplib.Commands.update(Commands)
class IMAP4(imaplib.IMAP4, object):
# This is a bugfix for imaplib's default readline method. It is
# identical except it raises abort() instead of error() as the
# internal state will certainly be bro... | import imaplib
import ssl
Commands = {
'STARTTLS': ('NONAUTH')
}
imaplib.Commands.update(Commands)
class IMAP4(imaplib.IMAP4, object):
# This is a bugfix for imaplib's default readline method. It is
# identical except it raises abort() instead of error() as the
# internal state will certainly be bro... |
20,805 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/plugins/autotag_sb.py | 14,15 | 1,43 | _classifier | 15,20 | 15,20 | # Add SpamBayes as an option to the autotagger. We like SpamBayes.
#
# We feed the classifier the same terms as go into the search engine,
# which should allow us to actually introspect a bit into the behavior
# of the classifier.
from mailpile.spambayes import Classifier
import mailpile.plugins.autotag
from mailpile... | # Add SpamBayes as an option to the autotagger. We like SpamBayes.
#
# We feed the classifier the same terms as go into the search engine,
# which should allow us to actually introspect a bit into the behavior
# of the classifier.
from mailpile.spambayes import Classifier
import mailpile.plugins.autotag
from mailpile... | if not hasattr(autotagger, 'spambayes'):
autotagger.spambayes = Classifier()
return autotagger.spambayes
| if not hasattr(autotagger, 'spambayes'):
autotagger.spambayes = Classifier()
return autotagger.spambayes
| 9 | 422 | 50 | 472 | # Add SpamBayes as an option to the autotagger. We like SpamBayes.
#
# We feed the classifier the same terms as go into the search engine,
# which should allow us to actually introspect a bit into the behavior
# of the classifier.
from mailpile.spambayes import Classifier
import mailpile.plugins.autotag
from mailpile... | # Add SpamBayes as an option to the autotagger. We like SpamBayes.
#
# We feed the classifier the same terms as go into the search engine,
# which should allow us to actually introspect a bit into the behavior
# of the classifier.
from mailpile.spambayes import Classifier
import mailpile.plugins.autotag
from mailpile... | |
20,806 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/plugins/autotag_sb.py | 21,22 | 20,33 | should_tag | SpamBayesTagger | 22,33 | 22,33 | class SpamBayesTagger(mailpile.plugins.autotag.Trainer):
def should_tag(self, atagger, at_config, msg, keywords):
FILL_FUNC_BODY | class SpamBayesTagger(mailpile.plugins.autotag.Trainer):
def should_tag(self, atagger, at_config, msg, keywords):
FILL_FUNC_BODY | score, evidence = _classifier(atagger).chi2_spamprob(keywords,
evidence=True)
if score >= 1 - at_config.threshold:
want = True
elif score > at_config.threshold:
want = None
else:
want = False... | score, evidence = _classifier(atagger).chi2_spamprob(keywords,
evidence=True)
if score >= 1 - at_config.threshold:
want = True
elif score > at_config.threshold:
want = None
else:
want = False... | 28 | 53 | 96 | 149 | # Add SpamBayes as an option to the autotagger. We like SpamBayes.
#
# We feed the classifier the same terms as go into the search engine,
# which should allow us to actually introspect a bit into the behavior
# of the classifier.
from mailpile.spambayes import Classifier
import mailpile.plugins.autotag
from mailpile... | # Add SpamBayes as an option to the autotagger. We like SpamBayes.
#
# We feed the classifier the same terms as go into the search engine,
# which should allow us to actually introspect a bit into the behavior
# of the classifier.
from mailpile.spambayes import Classifier
import mailpile.plugins.autotag
from mailpile... |
20,807 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/plugins/autotag_sb.py | 37,38 | 33,41 | reset | SpamBayesTrainer | 38,41 | 38,41 | class SpamBayesTrainer(mailpile.plugins.autotag.Trainer):
def learn(self, atagger, at_config, msg, keywords, should_tag):
_classifier(atagger).learn(keywords, should_tag)
def reset(self, atagger, at_config):
FILL_FUNC_BODY | class SpamBayesTrainer(mailpile.plugins.autotag.Trainer):
def learn(self, atagger, at_config, msg, keywords, should_tag):
_classifier(atagger).learn(keywords, should_tag)
def reset(self, atagger, at_config):
FILL_FUNC_BODY | atagger.spambayes = Classifier()
| atagger.spambayes = Classifier()
| 3 | 89 | 18 | 107 | # Add SpamBayes as an option to the autotagger. We like SpamBayes.
#
# We feed the classifier the same terms as go into the search engine,
# which should allow us to actually introspect a bit into the behavior
# of the classifier.
from mailpile.spambayes import Classifier
import mailpile.plugins.autotag
from mailpile... | # Add SpamBayes as an option to the autotagger. We like SpamBayes.
#
# We feed the classifier the same terms as go into the search engine,
# which should allow us to actually introspect a bit into the behavior
# of the classifier.
from mailpile.spambayes import Classifier
import mailpile.plugins.autotag
from mailpile... |
20,808 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/plugins/cryptostate.py | 93,94 | 1,102 | search | 94,100 | 94,100 | from __future__ import print_function
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
from mailpile.plugins import PluginManager
from mailpile.crypto.state import EncryptionInfo, SignatureInfo
_plugins = PluginManager(builtin=__file__)
##[ Keywords ]##################################... | from __future__ import print_function
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
from mailpile.plugins import PluginManager
from mailpile.crypto.state import EncryptionInfo, SignatureInfo
_plugins = PluginManager(builtin=__file__)
##[ Keywords ]##################################... | #
# FIXME: Translate things like pgp:signed into a search for all the
# tags that have signatures (good or bad).
#
return []
| #
# FIXME: Translate things like pgp:signed into a search for all the
# tags that have signatures (good or bad).
#
return []
| 24 | 1,064 | 52 | 1,116 | from __future__ import print_function
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
from mailpile.plugins import PluginManager
from mailpile.crypto.state import EncryptionInfo, SignatureInfo
_plugins = PluginManager(builtin=__file__)
##[ Keywords ]##################################... | from __future__ import print_function
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
from mailpile.plugins import PluginManager
from mailpile.crypto.state import EncryptionInfo, SignatureInfo
_plugins = PluginManager(builtin=__file__)
##[ Keywords ]##################################... | |
20,809 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/plugins/keylookup/email_keylookup.py | 128,129 | 1,158 | get_pgp_key_keywords | 129,144 | 129,144 | import datetime
import time
import copy
from mailpile.crypto.autocrypt import *
from mailpile.crypto.keyinfo import get_keyinfo, MailpileKeyInfo
from mailpile.i18n import gettext
from mailpile.plugins import PluginManager
from mailpile.plugins.keylookup import LookupHandler
from mailpile.plugins.keylookup import regis... | import datetime
import time
import copy
from mailpile.crypto.autocrypt import *
from mailpile.crypto.keyinfo import get_keyinfo, MailpileKeyInfo
from mailpile.i18n import gettext
from mailpile.plugins import PluginManager
from mailpile.plugins.keylookup import LookupHandler
from mailpile.plugins.keylookup import regis... | kws = []
for keyinfo in get_keyinfo(data):
for uid in keyinfo.uids:
if uid.email:
kws.append('%s:pgpkey' % uid.email.lower())
fingerprint = keyinfo.fingerprint.lower()
kws.append('pgpkey:has')
kws.append('%s:pgpkey' % fingerprint)
kws.append('%... | kws = []
for keyinfo in get_keyinfo(data):
for uid in keyinfo.uids:
if uid.email:
kws.append('%s:pgpkey' % uid.email.lower())
fingerprint = keyinfo.fingerprint.lower()
kws.append('pgpkey:has')
kws.append('%s:pgpkey' % fingerprint)
kws.append('%... | 38 | 1,608 | 207 | 1,815 | import datetime
import time
import copy
from mailpile.crypto.autocrypt import *
from mailpile.crypto.keyinfo import get_keyinfo, MailpileKeyInfo
from mailpile.i18n import gettext
from mailpile.plugins import PluginManager
from mailpile.plugins.keylookup import LookupHandler
from mailpile.plugins.keylookup import regis... | import datetime
import time
import copy
from mailpile.crypto.autocrypt import *
from mailpile.crypto.keyinfo import get_keyinfo, MailpileKeyInfo
from mailpile.i18n import gettext
from mailpile.plugins import PluginManager
from mailpile.plugins.keylookup import LookupHandler
from mailpile.plugins.keylookup import regis... | |
20,810 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/plugins/keylookup/email_keylookup.py | 58,59 | 38,128 | _lookup | EmailKeyLookupHandler | 59,79 | 59,79 | class EmailKeyLookupHandler(LookupHandler, Search):
NAME = _("E-mail keys")
SHORTNAME = 'e-mail'
PRIORITY = 5
TIMEOUT = 25 # 5 seconds per message we are willing to parse
LOCAL = True
PRIVACY_FRIENDLY = True
SCORE = 1
def __init__(self, session, *args, **kwargs):
LookupHandler.... | class EmailKeyLookupHandler(LookupHandler, Search):
NAME = _("E-mail keys")
SHORTNAME = 'e-mail'
PRIORITY = 5
TIMEOUT = 25 # 5 seconds per message we are willing to parse
LOCAL = True
PRIVACY_FRIENDLY = True
SCORE = 1
def __init__(self, session, *args, **kwargs):
LookupHandler.... | results = {}
canon_address = canonicalize_email(address)
terms = ['from:%s' % address, 'has:pgpkey', '+pgpkey:%s' % address]
session, idx = self._do_search(search=terms)
deadline = time.time() + (0.75 * self.TIMEOUT)
for messageid in session.results[:5]:
for k... | results = {}
canon_address = canonicalize_email(address)
terms = ['from:%s' % address, 'has:pgpkey', '+pgpkey:%s' % address]
session, idx = self._do_search(search=terms)
deadline = time.time() + (0.75 * self.TIMEOUT)
for messageid in session.results[:5]:
for k... | 75 | 798 | 276 | 1,074 | import datetime
import time
import copy
from mailpile.crypto.autocrypt import *
from mailpile.crypto.keyinfo import get_keyinfo, MailpileKeyInfo
from mailpile.i18n import gettext
from mailpile.plugins import PluginManager
from mailpile.plugins.keylookup import LookupHandler
from mailpile.plugins.keylookup import regis... | import datetime
import time
import copy
from mailpile.crypto.autocrypt import *
from mailpile.crypto.keyinfo import get_keyinfo, MailpileKeyInfo
from mailpile.i18n import gettext
from mailpile.plugins import PluginManager
from mailpile.plugins.keylookup import LookupHandler
from mailpile.plugins.keylookup import regis... |
20,811 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/plugins/sizes.py | 40,41 | 1,89 | _mk_logsize | 41,59 | 41,59 | import math
import time
import datetime
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
from mailpile.plugins import PluginManager
_plugins = PluginManager(builtin=__file__)
##[ Keywords ]################################################################
def meta_kw_extractor(index, ... | import math
import time
import datetime
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
from mailpile.plugins import PluginManager
_plugins = PluginManager(builtin=__file__)
##[ Keywords ]################################################################
def meta_kw_extractor(index, ... | if not size:
return 0
unit = 0
size = size.lower()
if size[-1].isdigit(): # ends with a number
unit = default_unit
elif len(size) >= 2 and size[-2] in _size_units and size[-1] == 'b':
unit = _size_units[size[-2]]
size = size[:-2]
elif size[-1] in _size_units:
... | if not size:
return 0
unit = 0
size = size.lower()
if size[-1].isdigit(): # ends with a number
unit = default_unit
elif len(size) >= 2 and size[-2] in _size_units and size[-1] == 'b':
unit = _size_units[size[-2]]
size = size[:-2]
elif size[-1] in _size_units:
... | 61 | 587 | 193 | 780 | import math
import time
import datetime
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
from mailpile.plugins import PluginManager
_plugins = PluginManager(builtin=__file__)
##[ Keywords ]################################################################
def meta_kw_extractor(index, ... | import math
import time
import datetime
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
from mailpile.plugins import PluginManager
_plugins = PluginManager(builtin=__file__)
##[ Keywords ]################################################################
def meta_kw_extractor(index, ... | |
20,812 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/mailpile/spambayes/Tester.py | 30,31 | 3,136 | reset_test_results | Test | 31,49 | 31,49 | class Test:
# Pass a classifier instance (an instance of Bayes).
# Loop:
# # Train the classifer with new ham and spam.
# train(ham, spam) # this implies reset_test_results
# Loop:
# Optional:
# # Possibly fiddle the classifier.
# set_classifie... | class Test:
# Pass a classifier instance (an instance of Bayes).
# Loop:
# # Train the classifer with new ham and spam.
# train(ham, spam) # this implies reset_test_results
# Loop:
# Optional:
# # Possibly fiddle the classifier.
# set_classifie... | # The number of ham and spam instances tested.
self.nham_tested = self.nspam_tested = 0
# The number of test instances correctly and incorrectly classified.
self.nham_right = 0
self.nham_wrong = 0
self.nham_unsure = 0
self.nspam_right = 0
self.nspam_wrong... | # The number of ham and spam instances tested.
self.nham_tested = self.nspam_tested = 0
# The number of test instances correctly and incorrectly classified.
self.nham_right = 0
self.nham_wrong = 0
self.nham_unsure = 0
self.nspam_right = 0
self.nspam_wrong... | 94 | 1,362 | 243 | 1,605 | from mailpile.spambayes.Options import options
class Test:
# Pass a classifier instance (an instance of Bayes).
# Loop:
# # Train the classifer with new ham and spam.
# train(ham, spam) # this implies reset_test_results
# Loop:
# Optional:
# # Possibly fiddle... | from mailpile.spambayes.Options import options
class Test:
# Pass a classifier instance (an instance of Bayes).
# Loop:
# # Train the classifer with new ham and spam.
# train(ham, spam) # this implies reset_test_results
# Loop:
# Optional:
# # Possibly fiddle... |
20,814 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/scripts/kite-runner.py | 158,159 | 127,193 | run | BuildbotAPI | 159,184 | 159,184 | class BuildbotAPI(object):
def __init__(self, server):
self.server = server
self.scripts = {}
self.script_lock = threading.Lock()
self.script_running = None
self.script_last = None
def _collect_stdout(self, sdata, logline):
if logline is None:
with se... | class BuildbotAPI(object):
def __init__(self, server):
self.server = server
self.scripts = {}
self.script_lock = threading.Lock()
self.script_running = None
self.script_last = None
def _collect_stdout(self, sdata, logline):
if logline is None:
with se... | with self.script_lock:
if name not in self.scripts:
raise ValueError('No such script')
elif self.script_running is None:
kid = subprocess.Popen(
[self.server.shell_binary, '-c',
self.scripts[name].replace('\\', '\\\... | with self.script_lock:
if name not in self.scripts:
raise ValueError('No such script')
elif self.script_running is None:
kid = subprocess.Popen(
[self.server.shell_binary, '-c',
self.scripts[name].replace('\\', '\\\... | 64 | 385 | 313 | 698 | #!/usr/bin/python
"""
kite-runner.py - XMLRPC-based script launcher with PageKite integration.
"""
from __future__ import print_function
import getopt
import json
import os
import sys
import subprocess
import threading
import time
import traceback
try:
import SimpleXMLRPCServer # Python 2.7
except ImportError:
... | #!/usr/bin/python
"""
kite-runner.py - XMLRPC-based script launcher with PageKite integration.
"""
from __future__ import print_function
import getopt
import json
import os
import sys
import subprocess
import threading
import time
import traceback
try:
import SimpleXMLRPCServer # Python 2.7
except ImportError:
... |
20,815 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/scripts/kite-runner.py | 219,220 | 193,332 | load_config | BuildbotServer | 220,229 | 220,229 | class BuildbotServer(object):
COMMON_OPT_FLAGS = 'p:k:c:'
COMMON_OPT_ARGS = [
'port=', 'runas=', 'config=',
'xmlrpc_path=', 'sh_binary=', 'script=', 'bin_path=',
'pagekite=', 'pk_binary=', 'pk_kite=', 'pk_secret=']
DEFAULT_CONFIG_FILE = '~/kite-runner.cfg'
DEFAULT_PORT = 33011
... | class BuildbotServer(object):
COMMON_OPT_FLAGS = 'p:k:c:'
COMMON_OPT_ARGS = [
'port=', 'runas=', 'config=',
'xmlrpc_path=', 'sh_binary=', 'script=', 'bin_path=',
'pagekite=', 'pk_binary=', 'pk_kite=', 'pk_secret=']
DEFAULT_CONFIG_FILE = '~/kite-runner.cfg'
DEFAULT_PORT = 33011
... | with open(filename or self.config_file, 'r') as fd:
lines = [l.split('#')[0].strip()
for l in fd.read().replace("\\\n", '').splitlines()]
args = []
for line in lines:
if line:
args.append('--%s' % line.replace(' = ', '='))
retu... | with open(filename or self.config_file, 'r') as fd:
lines = [l.split('#')[0].strip()
for l in fd.read().replace("\\\n", '').splitlines()]
args = []
for line in lines:
if line:
args.append('--%s' % line.replace(' = ', '='))
retu... | 32 | 1,397 | 115 | 1,512 | #!/usr/bin/python
"""
kite-runner.py - XMLRPC-based script launcher with PageKite integration.
"""
from __future__ import print_function
import getopt
import json
import os
import sys
import subprocess
import threading
import time
import traceback
try:
import SimpleXMLRPCServer # Python 2.7
except ImportError:
... | #!/usr/bin/python
"""
kite-runner.py - XMLRPC-based script launcher with PageKite integration.
"""
from __future__ import print_function
import getopt
import json
import os
import sys
import subprocess
import threading
import time
import traceback
try:
import SimpleXMLRPCServer # Python 2.7
except ImportError:
... |
20,816 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/scripts/kite-runner.py | 37,38 | 30,46 | run | OutputEater | 38,46 | 38,46 | class OutputEater(threading.Thread):
def __init__(self, fd, callback):
threading.Thread.__init__(self)
self.daemon = True
self.fd = fd
self.cb = callback
def run(self):
FILL_FUNC_BODY | class OutputEater(threading.Thread):
def __init__(self, fd, callback):
threading.Thread.__init__(self)
self.daemon = True
self.fd = fd
self.cb = callback
def run(self):
FILL_FUNC_BODY | while True:
line = self.fd.readline()
if not line:
break
self.cb(line.decode('utf-8').strip())
self.cb(None)
| while True:
line = self.fd.readline()
if not line:
break
self.cb(line.decode('utf-8').strip())
self.cb(None)
| 11 | 75 | 59 | 134 | #!/usr/bin/python
"""
kite-runner.py - XMLRPC-based script launcher with PageKite integration.
"""
from __future__ import print_function
import getopt
import json
import os
import sys
import subprocess
import threading
import time
import traceback
try:
import SimpleXMLRPCServer # Python 2.7
except ImportError:
... | #!/usr/bin/python
"""
kite-runner.py - XMLRPC-based script launcher with PageKite integration.
"""
from __future__ import print_function
import getopt
import json
import os
import sys
import subprocess
import threading
import time
import traceback
try:
import SimpleXMLRPCServer # Python 2.7
except ImportError:
... |
20,817 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/scripts/kite-runner.py | 62,63 | 46,114 | _run | PagekiteThread | 63,102 | 63,102 | class PagekiteThread(threading.Thread):
def __init__(self, server):
threading.Thread.__init__(self)
self.kid = None
self.server = server
self.lock = threading.Lock()
def _handle_logline(self, line):
print(line)
def run(self):
try:
self._run()
... | class PagekiteThread(threading.Thread):
def __init__(self, server):
threading.Thread.__init__(self)
self.kid = None
self.server = server
self.lock = threading.Lock()
def _handle_logline(self, line):
print(line)
def run(self):
try:
self._run()
... | skip_loops = 0
crash_count = 0
while not self.server.quitting:
command = ' '.join([
self.server.pagekite_binary,
self.server.pagekite_args])
command = command.replace('%PORT%', str(self.server.port))
command = command.replace('%... | skip_loops = 0
crash_count = 0
while not self.server.quitting:
command = ' '.join([
self.server.pagekite_binary,
self.server.pagekite_args])
command = command.replace('%PORT%', str(self.server.port))
command = command.replace('%... | 115 | 202 | 495 | 697 | #!/usr/bin/python
"""
kite-runner.py - XMLRPC-based script launcher with PageKite integration.
"""
from __future__ import print_function
import getopt
import json
import os
import sys
import subprocess
import threading
import time
import traceback
try:
import SimpleXMLRPCServer # Python 2.7
except ImportError:
... | #!/usr/bin/python
"""
kite-runner.py - XMLRPC-based script launcher with PageKite integration.
"""
from __future__ import print_function
import getopt
import json
import os
import sys
import subprocess
import threading
import time
import traceback
try:
import SimpleXMLRPCServer # Python 2.7
except ImportError:
... |
20,818 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/bin/with-mailpile-env.py | 23,24 | 1,105 | locate_parent | 24,41 | 24,41 | """
This script sets up a mailpile-compatible environment, then executes the
specified command. It localizes the majority of bootstrapping into python,
so that top-level entry points (like start menu items) only need to know
about python and this script.
Example: path\\to\\python with-mailpile-env.py mailpile-gui.py
"... | """
This script sets up a mailpile-compatible environment, then executes the
specified command. It localizes the majority of bootstrapping into python,
so that top-level entry points (like start menu items) only need to know
about python and this script.
Example: path\\to\\python with-mailpile-env.py mailpile-gui.py
"... |
if len( path_parts ) > 1:
path = reduce( os.path.join, path_parts )
else:
path = path_parts[ 0 ]
directory = os.path.abspath( __file__ )
while True:
test_path = os.path.join( directory, path )
if os.path.exists( test_path ):
return os.path.split( test_path )[... |
if len( path_parts ) > 1:
path = reduce( os.path.join, path_parts )
else:
path = path_parts[ 0 ]
directory = os.path.abspath( __file__ )
while True:
test_path = os.path.join( directory, path )
if os.path.exists( test_path ):
return os.path.split( test_path )[... | 62 | 898 | 181 | 1,079 | """
This script sets up a mailpile-compatible environment, then executes the
specified command. It localizes the majority of bootstrapping into python,
so that top-level entry points (like start menu items) only need to know
about python and this script.
Example: path\\to\\python with-mailpile-env.py mailpile-gui.py
"... | """
This script sets up a mailpile-compatible environment, then executes the
specified command. It localizes the majority of bootstrapping into python,
so that top-level entry points (like start menu items) only need to know
about python and this script.
Example: path\\to\\python with-mailpile-env.py mailpile-gui.py
"... | |
20,819 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/build.py | 145,146 | 13,252 | config | Build | 149,157 | 146,157 | class Build(object):
'''
Construct a build environment where providers can be invoked to
compose build artifacts.
'''
class Invoker(object):
'''
Utility class for invoking external binaries. Captures stderr on error,
otherwise returns stdout. The intention is for the invocat... | class Build(object):
'''
Construct a build environment where providers can be invoked to
compose build artifacts.
'''
class Invoker(object):
'''
Utility class for invoking external binaries. Captures stderr on error,
otherwise returns stdout. The intention is for the invocat... |
try:
result = self._config[keyword]
except KeyError:
result = self._build._defaults[keyword](keyword)
self.log().info("Using default '{}' config '{}'".format(keyword, result))
return result
| '''
Query a key-value config item.
'''
try:
result = self._config[keyword]
except KeyError:
result = self._build._defaults[keyword](keyword)
self.log().info("Using default '{}' config '{}'".format(keyword, resul... | 17 | 1,813 | 72 | 1,885 | import subprocess
import os.path
import tempfile
import argparse
import datetime
import logging
import json
import itertools
logger = logging.getLogger(__name__)
class Build(object):
'''
Construct a build environment where providers can be invoked to
compose build artifacts.
'''
class Invoker(ob... | import subprocess
import os.path
import tempfile
import argparse
import datetime
import logging
import json
import itertools
logger = logging.getLogger(__name__)
class Build(object):
'''
Construct a build environment where providers can be invoked to
compose build artifacts.
'''
class Invoker(ob... |
20,820 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/build.py | 134,135 | 58,171 | clear | Context | 138,145 | 135,145 | class Context(object):
'''
Build context that's disposed of after a build
'''
def __init__(self, build, cache, config):
'''
Attach the context to the parent build, and configure initial
properties.
'''
self._build = build
... | class Context(object):
'''
Build context that's disposed of after a build
'''
def __init__(self, build, cache, config):
'''
Attach the context to the parent build, and configure initial
properties.
'''
self._build = build
... |
for action in self._cleanup:
try:
action()
except:
self.log().exception("Error during cleanup!")
| '''
Delete everything in the build context.
'''
for action in self._cleanup:
try:
action()
except:
self.log().exception("Error during cleanup!")
| 10 | 837 | 45 | 882 | import subprocess
import os.path
import tempfile
import argparse
import datetime
import logging
import json
import itertools
logger = logging.getLogger(__name__)
class Build(object):
'''
Construct a build environment where providers can be invoked to
compose build artifacts.
'''
class Invoker(ob... | import subprocess
import os.path
import tempfile
import argparse
import datetime
import logging
import json
import itertools
logger = logging.getLogger(__name__)
class Build(object):
'''
Construct a build environment where providers can be invoked to
compose build artifacts.
'''
class Invoker(ob... |
20,821 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/bootstrap.py | 10,11 | 1,56 | bind | 14,56 | 11,56 | import os.path
import json
import sys
import logging
'''
Bootstrap execution in an entirely clean checkout to ensure we use build scripts
matched to the specified build target.
'''
def bind(framework):
FILL_FUNC_BODY | import os.path
import json
import sys
import logging
'''
Bootstrap execution in an entirely clean checkout to ensure we use build scripts
matched to the specified build target.
'''
def bind(framework):
'''
Attach build config+scripts to the build framework
'''
FILL_FUNC_BODY |
@framework.default_config('bootstrap')
def config_bootstrap(keyword):
'''
Inner configuration JSON for a fully bootstrapped build. All options
passed here are forwarded to the checked out build. The bootstrap env
will inherit this build's cache directory and log level. A second ... | '''
Attach build config+scripts to the build framework
'''
@framework.default_config('bootstrap')
def config_bootstrap(keyword):
'''
Inner configuration JSON for a fully bootstrapped build. All options
passed here are forwarded to the checked out build. The bootstrap env
... | 118 | 80 | 451 | 531 | import os.path
import json
import sys
import logging
'''
Bootstrap execution in an entirely clean checkout to ensure we use build scripts
matched to the specified build target.
'''
def bind(framework):
FILL_FUNC_BODY | import os.path
import json
import sys
import logging
'''
Bootstrap execution in an entirely clean checkout to ensure we use build scripts
matched to the specified build target.
'''
def bind(framework):
'''
Attach build config+scripts to the build framework
'''
FILL_FUNC_BODY | |
20,822 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/export.py | 4,5 | 1,26 | bind | 5,26 | 5,26 | import shutil
def bind(build):
FILL_FUNC_BODY | import shutil
def bind(build):
FILL_FUNC_BODY |
@build.provide('export')
def provide_export(build, keyword):
'''
Export build artifacts to arbitrary locations. Configured via a dictionary
of { dependency: export_path }.
'''
for dependency, export_path in build.config(keyword).items():
build.log().info("Ex... |
@build.provide('export')
def provide_export(build, keyword):
'''
Export build artifacts to arbitrary locations. Configured via a dictionary
of { dependency: export_path }.
'''
for dependency, export_path in build.config(keyword).items():
build.log().info("Ex... | 48 | 22 | 193 | 215 | import shutil
def bind(build):
FILL_FUNC_BODY | import shutil
def bind(build):
FILL_FUNC_BODY | |
20,823 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/external.py | 5,6 | 1,39 | bind | 6,39 | 6,39 | import os
import os.path
import itertools
def bind(build):
FILL_FUNC_BODY | import os
import os.path
import itertools
def bind(build):
FILL_FUNC_BODY |
@build.default_config('git', 'signtool')
def default_config_env(keyword):
'''
Commands expected to exist on PATH.
'''
return keyword + '.exe'
@build.default_config('signtool')
def default_config_sdk(keyword):
'''
Try to discover tools from the windows sd... |
@build.default_config('git', 'signtool')
def default_config_env(keyword):
'''
Commands expected to exist on PATH.
'''
return keyword + '.exe'
@build.default_config('signtool')
def default_config_sdk(keyword):
'''
Try to discover tools from the windows sd... | 87 | 29 | 348 | 377 | import os
import os.path
import itertools
def bind(build):
FILL_FUNC_BODY | import os
import os.path
import itertools
def bind(build):
FILL_FUNC_BODY | |
20,824 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/extract_msi.py | 63,64 | 1,71 | bind | 64,71 | 64,71 | #!/usr/bin/python
'''
Helper for unpacking MSIs in various ways. Generic high-level API:
extract( msi_path, out_path, features = ALL )
'''
ALL = '***ALL***'
import subprocess
import logging
import tempfile
import shutil
import os.path
import os
logger = logging.getLogger(__name__)
class LessMSI(object):
'''
... | #!/usr/bin/python
'''
Helper for unpacking MSIs in various ways. Generic high-level API:
extract( msi_path, out_path, features = ALL )
'''
ALL = '***ALL***'
import subprocess
import logging
import tempfile
import shutil
import os.path
import os
logger = logging.getLogger(__name__)
class LessMSI(object):
'''
... |
@build.provide('extract_msi')
def provide_extract_msi(build, keyword):
lessmsi_dir = build.depend('lessmsi')
lessmsi_path = os.path.join(build.depend('lessmsi'), 'lessmsi.exe')
extractor = LessMSI(lessmsi_path)
return extractor
|
@build.provide('extract_msi')
def provide_extract_msi(build, keyword):
lessmsi_dir = build.depend('lessmsi')
lessmsi_path = os.path.join(build.depend('lessmsi'), 'lessmsi.exe')
extractor = LessMSI(lessmsi_path)
return extractor
| 16 | 592 | 102 | 694 | #!/usr/bin/python
'''
Helper for unpacking MSIs in various ways. Generic high-level API:
extract( msi_path, out_path, features = ALL )
'''
ALL = '***ALL***'
import subprocess
import logging
import tempfile
import shutil
import os.path
import os
logger = logging.getLogger(__name__)
class LessMSI(object):
'''
... | #!/usr/bin/python
'''
Helper for unpacking MSIs in various ways. Generic high-level API:
extract( msi_path, out_path, features = ALL )
'''
ALL = '***ALL***'
import subprocess
import logging
import tempfile
import shutil
import os.path
import os
logger = logging.getLogger(__name__)
class LessMSI(object):
'''
... | |
20,825 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/extract_msi.py | 57,58 | 21,63 | log_error | LessMSI | 58,60 | 58,60 | class LessMSI(object):
'''
Use lessmsi to extract the msi. TODO: handle features
'''
def __init__(self, lessmsi_path):
self.lessmsi = lessmsi_path
def __call__(self, msi_path, out_path, features=ALL):
logger.info('Extracting {} to {} (features:{}) with lessmsi'.format(
... | class LessMSI(object):
'''
Use lessmsi to extract the msi. TODO: handle features
'''
def __init__(self, lessmsi_path):
self.lessmsi = lessmsi_path
def __call__(self, msi_path, out_path, features=ALL):
logger.info('Extracting {} to {} (features:{}) with lessmsi'.format(
... | logger.error("Error cleaning up {}: {} {}".format(msi_path, func, path),
exec_info=exec_info)
| logger.error("Error cleaning up {}: {} {}".format(msi_path, func, path),
exec_info=exec_info)
| 9 | 455 | 37 | 492 | #!/usr/bin/python
'''
Helper for unpacking MSIs in various ways. Generic high-level API:
extract( msi_path, out_path, features = ALL )
'''
ALL = '***ALL***'
import subprocess
import logging
import tempfile
import shutil
import os.path
import os
logger = logging.getLogger(__name__)
class LessMSI(object):
'''
... | #!/usr/bin/python
'''
Helper for unpacking MSIs in various ways. Generic high-level API:
extract( msi_path, out_path, features = ALL )
'''
ALL = '***ALL***'
import subprocess
import logging
import tempfile
import shutil
import os.path
import os
logger = logging.getLogger(__name__)
class LessMSI(object):
'''
... |
20,826 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/git_checkout.py | 4,5 | 1,75 | bind | 5,75 | 5,75 | import os.path
import shutil
def bind(build):
FILL_FUNC_BODY | import os.path
import shutil
def bind(build):
FILL_FUNC_BODY |
def repo_root():
'''
Find the root of the current checkout
'''
repo_path = os.path.abspath(os.path.dirname(__file__))
while not os.path.exists(os.path.join(repo_path,'.git')):
parts = os.path.split(repo_path)
if parts[0] == repo_path:
... |
def repo_root():
'''
Find the root of the current checkout
'''
repo_path = os.path.abspath(os.path.dirname(__file__))
while not os.path.exists(os.path.join(repo_path,'.git')):
parts = os.path.split(repo_path)
if parts[0] == repo_path:
... | 185 | 26 | 748 | 774 | import os.path
import shutil
def bind(build):
FILL_FUNC_BODY | import os.path
import shutil
def bind(build):
FILL_FUNC_BODY | |
20,827 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/python27.py | 6,7 | 1,74 | bind | 7,74 | 7,74 | import os.path
import glob
import subprocess
def bind(framework):
FILL_FUNC_BODY | import os.path
import glob
import subprocess
def bind(framework):
FILL_FUNC_BODY |
@framework.provide('python27')
def provide_python27(build, keyword):
'''
provide python27 prepared for mailpile
'''
build.depend('root')
dep_path = build.invoke('path', keyword)
extractor = build.depend('extract_msi')
extractor(build.cache().resource(ke... |
@framework.provide('python27')
def provide_python27(build, keyword):
'''
provide python27 prepared for mailpile
'''
build.depend('root')
dep_path = build.invoke('path', keyword)
extractor = build.depend('extract_msi')
extractor(build.cache().resource(ke... | 172 | 30 | 920 | 950 | import os.path
import glob
import subprocess
def bind(framework):
FILL_FUNC_BODY | import os.path
import glob
import subprocess
def bind(framework):
FILL_FUNC_BODY | |
20,828 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/root.py | 5,6 | 1,29 | bind | 6,29 | 6,29 | import os.path
import tempfile
def bind(build):
FILL_FUNC_BODY | import os.path
import tempfile
def bind(build):
FILL_FUNC_BODY |
@build.provide('root')
def provide_root(build, keyword):
'''
Provide build root temporary directory and 'path' invokable.
'''
util = build.depend('util')
root = tempfile.mkdtemp()
build.log().info("Initialized build root at '{}'".format(root))
def clean... |
@build.provide('root')
def provide_root(build, keyword):
'''
Provide build root temporary directory and 'path' invokable.
'''
util = build.depend('util')
root = tempfile.mkdtemp()
build.log().info("Initialized build root at '{}'".format(root))
def clean... | 43 | 27 | 204 | 231 | import os.path
import tempfile
def bind(build):
FILL_FUNC_BODY | import os.path
import tempfile
def bind(build):
FILL_FUNC_BODY | |
20,829 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/sign_tree.py | 4,5 | 1,82 | is_signable | 8,20 | 5,20 | import os
import os.path
def is_signable(path):
FILL_FUNC_BODYdef bind(build):
@build.default_config('timestamp_server')
def config_signing_timestamp_server(keyword):
'''
Time server for signing execubles
'''
return 'http://timestamp.digicert.com'
build.define_config('signi... | import os
import os.path
def is_signable(path):
'''
Check if a file is in the PE format by looking for the 'MZ' magic.
'''
FILL_FUNC_BODYdef bind(build):
@build.default_config('timestamp_server')
def config_signing_timestamp_server(keyword):
'''
Time server for signing execubles
... | try:
# FIXME--not the correct check...
with open(path, 'rb') as handle:
magic = handle.read(2)
if magic == "\x7F\x45":
return True
except IOError:
pass
recognized_formats = ('.msi', '.exe', '.dll', '.pyd')
return any( map( path.endswith, r... | '''
Check if a file is in the PE format by looking for the 'MZ' magic.
'''
try:
# FIXME--not the correct check...
with open(path, 'rb') as handle:
magic = handle.read(2)
if magic == "\x7F\x45":
return True
except IOError:
pass
reco... | 35 | 624 | 122 | 746 | import os
import os.path
def is_signable(path):
FILL_FUNC_BODYdef bind(build):
@build.default_config('timestamp_server')
def config_signing_timestamp_server(keyword):
'''
Time server for signing execubles
'''
return 'http://timestamp.digicert.com'
build.define_config('signi... | import os
import os.path
def is_signable(path):
'''
Check if a file is in the PE format by looking for the 'MZ' magic.
'''
FILL_FUNC_BODYdef bind(build):
@build.default_config('timestamp_server')
def config_signing_timestamp_server(keyword):
'''
Time server for signing execubles
... | |
20,830 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/version.py | 1,2 | 1,15 | bind | 2,15 | 2,15 | def bind(framework):
FILL_FUNC_BODY | def bind(framework):
FILL_FUNC_BODY |
@framework.provide('version')
def provide_version(build, keyword):
mailpile_dir = build.depend('mailpile')
util = build.depend('util')
build.depend('python27')
with util.pushdir(mailpile_dir):
version = build.invoke('python', 'scripts\\version.py').strip()
... |
@framework.provide('version')
def provide_version(build, keyword):
mailpile_dir = build.depend('mailpile')
util = build.depend('util')
build.depend('python27')
with util.pushdir(mailpile_dir):
version = build.invoke('python', 'scripts\\version.py').strip()
... | 26 | 16 | 141 | 157 | def bind(framework):
FILL_FUNC_BODY | def bind(framework):
FILL_FUNC_BODY | |
20,831 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/win4gpg.py | 5,6 | 1,147 | bind | 6,147 | 6,147 | import textwrap
import os
def bind(build):
FILL_FUNC_BODY | import textwrap
import os
def bind(build):
FILL_FUNC_BODY |
@build.provide('gpg')
def provide_gpg(build, keyword):
'''
install GPG in a temporary location and use mkportable to create a
portable GPG for the build. Requires ADMIN and that gpg4win *is not*
installed.
'''
build.depend('root')
dep_path = build.invoke(... |
@build.provide('gpg')
def provide_gpg(build, keyword):
'''
install GPG in a temporary location and use mkportable to create a
portable GPG for the build. Requires ADMIN and that gpg4win *is not*
installed.
'''
build.depend('root')
dep_path = build.invoke(... | 350 | 25 | 1,553 | 1,578 | import textwrap
import os
def bind(build):
FILL_FUNC_BODY | import textwrap
import os
def bind(build):
FILL_FUNC_BODY | |
20,832 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/packages/windows-wix/provide/scripts/zip.py | 4,5 | 1,20 | bind | 5,20 | 5,20 | import zipfile
def bind(build):
FILL_FUNC_BODY | import zipfile
def bind(build):
FILL_FUNC_BODY |
@build.provide('wix', 'tor', 'lessmsi', 'openssl', 'resource_hacker')
def provide_zip(build, keyword):
'''
Inflate zip files into the build path
'''
build.depend('root')
util = build.depend('util')
dep_path = build.invoke('path', keyword)
zip_path = buil... |
@build.provide('wix', 'tor', 'lessmsi', 'openssl', 'resource_hacker')
def provide_zip(build, keyword):
'''
Inflate zip files into the build path
'''
build.depend('root')
util = build.depend('util')
dep_path = build.invoke('path', keyword)
zip_path = buil... | 36 | 22 | 169 | 191 | import zipfile
def bind(build):
FILL_FUNC_BODY | import zipfile
def bind(build):
FILL_FUNC_BODY | |
20,833 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/scripts/create-debian-changelog.py | 13,14 | 1,39 | versionFromCommitNo | 15,18 | 14,18 | #!/usr/bin/env python2.7
#This script builds a DCH changelog from the git commit log
from __future__ import print_function
from subprocess import check_output, call
from multiprocessing import Pool
import os
def getLogMessage(commitSHA):
"""Get the log message for a given commit hash"""
output = check_output([... | #!/usr/bin/env python2.7
#This script builds a DCH changelog from the git commit log
from __future__ import print_function
from subprocess import check_output, call
from multiprocessing import Pool
import os
def getLogMessage(commitSHA):
"""Get the log message for a given commit hash"""
output = check_output([... | return "0.0.0-dev%d" % commitNo
#Execute git rev-list $(git rev-parse HEAD) to get list of revisions
| """Generate a version string from a numerical commit no"""
return "0.0.0-dev%d" % commitNo
#Execute git rev-list $(git rev-parse HEAD) to get list of revisions
| 15 | 485 | 43 | 528 | #!/usr/bin/env python2.7
#This script builds a DCH changelog from the git commit log
from __future__ import print_function
from subprocess import check_output, call
from multiprocessing import Pool
import os
def getLogMessage(commitSHA):
"""Get the log message for a given commit hash"""
output = check_output([... | #!/usr/bin/env python2.7
#This script builds a DCH changelog from the git commit log
from __future__ import print_function
from subprocess import check_output, call
from multiprocessing import Pool
import os
def getLogMessage(commitSHA):
"""Get the log message for a given commit hash"""
output = check_output([... | |
20,834 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/scripts/mbox-minimal.py | 12,13 | 1,55 | find_message_id | 13,25 | 13,25 | #!/usr/bin/env python2.7
from __future__ import print_function
import sys
import re
msgid_re = re.compile('(?im)^message-id:')
messages = []
msgids = []
buf = '\n'
pos = -1
def find_message_id(buf, LE, LFLF):
FILL_FUNC_BODYDELIM = '\nFrom '
READS = 4 * 64 * 1024
with open(sys.argv[1], 'rb') as fd:
chunk = fd.read... | #!/usr/bin/env python2.7
from __future__ import print_function
import sys
import re
msgid_re = re.compile('(?im)^message-id:')
messages = []
msgids = []
buf = '\n'
pos = -1
def find_message_id(buf, LE, LFLF):
FILL_FUNC_BODYDELIM = '\nFrom '
READS = 4 * 64 * 1024
with open(sys.argv[1], 'rb') as fd:
chunk = fd.read... | be = buf.find(LFLF)
mp = buf[:be].find('\nMessage-I')
if mp >= 0 and buf[mp + 10:mp + 12].lower() == 'd:':
return buf[mp + 1:mp + buf[mp + 1:mp + 150].find(LE) + 1]
mp = buf[:be].lower().find('\nmessage-id:')
if mp >= 0:
return buf[mp + 1:mp + buf[mp + 1:mp + 150].find(LE) + 1]
... | be = buf.find(LFLF)
mp = buf[:be].find('\nMessage-I')
if mp >= 0 and buf[mp + 10:mp + 12].lower() == 'd:':
return buf[mp + 1:mp + buf[mp + 1:mp + 150].find(LE) + 1]
mp = buf[:be].lower().find('\nmessage-id:')
if mp >= 0:
return buf[mp + 1:mp + buf[mp + 1:mp + 150].find(LE) + 1]
... | 51 | 504 | 160 | 664 | #!/usr/bin/env python2.7
from __future__ import print_function
import sys
import re
msgid_re = re.compile('(?im)^message-id:')
messages = []
msgids = []
buf = '\n'
pos = -1
def find_message_id(buf, LE, LFLF):
FILL_FUNC_BODYDELIM = '\nFrom '
READS = 4 * 64 * 1024
with open(sys.argv[1], 'rb') as fd:
chunk = fd.read... | #!/usr/bin/env python2.7
from __future__ import print_function
import sys
import re
msgid_re = re.compile('(?im)^message-id:')
messages = []
msgids = []
buf = '\n'
pos = -1
def find_message_id(buf, LE, LFLF):
FILL_FUNC_BODYDELIM = '\nFrom '
READS = 4 * 64 * 1024
with open(sys.argv[1], 'rb') as fd:
chunk = fd.read... | |
20,835 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/setup.py | 24,25 | 1,86 | _get_submodules | 25,31 | 25,31 | #!/usr/bin/env python2.7
from __future__ import print_function
from datetime import date
from setuptools import setup, find_packages
from setuptools.command.build_py import build_py
import datetime
import os
import re
import subprocess
from glob import glob
from scripts.version import APPVER
here = os.path.abspath(os... | #!/usr/bin/env python2.7
from __future__ import print_function
from datetime import date
from setuptools import setup, find_packages
from setuptools.command.build_py import build_py
import datetime
import os
import re
import subprocess
from glob import glob
from scripts.version import APPVER
here = os.path.abspath(os... | submodules = pbr.git._run_git_command(['submodule', 'status'], git_dir)
submodules = [s.strip().split(' ')[1]
for s in submodules.split('\n')
if s != '']
return submodules
| submodules = pbr.git._run_git_command(['submodule', 'status'], git_dir)
submodules = [s.strip().split(' ')[1]
for s in submodules.split('\n')
if s != '']
return submodules
| 19 | 711 | 75 | 786 | #!/usr/bin/env python2.7
from __future__ import print_function
from datetime import date
from setuptools import setup, find_packages
from setuptools.command.build_py import build_py
import datetime
import os
import re
import subprocess
from glob import glob
from scripts.version import APPVER
here = os.path.abspath(os... | #!/usr/bin/env python2.7
from __future__ import print_function
from datetime import date
from setuptools import setup, find_packages
from setuptools.command.build_py import build_py
import datetime
import os
import re
import subprocess
from glob import glob
from scripts.version import APPVER
here = os.path.abspath(os... | |
20,836 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/setup.py | 68,69 | 67,80 | run | Builder | 69,80 | 69,80 | class Builder(build_py):
def run(self):
FILL_FUNC_BODY | class Builder(build_py):
def run(self):
FILL_FUNC_BODY | try:
assert(0 == subprocess.call(['make', 'bdist-prep'], cwd=here))
except:
print("Error building package. Try running 'make'.")
exit(1)
else:
build_py.run(self)
## "Main" ####################################################################
| try:
assert(0 == subprocess.call(['make', 'bdist-prep'], cwd=here))
except:
print("Error building package. Try running 'make'.")
exit(1)
else:
build_py.run(self)
## "Main" ####################################################################
| 19 | 25 | 89 | 114 | #!/usr/bin/env python2.7
from __future__ import print_function
from datetime import date
from setuptools import setup, find_packages
from setuptools.command.build_py import build_py
import datetime
import os
import re
import subprocess
from glob import glob
from scripts.version import APPVER
here = os.path.abspath(os... | #!/usr/bin/env python2.7
from __future__ import print_function
from datetime import date
from setuptools import setup, find_packages
from setuptools.command.build_py import build_py
import datetime
import os
import re
import subprocess
from glob import glob
from scripts.version import APPVER
here = os.path.abspath(os... |
20,837 | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile | /home/hieuvd/dung_repo/raw/stars_01/mailpile_Mailpile/Mailpile/shared-data/multipile/mailpile-launcher.py | 29,30 | 1,71 | usage | 30,34 | 30,34 | #!/usr/bin/python
#
# IMPORTANT: This script runs as root and is invoked by the web server via sudo.
# So it's pretty security-sensitive: simple is better than clever!
#
from __future__ import print_function
DOC="""\
This is a script to launch Mailpile as a specific user.
The user must already have Mailpile... | #!/usr/bin/python
#
# IMPORTANT: This script runs as root and is invoked by the web server via sudo.
# So it's pretty security-sensitive: simple is better than clever!
#
from __future__ import print_function
DOC="""\
This is a script to launch Mailpile as a specific user.
The user must already have Mailpile... | print(DOC, msg, "\n")
sys.exit(code)
| print(DOC, msg, "\n")
sys.exit(code)
| 4 | 873 | 26 | 899 | #!/usr/bin/python
#
# IMPORTANT: This script runs as root and is invoked by the web server via sudo.
# So it's pretty security-sensitive: simple is better than clever!
#
from __future__ import print_function
DOC="""\
This is a script to launch Mailpile as a specific user.
The user must already have Mailpile... | #!/usr/bin/python
#
# IMPORTANT: This script runs as root and is invoked by the web server via sudo.
# So it's pretty security-sensitive: simple is better than clever!
#
from __future__ import print_function
DOC="""\
This is a script to launch Mailpile as a specific user.
The user must already have Mailpile... | |
20,915 | /home/hieuvd/dung_repo/raw/stars_01/miguelgrinberg_flasky/flasky | /home/hieuvd/dung_repo/raw/stars_01/miguelgrinberg_flasky/flasky/config.py | 93,95 | 92,105 | init_app | DockerConfig | 95,105 | 95,105 | class DockerConfig(ProductionConfig):
@classmethod
def init_app(cls, app):
FILL_FUNC_BODY | class DockerConfig(ProductionConfig):
@classmethod
def init_app(cls, app):
FILL_FUNC_BODY | ProductionConfig.init_app(app)
# log to stderr
import logging
from logging import StreamHandler
file_handler = StreamHandler()
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
| ProductionConfig.init_app(app)
# log to stderr
import logging
from logging import StreamHandler
file_handler = StreamHandler()
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
| 16 | 36 | 78 | 114 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_US... | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_US... |
20,916 | /home/hieuvd/dung_repo/raw/stars_01/miguelgrinberg_flasky/flasky | /home/hieuvd/dung_repo/raw/stars_01/miguelgrinberg_flasky/flasky/config.py | 73,75 | 70,92 | init_app | HerokuConfig | 75,92 | 75,92 | class HerokuConfig(ProductionConfig):
SSL_REDIRECT = True if os.environ.get('DYNO') else False
@classmethod
def init_app(cls, app):
FILL_FUNC_BODY | class HerokuConfig(ProductionConfig):
SSL_REDIRECT = True if os.environ.get('DYNO') else False
@classmethod
def init_app(cls, app):
FILL_FUNC_BODY | ProductionConfig.init_app(app)
# handle reverse proxy server headers
try:
from werkzeug.middleware.proxy_fix import ProxyFix
except ImportError:
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
# log to stderr
... | ProductionConfig.init_app(app)
# handle reverse proxy server headers
try:
from werkzeug.middleware.proxy_fix import ProxyFix
except ImportError:
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
# log to stderr
... | 36 | 61 | 160 | 221 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_US... | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_US... |
20,917 | /home/hieuvd/dung_repo/raw/stars_01/miguelgrinberg_flasky/flasky | /home/hieuvd/dung_repo/raw/stars_01/miguelgrinberg_flasky/flasky/config.py | 46,48 | 42,70 | init_app | ProductionConfig | 48,70 | 48,70 | class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
@classmethod
def init_app(cls, app):
FILL_FUNC_BODY | class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
@classmethod
def init_app(cls, app):
FILL_FUNC_BODY | Config.init_app(app)
# email errors to the administrators
import logging
from logging.handlers import SMTPHandler
credentials = None
secure = None
if getattr(cls, 'MAIL_USERNAME', None) is not None:
credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)... | Config.init_app(app)
# email errors to the administrators
import logging
from logging.handlers import SMTPHandler
credentials = None
secure = None
if getattr(cls, 'MAIL_USERNAME', None) is not None:
credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)... | 53 | 88 | 263 | 351 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_US... | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_US... |
20,918 | /home/hieuvd/dung_repo/raw/stars_01/miguelgrinberg_flasky/flasky | /home/hieuvd/dung_repo/raw/stars_01/miguelgrinberg_flasky/flasky/config.py | 106,108 | 105,118 | init_app | UnixConfig | 108,118 | 108,118 | class UnixConfig(ProductionConfig):
@classmethod
def init_app(cls, app):
FILL_FUNC_BODY | class UnixConfig(ProductionConfig):
@classmethod
def init_app(cls, app):
FILL_FUNC_BODY | ProductionConfig.init_app(app)
# log to syslog
import logging
from logging.handlers import SysLogHandler
syslog_handler = SysLogHandler()
syslog_handler.setLevel(logging.INFO)
app.logger.addHandler(syslog_handler)
| ProductionConfig.init_app(app)
# log to syslog
import logging
from logging.handlers import SysLogHandler
syslog_handler = SysLogHandler()
syslog_handler.setLevel(logging.INFO)
app.logger.addHandler(syslog_handler)
| 16 | 36 | 88 | 124 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_US... | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_US... |
21,427 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/actions.py | 54,55 | 25,94 | run | GlancesActions | 65,94 | 55,94 | class GlancesActions(object):
"""This class manage action if an alert is reached."""
def __init__(self, args=None):
"""Init GlancesActions class."""
# Dict with the criticality status
# - key: stat_name
# - value: criticality
# Goal: avoid to execute the same command twi... | class GlancesActions(object):
"""This class manage action if an alert is reached."""
def __init__(self, args=None):
"""Init GlancesActions class."""
# Dict with the criticality status
# - key: stat_name
# - value: criticality
# Goal: avoid to execute the same command twi... | if (self.get(stat_name) == criticality and not repeat) or not self.start_timer.finished():
# Action already executed => Exit
return False
logger.debug(
"{} action {} for {} ({}) with stats {}".format(
"Repeat" if repeat else "Run", commands, stat_name... | """Run the commands (in background).
:param stat_name: plugin_name (+ header)
:param criticality: criticality of the trigger
:param commands: a list of command line with optional {{mustache}}
:param repeat: If True, then repeat the action
:param mustache_dict: Plugin st... | 110 | 404 | 340 | 744 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage on alert actions."""
from glances.logger import logger
from glances.timer import Timer
from glances.secure import secure_popen
try:... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage on alert actions."""
from glances.logger import logger
from glances.timer import Timer
from glances.secure import secure_popen
try:... |
21,428 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/amps_list.py | 42,43 | 21,158 | load_configs | AmpsList | 44,76 | 43,76 | class AmpsList(object):
"""This class describes the optional application monitoring process list.
The AMP list is a list of processes with a specific monitoring action.
The list (Python list) is composed of items (Python dict).
An item is defined (dict keys):
*...
"""
# The dict
__amp... | class AmpsList(object):
"""This class describes the optional application monitoring process list.
The AMP list is a list of processes with a specific monitoring action.
The list (Python list) is composed of items (Python dict).
An item is defined (dict keys):
*...
"""
# The dict
__amp... | if self.config is None:
return False
# For each AMP script, call the load_config method
for s in self.config.sections():
if s.startswith("amp_"):
# An AMP section exists in the configuration file
# If an AMP module exist in amps_path (glan... | """Load the AMP configuration files."""
if self.config is None:
return False
# For each AMP script, call the load_config method
for s in self.config.sections():
if s.startswith("amp_"):
# An AMP section exists in the configuration file
... | 136 | 964 | 422 | 1,386 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage the AMPs list."""
import os
import re
import threading
from glances.globals import listkeys, iteritems, amps_path
from glances.logg... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage the AMPs list."""
import os
import re
import threading
from glances.globals import listkeys, iteritems, amps_path
from glances.logg... |
21,429 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/attribute.py | 107,108 | 15,134 | history_size | GlancesAttribute | 109,111 | 108,111 | class GlancesAttribute(object):
def __init__(self, name, description='', history_max_size=None):
"""Init the attribute
:param name: Attribute name (string)
:param description: Attribute human reading description (string)
:param history_max_size: Maximum size of the history list (def... | class GlancesAttribute(object):
def __init__(self, name, description='', history_max_size=None):
"""Init the attribute
:param name: Attribute name (string)
:param description: Attribute human reading description (string)
:param history_max_size: Maximum size of the history list (def... | return len(self._history)
| """Return the history size (maximum number of value in the history)"""
return len(self._history)
| 2 | 904 | 12 | 916 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Attribute class."""
from datetime import datetime
class GlancesAttribute(object):
def __init__(self, name, description='', history_ma... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Attribute class."""
from datetime import datetime
class GlancesAttribute(object):
def __init__(self, name, description='', history_ma... |
21,432 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/cpu_percent.py | 52,53 | 18,129 | get_info | CpuPercent | 54,74 | 53,74 | class CpuPercent(object):
"""Get and store the CPU percent."""
def __init__(self, cached_timer_cpu=3):
self.cpu_info = {'cpu_name': None, 'cpu_hz_current': None, 'cpu_hz': None}
self.cpu_percent = 0
self.percpu_percent = []
# Get CPU name
self.__get_cpu_name()
... | class CpuPercent(object):
"""Get and store the CPU percent."""
def __init__(self, cached_timer_cpu=3):
self.cpu_info = {'cpu_name': None, 'cpu_hz_current': None, 'cpu_hz': None}
self.cpu_percent = 0
self.percpu_percent = []
# Get CPU name
self.__get_cpu_name()
... | # Never update more than 1 time per cached_timer_cpu_info
if self.timer_cpu_info.finished() and hasattr(psutil, 'cpu_freq'):
# Get the CPU freq current/max
try:
cpu_freq = psutil.cpu_freq()
except Exception as e:
logger.debug('Can not g... | """Get additional information about the CPU"""
# Never update more than 1 time per cached_timer_cpu_info
if self.timer_cpu_info.finished() and hasattr(psutil, 'cpu_freq'):
# Get the CPU freq current/max
try:
cpu_freq = psutil.cpu_freq()
except ... | 63 | 1,121 | 278 | 1,399 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""CPU percent stats shared between CPU and Quicklook plugins."""
from glances.logger import logger
from glances.timer import Timer
import ps... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""CPU percent stats shared between CPU and Quicklook plugins."""
from glances.logger import logger
from glances.timer import Timer
import ps... |
21,433 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/event.py | 64,73 | 40,96 | update | GlancesEvent | 74,96 | 73,96 | @dataclass
class GlancesEvent:
begin: int
state: str
type: str
min: float
max: float
sum: float
count: int
avg: float
top: list
desc: str
sort: str
global_msg: str
end: int = -1
def is_ongoing(self):
"""Return True if the event is ongoing"""
retur... | @dataclass
class GlancesEvent:
begin: int
state: str
type: str
min: float
max: float
sum: float
count: int
avg: float
top: list
desc: str
sort: str
global_msg: str
end: int = -1
def is_ongoing(self):
"""Return True if the event is ongoing"""
retur... |
self.end = -1
self.min = min(self.min, value)
self.max = max(self.max, value)
self.sum += value
self.count += 1
self.avg = self.sum / self.count
if state == "CRITICAL":
# Avoid to change from CRITICAL to WARNING
# If an events have reach... | """Update an ongoing event"""
self.end = -1
self.min = min(self.min, value)
self.max = max(self.max, value)
self.sum += value
self.count += 1
self.avg = self.sum / self.count
if state == "CRITICAL":
# Avoid to change from CRITICAL to WARNING... | 84 | 228 | 241 | 469 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage Glances event class
This class is a Pydantic data class for the Glances event.
event_state = "OK|CAREFUL|WARNING|CRITICAL"
event_typ... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage Glances event class
This class is a Pydantic data class for the Glances event.
event_state = "OK|CAREFUL|WARNING|CRITICAL"
event_typ... |
21,436 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/filter.py | 100,102 | 58,185 | filter | GlancesFilter | 109,137 | 102,137 | class GlancesFilter(object):
"""Allow Glances to filter processes
>>> f = GlancesFilter()
>>> f.filter = '.*python.*'
>>> f.filter
'.*python.*'
>>> f.filter_key
None
>>> f.filter = 'username:nicolargo'
>>> f.filter
'nicolargo'
>>> f.filter_key
'username'
>>> f.filter... | class GlancesFilter(object):
"""Allow Glances to filter processes
>>> f = GlancesFilter()
>>> f.filter = '.*python.*'
>>> f.filter
'.*python.*'
>>> f.filter_key
None
>>> f.filter = 'username:nicolargo'
>>> f.filter
'nicolargo'
>>> f.filter_key
'username'
>>> f.filter... | self._filter_input = value
if value is None:
self._filter = None
self._filter_key = None
else:
new_filter = value.split(':')
if len(new_filter) == 1:
self._filter = new_filter[0]
self._filter_key = None
e... | """Set the filter (as a string) and compute the regular expression
A filter could be one of the following:
- python > Process name start with python
- .*python.* > Process name contain python
- user:nicolargo > Process belong to nicolargo user
"""
self._filter_in... | 91 | 882 | 307 | 1,189 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
import re
from glances.logger import logger
class GlancesFilterList(object):
"""Manage a lis of GlancesFilter objects
>>> fl = Glan... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
import re
from glances.logger import logger
class GlancesFilterList(object):
"""Manage a lis of GlancesFilter objects
>>> fl = Glan... |
21,437 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/filter.py | 44,45 | 15,58 | _add_filter | GlancesFilterList | 46,50 | 45,50 | class GlancesFilterList(object):
"""Manage a lis of GlancesFilter objects
>>> fl = GlancesFilterList()
>>> fl.filter = '.*python.*,user:nicolargo'
>>> fl.is_filtered({'name': 'python is in the place'})
True
>>> fl.is_filtered({'name': 'snake is in the place'})
False
>>> fl.is_filtered({... | class GlancesFilterList(object):
"""Manage a lis of GlancesFilter objects
>>> fl = GlancesFilterList()
>>> fl.filter = '.*python.*,user:nicolargo'
>>> fl.is_filtered({'name': 'python is in the place'})
True
>>> fl.is_filtered({'name': 'snake is in the place'})
False
>>> fl.is_filtered({... | f = GlancesFilter()
f.filter = filter_input
self._filter.append(f)
| """Add a filter"""
f = GlancesFilter()
f.filter = filter_input
self._filter.append(f)
| 7 | 353 | 32 | 385 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
import re
from glances.logger import logger
class GlancesFilterList(object):
"""Manage a lis of GlancesFilter objects
>>> fl = Glan... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
import re
from glances.logger import logger
class GlancesFilterList(object):
"""Manage a lis of GlancesFilter objects
>>> fl = Glan... |
21,438 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/folder_list.py | 117,118 | 19,177 | update | FolderList | 119,146 | 118,146 | class FolderList(object):
"""This class describes the optional monitored folder list.
The folder list is a list of 'important' folder to monitor.
The list (Python list) is composed of items (Python dict).
An item is defined (dict keys):
* path: Path to the folder
* careful: optional careful th... | class FolderList(object):
"""This class describes the optional monitored folder list.
The folder list is a list of 'important' folder to monitor.
The list (Python list) is composed of items (Python dict).
An item is defined (dict keys):
* path: Path to the folder
* careful: optional careful th... | # Only continue if monitor list is not empty
if len(self.__folder_list) == 0:
return self.__folder_list
# Iter upon the folder list
for i in range(len(self.get())):
# Update folder size
if not self.first_grab and not self.timer_folders[i].finished():
... | """Update the command result attributed."""
# Only continue if monitor list is not empty
if len(self.__folder_list) == 0:
return self.__folder_list
# Iter upon the folder list
for i in range(len(self.get())):
# Update folder size
if not self.f... | 93 | 1,227 | 322 | 1,549 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage the folder list."""
from __future__ import unicode_literals
from glances.timer import Timer
from glances.globals import nativestr, ... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage the folder list."""
from __future__ import unicode_literals
from glances.timer import Timer
from glances.globals import nativestr, ... |
21,439 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/history.py | 32,33 | 15,44 | reset | GlancesHistory | 34,37 | 33,37 | class GlancesHistory(object):
"""This class manage a dict of GlancesAttribute
- key: stats name
- value: GlancesAttribute"""
def __init__(self):
"""
items_history_list: list of stats to historized (define inside plugins)
"""
self.stats_history = {}
def add(self, key... | class GlancesHistory(object):
"""This class manage a dict of GlancesAttribute
- key: stats name
- value: GlancesAttribute"""
def __init__(self):
"""
items_history_list: list of stats to historized (define inside plugins)
"""
self.stats_history = {}
def add(self, key... | for a in self.stats_history:
self.stats_history[a].history_reset()
| """Reset all the stats history"""
for a in self.stats_history:
self.stats_history[a].history_reset()
| 5 | 324 | 29 | 353 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage stats history"""
from glances.attribute import GlancesAttribute
class GlancesHistory(object):
"""This class manage a dict of G... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage stats history"""
from glances.attribute import GlancesAttribute
class GlancesHistory(object):
"""This class manage a dict of G... |
21,440 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/logger.py | 75,76 | 1,102 | glances_logger | 83,101 | 76,101 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Custom logger class."""
import os
import json
import getpass
import tempfile
import logging
import logging.config
from glances.globals im... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Custom logger class."""
import os
import json
import getpass
import tempfile
import logging
import logging.config
from glances.globals im... | _logger = logging.getLogger()
# By default, use the LOGGING_CFG logger configuration
config = LOGGING_CFG
# Check if a specific configuration is available
user_file = os.getenv(env_key, None)
if user_file and os.path.exists(user_file):
# A user file as been defined. Use it...
w... | """Build and return the logger.
env_key define the env var where a path to a specific JSON logger
could be defined
:return: logger -- Logger instance
"""
_logger = logging.getLogger()
# By default, use the LOGGING_CFG logger configuration
config = LOGGING_CFG
# Check if a... | 54 | 1,023 | 164 | 1,187 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Custom logger class."""
import os
import json
import getpass
import tempfile
import logging
import logging.config
from glances.globals im... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Custom logger class."""
import os
import json
import getpass
import tempfile
import logging
import logging.config
from glances.globals im... | |
21,441 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/outdated.py | 64,65 | 35,172 | load_config | Outdated | 66,76 | 65,76 | class Outdated(object):
"""
This class aims at providing methods to warn the user when a new Glances
version is available on the PyPI repository (https://pypi.python.org/pypi/Glances/).
"""
def __init__(self, args, config):
"""Init the Outdated class"""
self.args = args
self... | class Outdated(object):
"""
This class aims at providing methods to warn the user when a new Glances
version is available on the PyPI repository (https://pypi.python.org/pypi/Glances/).
"""
def __init__(self, args, config):
"""Init the Outdated class"""
self.args = args
self... |
global_section = 'global'
if hasattr(config, 'has_section') and config.has_section(global_section):
self.args.disable_check_update = config.get_value(global_section, 'check_update').lower() == 'false'
else:
logger.debug("Cannot find section {} in the configuration file".... | """Load outdated parameter in the global section of the configuration file."""
global_section = 'global'
if hasattr(config, 'has_section') and config.has_section(global_section):
self.args.disable_check_update = config.get_value(global_section, 'check_update').lower() == 'false'
... | 27 | 1,334 | 112 | 1,446 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage Glances update."""
from datetime import datetime, timedelta
import threading
import json
import pickle
import os
from ssl import Cer... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage Glances update."""
from datetime import datetime, timedelta
import threading
import json
import pickle
import os
from ssl import Cer... |
21,442 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/outputs/glances_bars.py | 98,99 | 17,128 | get | Bar | 100,125 | 99,125 | class Bar(object):
"""Manage bar (progression or status).
import sys
import time
b = Bar(10)
for p in range(0, 100):
b.percent = p
print("\r%s" % b),
time.sleep(0.1)
sys.stdout.flush()
"""
def __init__(
self,
size,
bar_char='|',
... | class Bar(object):
"""Manage bar (progression or status).
import sys
import time
b = Bar(10)
for p in range(0, 100):
b.percent = p
print("\r%s" % b),
time.sleep(0.1)
sys.stdout.flush()
"""
def __init__(
self,
size,
bar_char='|',
... | value = self.max_value if self.percent > self.max_value else self.percent
# Build the bar
frac, whole = modf(self.size * value / 100.0)
ret = self.__curses_bars[8] * int(whole)
if frac > 0:
ret += self.__curses_bars[int(frac * 8)]
whole += 1
ret +... | """Return the bars."""
value = self.max_value if self.percent > self.max_value else self.percent
# Build the bar
frac, whole = modf(self.size * value / 100.0)
ret = self.__curses_bars[8] * int(whole)
if frac > 0:
ret += self.__curses_bars[int(frac * 8)]
... | 96 | 768 | 306 | 1,074 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage bars for Glances output."""
from __future__ import division
from math import modf
class Bar(object):
"""Manage bar (progressi... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage bars for Glances output."""
from __future__ import division
from math import modf
class Bar(object):
"""Manage bar (progressi... |
21,443 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/outputs/glances_curses.py | 1270,1271 | 1266,1278 | do_command | GlancesTextbox | 1271,1278 | 1271,1278 | class GlancesTextbox(Textbox, object):
def __init__(self, *args, **kwargs):
super(GlancesTextbox, self).__init__(*args, **kwargs)
def do_command(self, ch):
FILL_FUNC_BODY | class GlancesTextbox(Textbox, object):
def __init__(self, *args, **kwargs):
super(GlancesTextbox, self).__init__(*args, **kwargs)
def do_command(self, ch):
FILL_FUNC_BODY | if ch == 10: # Enter
return 0
if ch == 127: # Back
return 8
return super(GlancesTextbox, self).do_command(ch)
| if ch == 10: # Enter
return 0
if ch == 127: # Back
return 8
return super(GlancesTextbox, self).do_command(ch)
| 19 | 68 | 60 | 128 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Curses interface class."""
from __future__ import unicode_literals
import sys
from glances.globals import MACOS, WINDOWS, nativestr, u, it... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Curses interface class."""
from __future__ import unicode_literals
import sys
from glances.globals import MACOS, WINDOWS, nativestr, u, it... |
21,444 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/outputs/glances_curses.py | 1282,1283 | 1278,1284 | do_command | GlancesTextboxYesNo | 1283,1284 | 1283,1284 | class GlancesTextboxYesNo(Textbox, object):
def __init__(self, *args, **kwargs):
super(GlancesTextboxYesNo, self).__init__(*args, **kwargs)
def do_command(self, ch):
FILL_FUNC_BODY | class GlancesTextboxYesNo(Textbox, object):
def __init__(self, *args, **kwargs):
super(GlancesTextboxYesNo, self).__init__(*args, **kwargs)
def do_command(self, ch):
FILL_FUNC_BODY | return super(GlancesTextboxYesNo, self).do_command(ch)
| return super(GlancesTextboxYesNo, self).do_command(ch)
| 3 | 72 | 21 | 93 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Curses interface class."""
from __future__ import unicode_literals
import sys
from glances.globals import MACOS, WINDOWS, nativestr, u, it... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Curses interface class."""
from __future__ import unicode_literals
import sys
from glances.globals import MACOS, WINDOWS, nativestr, u, it... |
21,448 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/outputs/glances_restful_api.py | 56,58 | 52,76 | run_in_thread | GlancesUvicornServer | 58,76 | 58,76 | class GlancesUvicornServer(uvicorn.Server):
def install_signal_handlers(self):
pass
@contextlib.contextmanager
def run_in_thread(self, timeout=3):
FILL_FUNC_BODY | class GlancesUvicornServer(uvicorn.Server):
def install_signal_handlers(self):
pass
@contextlib.contextmanager
def run_in_thread(self, timeout=3):
FILL_FUNC_BODY | thread = threading.Thread(target=self.run)
thread.start()
try:
chrono = Timer(timeout)
while not self.started and not chrono.finished():
time.sleep(0.5)
# Timeout reached
# Something go wrong...
# The Uvicorn server shou... | thread = threading.Thread(target=self.run)
thread.start()
try:
chrono = Timer(timeout)
while not self.started and not chrono.finished():
time.sleep(0.5)
# Timeout reached
# Something go wrong...
# The Uvicorn server shou... | 42 | 65 | 151 | 216 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""RestFull API interface class."""
import os
import sys
import tempfile
from io import open
import webbrowser
from urllib.parse import urljoi... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""RestFull API interface class."""
import os
import sys
import tempfile
from io import open
import webbrowser
from urllib.parse import urljoi... |
21,449 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/outputs/glances_sparklines.py | 78,79 | 33,93 | get | Sparkline | 80,90 | 79,90 | class Sparkline(object):
"""Manage sparklines (see https://pypi.org/project/sparklines/)."""
def __init__(self, size, pre_char='[', post_char=']', unit_char='%', display_value=True):
# If the sparklines python module available ?
self.__available = sparklines_module
# Sparkline size
... | class Sparkline(object):
"""Manage sparklines (see https://pypi.org/project/sparklines/)."""
def __init__(self, size, pre_char='[', post_char=']', unit_char='%', display_value=True):
# If the sparklines python module available ?
self.__available = sparklines_module
# Sparkline size
... | ret = sparklines(self.percents, minimum=0, maximum=100)[0]
if self.__display_value:
percents_without_none = [x for x in self.percents if x is not None]
if len(percents_without_none) > 0:
ret = '{}{:5.1f}{}'.format(ret, percents_without_none[-1], self.__unit_char)
... | """Return the sparkline."""
ret = sparklines(self.percents, minimum=0, maximum=100)[0]
if self.__display_value:
percents_without_none = [x for x in self.percents if x is not None]
if len(percents_without_none) > 0:
ret = '{}{:5.1f}{}'.format(ret, percents_... | 47 | 408 | 170 | 578 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage sparklines for Glances output."""
from __future__ import unicode_literals
from __future__ import division
import sys
from glances.lo... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Manage sparklines for Glances output."""
from __future__ import unicode_literals
from __future__ import division
import sys
from glances.lo... |
21,451 | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances | /home/hieuvd/dung_repo/raw/stars_01/nicolargo_glances/glances/glances/outputs/glances_stdout_apidoc.py | 329,330 | 318,370 | update | GlancesStdoutApiDoc | 331,370 | 330,370 | class GlancesStdoutApiDoc(object):
"""This class manages the fields description display."""
def __init__(self, config=None, args=None):
# Init
self.config = config
self.args = args
def end(self):
pass
def update(self, stats, duration=1):
FILL_FUNC_BODY | class GlancesStdoutApiDoc(object):
"""This class manages the fields description display."""
def __init__(self, config=None, args=None):
# Init
self.config = config
self.args = args
def end(self):
pass
def update(self, stats, duration=1):
"""Display issue"""
FIL... |
# Display header
print(APIDOC_HEADER)
# Display API status
print_api_status()
# Display plugins list
print_plugins_list(sorted(stats._plugins))
# Loop over plugins
for plugin in sorted(stats._plugins):
stat = stats.get_plugin(plugin)
... | """Display issue"""
# Display header
print(APIDOC_HEADER)
# Display API status
print_api_status()
# Display plugins list
print_plugins_list(sorted(stats._plugins))
# Loop over plugins
for plugin in sorted(stats._plugins):
stat = sta... | 95 | 100 | 316 | 416 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Fields description interface class."""
from pprint import pformat
import json
import time
from glances import __apiversion__
from glances.... | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#
"""Fields description interface class."""
from pprint import pformat
import json
import time
from glances import __apiversion__
from glances.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.