meerschaum.utils.misc
Miscellaneous functions go here
1#! /usr/bin/env python 2# -*- coding: utf-8 -*- 3# vim:fenc=utf-8 4""" 5Miscellaneous functions go here 6""" 7 8from __future__ import annotations 9 10import os 11import sys 12import functools 13import pathlib 14from datetime import timedelta, datetime 15 16from meerschaum.utils.typing import ( 17 Union, 18 Any, 19 Callable, 20 Optional, 21 List, 22 Dict, 23 SuccessTuple, 24 Iterable, 25 PipesDict, 26 Tuple, 27 TYPE_CHECKING, 28) 29if TYPE_CHECKING: 30 import collections 31 32__pdoc__: Dict[str, bool] = { 33 'to_pandas_dtype': False, 34 'filter_unseen_df': False, 35 'add_missing_cols_to_df': False, 36 'parse_df_datetimes': False, 37 'df_from_literal': False, 38 'get_json_cols': False, 39 'get_unhashable_cols': False, 40 'enforce_dtypes': False, 41 'get_datetime_bound_from_df': False, 42 'df_is_chunk_generator': False, 43 'choices_docstring': False, 44 '_get_subaction_names': False, 45 'is_pipe_registered': False, 46 'replace_pipes_in_dict': False, 47 'round_time': False, 48} 49 50 51def add_method_to_class( 52 func: Callable[[Any], Any], 53 class_def: type, 54 method_name: Optional[str] = None, 55 keep_self: Optional[bool] = None, 56) -> Callable[[Any], Any]: 57 """ 58 Add function `func` to class `class_def`. 59 60 Parameters 61 ---------- 62 func: Callable[[Any], Any] 63 Function to be added as a method of the class 64 65 class_def: Class 66 Class to be modified. 67 68 method_name: Optional[str], default None 69 New name of the method. None will use func.__name__ (default). 70 71 Returns 72 ------- 73 The modified function object. 74 75 """ 76 from functools import wraps 77 78 is_class = isinstance(class_def, type) 79 80 @wraps(func) 81 def wrapper(self, *args, **kw): 82 return func(*args, **kw) 83 84 if method_name is None: 85 method_name = func.__name__ 86 87 setattr(class_def, method_name, ( 88 wrapper if ((is_class and keep_self is None) or keep_self is False) else func 89 ) 90 ) 91 92 return func 93 94 95def generate_password(length: int = 12) -> str: 96 """ 97 Generate a secure password of given length. 98 99 Parameters 100 ---------- 101 length: int, default 12 102 The length of the password. 103 104 Returns 105 ------- 106 A random password string. 107 """ 108 import secrets 109 import string 110 return ''.join((secrets.choice(string.ascii_letters + string.digits) for i in range(length))) 111 112 113def is_int(s: str) -> bool: 114 """ 115 Check if string is an int. 116 117 Parameters 118 ---------- 119 s: str 120 The string to be checked. 121 122 Returns 123 ------- 124 A bool indicating whether the string was able to be cast to an integer. 125 126 """ 127 try: 128 return float(s).is_integer() 129 except Exception: 130 return False 131 132 133def is_uuid(s: str) -> bool: 134 """ 135 Check if a string is a valid UUID. 136 137 Parameters 138 ---------- 139 s: str 140 The string to be checked. 141 142 Returns 143 ------- 144 A bool indicating whether the string is a valid UUID. 145 """ 146 import uuid 147 try: 148 uuid.UUID(str(s)) 149 return True 150 except Exception: 151 return False 152 153 154def string_to_dict(params_string: str) -> Dict[str, Any]: 155 """ 156 Parse a string into a dictionary. 157 158 If the string begins with '{', parse as JSON. Otherwise use simple parsing. 159 160 Parameters 161 ---------- 162 params_string: str 163 The string to be parsed. 164 165 Returns 166 ------- 167 The parsed dictionary. 168 169 Examples 170 -------- 171 >>> string_to_dict("a:1,b:2") 172 {'a': 1, 'b': 2} 173 >>> string_to_dict('{"a": 1, "b": 2}') 174 {'a': 1, 'b': 2} 175 176 """ 177 if not params_string: 178 return {} 179 180 import json 181 182 ### Kind of a weird edge case. 183 ### In the generated compose file, there is some weird escaping happening, 184 ### so the string to be parsed starts and ends with a single quote. 185 if ( 186 isinstance(params_string, str) 187 and len(params_string) > 4 188 and params_string[1] == "{" 189 and params_string[-2] == "}" 190 ): 191 return json.loads(params_string[1:-1]) 192 193 if str(params_string).startswith('{'): 194 return json.loads(params_string) 195 196 import ast 197 params_dict = {} 198 199 items = [] 200 bracket_level = 0 201 brace_level = 0 202 current_item = '' 203 in_quotes = False 204 quote_char = '' 205 206 i = 0 207 while i < len(params_string): 208 char = params_string[i] 209 210 if in_quotes: 211 if char == quote_char and (i == 0 or params_string[i-1] != '\\'): 212 in_quotes = False 213 else: 214 if char in ('"', "'"): 215 in_quotes = True 216 quote_char = char 217 elif char == '[': 218 bracket_level += 1 219 elif char == ']': 220 bracket_level -= 1 221 elif char == '{': 222 brace_level += 1 223 elif char == '}': 224 brace_level -= 1 225 elif char == ',' and bracket_level == 0 and brace_level == 0: 226 items.append(current_item) 227 current_item = '' 228 i += 1 229 continue 230 231 current_item += char 232 i += 1 233 234 if current_item: 235 items.append(current_item) 236 237 for param in items: 238 param = param.strip() 239 if not param: 240 continue 241 242 _keys = param.split(":", maxsplit=1) 243 if len(_keys) != 2: 244 continue 245 246 keys = _keys[:-1] 247 try: 248 val = ast.literal_eval(_keys[-1]) 249 except Exception: 250 val = str(_keys[-1]) 251 252 c = params_dict 253 for _k in keys[:-1]: 254 try: 255 k = ast.literal_eval(_k) 256 except Exception: 257 k = str(_k) 258 if k not in c: 259 c[k] = {} 260 c = c[k] 261 262 c[keys[-1]] = val 263 264 return params_dict 265 266 267def to_simple_dict(doc: Dict[str, Any]) -> str: 268 """ 269 Serialize a document dictionary in simple-dict format. 270 """ 271 import json 272 import ast 273 from meerschaum.utils.dtypes import json_serialize_value 274 275 def serialize_value(value): 276 if isinstance(value, str): 277 try: 278 evaluated = ast.literal_eval(value) 279 if not isinstance(evaluated, str): 280 return json.dumps(value, separators=(',', ':'), default=json_serialize_value) 281 return value 282 except (ValueError, SyntaxError, TypeError, MemoryError): 283 return value 284 285 return json.dumps(value, separators=(',', ':'), default=json_serialize_value) 286 287 return ','.join(f"{key}:{serialize_value(val)}" for key, val in doc.items()) 288 289 290def parse_config_substitution( 291 value: str, 292 leading_key: str = 'MRSM', 293 begin_key: str = '{', 294 end_key: str = '}', 295 delimeter: str = ':', 296) -> List[Any]: 297 """ 298 Parse Meerschaum substitution syntax 299 E.g. MRSM{value1:value2} => ['value1', 'value2'] 300 NOTE: Not currently used. See `search_and_substitute_config` in `meerschaum.config._read_yaml`. 301 """ 302 if not value.beginswith(leading_key): 303 return value 304 305 return leading_key[len(leading_key):][len():-1].split(delimeter) 306 307 308def edit_file( 309 path: Union[pathlib.Path, str], 310 default_editor: str = 'pyvim', 311 debug: bool = False 312) -> bool: 313 """ 314 Open a file for editing. 315 316 Attempt to launch the user's defined `$EDITOR`, otherwise use `pyvim`. 317 318 Parameters 319 ---------- 320 path: Union[pathlib.Path, str] 321 The path to the file to be edited. 322 323 default_editor: str, default 'pyvim' 324 If `$EDITOR` is not set, use this instead. 325 If `pyvim` is not installed, it will install it from PyPI. 326 327 debug: bool, default False 328 Verbosity toggle. 329 330 Returns 331 ------- 332 A bool indicating the file was successfully edited. 333 """ 334 from subprocess import call 335 from meerschaum.utils.debug import dprint 336 from meerschaum.utils.packages import run_python_package, attempt_import, package_venv 337 try: 338 EDITOR = os.environ.get('EDITOR', default_editor) 339 if debug: 340 dprint(f"Opening file '{path}' with editor '{EDITOR}'...") 341 from meerschaum.config.environment import get_child_env 342 rc = call([EDITOR, path], env=get_child_env()) 343 except Exception as e: ### can't open with default editors 344 if debug: 345 dprint(str(e)) 346 dprint('Failed to open file with system editor. Falling back to pyvim...') 347 pyvim = attempt_import('pyvim', lazy=False) 348 rc = run_python_package('pyvim', [path], venv=package_venv(pyvim), debug=debug) 349 return rc == 0 350 351 352def get_cols_lines(default_cols: int = 100, default_lines: int = 120) -> Tuple[int, int]: 353 """ 354 Determine the columns and lines in the terminal. 355 If they cannot be determined, return the default values (100 columns and 120 lines). 356 357 Parameters 358 ---------- 359 default_cols: int, default 100 360 If the columns cannot be determined, return this value. 361 362 default_lines: int, default 120 363 If the lines cannot be determined, return this value. 364 365 Returns 366 ------- 367 A tuple if integers for the columns and lines. 368 """ 369 try: 370 size = os.get_terminal_size() 371 _cols, _lines = size.columns, size.lines 372 except Exception: 373 _cols, _lines = ( 374 int(os.environ.get('COLUMNS', str(default_cols))), 375 int(os.environ.get('LINES', str(default_lines))), 376 ) 377 return _cols, _lines 378 379 380def iterate_chunks(iterable, chunksize: int, fillvalue: Optional[Any] = None): 381 """ 382 Iterate over a list in chunks. 383 https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks 384 385 Parameters 386 ---------- 387 iterable: Iterable[Any] 388 The iterable to iterate over in chunks. 389 390 chunksize: int 391 The size of chunks to iterate with. 392 393 fillvalue: Optional[Any], default None 394 If the chunks do not evenly divide into the iterable, pad the end with this value. 395 396 Returns 397 ------- 398 A generator of tuples of size `chunksize`. 399 400 """ 401 from itertools import zip_longest 402 args = [iter(iterable)] * chunksize 403 return zip_longest(*args, fillvalue=fillvalue) 404 405def sorted_dict(d: Dict[Any, Any]) -> Dict[Any, Any]: 406 """ 407 Sort a dictionary's values and return a new dictionary. 408 409 Parameters 410 ---------- 411 d: Dict[Any, Any] 412 The dictionary to be sorted. 413 414 Returns 415 ------- 416 A sorted dictionary. 417 418 Examples 419 -------- 420 >>> sorted_dict({'b': 1, 'a': 2}) 421 {'b': 1, 'a': 2} 422 >>> sorted_dict({'b': 2, 'a': 1}) 423 {'a': 1, 'b': 2} 424 425 """ 426 try: 427 return {key: value for key, value in sorted(d.items(), key=lambda item: item[1])} 428 except Exception: 429 return d 430 431 432def timed_input( 433 seconds: int = 10, 434 timeout_message: str = "", 435 prompt: str = "", 436 icon: bool = False, 437 **kw 438) -> Union[str, None]: 439 """ 440 Accept user input only for a brief period of time. 441 442 Parameters 443 ---------- 444 seconds: int, default 10 445 The number of seconds to wait. 446 447 timeout_message: str, default '' 448 The message to print after the window has elapsed. 449 450 prompt: str, default '' 451 The prompt to print during the window. 452 453 icon: bool, default False 454 If `True`, print the configured input icon. 455 456 457 Returns 458 ------- 459 The input string entered by the user. 460 461 """ 462 import signal, time 463 464 class TimeoutExpired(Exception): 465 """Raise this exception when the timeout is reached.""" 466 467 def alarm_handler(signum, frame): 468 raise TimeoutExpired 469 470 # set signal handler 471 signal.signal(signal.SIGALRM, alarm_handler) 472 signal.alarm(seconds) # produce SIGALRM in `timeout` seconds 473 474 try: 475 return input(prompt) 476 except TimeoutExpired: 477 return None 478 except (EOFError, RuntimeError): 479 try: 480 print(prompt) 481 time.sleep(seconds) 482 except TimeoutExpired: 483 return None 484 finally: 485 signal.alarm(0) # cancel alarm 486 487 488def enforce_gevent_monkey_patch(): 489 """ 490 Check if gevent monkey patching is enabled, and if not, then apply patching. 491 """ 492 from meerschaum.utils.packages import attempt_import 493 import socket 494 gevent, gevent_socket, gevent_monkey = attempt_import( 495 'gevent', 'gevent.socket', 'gevent.monkey' 496 ) 497 if not socket.socket is gevent_socket.socket: 498 gevent_monkey.patch_all() 499 500def is_valid_email(email: str) -> Union['re.Match', None]: 501 """ 502 Check whether a string is a valid email. 503 504 Parameters 505 ---------- 506 email: str 507 The string to be examined. 508 509 Returns 510 ------- 511 None if a string is not in email format, otherwise a `re.Match` object, which is truthy. 512 513 Examples 514 -------- 515 >>> is_valid_email('foo') 516 >>> is_valid_email('foo@foo.com') 517 <re.Match object; span=(0, 11), match='foo@foo.com'> 518 519 """ 520 import re 521 regex = r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' 522 return re.search(regex, email) 523 524 525def string_width(string: str, widest: bool = True) -> int: 526 """ 527 Calculate the width of a string, either by its widest or last line. 528 529 Parameters 530 ---------- 531 string: str: 532 The string to be examined. 533 534 widest: bool, default True 535 No longer used because `widest` is always assumed to be true. 536 537 Returns 538 ------- 539 An integer for the text's visual width. 540 541 Examples 542 -------- 543 >>> string_width('a') 544 1 545 >>> string_width('a\\nbc\\nd') 546 2 547 548 """ 549 def _widest(): 550 words = string.split('\n') 551 max_length = 0 552 for w in words: 553 length = len(w) 554 if length > max_length: 555 max_length = length 556 return max_length 557 558 return _widest() 559 560def _pyinstaller_traverse_dir( 561 directory: str, 562 ignore_patterns: Iterable[str] = ('.pyc', 'dist', 'build', '.git', '.log'), 563 include_dotfiles: bool = False 564) -> list: 565 """ 566 Recursively traverse a directory and return a list of its contents. 567 """ 568 paths = [] 569 _directory = pathlib.Path(directory) 570 571 def _found_pattern(name: str): 572 for pattern in ignore_patterns: 573 if pattern.replace('/', os.path.sep) in str(name): 574 return True 575 return False 576 577 for root, dirs, files in os.walk(_directory): 578 _root = str(root)[len(str(_directory.parent)):] 579 if _root.startswith(os.path.sep): 580 _root = _root[len(os.path.sep):] 581 if _root.startswith('.') and not include_dotfiles: 582 continue 583 ### ignore certain patterns 584 if _found_pattern(_root): 585 continue 586 587 for filename in files: 588 if filename.startswith('.') and not include_dotfiles: 589 continue 590 path = os.path.join(root, filename) 591 if _found_pattern(path): 592 continue 593 594 _path = str(path)[len(str(_directory.parent)):] 595 if _path.startswith(os.path.sep): 596 _path = _path[len(os.path.sep):] 597 _path = os.path.sep.join(_path.split(os.path.sep)[:-1]) 598 599 paths.append((path, _path)) 600 return paths 601 602 603def get_val_from_dict_path(d: Dict[Any, Any], path: Tuple[Any, ...]) -> Any: 604 """ 605 Get a value from a dictionary with a tuple of keys. 606 607 Parameters 608 ---------- 609 d: Dict[Any, Any] 610 The dictionary to search. 611 612 path: Tuple[Any, ...] 613 The path of keys to traverse. 614 615 Returns 616 ------- 617 The value from the end of the path. 618 """ 619 return functools.reduce(lambda di, key: di[key], path, d) 620 621 622def set_val_in_dict_path(d: Dict[Any, Any], path: Tuple[Any, ...], val: Any) -> None: 623 """ 624 Set a value in a dictionary with a tuple of keys. 625 626 Parameters 627 ---------- 628 d: Dict[Any, Any] 629 The dictionary to search. 630 631 path: Tuple[Any, ...] 632 The path of keys to traverse. 633 634 val: Any 635 The value to set at the end of the path. 636 """ 637 get_val_from_dict_path(d, path[:-1])[path[-1]] = val 638 639 640def replace_password(d: Dict[str, Any], replace_with: str = '*') -> Dict[str, Any]: 641 """ 642 Recursively replace passwords in a dictionary. 643 644 Parameters 645 ---------- 646 d: Dict[str, Any] 647 The dictionary to search through. 648 649 replace_with: str, default '*' 650 The string to replace each character of the password with. 651 652 Returns 653 ------- 654 Another dictionary where values to the keys `'password'` 655 are replaced with `replace_with` (`'*'`). 656 657 Examples 658 -------- 659 >>> replace_password({'a': 1}) 660 {'a': 1} 661 >>> replace_password({'password': '123'}) 662 {'password': '***'} 663 >>> replace_password({'nested': {'password': '123'}}) 664 {'nested': {'password': '***'}} 665 >>> replace_password({'password': '123'}, replace_with='!') 666 {'password': '!!!'} 667 668 """ 669 import copy 670 _d = copy.deepcopy(d) 671 for k, v in d.items(): 672 if isinstance(v, dict): 673 _d[k] = replace_password(v) 674 elif 'password' in str(k).lower(): 675 _d[k] = ''.join([replace_with for char in str(v)]) 676 elif str(k).lower() == 'uri': 677 from meerschaum.connectors.sql import SQLConnector 678 try: 679 uri_params = SQLConnector.parse_uri(v) 680 except Exception: 681 uri_params = None 682 if not uri_params: 683 continue 684 if not 'username' in uri_params or not 'password' in uri_params: 685 continue 686 _d[k] = v.replace( 687 uri_params['username'] + ':' + uri_params['password'], 688 uri_params['username'] + ':' + ''.join( 689 [replace_with for char in str(uri_params['password'])] 690 ) 691 ) 692 return _d 693 694 695def filter_arguments( 696 func: Callable[[Any], Any], 697 *args: Any, 698 **kwargs: Any 699) -> Tuple[Tuple[Any], Dict[str, Any]]: 700 """ 701 Filter out unsupported positional and keyword arguments. 702 703 Parameters 704 ---------- 705 func: Callable[[Any], Any] 706 The function to inspect. 707 708 *args: Any 709 Positional arguments to filter and pass to `func`. 710 711 **kwargs 712 Keyword arguments to filter and pass to `func`. 713 714 Returns 715 ------- 716 The `args` and `kwargs` accepted by `func`. 717 """ 718 args = filter_positionals(func, *args) 719 kwargs = filter_keywords(func, **kwargs) 720 return args, kwargs 721 722 723def filter_keywords( 724 func: Callable[[Any], Any], 725 **kw: Any 726) -> Dict[str, Any]: 727 """ 728 Filter out unsupported keyword arguments. 729 730 Parameters 731 ---------- 732 func: Callable[[Any], Any] 733 The function to inspect. 734 735 **kw: Any 736 The arguments to be filtered and passed into `func`. 737 738 Returns 739 ------- 740 A dictionary of keyword arguments accepted by `func`. 741 742 Examples 743 -------- 744 ```python 745 >>> def foo(a=1, b=2): 746 ... return a * b 747 >>> filter_keywords(foo, a=2, b=4, c=6) 748 {'a': 2, 'b': 4} 749 >>> foo(**filter_keywords(foo, **{'a': 2, 'b': 4, 'c': 6})) 750 8 751 ``` 752 753 """ 754 import inspect 755 func_params = inspect.signature(func).parameters 756 ### If the function has a **kw method, skip filtering. 757 for param, _type in func_params.items(): 758 if '**' in str(_type): 759 return kw 760 return {k: v for k, v in kw.items() if k in func_params} 761 762 763def filter_positionals( 764 func: Callable[[Any], Any], 765 *args: Any 766) -> Tuple[Any]: 767 """ 768 Filter out unsupported positional arguments. 769 770 Parameters 771 ---------- 772 func: Callable[[Any], Any] 773 The function to inspect. 774 775 *args: Any 776 The arguments to be filtered and passed into `func`. 777 NOTE: If the function signature expects more arguments than provided, 778 the missing slots will be filled with `None`. 779 780 Returns 781 ------- 782 A tuple of positional arguments accepted by `func`. 783 784 Examples 785 -------- 786 ```python 787 >>> def foo(a, b): 788 ... return a * b 789 >>> filter_positionals(foo, 2, 4, 6) 790 (2, 4) 791 >>> foo(*filter_positionals(foo, 2, 4, 6)) 792 8 793 ``` 794 795 """ 796 import inspect 797 from meerschaum.utils.warnings import warn 798 func_params = inspect.signature(func).parameters 799 acceptable_args: List[Any] = [] 800 801 def _warn_invalids(_num_invalid): 802 if _num_invalid > 0: 803 warn( 804 "Too few arguments were provided. " 805 + f"{_num_invalid} argument" 806 + ('s have ' if _num_invalid != 1 else " has ") 807 + " been filled with `None`.", 808 ) 809 810 num_invalid: int = 0 811 for i, (param, val) in enumerate(func_params.items()): 812 if '=' in str(val) or '*' in str(val): 813 _warn_invalids(num_invalid) 814 return tuple(acceptable_args) 815 816 try: 817 acceptable_args.append(args[i]) 818 except IndexError: 819 acceptable_args.append(None) 820 num_invalid += 1 821 822 _warn_invalids(num_invalid) 823 return tuple(acceptable_args) 824 825 826def dict_from_od(od: collections.OrderedDict) -> Dict[Any, Any]: 827 """ 828 Convert an ordered dict to a dict. 829 Does not mutate the original OrderedDict. 830 """ 831 from collections import OrderedDict 832 _d = dict(od) 833 for k, v in od.items(): 834 if isinstance(v, OrderedDict) or ( 835 issubclass(type(v), OrderedDict) 836 ): 837 _d[k] = dict_from_od(v) 838 return _d 839 840 841def remove_ansi(s: str) -> str: 842 """ 843 Remove ANSI escape characters from a string. 844 845 Parameters 846 ---------- 847 s: str: 848 The string to be cleaned. 849 850 Returns 851 ------- 852 A string with the ANSI characters removed. 853 854 Examples 855 -------- 856 >>> remove_ansi("\x1b[1;31mHello, World!\x1b[0m") 857 'Hello, World!' 858 859 """ 860 import re 861 return re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])').sub('', s) 862 863 864def get_connector_labels( 865 *types: str, 866 search_term: str = '', 867 ignore_exact_match = True, 868 _additional_options: Optional[List[str]] = None, 869) -> List[str]: 870 """ 871 Read connector labels from the configuration dictionary. 872 873 Parameters 874 ---------- 875 *types: str 876 The connector types. 877 If none are provided, use the defined types (`'sql'` and `'api'`) and `'plugin'`. 878 879 search_term: str, default '' 880 A filter on the connectors' labels. 881 882 ignore_exact_match: bool, default True 883 If `True`, skip a connector if the search_term is an exact match. 884 885 Returns 886 ------- 887 A list of the keys of defined connectors. 888 889 """ 890 from meerschaum.config import get_config 891 connectors = get_config('meerschaum', 'connectors') 892 893 _types = list(types) 894 if len(_types) == 0: 895 _types = list(connectors.keys()) + ['plugin'] 896 897 conns = [] 898 for t in _types: 899 if t == 'plugin': 900 from meerschaum.plugins import get_data_plugins 901 conns += [ 902 f'{t}:' + plugin.module.__name__.split('.')[-1] 903 for plugin in get_data_plugins() 904 ] 905 continue 906 conns += [ f'{t}:{label}' for label in connectors.get(t, {}) if label != 'default' ] 907 908 if _additional_options: 909 conns += _additional_options 910 911 possibilities = [ 912 c 913 for c in conns 914 if c.startswith(search_term) 915 and c != ( 916 search_term if ignore_exact_match else '' 917 ) 918 ] 919 return sorted(possibilities) 920 921 922def wget( 923 url: str, 924 dest: Optional[Union[str, 'pathlib.Path']] = None, 925 headers: Optional[Dict[str, Any]] = None, 926 color: bool = True, 927 debug: bool = False, 928 **kw: Any 929) -> 'pathlib.Path': 930 """ 931 Mimic `wget` with `requests`. 932 933 Parameters 934 ---------- 935 url: str 936 The URL to the resource to be downloaded. 937 938 dest: Optional[Union[str, pathlib.Path]], default None 939 The destination path of the downloaded file. 940 If `None`, save to the current directory. 941 942 color: bool, default True 943 If `debug` is `True`, print color output. 944 945 debug: bool, default False 946 Verbosity toggle. 947 948 Returns 949 ------- 950 The path to the downloaded file. 951 952 """ 953 from meerschaum.utils.warnings import warn, error 954 from meerschaum.utils.debug import dprint 955 import re, urllib.request 956 if headers is None: 957 headers = {} 958 request = urllib.request.Request(url, headers=headers) 959 if not color: 960 dprint = print 961 if debug: 962 dprint(f"Downloading from '{url}'...") 963 try: 964 response = urllib.request.urlopen(request) 965 except Exception as e: 966 import ssl 967 ssl._create_default_https_context = ssl._create_unverified_context 968 try: 969 response = urllib.request.urlopen(request) 970 except Exception as _e: 971 print(_e) 972 response = None 973 if response is None or response.code != 200: 974 error_msg = f"Failed to download from '{url}'." 975 if color: 976 error(error_msg) 977 else: 978 print(error_msg) 979 import sys 980 sys.exit(1) 981 982 d = response.headers.get('content-disposition', None) 983 fname = ( 984 re.findall("filename=(.+)", d)[0].strip('"') if d is not None 985 else url.split('/')[-1] 986 ) 987 988 if dest is None: 989 dest = pathlib.Path(os.path.join(os.getcwd(), fname)) 990 elif isinstance(dest, str): 991 dest = pathlib.Path(dest) 992 993 with open(dest, 'wb') as f: 994 f.write(response.fp.read()) 995 996 if debug: 997 dprint(f"Downloaded file '{dest}'.") 998 999 return dest 1000 1001 1002def async_wrap(func): 1003 """ 1004 Run a synchronous function as async. 1005 https://dev.to/0xbf/turn-sync-function-to-async-python-tips-58nn 1006 """ 1007 import asyncio 1008 from functools import wraps, partial 1009 1010 @wraps(func) 1011 async def run(*args, loop=None, executor=None, **kwargs): 1012 if loop is None: 1013 loop = asyncio.get_event_loop() 1014 pfunc = partial(func, *args, **kwargs) 1015 return await loop.run_in_executor(executor, pfunc) 1016 return run 1017 1018 1019def debug_trace(browser: bool = True): 1020 """ 1021 Open a web-based debugger to trace the execution of the program. 1022 1023 This is an alias import for `meerschaum.utils.debug.debug_trace`. 1024 """ 1025 from meerschaum.utils.debug import trace 1026 trace(browser=browser) 1027 1028 1029def items_str( 1030 items: List[Any], 1031 quotes: bool = True, 1032 quote_str: str = "'", 1033 commas: bool = True, 1034 comma_str: str = ',', 1035 and_: bool = True, 1036 and_str: str = 'and', 1037 oxford_comma: bool = True, 1038 spaces: bool = True, 1039 space_str = ' ', 1040) -> str: 1041 """ 1042 Return a formatted string if list items separated by commas. 1043 1044 Parameters 1045 ---------- 1046 items: [List[Any]] 1047 The items to be printed as an English list. 1048 1049 quotes: bool, default True 1050 If `True`, wrap items in quotes. 1051 1052 quote_str: str, default "'" 1053 If `quotes` is `True`, prepend and append each item with this string. 1054 1055 and_: bool, default True 1056 If `True`, include the word 'and' before the final item in the list. 1057 1058 and_str: str, default 'and' 1059 If `and_` is True, insert this string where 'and' normally would in and English list. 1060 1061 oxford_comma: bool, default True 1062 If `True`, include the Oxford Comma (comma before the final 'and'). 1063 Only applies when `and_` is `True`. 1064 1065 spaces: bool, default True 1066 If `True`, separate items with `space_str` 1067 1068 space_str: str, default ' ' 1069 If `spaces` is `True`, separate items with this string. 1070 1071 Returns 1072 ------- 1073 A string of the items as an English list. 1074 1075 Examples 1076 -------- 1077 >>> items_str([1,2,3]) 1078 "'1', '2', and '3'" 1079 >>> items_str([1,2,3], quotes=False) 1080 '1, 2, and 3' 1081 >>> items_str([1,2,3], and_=False) 1082 "'1', '2', '3'" 1083 >>> items_str([1,2,3], spaces=False, and_=False) 1084 "'1','2','3'" 1085 >>> items_str([1,2,3], oxford_comma=False) 1086 "'1', '2' and '3'" 1087 >>> items_str([1,2,3], quote_str=":") 1088 ':1:, :2:, and :3:' 1089 >>> items_str([1,2,3], and_str="or") 1090 "'1', '2', or '3'" 1091 >>> items_str([1,2,3], space_str="_") 1092 "'1',_'2',_and_'3'" 1093 1094 """ 1095 if not items: 1096 return '' 1097 1098 q = quote_str if quotes else '' 1099 s = space_str if spaces else '' 1100 a = and_str if and_ else '' 1101 c = comma_str if commas else '' 1102 1103 if len(items) == 1: 1104 return q + str(list(items)[0]) + q 1105 1106 if len(items) == 2: 1107 return q + str(list(items)[0]) + q + s + a + s + q + str(list(items)[1]) + q 1108 1109 sep = q + c + s + q 1110 output = q + sep.join(str(i) for i in items[:-1]) + q 1111 if oxford_comma: 1112 output += c 1113 output += s + a + (s if and_ else '') + q + str(items[-1]) + q 1114 return output 1115 1116 1117_TIMESPAN_UNITS = ( 1118 (1, 'second', 'seconds'), 1119 (60, 'minute', 'minutes'), 1120 (60 * 60, 'hour', 'hours'), 1121 (60 * 60 * 24, 'day', 'days'), 1122 (60 * 60 * 24 * 7, 'week', 'weeks'), 1123 (60 * 60 * 24 * 7 * 52, 'year', 'years'), 1124) 1125 1126 1127def _format_timespan(num_seconds: Union[int, float], max_units: int = 3) -> str: 1128 """ 1129 Format a number of seconds as English text (`1 year, 2 days and 3 hours`): the output of 1130 `humanfriendly.format_timespan()` (10.0) without the package, which is not a dependency. 1131 """ 1132 import re 1133 import decimal 1134 1135 def _number(count: Any) -> str: 1136 text = '%.2f' % float(count) 1137 text = re.sub('0+$', '', text) 1138 return re.sub(r'\.$', '', text) 1139 1140 def _unit(count: Any, singular: str, plural: str) -> str: 1141 return f"{count} {singular if float(count) == 1.0 else plural}" 1142 1143 if num_seconds < 60: 1144 return _unit(_number(num_seconds), 'second', 'seconds') 1145 1146 remaining = decimal.Decimal(str(num_seconds)) 1147 result = [] 1148 for divider, singular, plural in reversed(_TIMESPAN_UNITS): 1149 divider = decimal.Decimal(str(divider)) 1150 count = remaining / divider 1151 remaining %= divider 1152 count = int(count) if divider != 1 else _number(count) 1153 if count not in (0, '0'): 1154 result.append(_unit(count, singular, plural)) 1155 if len(result) == 1: 1156 return result[0] 1157 result = result[:max_units] 1158 if len(result) > 1: 1159 return ', '.join(result[:-1]) + ' and ' + result[-1] 1160 return result[0] if result else '' 1161 1162 1163def interval_str(delta: Union[timedelta, int], round_unit: bool = False) -> str: 1164 """ 1165 Return a human-readable string for a `timedelta` (or `int` minutes). 1166 1167 Parameters 1168 ---------- 1169 delta: Union[timedelta, int] 1170 The interval to print. If `delta` is an integer, assume it corresponds to minutes. 1171 1172 round_unit: bool, default False 1173 If `True`, round the output to a single unit. 1174 1175 Returns 1176 ------- 1177 A formatted string, fit for human eyes. 1178 """ 1179 from meerschaum.utils.packages import attempt_import 1180 if is_int(str(delta)) and not round_unit: 1181 return str(delta) 1182 1183 delta_seconds = ( 1184 delta.total_seconds() 1185 if hasattr(delta, 'total_seconds') 1186 else (delta * 60) 1187 ) 1188 1189 is_negative = delta_seconds < 0 1190 delta_seconds = abs(delta_seconds) 1191 replace_units = {} 1192 1193 if round_unit: 1194 if delta_seconds < 1: 1195 delta_seconds = round(delta_seconds, 2) 1196 elif delta_seconds < 60: 1197 delta_seconds = int(delta_seconds) 1198 elif delta_seconds < 3600: 1199 delta_seconds = int(delta_seconds / 60) * 60 1200 elif delta_seconds < 86400: 1201 delta_seconds = int(delta_seconds / 3600) * 3600 1202 elif delta_seconds < (86400 * 7): 1203 delta_seconds = int(delta_seconds / 86400) * 86400 1204 elif delta_seconds < (86400 * 7 * 4): 1205 delta_seconds = int(delta_seconds / (86400 * 7)) * (86400 * 7) 1206 elif delta_seconds < (86400 * 7 * 4 * 13): 1207 delta_seconds = int(delta_seconds / (86400 * 7 * 4)) * (86400 * 7) 1208 replace_units['weeks'] = 'months' 1209 else: 1210 delta_seconds = int(delta_seconds / (86400 * 364)) * (86400 * 364) 1211 1212 delta_str = _format_timespan(delta_seconds) 1213 if ',' in delta_str and round_unit: 1214 delta_str = delta_str.split(',')[0] 1215 elif ' and ' in delta_str and round_unit: 1216 delta_str = delta_str.split(' and ')[0] 1217 1218 for parsed_unit, replacement_unit in replace_units.items(): 1219 delta_str = delta_str.replace(parsed_unit, replacement_unit) 1220 1221 return delta_str + (' ago' if is_negative else '') 1222 1223 1224def is_docker_available() -> bool: 1225 """Check if we can connect to the Docker engine.""" 1226 import subprocess 1227 from meerschaum.config.environment import get_child_env 1228 try: 1229 has_docker = subprocess.call( 1230 ['docker', 'ps'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, 1231 env=get_child_env() 1232 ) == 0 1233 except Exception: 1234 has_docker = False 1235 return has_docker 1236 1237 1238def is_android() -> bool: 1239 """Return `True` if the current platform is Android.""" 1240 import sys 1241 return hasattr(sys, 'getandroidapilevel') 1242 1243 1244def is_bcp_available() -> bool: 1245 """Check if the MSSQL `bcp` utility is installed.""" 1246 import subprocess 1247 from meerschaum.config.environment import get_child_env 1248 1249 try: 1250 has_bcp = subprocess.call( 1251 ['bcp', '-v'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, 1252 env=get_child_env() 1253 ) == 0 1254 except Exception: 1255 has_bcp = False 1256 return has_bcp 1257 1258 1259def is_systemd_available() -> bool: 1260 """Check if running on systemd.""" 1261 return os.path.isdir('/run/systemd/system') 1262 1263 1264def is_tmux_available() -> bool: 1265 """ 1266 Check if `tmux` is installed. 1267 """ 1268 import subprocess 1269 from meerschaum.config.environment import get_child_env 1270 try: 1271 has_tmux = subprocess.call( 1272 ['tmux', '-V'], 1273 stdout=subprocess.DEVNULL, 1274 stderr=subprocess.STDOUT, 1275 env=get_child_env() 1276 ) == 0 1277 except FileNotFoundError: 1278 has_tmux = False 1279 except Exception: 1280 has_tmux = False 1281 return has_tmux 1282 1283def get_last_n_lines(file_name: str, N: int): 1284 """ 1285 https://thispointer.com/python-get-last-n-lines-of-a-text-file-like-tail-command/ 1286 """ 1287 # Create an empty list to keep the track of last N lines 1288 list_of_lines = [] 1289 # Open file for reading in binary mode 1290 with open(file_name, 'rb') as read_obj: 1291 # Move the cursor to the end of the file 1292 read_obj.seek(0, os.SEEK_END) 1293 # Create a buffer to keep the last read line 1294 buffer = bytearray() 1295 # Get the current position of pointer i.e eof 1296 pointer_location = read_obj.tell() 1297 # Loop till pointer reaches the top of the file 1298 while pointer_location >= 0: 1299 # Move the file pointer to the location pointed by pointer_location 1300 read_obj.seek(pointer_location) 1301 # Shift pointer location by -1 1302 pointer_location = pointer_location -1 1303 # read that byte / character 1304 new_byte = read_obj.read(1) 1305 # If the read byte is new line character then it means one line is read 1306 if new_byte == b'\n': 1307 # Save the line in list of lines 1308 list_of_lines.append(buffer.decode()[::-1]) 1309 # If the size of list reaches N, then return the reversed list 1310 if len(list_of_lines) == N: 1311 return list(reversed(list_of_lines)) 1312 # Reinitialize the byte array to save next line 1313 buffer = bytearray() 1314 else: 1315 # If last read character is not eol then add it in buffer 1316 buffer.extend(new_byte) 1317 # As file is read completely, if there is still data in buffer, then its first line. 1318 if len(buffer) > 0: 1319 list_of_lines.append(buffer.decode()[::-1]) 1320 # return the reversed list 1321 return list(reversed(list_of_lines)) 1322 1323 1324def tail(f, n, offset=None): 1325 """ 1326 https://stackoverflow.com/a/692616/9699829 1327 1328 Reads n lines from f with an offset of offset lines. The return 1329 value is a tuple in the form ``(lines, has_more)`` where `has_more` is 1330 an indicator that is `True` if there are more lines in the file. 1331 """ 1332 avg_line_length = 74 1333 to_read = n + (offset or 0) 1334 1335 while True: 1336 try: 1337 f.seek(-(avg_line_length * to_read), 2) 1338 except IOError: 1339 # woops. apparently file is smaller than what we want 1340 # to step back, go to the beginning instead 1341 f.seek(0) 1342 pos = f.tell() 1343 lines = f.read().splitlines() 1344 if len(lines) >= to_read or pos == 0: 1345 return lines[-to_read:offset and -offset or None], \ 1346 len(lines) > to_read or pos > 0 1347 avg_line_length *= 1.3 1348 1349 1350def truncate_string_sections(item: str, delimeter: str = '_', max_len: int = 128) -> str: 1351 """ 1352 Remove characters from each section of a string until the length is within the limit. 1353 1354 Parameters 1355 ---------- 1356 item: str 1357 The item name to be truncated. 1358 1359 delimeter: str, default '_' 1360 Split `item` by this string into several sections. 1361 1362 max_len: int, default 128 1363 The max acceptable length of the truncated version of `item`. 1364 1365 Returns 1366 ------- 1367 The truncated string. 1368 1369 Examples 1370 -------- 1371 >>> truncate_string_sections('abc_def_ghi', max_len=10) 1372 'ab_de_gh' 1373 1374 """ 1375 if len(item) < max_len: 1376 return item 1377 1378 def _shorten(s: str) -> str: 1379 return s[:-1] if len(s) > 1 else s 1380 1381 sections = list(enumerate(item.split(delimeter))) 1382 sorted_sections = sorted(sections, key=lambda x: (-1 * len(x[1]))) 1383 available_chars = max_len - len(sections) 1384 1385 _sections = [(i, s) for i, s in sorted_sections] 1386 _sections_len = sum([len(s) for i, s in _sections]) 1387 _old_sections_len = _sections_len 1388 while _sections_len > available_chars: 1389 _sections = [(i, _shorten(s)) for i, s in _sections] 1390 _old_sections_len = _sections_len 1391 _sections_len = sum([len(s) for i, s in _sections]) 1392 if _old_sections_len == _sections_len: 1393 raise Exception(f"String could not be truncated: '{item}'") 1394 1395 new_sections = sorted(_sections, key=lambda x: x[0]) 1396 return delimeter.join([s for i, s in new_sections]) 1397 1398 1399def truncate_text_for_display( 1400 text: str, 1401 max_length: int = 50, 1402 suffix: str = '…', 1403) -> str: 1404 """ 1405 Truncate a potentially long string for display purposes. 1406 1407 Parameters 1408 ---------- 1409 text: str 1410 The string to be truncated. 1411 1412 max_length: int, default 60 1413 The maximum length of `text` before truncation. 1414 1415 suffix: str, default '…' 1416 The string to append to the length of `text` to indicate truncation. 1417 1418 Returns 1419 ------- 1420 A string of length `max_length` or less. 1421 """ 1422 text_length = len(text) 1423 if text_length <= max_length: 1424 return text 1425 1426 suffix_length = len(suffix) 1427 1428 truncated_text = text[:max_length - suffix_length] 1429 return truncated_text + suffix 1430 1431 1432def separate_negation_values( 1433 vals: Union[List[str], Tuple[str]], 1434 negation_prefix: Optional[str] = None, 1435) -> Tuple[List[str], List[str]]: 1436 """ 1437 Separate the negated values from the positive ones. 1438 Return two lists: positive and negative values. 1439 1440 Parameters 1441 ---------- 1442 vals: Union[List[str], Tuple[str]] 1443 A list of strings to parse. 1444 1445 negation_prefix: Optional[str], default None 1446 Include values that start with this string in the second list. 1447 If `None`, use the system default (`_`). 1448 """ 1449 if negation_prefix is None: 1450 from meerschaum._internal.static import STATIC_CONFIG 1451 negation_prefix = STATIC_CONFIG['system']['fetch_pipes_keys']['negation_prefix'] 1452 _in_vals, _ex_vals = [], [] 1453 for v in vals: 1454 if str(v).startswith(negation_prefix): 1455 _ex_vals.append(str(v)[len(negation_prefix):]) 1456 else: 1457 _in_vals.append(v) 1458 1459 return _in_vals, _ex_vals 1460 1461 1462def get_in_ex_params(params: Optional[Dict[str, Any]]) -> Dict[str, Tuple[List[Any], List[Any]]]: 1463 """ 1464 Translate a params dictionary into lists of include- and exclude-values. 1465 1466 Parameters 1467 ---------- 1468 params: Optional[Dict[str, Any]] 1469 A params query dictionary. 1470 1471 Returns 1472 ------- 1473 A dictionary mapping keys to a tuple of lists for include and exclude values. 1474 1475 Examples 1476 -------- 1477 >>> get_in_ex_params({'a': ['b', 'c', '_d', 'e', '_f']}) 1478 {'a': (['b', 'c', 'e'], ['d', 'f'])} 1479 """ 1480 if not params: 1481 return {} 1482 return { 1483 col: separate_negation_values( 1484 ( 1485 val 1486 if isinstance(val, (list, tuple, set)) or hasattr(val, 'astype') 1487 else [val] 1488 ) 1489 ) 1490 for col, val in params.items() 1491 } 1492 1493 1494def flatten_list(list_: List[Any]) -> List[Any]: 1495 """ 1496 Recursively flatten a list. 1497 """ 1498 for item in list_: 1499 if isinstance(item, list): 1500 yield from flatten_list(item) 1501 else: 1502 yield item 1503 1504 1505def parse_arguments_str(args_str: str) -> Tuple[Tuple[Any], Dict[str, Any]]: 1506 """ 1507 Parse a string containing the text to be passed into a function 1508 and return a tuple of args, kwargs. 1509 1510 Parameters 1511 ---------- 1512 args_str: str 1513 The contents of the function parameter (as a string). 1514 1515 Returns 1516 ------- 1517 A tuple of args (tuple) and kwargs (dict[str, Any]). 1518 1519 Examples 1520 -------- 1521 >>> parse_arguments_str('123, 456, foo=789, bar="baz"') 1522 (123, 456), {'foo': 789, 'bar': 'baz'} 1523 """ 1524 import ast 1525 args = [] 1526 kwargs = {} 1527 1528 for part in args_str.split(','): 1529 if '=' in part: 1530 key, val = part.split('=', 1) 1531 kwargs[key.strip()] = ast.literal_eval(val) 1532 else: 1533 args.append(ast.literal_eval(part.strip())) 1534 1535 return tuple(args), kwargs 1536 1537 1538def make_symlink(src_path: 'pathlib.Path', dest_path: 'pathlib.Path') -> SuccessTuple: 1539 """ 1540 Wrap around `pathlib.Path.symlink_to`, but add support for Windows. 1541 1542 Parameters 1543 ---------- 1544 src_path: pathlib.Path 1545 The source path. 1546 1547 dest_path: pathlib.Path 1548 The destination path. 1549 1550 Returns 1551 ------- 1552 A SuccessTuple indicating success. 1553 """ 1554 if dest_path.exists() and dest_path.resolve() == src_path.resolve(): 1555 return True, "Symlink already exists." 1556 try: 1557 dest_path.symlink_to(src_path) 1558 success = True 1559 except Exception as e: 1560 success = False 1561 msg = str(e) 1562 if success: 1563 return success, "Success" 1564 1565 ### Failed to create a symlink. 1566 ### If we're not on Windows, return an error. 1567 import platform 1568 if platform.system() != 'Windows': 1569 return success, msg 1570 1571 try: 1572 import _winapi 1573 except ImportError: 1574 return False, "Unable to import _winapi." 1575 1576 if src_path.is_dir(): 1577 try: 1578 _winapi.CreateJunction(str(src_path), str(dest_path)) 1579 except Exception as e: 1580 return False, str(e) 1581 return True, "Success" 1582 1583 ### Last resort: copy the file on Windows. 1584 import shutil 1585 try: 1586 shutil.copy(src_path, dest_path) 1587 except Exception as e: 1588 return False, str(e) 1589 1590 return True, "Success" 1591 1592 1593def is_symlink(path: pathlib.Path) -> bool: 1594 """ 1595 Wrap `path.is_symlink()` but add support for Windows junctions. 1596 """ 1597 if path.is_symlink(): 1598 return True 1599 1600 import platform 1601 if platform.system() != 'Windows': 1602 return False 1603 try: 1604 return bool(os.readlink(path)) 1605 except OSError: 1606 return False 1607 1608 1609def parametrized(dec): 1610 """ 1611 A meta-decorator for allowing other decorator functions to have parameters. 1612 1613 https://stackoverflow.com/a/26151604/9699829 1614 """ 1615 def layer(*args, **kwargs): 1616 def repl(f): 1617 return dec(f, *args, **kwargs) 1618 return repl 1619 return layer 1620 1621 1622def safely_extract_tar(tarf: Any, output_dir: Union[str, 'pathlib.Path']) -> None: 1623 """ 1624 Safely extract a TAR file to a give directory. 1625 This defends against CVE-2007-4559. 1626 1627 Parameters 1628 ---------- 1629 tarf: file 1630 The TAR file opened with `tarfile.open(path, 'r:gz')`. 1631 1632 output_dir: Union[str, pathlib.Path] 1633 The output directory. 1634 """ 1635 1636 def is_within_directory(directory, target): 1637 abs_directory = os.path.abspath(directory) 1638 abs_target = os.path.abspath(target) 1639 prefix = os.path.commonprefix([abs_directory, abs_target]) 1640 return prefix == abs_directory 1641 1642 def safe_extract(tar, path=".", members=None, *, numeric_owner=False): 1643 for member in tar.getmembers(): 1644 member_path = os.path.join(path, member.name) 1645 if not is_within_directory(path, member_path): 1646 raise Exception("Attempted Path Traversal in Tar File") 1647 1648 tar.extractall(path=path, members=members, numeric_owner=numeric_owner) 1649 1650 return safe_extract(tarf, output_dir) 1651 1652 1653def to_snake_case(name: str) -> str: 1654 """ 1655 Return the given string in snake-case-style. 1656 1657 Parameters 1658 ---------- 1659 name: str 1660 The input text to convert to snake case. 1661 1662 Returns 1663 ------- 1664 A snake-case version of `name`. 1665 1666 Examples 1667 -------- 1668 >>> to_snake_case("HelloWorld!") 1669 'hello_world' 1670 >>> to_snake_case("This has spaces in it.") 1671 'this_has_spaces_in_it' 1672 >>> to_snake_case("already_in_snake_case") 1673 'already_in_snake_case' 1674 """ 1675 import re 1676 name = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', name) 1677 name = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', name) 1678 name = re.sub(r'[^\w\s]', '', name) 1679 name = re.sub(r'\s+', '_', name) 1680 return name.lower() 1681 1682 1683def get_directory_size(path: 'pathlib.Path') -> int: 1684 """ 1685 Return the cumulative size of a directory's files in bytes. 1686 https://stackoverflow.com/a/55659577/9699829 1687 """ 1688 return sum(file.stat().st_size for file in path.rglob('*')) 1689 1690 1691################## 1692# Legacy imports # 1693################## 1694 1695def choose_subaction(*args, **kwargs) -> Any: 1696 """ 1697 Placeholder function to prevent breaking legacy behavior. 1698 See `meerschaum.actions.choose_subaction`. 1699 """ 1700 from meerschaum.actions import choose_subaction as _choose_subactions 1701 return _choose_subactions(*args, **kwargs) 1702 1703 1704def print_options(*args, **kwargs) -> None: 1705 """ 1706 Placeholder function to prevent breaking legacy behavior. 1707 See `meerschaum.utils.formatting.print_options`. 1708 """ 1709 from meerschaum.utils.formatting import print_options as _print_options 1710 return _print_options(*args, **kwargs) 1711 1712 1713def to_pandas_dtype(*args, **kwargs) -> Any: 1714 """ 1715 Placeholder function to prevent breaking legacy behavior. 1716 See `meerschaum.utils.dtypes.to_pandas_dtype`. 1717 """ 1718 from meerschaum.utils.dtypes import to_pandas_dtype as _to_pandas_dtype 1719 return _to_pandas_dtype(*args, **kwargs) 1720 1721 1722def filter_unseen_df(*args, **kwargs) -> Any: 1723 """ 1724 Placeholder function to prevent breaking legacy behavior. 1725 See `meerschaum.utils.dataframe.filter_unseen_df`. 1726 """ 1727 from meerschaum.utils.dataframe import filter_unseen_df as real_function 1728 return real_function(*args, **kwargs) 1729 1730 1731def add_missing_cols_to_df(*args, **kwargs) -> Any: 1732 """ 1733 Placeholder function to prevent breaking legacy behavior. 1734 See `meerschaum.utils.dataframe.add_missing_cols_to_df`. 1735 """ 1736 from meerschaum.utils.dataframe import add_missing_cols_to_df as real_function 1737 return real_function(*args, **kwargs) 1738 1739 1740def parse_df_datetimes(*args, **kwargs) -> Any: 1741 """ 1742 Placeholder function to prevent breaking legacy behavior. 1743 See `meerschaum.utils.dataframe.parse_df_datetimes`. 1744 """ 1745 from meerschaum.utils.dataframe import parse_df_datetimes as real_function 1746 return real_function(*args, **kwargs) 1747 1748 1749def df_from_literal(*args, **kwargs) -> Any: 1750 """ 1751 Placeholder function to prevent breaking legacy behavior. 1752 See `meerschaum.utils.dataframe.df_from_literal`. 1753 """ 1754 from meerschaum.utils.dataframe import df_from_literal as real_function 1755 return real_function(*args, **kwargs) 1756 1757 1758def get_json_cols(*args, **kwargs) -> Any: 1759 """ 1760 Placeholder function to prevent breaking legacy behavior. 1761 See `meerschaum.utils.dataframe.get_json_cols`. 1762 """ 1763 from meerschaum.utils.dataframe import get_json_cols as real_function 1764 return real_function(*args, **kwargs) 1765 1766 1767def get_unhashable_cols(*args, **kwargs) -> Any: 1768 """ 1769 Placeholder function to prevent breaking legacy behavior. 1770 See `meerschaum.utils.dataframe.get_unhashable_cols`. 1771 """ 1772 from meerschaum.utils.dataframe import get_unhashable_cols as real_function 1773 return real_function(*args, **kwargs) 1774 1775 1776def enforce_dtypes(*args, **kwargs) -> Any: 1777 """ 1778 Placeholder function to prevent breaking legacy behavior. 1779 See `meerschaum.utils.dataframe.enforce_dtypes`. 1780 """ 1781 from meerschaum.utils.dataframe import enforce_dtypes as real_function 1782 return real_function(*args, **kwargs) 1783 1784 1785def get_datetime_bound_from_df(*args, **kwargs) -> Any: 1786 """ 1787 Placeholder function to prevent breaking legacy behavior. 1788 See `meerschaum.utils.dataframe.get_datetime_bound_from_df`. 1789 """ 1790 from meerschaum.utils.dataframe import get_datetime_bound_from_df as real_function 1791 return real_function(*args, **kwargs) 1792 1793 1794def df_is_chunk_generator(*args, **kwargs) -> Any: 1795 """ 1796 Placeholder function to prevent breaking legacy behavior. 1797 See `meerschaum.utils.dataframe.df_is_chunk_generator`. 1798 """ 1799 from meerschaum.utils.dataframe import df_is_chunk_generator as real_function 1800 return real_function(*args, **kwargs) 1801 1802 1803def choices_docstring(*args, **kwargs) -> Any: 1804 """ 1805 Placeholder function to prevent breaking legacy behavior. 1806 See `meerschaum.actions.choices_docstring`. 1807 """ 1808 from meerschaum.actions import choices_docstring as real_function 1809 return real_function(*args, **kwargs) 1810 1811 1812def _get_subaction_names(*args, **kwargs) -> Any: 1813 """ 1814 Placeholder function to prevent breaking legacy behavior. 1815 See `meerschaum.actions._get_subaction_names`. 1816 """ 1817 from meerschaum.actions import _get_subaction_names as real_function 1818 return real_function(*args, **kwargs) 1819 1820 1821def json_serialize_datetime(dt: datetime) -> Union[str, None]: 1822 """ 1823 Serialize a datetime object into JSON (ISO format string). 1824 1825 Examples 1826 -------- 1827 >>> import json 1828 >>> from datetime import datetime 1829 >>> json.dumps({'a': datetime(2022, 1, 1)}, default=json_serialize_datetime) 1830 '{"a": "2022-01-01T00:00:00Z"}' 1831 1832 """ 1833 from meerschaum.utils.dtypes import serialize_datetime 1834 return serialize_datetime(dt) 1835 1836 1837def replace_pipes_in_dict(*args, **kwargs): 1838 """ 1839 Placeholder function to prevent breaking legacy behavior. 1840 See `meerschaum.utils.pipes.replace_pipes_in_dict`. 1841 """ 1842 from meerschaum.utils.pipes import replace_pipes_in_dict 1843 return replace_pipes_in_dict(*args, **kwargs) 1844 1845 1846def is_pipe_registered(*args, **kwargs): 1847 """ 1848 Placeholder function to prevent breaking legacy behavior. 1849 See `meerschaum.utils.pipes.is_pipe_registered`. 1850 """ 1851 from meerschaum.utils.pipes import is_pipe_registered 1852 return is_pipe_registered(*args, **kwargs) 1853 1854 1855def round_time(*args, **kwargs): 1856 """ 1857 Placeholder function to prevent breaking legacy behavior. 1858 See `meerschaum.utils.dtypes.round_time`. 1859 """ 1860 from meerschaum.utils.dtypes import round_time 1861 return round_time(*args, **kwargs) 1862 1863 1864def flatten_pipes_dict(*args, **kwargs): 1865 """ 1866 Placeholder function to prevent breaking legacy behavior. 1867 See `meerschaum.utils.pipes.flatten_pipes_dict`. 1868 """ 1869 from meerschaum.utils.pipes import flatten_pipes_dict 1870 return flatten_pipes_dict(*args, **kwargs) 1871 1872 1873_current_module = sys.modules[__name__] 1874__all__ = tuple( 1875 name 1876 for name, obj in globals().items() 1877 if callable(obj) 1878 and name not in __pdoc__ 1879 and getattr(obj, '__module__', None) == _current_module.__name__ 1880 and not name.startswith('_') 1881)
52def add_method_to_class( 53 func: Callable[[Any], Any], 54 class_def: type, 55 method_name: Optional[str] = None, 56 keep_self: Optional[bool] = None, 57) -> Callable[[Any], Any]: 58 """ 59 Add function `func` to class `class_def`. 60 61 Parameters 62 ---------- 63 func: Callable[[Any], Any] 64 Function to be added as a method of the class 65 66 class_def: Class 67 Class to be modified. 68 69 method_name: Optional[str], default None 70 New name of the method. None will use func.__name__ (default). 71 72 Returns 73 ------- 74 The modified function object. 75 76 """ 77 from functools import wraps 78 79 is_class = isinstance(class_def, type) 80 81 @wraps(func) 82 def wrapper(self, *args, **kw): 83 return func(*args, **kw) 84 85 if method_name is None: 86 method_name = func.__name__ 87 88 setattr(class_def, method_name, ( 89 wrapper if ((is_class and keep_self is None) or keep_self is False) else func 90 ) 91 ) 92 93 return func
Add function func to class class_def.
Parameters
- func (Callable[[Any], Any]): Function to be added as a method of the class
- class_def (Class): Class to be modified.
- method_name (Optional[str], default None): New name of the method. None will use func.__name__ (default).
Returns
- The modified function object.
96def generate_password(length: int = 12) -> str: 97 """ 98 Generate a secure password of given length. 99 100 Parameters 101 ---------- 102 length: int, default 12 103 The length of the password. 104 105 Returns 106 ------- 107 A random password string. 108 """ 109 import secrets 110 import string 111 return ''.join((secrets.choice(string.ascii_letters + string.digits) for i in range(length)))
Generate a secure password of given length.
Parameters
- length (int, default 12): The length of the password.
Returns
- A random password string.
114def is_int(s: str) -> bool: 115 """ 116 Check if string is an int. 117 118 Parameters 119 ---------- 120 s: str 121 The string to be checked. 122 123 Returns 124 ------- 125 A bool indicating whether the string was able to be cast to an integer. 126 127 """ 128 try: 129 return float(s).is_integer() 130 except Exception: 131 return False
Check if string is an int.
Parameters
- s (str): The string to be checked.
Returns
- A bool indicating whether the string was able to be cast to an integer.
134def is_uuid(s: str) -> bool: 135 """ 136 Check if a string is a valid UUID. 137 138 Parameters 139 ---------- 140 s: str 141 The string to be checked. 142 143 Returns 144 ------- 145 A bool indicating whether the string is a valid UUID. 146 """ 147 import uuid 148 try: 149 uuid.UUID(str(s)) 150 return True 151 except Exception: 152 return False
Check if a string is a valid UUID.
Parameters
- s (str): The string to be checked.
Returns
- A bool indicating whether the string is a valid UUID.
155def string_to_dict(params_string: str) -> Dict[str, Any]: 156 """ 157 Parse a string into a dictionary. 158 159 If the string begins with '{', parse as JSON. Otherwise use simple parsing. 160 161 Parameters 162 ---------- 163 params_string: str 164 The string to be parsed. 165 166 Returns 167 ------- 168 The parsed dictionary. 169 170 Examples 171 -------- 172 >>> string_to_dict("a:1,b:2") 173 {'a': 1, 'b': 2} 174 >>> string_to_dict('{"a": 1, "b": 2}') 175 {'a': 1, 'b': 2} 176 177 """ 178 if not params_string: 179 return {} 180 181 import json 182 183 ### Kind of a weird edge case. 184 ### In the generated compose file, there is some weird escaping happening, 185 ### so the string to be parsed starts and ends with a single quote. 186 if ( 187 isinstance(params_string, str) 188 and len(params_string) > 4 189 and params_string[1] == "{" 190 and params_string[-2] == "}" 191 ): 192 return json.loads(params_string[1:-1]) 193 194 if str(params_string).startswith('{'): 195 return json.loads(params_string) 196 197 import ast 198 params_dict = {} 199 200 items = [] 201 bracket_level = 0 202 brace_level = 0 203 current_item = '' 204 in_quotes = False 205 quote_char = '' 206 207 i = 0 208 while i < len(params_string): 209 char = params_string[i] 210 211 if in_quotes: 212 if char == quote_char and (i == 0 or params_string[i-1] != '\\'): 213 in_quotes = False 214 else: 215 if char in ('"', "'"): 216 in_quotes = True 217 quote_char = char 218 elif char == '[': 219 bracket_level += 1 220 elif char == ']': 221 bracket_level -= 1 222 elif char == '{': 223 brace_level += 1 224 elif char == '}': 225 brace_level -= 1 226 elif char == ',' and bracket_level == 0 and brace_level == 0: 227 items.append(current_item) 228 current_item = '' 229 i += 1 230 continue 231 232 current_item += char 233 i += 1 234 235 if current_item: 236 items.append(current_item) 237 238 for param in items: 239 param = param.strip() 240 if not param: 241 continue 242 243 _keys = param.split(":", maxsplit=1) 244 if len(_keys) != 2: 245 continue 246 247 keys = _keys[:-1] 248 try: 249 val = ast.literal_eval(_keys[-1]) 250 except Exception: 251 val = str(_keys[-1]) 252 253 c = params_dict 254 for _k in keys[:-1]: 255 try: 256 k = ast.literal_eval(_k) 257 except Exception: 258 k = str(_k) 259 if k not in c: 260 c[k] = {} 261 c = c[k] 262 263 c[keys[-1]] = val 264 265 return params_dict
Parse a string into a dictionary.
If the string begins with '{', parse as JSON. Otherwise use simple parsing.
Parameters
- params_string (str): The string to be parsed.
Returns
- The parsed dictionary.
Examples
>>> string_to_dict("a:1,b:2")
{'a': 1, 'b': 2}
>>> string_to_dict('{"a": 1, "b": 2}')
{'a': 1, 'b': 2}
268def to_simple_dict(doc: Dict[str, Any]) -> str: 269 """ 270 Serialize a document dictionary in simple-dict format. 271 """ 272 import json 273 import ast 274 from meerschaum.utils.dtypes import json_serialize_value 275 276 def serialize_value(value): 277 if isinstance(value, str): 278 try: 279 evaluated = ast.literal_eval(value) 280 if not isinstance(evaluated, str): 281 return json.dumps(value, separators=(',', ':'), default=json_serialize_value) 282 return value 283 except (ValueError, SyntaxError, TypeError, MemoryError): 284 return value 285 286 return json.dumps(value, separators=(',', ':'), default=json_serialize_value) 287 288 return ','.join(f"{key}:{serialize_value(val)}" for key, val in doc.items())
Serialize a document dictionary in simple-dict format.
291def parse_config_substitution( 292 value: str, 293 leading_key: str = 'MRSM', 294 begin_key: str = '{', 295 end_key: str = '}', 296 delimeter: str = ':', 297) -> List[Any]: 298 """ 299 Parse Meerschaum substitution syntax 300 E.g. MRSM{value1:value2} => ['value1', 'value2'] 301 NOTE: Not currently used. See `search_and_substitute_config` in `meerschaum.config._read_yaml`. 302 """ 303 if not value.beginswith(leading_key): 304 return value 305 306 return leading_key[len(leading_key):][len():-1].split(delimeter)
Parse Meerschaum substitution syntax
E.g. MRSM{value1:value2} => ['value1', 'value2']
NOTE: Not currently used. See search_and_substitute_config in meerschaum.config._read_yaml.
309def edit_file( 310 path: Union[pathlib.Path, str], 311 default_editor: str = 'pyvim', 312 debug: bool = False 313) -> bool: 314 """ 315 Open a file for editing. 316 317 Attempt to launch the user's defined `$EDITOR`, otherwise use `pyvim`. 318 319 Parameters 320 ---------- 321 path: Union[pathlib.Path, str] 322 The path to the file to be edited. 323 324 default_editor: str, default 'pyvim' 325 If `$EDITOR` is not set, use this instead. 326 If `pyvim` is not installed, it will install it from PyPI. 327 328 debug: bool, default False 329 Verbosity toggle. 330 331 Returns 332 ------- 333 A bool indicating the file was successfully edited. 334 """ 335 from subprocess import call 336 from meerschaum.utils.debug import dprint 337 from meerschaum.utils.packages import run_python_package, attempt_import, package_venv 338 try: 339 EDITOR = os.environ.get('EDITOR', default_editor) 340 if debug: 341 dprint(f"Opening file '{path}' with editor '{EDITOR}'...") 342 from meerschaum.config.environment import get_child_env 343 rc = call([EDITOR, path], env=get_child_env()) 344 except Exception as e: ### can't open with default editors 345 if debug: 346 dprint(str(e)) 347 dprint('Failed to open file with system editor. Falling back to pyvim...') 348 pyvim = attempt_import('pyvim', lazy=False) 349 rc = run_python_package('pyvim', [path], venv=package_venv(pyvim), debug=debug) 350 return rc == 0
Open a file for editing.
Attempt to launch the user's defined $EDITOR, otherwise use pyvim.
Parameters
- path (Union[pathlib.Path, str]): The path to the file to be edited.
- default_editor (str, default 'pyvim'):
If
$EDITORis not set, use this instead. Ifpyvimis not installed, it will install it from PyPI. - debug (bool, default False): Verbosity toggle.
Returns
- A bool indicating the file was successfully edited.
353def get_cols_lines(default_cols: int = 100, default_lines: int = 120) -> Tuple[int, int]: 354 """ 355 Determine the columns and lines in the terminal. 356 If they cannot be determined, return the default values (100 columns and 120 lines). 357 358 Parameters 359 ---------- 360 default_cols: int, default 100 361 If the columns cannot be determined, return this value. 362 363 default_lines: int, default 120 364 If the lines cannot be determined, return this value. 365 366 Returns 367 ------- 368 A tuple if integers for the columns and lines. 369 """ 370 try: 371 size = os.get_terminal_size() 372 _cols, _lines = size.columns, size.lines 373 except Exception: 374 _cols, _lines = ( 375 int(os.environ.get('COLUMNS', str(default_cols))), 376 int(os.environ.get('LINES', str(default_lines))), 377 ) 378 return _cols, _lines
Determine the columns and lines in the terminal. If they cannot be determined, return the default values (100 columns and 120 lines).
Parameters
- default_cols (int, default 100): If the columns cannot be determined, return this value.
- default_lines (int, default 120): If the lines cannot be determined, return this value.
Returns
- A tuple if integers for the columns and lines.
381def iterate_chunks(iterable, chunksize: int, fillvalue: Optional[Any] = None): 382 """ 383 Iterate over a list in chunks. 384 https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks 385 386 Parameters 387 ---------- 388 iterable: Iterable[Any] 389 The iterable to iterate over in chunks. 390 391 chunksize: int 392 The size of chunks to iterate with. 393 394 fillvalue: Optional[Any], default None 395 If the chunks do not evenly divide into the iterable, pad the end with this value. 396 397 Returns 398 ------- 399 A generator of tuples of size `chunksize`. 400 401 """ 402 from itertools import zip_longest 403 args = [iter(iterable)] * chunksize 404 return zip_longest(*args, fillvalue=fillvalue)
Iterate over a list in chunks. https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks
Parameters
- iterable (Iterable[Any]): The iterable to iterate over in chunks.
- chunksize (int): The size of chunks to iterate with.
- fillvalue (Optional[Any], default None): If the chunks do not evenly divide into the iterable, pad the end with this value.
Returns
- A generator of tuples of size
chunksize.
406def sorted_dict(d: Dict[Any, Any]) -> Dict[Any, Any]: 407 """ 408 Sort a dictionary's values and return a new dictionary. 409 410 Parameters 411 ---------- 412 d: Dict[Any, Any] 413 The dictionary to be sorted. 414 415 Returns 416 ------- 417 A sorted dictionary. 418 419 Examples 420 -------- 421 >>> sorted_dict({'b': 1, 'a': 2}) 422 {'b': 1, 'a': 2} 423 >>> sorted_dict({'b': 2, 'a': 1}) 424 {'a': 1, 'b': 2} 425 426 """ 427 try: 428 return {key: value for key, value in sorted(d.items(), key=lambda item: item[1])} 429 except Exception: 430 return d
Sort a dictionary's values and return a new dictionary.
Parameters
- d (Dict[Any, Any]): The dictionary to be sorted.
Returns
- A sorted dictionary.
Examples
>>> sorted_dict({'b': 1, 'a': 2})
{'b': 1, 'a': 2}
>>> sorted_dict({'b': 2, 'a': 1})
{'a': 1, 'b': 2}
433def timed_input( 434 seconds: int = 10, 435 timeout_message: str = "", 436 prompt: str = "", 437 icon: bool = False, 438 **kw 439) -> Union[str, None]: 440 """ 441 Accept user input only for a brief period of time. 442 443 Parameters 444 ---------- 445 seconds: int, default 10 446 The number of seconds to wait. 447 448 timeout_message: str, default '' 449 The message to print after the window has elapsed. 450 451 prompt: str, default '' 452 The prompt to print during the window. 453 454 icon: bool, default False 455 If `True`, print the configured input icon. 456 457 458 Returns 459 ------- 460 The input string entered by the user. 461 462 """ 463 import signal, time 464 465 class TimeoutExpired(Exception): 466 """Raise this exception when the timeout is reached.""" 467 468 def alarm_handler(signum, frame): 469 raise TimeoutExpired 470 471 # set signal handler 472 signal.signal(signal.SIGALRM, alarm_handler) 473 signal.alarm(seconds) # produce SIGALRM in `timeout` seconds 474 475 try: 476 return input(prompt) 477 except TimeoutExpired: 478 return None 479 except (EOFError, RuntimeError): 480 try: 481 print(prompt) 482 time.sleep(seconds) 483 except TimeoutExpired: 484 return None 485 finally: 486 signal.alarm(0) # cancel alarm
Accept user input only for a brief period of time.
Parameters
- seconds (int, default 10): The number of seconds to wait.
- timeout_message (str, default ''): The message to print after the window has elapsed.
- prompt (str, default ''): The prompt to print during the window.
- icon (bool, default False):
If
True, print the configured input icon.
Returns
- The input string entered by the user.
489def enforce_gevent_monkey_patch(): 490 """ 491 Check if gevent monkey patching is enabled, and if not, then apply patching. 492 """ 493 from meerschaum.utils.packages import attempt_import 494 import socket 495 gevent, gevent_socket, gevent_monkey = attempt_import( 496 'gevent', 'gevent.socket', 'gevent.monkey' 497 ) 498 if not socket.socket is gevent_socket.socket: 499 gevent_monkey.patch_all()
Check if gevent monkey patching is enabled, and if not, then apply patching.
501def is_valid_email(email: str) -> Union['re.Match', None]: 502 """ 503 Check whether a string is a valid email. 504 505 Parameters 506 ---------- 507 email: str 508 The string to be examined. 509 510 Returns 511 ------- 512 None if a string is not in email format, otherwise a `re.Match` object, which is truthy. 513 514 Examples 515 -------- 516 >>> is_valid_email('foo') 517 >>> is_valid_email('foo@foo.com') 518 <re.Match object; span=(0, 11), match='foo@foo.com'> 519 520 """ 521 import re 522 regex = r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' 523 return re.search(regex, email)
Check whether a string is a valid email.
Parameters
- email (str): The string to be examined.
Returns
- None if a string is not in email format, otherwise a
re.Matchobject, which is truthy.
Examples
>>> is_valid_email('foo')
>>> is_valid_email('foo@foo.com')
<re.Match object; span=(0, 11), match='foo@foo.com'>
526def string_width(string: str, widest: bool = True) -> int: 527 """ 528 Calculate the width of a string, either by its widest or last line. 529 530 Parameters 531 ---------- 532 string: str: 533 The string to be examined. 534 535 widest: bool, default True 536 No longer used because `widest` is always assumed to be true. 537 538 Returns 539 ------- 540 An integer for the text's visual width. 541 542 Examples 543 -------- 544 >>> string_width('a') 545 1 546 >>> string_width('a\\nbc\\nd') 547 2 548 549 """ 550 def _widest(): 551 words = string.split('\n') 552 max_length = 0 553 for w in words: 554 length = len(w) 555 if length > max_length: 556 max_length = length 557 return max_length 558 559 return _widest()
Calculate the width of a string, either by its widest or last line.
Parameters
- string (str:): The string to be examined.
- widest (bool, default True):
No longer used because
widestis always assumed to be true.
Returns
- An integer for the text's visual width.
Examples
>>> string_width('a')
1
>>> string_width('a\nbc\nd')
2
604def get_val_from_dict_path(d: Dict[Any, Any], path: Tuple[Any, ...]) -> Any: 605 """ 606 Get a value from a dictionary with a tuple of keys. 607 608 Parameters 609 ---------- 610 d: Dict[Any, Any] 611 The dictionary to search. 612 613 path: Tuple[Any, ...] 614 The path of keys to traverse. 615 616 Returns 617 ------- 618 The value from the end of the path. 619 """ 620 return functools.reduce(lambda di, key: di[key], path, d)
Get a value from a dictionary with a tuple of keys.
Parameters
- d (Dict[Any, Any]): The dictionary to search.
- path (Tuple[Any, ...]): The path of keys to traverse.
Returns
- The value from the end of the path.
623def set_val_in_dict_path(d: Dict[Any, Any], path: Tuple[Any, ...], val: Any) -> None: 624 """ 625 Set a value in a dictionary with a tuple of keys. 626 627 Parameters 628 ---------- 629 d: Dict[Any, Any] 630 The dictionary to search. 631 632 path: Tuple[Any, ...] 633 The path of keys to traverse. 634 635 val: Any 636 The value to set at the end of the path. 637 """ 638 get_val_from_dict_path(d, path[:-1])[path[-1]] = val
Set a value in a dictionary with a tuple of keys.
Parameters
- d (Dict[Any, Any]): The dictionary to search.
- path (Tuple[Any, ...]): The path of keys to traverse.
- val (Any): The value to set at the end of the path.
641def replace_password(d: Dict[str, Any], replace_with: str = '*') -> Dict[str, Any]: 642 """ 643 Recursively replace passwords in a dictionary. 644 645 Parameters 646 ---------- 647 d: Dict[str, Any] 648 The dictionary to search through. 649 650 replace_with: str, default '*' 651 The string to replace each character of the password with. 652 653 Returns 654 ------- 655 Another dictionary where values to the keys `'password'` 656 are replaced with `replace_with` (`'*'`). 657 658 Examples 659 -------- 660 >>> replace_password({'a': 1}) 661 {'a': 1} 662 >>> replace_password({'password': '123'}) 663 {'password': '***'} 664 >>> replace_password({'nested': {'password': '123'}}) 665 {'nested': {'password': '***'}} 666 >>> replace_password({'password': '123'}, replace_with='!') 667 {'password': '!!!'} 668 669 """ 670 import copy 671 _d = copy.deepcopy(d) 672 for k, v in d.items(): 673 if isinstance(v, dict): 674 _d[k] = replace_password(v) 675 elif 'password' in str(k).lower(): 676 _d[k] = ''.join([replace_with for char in str(v)]) 677 elif str(k).lower() == 'uri': 678 from meerschaum.connectors.sql import SQLConnector 679 try: 680 uri_params = SQLConnector.parse_uri(v) 681 except Exception: 682 uri_params = None 683 if not uri_params: 684 continue 685 if not 'username' in uri_params or not 'password' in uri_params: 686 continue 687 _d[k] = v.replace( 688 uri_params['username'] + ':' + uri_params['password'], 689 uri_params['username'] + ':' + ''.join( 690 [replace_with for char in str(uri_params['password'])] 691 ) 692 ) 693 return _d
Recursively replace passwords in a dictionary.
Parameters
- d (Dict[str, Any]): The dictionary to search through.
- replace_with (str, default '*'): The string to replace each character of the password with.
Returns
- Another dictionary where values to the keys
'password' - are replaced with
replace_with('*').
Examples
>>> replace_password({'a': 1})
{'a': 1}
>>> replace_password({'password': '123'})
{'password': '***'}
>>> replace_password({'nested': {'password': '123'}})
{'nested': {'password': '***'}}
>>> replace_password({'password': '123'}, replace_with='!')
{'password': '!!!'}
696def filter_arguments( 697 func: Callable[[Any], Any], 698 *args: Any, 699 **kwargs: Any 700) -> Tuple[Tuple[Any], Dict[str, Any]]: 701 """ 702 Filter out unsupported positional and keyword arguments. 703 704 Parameters 705 ---------- 706 func: Callable[[Any], Any] 707 The function to inspect. 708 709 *args: Any 710 Positional arguments to filter and pass to `func`. 711 712 **kwargs 713 Keyword arguments to filter and pass to `func`. 714 715 Returns 716 ------- 717 The `args` and `kwargs` accepted by `func`. 718 """ 719 args = filter_positionals(func, *args) 720 kwargs = filter_keywords(func, **kwargs) 721 return args, kwargs
Filter out unsupported positional and keyword arguments.
Parameters
- func (Callable[[Any], Any]): The function to inspect.
- *args (Any):
Positional arguments to filter and pass to
func. - **kwargs: Keyword arguments to filter and pass to
func.
Returns
- The
argsandkwargsaccepted byfunc.
724def filter_keywords( 725 func: Callable[[Any], Any], 726 **kw: Any 727) -> Dict[str, Any]: 728 """ 729 Filter out unsupported keyword arguments. 730 731 Parameters 732 ---------- 733 func: Callable[[Any], Any] 734 The function to inspect. 735 736 **kw: Any 737 The arguments to be filtered and passed into `func`. 738 739 Returns 740 ------- 741 A dictionary of keyword arguments accepted by `func`. 742 743 Examples 744 -------- 745 ```python 746 >>> def foo(a=1, b=2): 747 ... return a * b 748 >>> filter_keywords(foo, a=2, b=4, c=6) 749 {'a': 2, 'b': 4} 750 >>> foo(**filter_keywords(foo, **{'a': 2, 'b': 4, 'c': 6})) 751 8 752 ``` 753 754 """ 755 import inspect 756 func_params = inspect.signature(func).parameters 757 ### If the function has a **kw method, skip filtering. 758 for param, _type in func_params.items(): 759 if '**' in str(_type): 760 return kw 761 return {k: v for k, v in kw.items() if k in func_params}
Filter out unsupported keyword arguments.
Parameters
- func (Callable[[Any], Any]): The function to inspect.
- **kw (Any):
The arguments to be filtered and passed into
func.
Returns
- A dictionary of keyword arguments accepted by
func.
Examples
>>> def foo(a=1, b=2):
... return a * b
>>> filter_keywords(foo, a=2, b=4, c=6)
{'a': 2, 'b': 4}
>>> foo(**filter_keywords(foo, **{'a': 2, 'b': 4, 'c': 6}))
8
764def filter_positionals( 765 func: Callable[[Any], Any], 766 *args: Any 767) -> Tuple[Any]: 768 """ 769 Filter out unsupported positional arguments. 770 771 Parameters 772 ---------- 773 func: Callable[[Any], Any] 774 The function to inspect. 775 776 *args: Any 777 The arguments to be filtered and passed into `func`. 778 NOTE: If the function signature expects more arguments than provided, 779 the missing slots will be filled with `None`. 780 781 Returns 782 ------- 783 A tuple of positional arguments accepted by `func`. 784 785 Examples 786 -------- 787 ```python 788 >>> def foo(a, b): 789 ... return a * b 790 >>> filter_positionals(foo, 2, 4, 6) 791 (2, 4) 792 >>> foo(*filter_positionals(foo, 2, 4, 6)) 793 8 794 ``` 795 796 """ 797 import inspect 798 from meerschaum.utils.warnings import warn 799 func_params = inspect.signature(func).parameters 800 acceptable_args: List[Any] = [] 801 802 def _warn_invalids(_num_invalid): 803 if _num_invalid > 0: 804 warn( 805 "Too few arguments were provided. " 806 + f"{_num_invalid} argument" 807 + ('s have ' if _num_invalid != 1 else " has ") 808 + " been filled with `None`.", 809 ) 810 811 num_invalid: int = 0 812 for i, (param, val) in enumerate(func_params.items()): 813 if '=' in str(val) or '*' in str(val): 814 _warn_invalids(num_invalid) 815 return tuple(acceptable_args) 816 817 try: 818 acceptable_args.append(args[i]) 819 except IndexError: 820 acceptable_args.append(None) 821 num_invalid += 1 822 823 _warn_invalids(num_invalid) 824 return tuple(acceptable_args)
Filter out unsupported positional arguments.
Parameters
- func (Callable[[Any], Any]): The function to inspect.
- *args (Any):
The arguments to be filtered and passed into
func. NOTE: If the function signature expects more arguments than provided, the missing slots will be filled withNone.
Returns
- A tuple of positional arguments accepted by
func.
Examples
>>> def foo(a, b):
... return a * b
>>> filter_positionals(foo, 2, 4, 6)
(2, 4)
>>> foo(*filter_positionals(foo, 2, 4, 6))
8
827def dict_from_od(od: collections.OrderedDict) -> Dict[Any, Any]: 828 """ 829 Convert an ordered dict to a dict. 830 Does not mutate the original OrderedDict. 831 """ 832 from collections import OrderedDict 833 _d = dict(od) 834 for k, v in od.items(): 835 if isinstance(v, OrderedDict) or ( 836 issubclass(type(v), OrderedDict) 837 ): 838 _d[k] = dict_from_od(v) 839 return _d
Convert an ordered dict to a dict. Does not mutate the original OrderedDict.
842def remove_ansi(s: str) -> str: 843 """ 844 Remove ANSI escape characters from a string. 845 846 Parameters 847 ---------- 848 s: str: 849 The string to be cleaned. 850 851 Returns 852 ------- 853 A string with the ANSI characters removed. 854 855 Examples 856 -------- 857 >>> remove_ansi("\x1b[1;31mHello, World!\x1b[0m") 858 'Hello, World!' 859 860 """ 861 import re 862 return re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])').sub('', s)
Remove ANSI escape characters from a string.
Parameters
- s (str:): The string to be cleaned.
Returns
- A string with the ANSI characters removed.
Examples
>>> remove_ansi("[1;31mHello, World![0m")
'Hello, World!'
865def get_connector_labels( 866 *types: str, 867 search_term: str = '', 868 ignore_exact_match = True, 869 _additional_options: Optional[List[str]] = None, 870) -> List[str]: 871 """ 872 Read connector labels from the configuration dictionary. 873 874 Parameters 875 ---------- 876 *types: str 877 The connector types. 878 If none are provided, use the defined types (`'sql'` and `'api'`) and `'plugin'`. 879 880 search_term: str, default '' 881 A filter on the connectors' labels. 882 883 ignore_exact_match: bool, default True 884 If `True`, skip a connector if the search_term is an exact match. 885 886 Returns 887 ------- 888 A list of the keys of defined connectors. 889 890 """ 891 from meerschaum.config import get_config 892 connectors = get_config('meerschaum', 'connectors') 893 894 _types = list(types) 895 if len(_types) == 0: 896 _types = list(connectors.keys()) + ['plugin'] 897 898 conns = [] 899 for t in _types: 900 if t == 'plugin': 901 from meerschaum.plugins import get_data_plugins 902 conns += [ 903 f'{t}:' + plugin.module.__name__.split('.')[-1] 904 for plugin in get_data_plugins() 905 ] 906 continue 907 conns += [ f'{t}:{label}' for label in connectors.get(t, {}) if label != 'default' ] 908 909 if _additional_options: 910 conns += _additional_options 911 912 possibilities = [ 913 c 914 for c in conns 915 if c.startswith(search_term) 916 and c != ( 917 search_term if ignore_exact_match else '' 918 ) 919 ] 920 return sorted(possibilities)
Read connector labels from the configuration dictionary.
Parameters
- *types (str):
The connector types.
If none are provided, use the defined types (
'sql'and'api') and'plugin'. - search_term (str, default ''): A filter on the connectors' labels.
- ignore_exact_match (bool, default True):
If
True, skip a connector if the search_term is an exact match.
Returns
- A list of the keys of defined connectors.
923def wget( 924 url: str, 925 dest: Optional[Union[str, 'pathlib.Path']] = None, 926 headers: Optional[Dict[str, Any]] = None, 927 color: bool = True, 928 debug: bool = False, 929 **kw: Any 930) -> 'pathlib.Path': 931 """ 932 Mimic `wget` with `requests`. 933 934 Parameters 935 ---------- 936 url: str 937 The URL to the resource to be downloaded. 938 939 dest: Optional[Union[str, pathlib.Path]], default None 940 The destination path of the downloaded file. 941 If `None`, save to the current directory. 942 943 color: bool, default True 944 If `debug` is `True`, print color output. 945 946 debug: bool, default False 947 Verbosity toggle. 948 949 Returns 950 ------- 951 The path to the downloaded file. 952 953 """ 954 from meerschaum.utils.warnings import warn, error 955 from meerschaum.utils.debug import dprint 956 import re, urllib.request 957 if headers is None: 958 headers = {} 959 request = urllib.request.Request(url, headers=headers) 960 if not color: 961 dprint = print 962 if debug: 963 dprint(f"Downloading from '{url}'...") 964 try: 965 response = urllib.request.urlopen(request) 966 except Exception as e: 967 import ssl 968 ssl._create_default_https_context = ssl._create_unverified_context 969 try: 970 response = urllib.request.urlopen(request) 971 except Exception as _e: 972 print(_e) 973 response = None 974 if response is None or response.code != 200: 975 error_msg = f"Failed to download from '{url}'." 976 if color: 977 error(error_msg) 978 else: 979 print(error_msg) 980 import sys 981 sys.exit(1) 982 983 d = response.headers.get('content-disposition', None) 984 fname = ( 985 re.findall("filename=(.+)", d)[0].strip('"') if d is not None 986 else url.split('/')[-1] 987 ) 988 989 if dest is None: 990 dest = pathlib.Path(os.path.join(os.getcwd(), fname)) 991 elif isinstance(dest, str): 992 dest = pathlib.Path(dest) 993 994 with open(dest, 'wb') as f: 995 f.write(response.fp.read()) 996 997 if debug: 998 dprint(f"Downloaded file '{dest}'.") 999 1000 return dest
Mimic wget with requests.
Parameters
- url (str): The URL to the resource to be downloaded.
- dest (Optional[Union[str, pathlib.Path]], default None):
The destination path of the downloaded file.
If
None, save to the current directory. - color (bool, default True):
If
debugisTrue, print color output. - debug (bool, default False): Verbosity toggle.
Returns
- The path to the downloaded file.
1003def async_wrap(func): 1004 """ 1005 Run a synchronous function as async. 1006 https://dev.to/0xbf/turn-sync-function-to-async-python-tips-58nn 1007 """ 1008 import asyncio 1009 from functools import wraps, partial 1010 1011 @wraps(func) 1012 async def run(*args, loop=None, executor=None, **kwargs): 1013 if loop is None: 1014 loop = asyncio.get_event_loop() 1015 pfunc = partial(func, *args, **kwargs) 1016 return await loop.run_in_executor(executor, pfunc) 1017 return run
Run a synchronous function as async. https://dev.to/0xbf/turn-sync-function-to-async-python-tips-58nn
1020def debug_trace(browser: bool = True): 1021 """ 1022 Open a web-based debugger to trace the execution of the program. 1023 1024 This is an alias import for `meerschaum.utils.debug.debug_trace`. 1025 """ 1026 from meerschaum.utils.debug import trace 1027 trace(browser=browser)
Open a web-based debugger to trace the execution of the program.
This is an alias import for meerschaum.utils.debug.debug_trace.
1030def items_str( 1031 items: List[Any], 1032 quotes: bool = True, 1033 quote_str: str = "'", 1034 commas: bool = True, 1035 comma_str: str = ',', 1036 and_: bool = True, 1037 and_str: str = 'and', 1038 oxford_comma: bool = True, 1039 spaces: bool = True, 1040 space_str = ' ', 1041) -> str: 1042 """ 1043 Return a formatted string if list items separated by commas. 1044 1045 Parameters 1046 ---------- 1047 items: [List[Any]] 1048 The items to be printed as an English list. 1049 1050 quotes: bool, default True 1051 If `True`, wrap items in quotes. 1052 1053 quote_str: str, default "'" 1054 If `quotes` is `True`, prepend and append each item with this string. 1055 1056 and_: bool, default True 1057 If `True`, include the word 'and' before the final item in the list. 1058 1059 and_str: str, default 'and' 1060 If `and_` is True, insert this string where 'and' normally would in and English list. 1061 1062 oxford_comma: bool, default True 1063 If `True`, include the Oxford Comma (comma before the final 'and'). 1064 Only applies when `and_` is `True`. 1065 1066 spaces: bool, default True 1067 If `True`, separate items with `space_str` 1068 1069 space_str: str, default ' ' 1070 If `spaces` is `True`, separate items with this string. 1071 1072 Returns 1073 ------- 1074 A string of the items as an English list. 1075 1076 Examples 1077 -------- 1078 >>> items_str([1,2,3]) 1079 "'1', '2', and '3'" 1080 >>> items_str([1,2,3], quotes=False) 1081 '1, 2, and 3' 1082 >>> items_str([1,2,3], and_=False) 1083 "'1', '2', '3'" 1084 >>> items_str([1,2,3], spaces=False, and_=False) 1085 "'1','2','3'" 1086 >>> items_str([1,2,3], oxford_comma=False) 1087 "'1', '2' and '3'" 1088 >>> items_str([1,2,3], quote_str=":") 1089 ':1:, :2:, and :3:' 1090 >>> items_str([1,2,3], and_str="or") 1091 "'1', '2', or '3'" 1092 >>> items_str([1,2,3], space_str="_") 1093 "'1',_'2',_and_'3'" 1094 1095 """ 1096 if not items: 1097 return '' 1098 1099 q = quote_str if quotes else '' 1100 s = space_str if spaces else '' 1101 a = and_str if and_ else '' 1102 c = comma_str if commas else '' 1103 1104 if len(items) == 1: 1105 return q + str(list(items)[0]) + q 1106 1107 if len(items) == 2: 1108 return q + str(list(items)[0]) + q + s + a + s + q + str(list(items)[1]) + q 1109 1110 sep = q + c + s + q 1111 output = q + sep.join(str(i) for i in items[:-1]) + q 1112 if oxford_comma: 1113 output += c 1114 output += s + a + (s if and_ else '') + q + str(items[-1]) + q 1115 return output
Return a formatted string if list items separated by commas.
Parameters
- items ([List[Any]]): The items to be printed as an English list.
- quotes (bool, default True):
If
True, wrap items in quotes. - quote_str (str, default "'"):
If
quotesisTrue, prepend and append each item with this string. - and_ (bool, default True):
If
True, include the word 'and' before the final item in the list. - and_str (str, default 'and'):
If
and_is True, insert this string where 'and' normally would in and English list. - oxford_comma (bool, default True):
If
True, include the Oxford Comma (comma before the final 'and'). Only applies whenand_isTrue. - spaces (bool, default True):
If
True, separate items withspace_str - space_str (str, default ' '):
If
spacesisTrue, separate items with this string.
Returns
- A string of the items as an English list.
Examples
>>> items_str([1,2,3])
"'1', '2', and '3'"
>>> items_str([1,2,3], quotes=False)
'1, 2, and 3'
>>> items_str([1,2,3], and_=False)
"'1', '2', '3'"
>>> items_str([1,2,3], spaces=False, and_=False)
"'1','2','3'"
>>> items_str([1,2,3], oxford_comma=False)
"'1', '2' and '3'"
>>> items_str([1,2,3], quote_str=":")
':1:, :2:, and :3:'
>>> items_str([1,2,3], and_str="or")
"'1', '2', or '3'"
>>> items_str([1,2,3], space_str="_")
"'1',_'2',_and_'3'"
1164def interval_str(delta: Union[timedelta, int], round_unit: bool = False) -> str: 1165 """ 1166 Return a human-readable string for a `timedelta` (or `int` minutes). 1167 1168 Parameters 1169 ---------- 1170 delta: Union[timedelta, int] 1171 The interval to print. If `delta` is an integer, assume it corresponds to minutes. 1172 1173 round_unit: bool, default False 1174 If `True`, round the output to a single unit. 1175 1176 Returns 1177 ------- 1178 A formatted string, fit for human eyes. 1179 """ 1180 from meerschaum.utils.packages import attempt_import 1181 if is_int(str(delta)) and not round_unit: 1182 return str(delta) 1183 1184 delta_seconds = ( 1185 delta.total_seconds() 1186 if hasattr(delta, 'total_seconds') 1187 else (delta * 60) 1188 ) 1189 1190 is_negative = delta_seconds < 0 1191 delta_seconds = abs(delta_seconds) 1192 replace_units = {} 1193 1194 if round_unit: 1195 if delta_seconds < 1: 1196 delta_seconds = round(delta_seconds, 2) 1197 elif delta_seconds < 60: 1198 delta_seconds = int(delta_seconds) 1199 elif delta_seconds < 3600: 1200 delta_seconds = int(delta_seconds / 60) * 60 1201 elif delta_seconds < 86400: 1202 delta_seconds = int(delta_seconds / 3600) * 3600 1203 elif delta_seconds < (86400 * 7): 1204 delta_seconds = int(delta_seconds / 86400) * 86400 1205 elif delta_seconds < (86400 * 7 * 4): 1206 delta_seconds = int(delta_seconds / (86400 * 7)) * (86400 * 7) 1207 elif delta_seconds < (86400 * 7 * 4 * 13): 1208 delta_seconds = int(delta_seconds / (86400 * 7 * 4)) * (86400 * 7) 1209 replace_units['weeks'] = 'months' 1210 else: 1211 delta_seconds = int(delta_seconds / (86400 * 364)) * (86400 * 364) 1212 1213 delta_str = _format_timespan(delta_seconds) 1214 if ',' in delta_str and round_unit: 1215 delta_str = delta_str.split(',')[0] 1216 elif ' and ' in delta_str and round_unit: 1217 delta_str = delta_str.split(' and ')[0] 1218 1219 for parsed_unit, replacement_unit in replace_units.items(): 1220 delta_str = delta_str.replace(parsed_unit, replacement_unit) 1221 1222 return delta_str + (' ago' if is_negative else '')
Return a human-readable string for a timedelta (or int minutes).
Parameters
- delta (Union[timedelta, int]):
The interval to print. If
deltais an integer, assume it corresponds to minutes. - round_unit (bool, default False):
If
True, round the output to a single unit.
Returns
- A formatted string, fit for human eyes.
1225def is_docker_available() -> bool: 1226 """Check if we can connect to the Docker engine.""" 1227 import subprocess 1228 from meerschaum.config.environment import get_child_env 1229 try: 1230 has_docker = subprocess.call( 1231 ['docker', 'ps'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, 1232 env=get_child_env() 1233 ) == 0 1234 except Exception: 1235 has_docker = False 1236 return has_docker
Check if we can connect to the Docker engine.
1239def is_android() -> bool: 1240 """Return `True` if the current platform is Android.""" 1241 import sys 1242 return hasattr(sys, 'getandroidapilevel')
Return True if the current platform is Android.
1245def is_bcp_available() -> bool: 1246 """Check if the MSSQL `bcp` utility is installed.""" 1247 import subprocess 1248 from meerschaum.config.environment import get_child_env 1249 1250 try: 1251 has_bcp = subprocess.call( 1252 ['bcp', '-v'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, 1253 env=get_child_env() 1254 ) == 0 1255 except Exception: 1256 has_bcp = False 1257 return has_bcp
Check if the MSSQL bcp utility is installed.
1260def is_systemd_available() -> bool: 1261 """Check if running on systemd.""" 1262 return os.path.isdir('/run/systemd/system')
Check if running on systemd.
1265def is_tmux_available() -> bool: 1266 """ 1267 Check if `tmux` is installed. 1268 """ 1269 import subprocess 1270 from meerschaum.config.environment import get_child_env 1271 try: 1272 has_tmux = subprocess.call( 1273 ['tmux', '-V'], 1274 stdout=subprocess.DEVNULL, 1275 stderr=subprocess.STDOUT, 1276 env=get_child_env() 1277 ) == 0 1278 except FileNotFoundError: 1279 has_tmux = False 1280 except Exception: 1281 has_tmux = False 1282 return has_tmux
Check if tmux is installed.
1284def get_last_n_lines(file_name: str, N: int): 1285 """ 1286 https://thispointer.com/python-get-last-n-lines-of-a-text-file-like-tail-command/ 1287 """ 1288 # Create an empty list to keep the track of last N lines 1289 list_of_lines = [] 1290 # Open file for reading in binary mode 1291 with open(file_name, 'rb') as read_obj: 1292 # Move the cursor to the end of the file 1293 read_obj.seek(0, os.SEEK_END) 1294 # Create a buffer to keep the last read line 1295 buffer = bytearray() 1296 # Get the current position of pointer i.e eof 1297 pointer_location = read_obj.tell() 1298 # Loop till pointer reaches the top of the file 1299 while pointer_location >= 0: 1300 # Move the file pointer to the location pointed by pointer_location 1301 read_obj.seek(pointer_location) 1302 # Shift pointer location by -1 1303 pointer_location = pointer_location -1 1304 # read that byte / character 1305 new_byte = read_obj.read(1) 1306 # If the read byte is new line character then it means one line is read 1307 if new_byte == b'\n': 1308 # Save the line in list of lines 1309 list_of_lines.append(buffer.decode()[::-1]) 1310 # If the size of list reaches N, then return the reversed list 1311 if len(list_of_lines) == N: 1312 return list(reversed(list_of_lines)) 1313 # Reinitialize the byte array to save next line 1314 buffer = bytearray() 1315 else: 1316 # If last read character is not eol then add it in buffer 1317 buffer.extend(new_byte) 1318 # As file is read completely, if there is still data in buffer, then its first line. 1319 if len(buffer) > 0: 1320 list_of_lines.append(buffer.decode()[::-1]) 1321 # return the reversed list 1322 return list(reversed(list_of_lines))
1325def tail(f, n, offset=None): 1326 """ 1327 https://stackoverflow.com/a/692616/9699829 1328 1329 Reads n lines from f with an offset of offset lines. The return 1330 value is a tuple in the form ``(lines, has_more)`` where `has_more` is 1331 an indicator that is `True` if there are more lines in the file. 1332 """ 1333 avg_line_length = 74 1334 to_read = n + (offset or 0) 1335 1336 while True: 1337 try: 1338 f.seek(-(avg_line_length * to_read), 2) 1339 except IOError: 1340 # woops. apparently file is smaller than what we want 1341 # to step back, go to the beginning instead 1342 f.seek(0) 1343 pos = f.tell() 1344 lines = f.read().splitlines() 1345 if len(lines) >= to_read or pos == 0: 1346 return lines[-to_read:offset and -offset or None], \ 1347 len(lines) > to_read or pos > 0 1348 avg_line_length *= 1.3
https://stackoverflow.com/a/692616/9699829
Reads n lines from f with an offset of offset lines. The return
value is a tuple in the form (lines, has_more) where has_more is
an indicator that is True if there are more lines in the file.
1351def truncate_string_sections(item: str, delimeter: str = '_', max_len: int = 128) -> str: 1352 """ 1353 Remove characters from each section of a string until the length is within the limit. 1354 1355 Parameters 1356 ---------- 1357 item: str 1358 The item name to be truncated. 1359 1360 delimeter: str, default '_' 1361 Split `item` by this string into several sections. 1362 1363 max_len: int, default 128 1364 The max acceptable length of the truncated version of `item`. 1365 1366 Returns 1367 ------- 1368 The truncated string. 1369 1370 Examples 1371 -------- 1372 >>> truncate_string_sections('abc_def_ghi', max_len=10) 1373 'ab_de_gh' 1374 1375 """ 1376 if len(item) < max_len: 1377 return item 1378 1379 def _shorten(s: str) -> str: 1380 return s[:-1] if len(s) > 1 else s 1381 1382 sections = list(enumerate(item.split(delimeter))) 1383 sorted_sections = sorted(sections, key=lambda x: (-1 * len(x[1]))) 1384 available_chars = max_len - len(sections) 1385 1386 _sections = [(i, s) for i, s in sorted_sections] 1387 _sections_len = sum([len(s) for i, s in _sections]) 1388 _old_sections_len = _sections_len 1389 while _sections_len > available_chars: 1390 _sections = [(i, _shorten(s)) for i, s in _sections] 1391 _old_sections_len = _sections_len 1392 _sections_len = sum([len(s) for i, s in _sections]) 1393 if _old_sections_len == _sections_len: 1394 raise Exception(f"String could not be truncated: '{item}'") 1395 1396 new_sections = sorted(_sections, key=lambda x: x[0]) 1397 return delimeter.join([s for i, s in new_sections])
Remove characters from each section of a string until the length is within the limit.
Parameters
- item (str): The item name to be truncated.
- delimeter (str, default '_'):
Split
itemby this string into several sections. - max_len (int, default 128):
The max acceptable length of the truncated version of
item.
Returns
- The truncated string.
Examples
>>> truncate_string_sections('abc_def_ghi', max_len=10)
'ab_de_gh'
1400def truncate_text_for_display( 1401 text: str, 1402 max_length: int = 50, 1403 suffix: str = '…', 1404) -> str: 1405 """ 1406 Truncate a potentially long string for display purposes. 1407 1408 Parameters 1409 ---------- 1410 text: str 1411 The string to be truncated. 1412 1413 max_length: int, default 60 1414 The maximum length of `text` before truncation. 1415 1416 suffix: str, default '…' 1417 The string to append to the length of `text` to indicate truncation. 1418 1419 Returns 1420 ------- 1421 A string of length `max_length` or less. 1422 """ 1423 text_length = len(text) 1424 if text_length <= max_length: 1425 return text 1426 1427 suffix_length = len(suffix) 1428 1429 truncated_text = text[:max_length - suffix_length] 1430 return truncated_text + suffix
Truncate a potentially long string for display purposes.
Parameters
- text (str): The string to be truncated.
- max_length (int, default 60):
The maximum length of
textbefore truncation. - suffix (str, default '…'):
The string to append to the length of
textto indicate truncation.
Returns
- A string of length
max_lengthor less.
1433def separate_negation_values( 1434 vals: Union[List[str], Tuple[str]], 1435 negation_prefix: Optional[str] = None, 1436) -> Tuple[List[str], List[str]]: 1437 """ 1438 Separate the negated values from the positive ones. 1439 Return two lists: positive and negative values. 1440 1441 Parameters 1442 ---------- 1443 vals: Union[List[str], Tuple[str]] 1444 A list of strings to parse. 1445 1446 negation_prefix: Optional[str], default None 1447 Include values that start with this string in the second list. 1448 If `None`, use the system default (`_`). 1449 """ 1450 if negation_prefix is None: 1451 from meerschaum._internal.static import STATIC_CONFIG 1452 negation_prefix = STATIC_CONFIG['system']['fetch_pipes_keys']['negation_prefix'] 1453 _in_vals, _ex_vals = [], [] 1454 for v in vals: 1455 if str(v).startswith(negation_prefix): 1456 _ex_vals.append(str(v)[len(negation_prefix):]) 1457 else: 1458 _in_vals.append(v) 1459 1460 return _in_vals, _ex_vals
Separate the negated values from the positive ones. Return two lists: positive and negative values.
Parameters
- vals (Union[List[str], Tuple[str]]): A list of strings to parse.
- negation_prefix (Optional[str], default None):
Include values that start with this string in the second list.
If
None, use the system default (_).
1463def get_in_ex_params(params: Optional[Dict[str, Any]]) -> Dict[str, Tuple[List[Any], List[Any]]]: 1464 """ 1465 Translate a params dictionary into lists of include- and exclude-values. 1466 1467 Parameters 1468 ---------- 1469 params: Optional[Dict[str, Any]] 1470 A params query dictionary. 1471 1472 Returns 1473 ------- 1474 A dictionary mapping keys to a tuple of lists for include and exclude values. 1475 1476 Examples 1477 -------- 1478 >>> get_in_ex_params({'a': ['b', 'c', '_d', 'e', '_f']}) 1479 {'a': (['b', 'c', 'e'], ['d', 'f'])} 1480 """ 1481 if not params: 1482 return {} 1483 return { 1484 col: separate_negation_values( 1485 ( 1486 val 1487 if isinstance(val, (list, tuple, set)) or hasattr(val, 'astype') 1488 else [val] 1489 ) 1490 ) 1491 for col, val in params.items() 1492 }
Translate a params dictionary into lists of include- and exclude-values.
Parameters
- params (Optional[Dict[str, Any]]): A params query dictionary.
Returns
- A dictionary mapping keys to a tuple of lists for include and exclude values.
Examples
>>> get_in_ex_params({'a': ['b', 'c', '_d', 'e', '_f']})
{'a': (['b', 'c', 'e'], ['d', 'f'])}
1495def flatten_list(list_: List[Any]) -> List[Any]: 1496 """ 1497 Recursively flatten a list. 1498 """ 1499 for item in list_: 1500 if isinstance(item, list): 1501 yield from flatten_list(item) 1502 else: 1503 yield item
Recursively flatten a list.
1506def parse_arguments_str(args_str: str) -> Tuple[Tuple[Any], Dict[str, Any]]: 1507 """ 1508 Parse a string containing the text to be passed into a function 1509 and return a tuple of args, kwargs. 1510 1511 Parameters 1512 ---------- 1513 args_str: str 1514 The contents of the function parameter (as a string). 1515 1516 Returns 1517 ------- 1518 A tuple of args (tuple) and kwargs (dict[str, Any]). 1519 1520 Examples 1521 -------- 1522 >>> parse_arguments_str('123, 456, foo=789, bar="baz"') 1523 (123, 456), {'foo': 789, 'bar': 'baz'} 1524 """ 1525 import ast 1526 args = [] 1527 kwargs = {} 1528 1529 for part in args_str.split(','): 1530 if '=' in part: 1531 key, val = part.split('=', 1) 1532 kwargs[key.strip()] = ast.literal_eval(val) 1533 else: 1534 args.append(ast.literal_eval(part.strip())) 1535 1536 return tuple(args), kwargs
Parse a string containing the text to be passed into a function and return a tuple of args, kwargs.
Parameters
- args_str (str): The contents of the function parameter (as a string).
Returns
- A tuple of args (tuple) and kwargs (dict[str, Any]).
Examples
>>> parse_arguments_str('123, 456, foo=789, bar="baz"')
(123, 456), {'foo': 789, 'bar': 'baz'}
1539def make_symlink(src_path: 'pathlib.Path', dest_path: 'pathlib.Path') -> SuccessTuple: 1540 """ 1541 Wrap around `pathlib.Path.symlink_to`, but add support for Windows. 1542 1543 Parameters 1544 ---------- 1545 src_path: pathlib.Path 1546 The source path. 1547 1548 dest_path: pathlib.Path 1549 The destination path. 1550 1551 Returns 1552 ------- 1553 A SuccessTuple indicating success. 1554 """ 1555 if dest_path.exists() and dest_path.resolve() == src_path.resolve(): 1556 return True, "Symlink already exists." 1557 try: 1558 dest_path.symlink_to(src_path) 1559 success = True 1560 except Exception as e: 1561 success = False 1562 msg = str(e) 1563 if success: 1564 return success, "Success" 1565 1566 ### Failed to create a symlink. 1567 ### If we're not on Windows, return an error. 1568 import platform 1569 if platform.system() != 'Windows': 1570 return success, msg 1571 1572 try: 1573 import _winapi 1574 except ImportError: 1575 return False, "Unable to import _winapi." 1576 1577 if src_path.is_dir(): 1578 try: 1579 _winapi.CreateJunction(str(src_path), str(dest_path)) 1580 except Exception as e: 1581 return False, str(e) 1582 return True, "Success" 1583 1584 ### Last resort: copy the file on Windows. 1585 import shutil 1586 try: 1587 shutil.copy(src_path, dest_path) 1588 except Exception as e: 1589 return False, str(e) 1590 1591 return True, "Success"
Wrap around pathlib.Path.symlink_to, but add support for Windows.
Parameters
- src_path (pathlib.Path): The source path.
- dest_path (pathlib.Path): The destination path.
Returns
- A SuccessTuple indicating success.
1594def is_symlink(path: pathlib.Path) -> bool: 1595 """ 1596 Wrap `path.is_symlink()` but add support for Windows junctions. 1597 """ 1598 if path.is_symlink(): 1599 return True 1600 1601 import platform 1602 if platform.system() != 'Windows': 1603 return False 1604 try: 1605 return bool(os.readlink(path)) 1606 except OSError: 1607 return False
Wrap path.is_symlink() but add support for Windows junctions.
1610def parametrized(dec): 1611 """ 1612 A meta-decorator for allowing other decorator functions to have parameters. 1613 1614 https://stackoverflow.com/a/26151604/9699829 1615 """ 1616 def layer(*args, **kwargs): 1617 def repl(f): 1618 return dec(f, *args, **kwargs) 1619 return repl 1620 return layer
A meta-decorator for allowing other decorator functions to have parameters.
1623def safely_extract_tar(tarf: Any, output_dir: Union[str, 'pathlib.Path']) -> None: 1624 """ 1625 Safely extract a TAR file to a give directory. 1626 This defends against CVE-2007-4559. 1627 1628 Parameters 1629 ---------- 1630 tarf: file 1631 The TAR file opened with `tarfile.open(path, 'r:gz')`. 1632 1633 output_dir: Union[str, pathlib.Path] 1634 The output directory. 1635 """ 1636 1637 def is_within_directory(directory, target): 1638 abs_directory = os.path.abspath(directory) 1639 abs_target = os.path.abspath(target) 1640 prefix = os.path.commonprefix([abs_directory, abs_target]) 1641 return prefix == abs_directory 1642 1643 def safe_extract(tar, path=".", members=None, *, numeric_owner=False): 1644 for member in tar.getmembers(): 1645 member_path = os.path.join(path, member.name) 1646 if not is_within_directory(path, member_path): 1647 raise Exception("Attempted Path Traversal in Tar File") 1648 1649 tar.extractall(path=path, members=members, numeric_owner=numeric_owner) 1650 1651 return safe_extract(tarf, output_dir)
Safely extract a TAR file to a give directory. This defends against CVE-2007-4559.
Parameters
- tarf (file):
The TAR file opened with
tarfile.open(path, 'r:gz'). - output_dir (Union[str, pathlib.Path]): The output directory.
1654def to_snake_case(name: str) -> str: 1655 """ 1656 Return the given string in snake-case-style. 1657 1658 Parameters 1659 ---------- 1660 name: str 1661 The input text to convert to snake case. 1662 1663 Returns 1664 ------- 1665 A snake-case version of `name`. 1666 1667 Examples 1668 -------- 1669 >>> to_snake_case("HelloWorld!") 1670 'hello_world' 1671 >>> to_snake_case("This has spaces in it.") 1672 'this_has_spaces_in_it' 1673 >>> to_snake_case("already_in_snake_case") 1674 'already_in_snake_case' 1675 """ 1676 import re 1677 name = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', name) 1678 name = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', name) 1679 name = re.sub(r'[^\w\s]', '', name) 1680 name = re.sub(r'\s+', '_', name) 1681 return name.lower()
Return the given string in snake-case-style.
Parameters
- name (str): The input text to convert to snake case.
Returns
- A snake-case version of
name.
Examples
>>> to_snake_case("HelloWorld!")
'hello_world'
>>> to_snake_case("This has spaces in it.")
'this_has_spaces_in_it'
>>> to_snake_case("already_in_snake_case")
'already_in_snake_case'
1684def get_directory_size(path: 'pathlib.Path') -> int: 1685 """ 1686 Return the cumulative size of a directory's files in bytes. 1687 https://stackoverflow.com/a/55659577/9699829 1688 """ 1689 return sum(file.stat().st_size for file in path.rglob('*'))
Return the cumulative size of a directory's files in bytes. https://stackoverflow.com/a/55659577/9699829
1696def choose_subaction(*args, **kwargs) -> Any: 1697 """ 1698 Placeholder function to prevent breaking legacy behavior. 1699 See `meerschaum.actions.choose_subaction`. 1700 """ 1701 from meerschaum.actions import choose_subaction as _choose_subactions 1702 return _choose_subactions(*args, **kwargs)
Placeholder function to prevent breaking legacy behavior.
See meerschaum.actions.choose_subaction.
1705def print_options(*args, **kwargs) -> None: 1706 """ 1707 Placeholder function to prevent breaking legacy behavior. 1708 See `meerschaum.utils.formatting.print_options`. 1709 """ 1710 from meerschaum.utils.formatting import print_options as _print_options 1711 return _print_options(*args, **kwargs)
Placeholder function to prevent breaking legacy behavior.
See meerschaum.utils.formatting.print_options.
1822def json_serialize_datetime(dt: datetime) -> Union[str, None]: 1823 """ 1824 Serialize a datetime object into JSON (ISO format string). 1825 1826 Examples 1827 -------- 1828 >>> import json 1829 >>> from datetime import datetime 1830 >>> json.dumps({'a': datetime(2022, 1, 1)}, default=json_serialize_datetime) 1831 '{"a": "2022-01-01T00:00:00Z"}' 1832 1833 """ 1834 from meerschaum.utils.dtypes import serialize_datetime 1835 return serialize_datetime(dt)
Serialize a datetime object into JSON (ISO format string).
Examples
>>> import json
>>> from datetime import datetime
>>> json.dumps({'a': datetime(2022, 1, 1)}, default=json_serialize_datetime)
'{"a": "2022-01-01T00:00:00Z"}'
1865def flatten_pipes_dict(*args, **kwargs): 1866 """ 1867 Placeholder function to prevent breaking legacy behavior. 1868 See `meerschaum.utils.pipes.flatten_pipes_dict`. 1869 """ 1870 from meerschaum.utils.pipes import flatten_pipes_dict 1871 return flatten_pipes_dict(*args, **kwargs)
Placeholder function to prevent breaking legacy behavior.
See meerschaum.utils.pipes.flatten_pipes_dict.