query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
r stacks values from two dicts into a new dict where the values are list of the input values . the keys are the same .
def dict_stack ( dict_list , key_prefix = '' ) : dict_stacked_ = defaultdict ( list ) for dict_ in dict_list : for key , val in six . iteritems ( dict_ ) : dict_stacked_ [ key_prefix + key ] . append ( val ) dict_stacked = dict ( dict_stacked_ ) return dict_stacked
9,400
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L332-L379
[ "def", "_ParseStorageMediaOptions", "(", "self", ",", "options", ")", ":", "self", ".", "_ParseStorageMediaImageOptions", "(", "options", ")", "self", ".", "_ParseVSSProcessingOptions", "(", "options", ")", "self", ".", "_ParseCredentialOptions", "(", "options", ")", "self", ".", "_ParseSourcePathOption", "(", "options", ")" ]
Stacks vals from a list of dicts into a dict of lists . Inserts Nones in place of empty items to preserve order .
def dict_stack2 ( dict_list , key_suffix = None , default = None ) : if len ( dict_list ) > 0 : dict_list_ = [ map_dict_vals ( lambda x : [ x ] , kw ) for kw in dict_list ] # Reduce does not handle default quite correctly default1 = [ ] default2 = [ default ] accum_ = dict_list_ [ 0 ] for dict_ in dict_list_ [ 1 : ] : default1 . append ( default ) accum_ = dict_union_combine ( accum_ , dict_ , default = default1 , default2 = default2 ) stacked_dict = accum_ # stacked_dict = reduce(partial(dict_union_combine, default=[default]), dict_list_) else : stacked_dict = { } # Augment keys if requested if key_suffix is not None : stacked_dict = map_dict_keys ( lambda x : x + key_suffix , stacked_dict ) return stacked_dict
9,401
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L382-L496
[ "def", "get_max_devices_per_port_for_storage_bus", "(", "self", ",", "bus", ")", ":", "if", "not", "isinstance", "(", "bus", ",", "StorageBus", ")", ":", "raise", "TypeError", "(", "\"bus can only be an instance of type StorageBus\"", ")", "max_devices_per_port", "=", "self", ".", "_call", "(", "\"getMaxDevicesPerPortForStorageBus\"", ",", "in_p", "=", "[", "bus", "]", ")", "return", "max_devices_per_port" ]
Reverses the keys and values in a dictionary . Set unique_vals to False if the values in the dict are not unique .
def invert_dict ( dict_ , unique_vals = True ) : if unique_vals : inverted_items = [ ( val , key ) for key , val in six . iteritems ( dict_ ) ] inverted_dict = type ( dict_ ) ( inverted_items ) else : inverted_dict = group_items ( dict_ . keys ( ) , dict_ . values ( ) ) return inverted_dict
9,402
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L499-L550
[ "def", "interface_direct_class", "(", "data_class", ")", ":", "if", "data_class", "in", "ASSET", ":", "interface", "=", "AssetsInterface", "(", ")", "elif", "data_class", "in", "PARTY", ":", "interface", "=", "PartiesInterface", "(", ")", "elif", "data_class", "in", "BOOK", ":", "interface", "=", "BooksInterface", "(", ")", "elif", "data_class", "in", "CORPORATE_ACTION", ":", "interface", "=", "CorporateActionsInterface", "(", ")", "elif", "data_class", "in", "MARKET_DATA", ":", "interface", "=", "MarketDataInterface", "(", ")", "elif", "data_class", "in", "TRANSACTION", ":", "interface", "=", "TransactionsInterface", "(", ")", "else", ":", "interface", "=", "AssetManagersInterface", "(", ")", "return", "interface" ]
Same as all_dict_combinations but preserves order
def iter_all_dict_combinations_ordered ( varied_dict ) : tups_list = [ [ ( key , val ) for val in val_list ] for ( key , val_list ) in six . iteritems ( varied_dict ) ] dict_iter = ( OrderedDict ( tups ) for tups in it . product ( * tups_list ) ) return dict_iter
9,403
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L553-L560
[ "def", "truncate", "(", "self", ",", "frames", "=", "None", ")", ":", "if", "frames", "is", "None", ":", "frames", "=", "self", ".", "tell", "(", ")", "err", "=", "_snd", ".", "sf_command", "(", "self", ".", "_file", ",", "_snd", ".", "SFC_FILE_TRUNCATE", ",", "_ffi", ".", "new", "(", "\"sf_count_t*\"", ",", "frames", ")", ",", "_ffi", ".", "sizeof", "(", "\"sf_count_t\"", ")", ")", "if", "err", ":", "raise", "RuntimeError", "(", "\"Error truncating the file\"", ")", "self", ".", "_info", ".", "frames", "=", "frames" ]
returns a label for each variation in a varydict .
def all_dict_combinations_lbls ( varied_dict , remove_singles = True , allow_lone_singles = False ) : is_lone_single = all ( [ isinstance ( val_list , ( list , tuple ) ) and len ( val_list ) == 1 for key , val_list in iteritems_sorted ( varied_dict ) ] ) if not remove_singles or ( allow_lone_singles and is_lone_single ) : # all entries have one length multitups_list = [ [ ( key , val ) for val in val_list ] for key , val_list in iteritems_sorted ( varied_dict ) ] else : multitups_list = [ [ ( key , val ) for val in val_list ] for key , val_list in iteritems_sorted ( varied_dict ) if isinstance ( val_list , ( list , tuple ) ) and len ( val_list ) > 1 ] combtup_list = list ( it . product ( * multitups_list ) ) combtup_list2 = [ [ ( key , val ) if isinstance ( val , six . string_types ) else ( key , repr ( val ) ) for ( key , val ) in combtup ] for combtup in combtup_list ] comb_lbls = [ ',' . join ( [ '%s=%s' % ( key , val ) for ( key , val ) in combtup ] ) for combtup in combtup_list2 ] #comb_lbls = list(map(str, comb_pairs)) return comb_lbls
9,404
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L617-L681
[ "def", "get_power_status", "(", ")", "->", "SystemPowerStatus", ":", "get_system_power_status", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "GetSystemPowerStatus", "get_system_power_status", ".", "argtypes", "=", "[", "ctypes", ".", "POINTER", "(", "SystemPowerStatus", ")", "]", "get_system_power_status", ".", "restype", "=", "wintypes", ".", "BOOL", "status", "=", "SystemPowerStatus", "(", ")", "if", "not", "get_system_power_status", "(", "ctypes", ".", "pointer", "(", "status", ")", ")", ":", "raise", "ctypes", ".", "WinError", "(", ")", "else", ":", "return", "status" ]
Builds dict where a list of values is associated with more than one key
def build_conflict_dict ( key_list , val_list ) : key_to_vals = defaultdict ( list ) for key , val in zip ( key_list , val_list ) : key_to_vals [ key ] . append ( val ) return key_to_vals
9,405
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L692-L724
[ "def", "InitializeFD", "(", "self", ",", "Channel", ",", "BitrateFD", ")", ":", "try", ":", "res", "=", "self", ".", "__m_dllBasic", ".", "CAN_InitializeFD", "(", "Channel", ",", "BitrateFD", ")", "return", "TPCANStatus", "(", "res", ")", "except", ":", "logger", ".", "error", "(", "\"Exception on PCANBasic.InitializeFD\"", ")", "raise" ]
r updates vals in dict1 using vals from dict2 only if the key is already in dict1 .
def update_existing ( dict1 , dict2 , copy = False , assert_exists = False , iswarning = False , alias_dict = None ) : if assert_exists : try : assert_keys_are_subset ( dict1 , dict2 ) except AssertionError as ex : from utool import util_dbg util_dbg . printex ( ex , iswarning = iswarning , N = 1 ) if not iswarning : raise if copy : dict1 = dict ( dict1 ) if alias_dict is None : alias_dict = { } for key , val in six . iteritems ( dict2 ) : key = alias_dict . get ( key , key ) if key in dict1 : dict1 [ key ] = val return dict1
9,406
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L751-L796
[ "def", "isSupportedContent", "(", "cls", ",", "fileContent", ")", ":", "magic", "=", "bytearray", "(", "fileContent", ")", "[", ":", "4", "]", "return", "magic", "==", "p", "(", "'>I'", ",", "0xfeedface", ")", "or", "magic", "==", "p", "(", "'>I'", ",", "0xfeedfacf", ")", "or", "magic", "==", "p", "(", "'<I'", ",", "0xfeedface", ")", "or", "magic", "==", "p", "(", "'<I'", ",", "0xfeedfacf", ")" ]
Like dict . update but does not overwrite items
def dict_update_newkeys ( dict_ , dict2 ) : for key , val in six . iteritems ( dict2 ) : if key not in dict_ : dict_ [ key ] = val
9,407
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L810-L814
[ "def", "disconnect", "(", "self", ",", "close", "=", "True", ")", ":", "if", "not", "self", ".", "_connected", ":", "# already disconnected so let's return", "return", "if", "close", ":", "for", "open", "in", "list", "(", "self", ".", "open_table", ".", "values", "(", ")", ")", ":", "open", ".", "close", "(", "False", ")", "for", "tree", "in", "list", "(", "self", ".", "tree_connect_table", ".", "values", "(", ")", ")", ":", "tree", ".", "disconnect", "(", ")", "log", ".", "info", "(", "\"Session: %s - Logging off of SMB Session\"", "%", "self", ".", "username", ")", "logoff", "=", "SMB2Logoff", "(", ")", "log", ".", "info", "(", "\"Session: %s - Sending Logoff message\"", "%", "self", ".", "username", ")", "log", ".", "debug", "(", "str", "(", "logoff", ")", ")", "request", "=", "self", ".", "connection", ".", "send", "(", "logoff", ",", "sid", "=", "self", ".", "session_id", ")", "log", ".", "info", "(", "\"Session: %s - Receiving Logoff response\"", "%", "self", ".", "username", ")", "res", "=", "self", ".", "connection", ".", "receive", "(", "request", ")", "res_logoff", "=", "SMB2Logoff", "(", ")", "res_logoff", ".", "unpack", "(", "res", "[", "'data'", "]", ".", "get_value", "(", ")", ")", "log", ".", "debug", "(", "str", "(", "res_logoff", ")", ")", "self", ".", "_connected", "=", "False", "del", "self", ".", "connection", ".", "session_table", "[", "self", ".", "session_id", "]" ]
Checks to see if dicts are the same . Performs recursion . Handles numpy
def is_dicteq ( dict1_ , dict2_ , almosteq_ok = True , verbose_err = True ) : import utool as ut assert len ( dict1_ ) == len ( dict2_ ) , 'dicts are not of same length' try : for ( key1 , val1 ) , ( key2 , val2 ) in zip ( dict1_ . items ( ) , dict2_ . items ( ) ) : assert key1 == key2 , 'key mismatch' assert type ( val1 ) == type ( val2 ) , 'vals are not same type' if HAVE_NUMPY and np . iterable ( val1 ) : if almosteq_ok and ut . is_float ( val1 ) : assert np . all ( ut . almost_eq ( val1 , val2 ) ) , 'float vals are not within thresh' else : assert all ( [ np . all ( x1 == x2 ) for ( x1 , x2 ) in zip ( val1 , val2 ) ] ) , 'np vals are different' elif isinstance ( val1 , dict ) : is_dicteq ( val1 , val2 , almosteq_ok = almosteq_ok , verbose_err = verbose_err ) else : assert val1 == val2 , 'vals are different' except AssertionError as ex : if verbose_err : ut . printex ( ex ) return False return True
9,408
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L817-L838
[ "async", "def", "delete_lease_async", "(", "self", ",", "lease", ")", ":", "await", "self", ".", "host", ".", "loop", ".", "run_in_executor", "(", "self", ".", "executor", ",", "functools", ".", "partial", "(", "self", ".", "storage_client", ".", "delete_blob", ",", "self", ".", "lease_container_name", ",", "lease", ".", "partition_id", ",", "lease_id", "=", "lease", ".", "token", ")", ")" ]
r returns a copy of dict_ without keys in the negative_keys list
def dict_setdiff ( dict_ , negative_keys ) : keys = [ key for key in six . iterkeys ( dict_ ) if key not in set ( negative_keys ) ] subdict_ = dict_subset ( dict_ , keys ) return subdict_
9,409
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L877-L888
[ "def", "getOverlayTextureColorSpace", "(", "self", ",", "ulOverlayHandle", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getOverlayTextureColorSpace", "peTextureColorSpace", "=", "EColorSpace", "(", ")", "result", "=", "fn", "(", "ulOverlayHandle", ",", "byref", "(", "peTextureColorSpace", ")", ")", "return", "result", ",", "peTextureColorSpace" ]
r Removes items from a dictionary inplace . Keys that do not exist are ignored .
def delete_dict_keys ( dict_ , key_list ) : invalid_keys = set ( key_list ) - set ( dict_ . keys ( ) ) valid_keys = set ( key_list ) - invalid_keys for key in valid_keys : del dict_ [ key ] return dict_
9,410
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L891-L919
[ "def", "get_console_width", "(", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "STD_INPUT_HANDLE", "=", "-", "10", "STD_OUTPUT_HANDLE", "=", "-", "11", "STD_ERROR_HANDLE", "=", "-", "12", "# get console handle", "from", "ctypes", "import", "windll", ",", "Structure", ",", "byref", "try", ":", "from", "ctypes", ".", "wintypes", "import", "SHORT", ",", "WORD", ",", "DWORD", "except", "ImportError", ":", "# workaround for missing types in Python 2.5", "from", "ctypes", "import", "(", "c_short", "as", "SHORT", ",", "c_ushort", "as", "WORD", ",", "c_ulong", "as", "DWORD", ")", "console_handle", "=", "windll", ".", "kernel32", ".", "GetStdHandle", "(", "STD_OUTPUT_HANDLE", ")", "# CONSOLE_SCREEN_BUFFER_INFO Structure", "class", "COORD", "(", "Structure", ")", ":", "_fields_", "=", "[", "(", "\"X\"", ",", "SHORT", ")", ",", "(", "\"Y\"", ",", "SHORT", ")", "]", "class", "SMALL_RECT", "(", "Structure", ")", ":", "_fields_", "=", "[", "(", "\"Left\"", ",", "SHORT", ")", ",", "(", "\"Top\"", ",", "SHORT", ")", ",", "(", "\"Right\"", ",", "SHORT", ")", ",", "(", "\"Bottom\"", ",", "SHORT", ")", "]", "class", "CONSOLE_SCREEN_BUFFER_INFO", "(", "Structure", ")", ":", "_fields_", "=", "[", "(", "\"dwSize\"", ",", "COORD", ")", ",", "(", "\"dwCursorPosition\"", ",", "COORD", ")", ",", "(", "\"wAttributes\"", ",", "WORD", ")", ",", "(", "\"srWindow\"", ",", "SMALL_RECT", ")", ",", "(", "\"dwMaximumWindowSize\"", ",", "DWORD", ")", "]", "sbi", "=", "CONSOLE_SCREEN_BUFFER_INFO", "(", ")", "ret", "=", "windll", ".", "kernel32", ".", "GetConsoleScreenBufferInfo", "(", "console_handle", ",", "byref", "(", "sbi", ")", ")", "if", "ret", "==", "0", ":", "return", "0", "return", "sbi", ".", "srWindow", ".", "Right", "+", "1", "elif", "os", ".", "name", "==", "'posix'", ":", "from", "fcntl", "import", "ioctl", "from", "termios", "import", "TIOCGWINSZ", "from", "array", "import", "array", "winsize", "=", "array", "(", "\"H\"", ",", "[", "0", "]", "*", "4", ")", "try", ":", "ioctl", "(", "sys", ".", "stdout", ".", "fileno", "(", ")", ",", "TIOCGWINSZ", ",", "winsize", ")", "except", "IOError", ":", "pass", "return", "(", "winsize", "[", "1", "]", ",", "winsize", "[", "0", "]", ")", "[", "0", "]", "return", "80" ]
r generate multiple values from a dictionary
def dict_take_gen ( dict_ , keys , * d ) : if isinstance ( keys , six . string_types ) : # hack for string keys that makes copy-past easier keys = keys . split ( ', ' ) if len ( d ) == 0 : # no default given throws key error dictget = dict_ . __getitem__ elif len ( d ) == 1 : # default given does not throw key erro dictget = dict_ . get else : raise ValueError ( 'len(d) must be 1 or 0' ) for key in keys : if HAVE_NUMPY and isinstance ( key , np . ndarray ) : # recursive call yield list ( dict_take_gen ( dict_ , key , * d ) ) else : yield dictget ( key , * d )
9,411
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L925-L979
[ "def", "saelgv", "(", "vec1", ",", "vec2", ")", ":", "vec1", "=", "stypes", ".", "toDoubleVector", "(", "vec1", ")", "vec2", "=", "stypes", ".", "toDoubleVector", "(", "vec2", ")", "smajor", "=", "stypes", ".", "emptyDoubleVector", "(", "3", ")", "sminor", "=", "stypes", ".", "emptyDoubleVector", "(", "3", ")", "libspice", ".", "saelgv_c", "(", "vec1", ",", "vec2", ",", "smajor", ",", "sminor", ")", "return", "stypes", ".", "cVectorToPython", "(", "smajor", ")", ",", "stypes", ".", "cVectorToPython", "(", "sminor", ")" ]
get multiple values from a dictionary
def dict_take ( dict_ , keys , * d ) : try : return list ( dict_take_gen ( dict_ , keys , * d ) ) except TypeError : return list ( dict_take_gen ( dict_ , keys , * d ) ) [ 0 ]
9,412
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L982-L987
[ "def", "edlimb", "(", "a", ",", "b", ",", "c", ",", "viewpt", ")", ":", "limb", "=", "stypes", ".", "Ellipse", "(", ")", "a", "=", "ctypes", ".", "c_double", "(", "a", ")", "b", "=", "ctypes", ".", "c_double", "(", "b", ")", "c", "=", "ctypes", ".", "c_double", "(", "c", ")", "viewpt", "=", "stypes", ".", "toDoubleVector", "(", "viewpt", ")", "libspice", ".", "edlimb_c", "(", "a", ",", "b", ",", "c", ",", "viewpt", ",", "ctypes", ".", "byref", "(", "limb", ")", ")", "return", "limb" ]
like dict_take but pops values off
def dict_take_pop ( dict_ , keys , * d ) : if len ( d ) == 0 : return [ dict_ . pop ( key ) for key in keys ] elif len ( d ) == 1 : default = d [ 0 ] return [ dict_ . pop ( key , default ) for key in keys ] else : raise ValueError ( 'len(d) must be 1 or 0' )
9,413
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1014-L1057
[ "def", "updateSeriesRegistrationStatus", "(", ")", ":", "from", ".", "models", "import", "Series", "if", "not", "getConstant", "(", "'general__enableCronTasks'", ")", ":", "return", "logger", ".", "info", "(", "'Checking status of Series that are open for registration.'", ")", "open_series", "=", "Series", ".", "objects", ".", "filter", "(", ")", ".", "filter", "(", "*", "*", "{", "'registrationOpen'", ":", "True", "}", ")", "for", "series", "in", "open_series", ":", "series", ".", "updateRegistrationStatus", "(", ")" ]
simple method for assigning or setting values with a similar interface to dict_take
def dict_assign ( dict_ , keys , vals ) : for key , val in zip ( keys , vals ) : dict_ [ key ] = val
9,414
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1060-L1064
[ "def", "_setup_metrics", "(", "self", ")", ":", "path", "=", "os", ".", "environ", ".", "get", "(", "\"prometheus_multiproc_dir\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "metrics_dir", ")", ":", "try", ":", "log", ".", "info", "(", "\"Creating metrics directory\"", ")", "os", ".", "makedirs", "(", "self", ".", "metrics_dir", ")", "except", "OSError", ":", "log", ".", "error", "(", "\"Failed to create metrics directory!\"", ")", "raise", "ConfigurationException", "(", "\"Failed to create metrics directory!\"", ")", "path", "=", "self", ".", "metrics_dir", "elif", "path", "!=", "self", ".", "metrics_dir", ":", "path", "=", "self", ".", "metrics_dir", "os", ".", "environ", "[", "'prometheus_multiproc_dir'", "]", "=", "path", "log", ".", "info", "(", "\"Cleaning metrics collection directory\"", ")", "log", ".", "debug", "(", "\"Metrics directory set to: {}\"", ".", "format", "(", "path", ")", ")", "files", "=", "os", ".", "listdir", "(", "path", ")", "for", "f", "in", "files", ":", "if", "f", ".", "endswith", "(", "\".db\"", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", ")", "log", ".", "debug", "(", "\"Starting metrics exposition\"", ")", "if", "self", ".", "metrics_enabled", ":", "registry", "=", "CollectorRegistry", "(", ")", "multiprocess", ".", "MultiProcessCollector", "(", "registry", ")", "start_http_server", "(", "port", "=", "self", ".", "metrics_port", ",", "addr", "=", "self", ".", "metrics_address", ",", "registry", "=", "registry", ")" ]
Accepts a dict of lists . Returns keys that have vals with no length
def dict_where_len0 ( dict_ ) : keys = np . array ( dict_ . keys ( ) ) flags = np . array ( list ( map ( len , dict_ . values ( ) ) ) ) == 0 indices = np . where ( flags ) [ 0 ] return keys [ indices ]
9,415
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1067-L1074
[ "def", "_earth_orientation", "(", "date", ")", ":", "ttt", "=", "date", ".", "change_scale", "(", "'TT'", ")", ".", "julian_century", "# a_a = 0.12", "# a_c = 0.26", "# s_prime = -0.0015 * (a_c ** 2 / 1.2 + a_a ** 2) * ttt", "s_prime", "=", "-", "0.000047", "*", "ttt", "return", "date", ".", "eop", ".", "x", "/", "3600.", ",", "date", ".", "eop", ".", "y", "/", "3600.", ",", "s_prime", "/", "3600" ]
r Builds a histogram of items in item_list
def dict_hist ( item_list , weight_list = None , ordered = False , labels = None ) : if labels is None : # hist_ = defaultdict(lambda: 0) hist_ = defaultdict ( int ) else : hist_ = { k : 0 for k in labels } if weight_list is None : # weight_list = it.repeat(1) for item in item_list : hist_ [ item ] += 1 else : for item , weight in zip ( item_list , weight_list ) : hist_ [ item ] += weight # hist_ = dict(hist_) if ordered : # import utool as ut # key_order = ut.sortedby(list(hist_.keys()), list(hist_.values())) getval = op . itemgetter ( 1 ) key_order = [ key for ( key , value ) in sorted ( hist_ . items ( ) , key = getval ) ] hist_ = order_dict_by ( hist_ , key_order ) return hist_
9,416
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1236-L1279
[ "def", "private_messenger", "(", ")", ":", "while", "__websocket_server_running__", ":", "pipein", "=", "open", "(", "PRIVATE_PIPE", ",", "'r'", ")", "line", "=", "pipein", ".", "readline", "(", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", ".", "replace", "(", "'\\r'", ",", "''", ")", "if", "line", "!=", "''", ":", "message", "=", "json", ".", "loads", "(", "line", ")", "WebSocketHandler", ".", "send_private_message", "(", "user_id", "=", "message", "[", "'user_id'", "]", ",", "message", "=", "message", ")", "print", "line", "remaining_lines", "=", "pipein", ".", "read", "(", ")", "pipein", ".", "close", "(", ")", "pipeout", "=", "open", "(", "PRIVATE_PIPE", ",", "'w'", ")", "pipeout", ".", "write", "(", "remaining_lines", ")", "pipeout", ".", "close", "(", ")", "else", ":", "pipein", ".", "close", "(", ")", "time", ".", "sleep", "(", "0.05", ")" ]
Intersection of dict keys and combination of dict values
def dict_isect_combine ( dict1 , dict2 , combine_op = op . add ) : keys3 = set ( dict1 . keys ( ) ) . intersection ( set ( dict2 . keys ( ) ) ) dict3 = { key : combine_op ( dict1 [ key ] , dict2 [ key ] ) for key in keys3 } return dict3
9,417
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1438-L1442
[ "def", "getRenderModelThumbnailURL", "(", "self", ",", "pchRenderModelName", ",", "pchThumbnailURL", ",", "unThumbnailURLLen", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getRenderModelThumbnailURL", "peError", "=", "EVRRenderModelError", "(", ")", "result", "=", "fn", "(", "pchRenderModelName", ",", "pchThumbnailURL", ",", "unThumbnailURLLen", ",", "byref", "(", "peError", ")", ")", "return", "result", ",", "peError" ]
Combine of dict keys and uses dfault value when key does not exist
def dict_union_combine ( dict1 , dict2 , combine_op = op . add , default = util_const . NoParam , default2 = util_const . NoParam ) : keys3 = set ( dict1 . keys ( ) ) . union ( set ( dict2 . keys ( ) ) ) if default is util_const . NoParam : dict3 = { key : combine_op ( dict1 [ key ] , dict2 [ key ] ) for key in keys3 } else : if default2 is util_const . NoParam : default2 = default dict3 = { key : combine_op ( dict1 . get ( key , default ) , dict2 . get ( key , default2 ) ) for key in keys3 } return dict3
9,418
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1445-L1461
[ "def", "_orthogonalize", "(", "X", ")", ":", "if", "X", ".", "size", "==", "X", ".", "shape", "[", "0", "]", ":", "return", "X", "from", "scipy", ".", "linalg", "import", "pinv", ",", "norm", "for", "i", "in", "range", "(", "1", ",", "X", ".", "shape", "[", "1", "]", ")", ":", "X", "[", ":", ",", "i", "]", "-=", "np", ".", "dot", "(", "np", ".", "dot", "(", "X", "[", ":", ",", "i", "]", ",", "X", "[", ":", ",", ":", "i", "]", ")", ",", "pinv", "(", "X", "[", ":", ",", ":", "i", "]", ")", ")", "# X[:, i] /= norm(X[:, i])", "return", "X" ]
r Removes None values
def dict_filter_nones ( dict_ ) : dict2_ = { key : val for key , val in six . iteritems ( dict_ ) if val is not None } return dict2_
9,419
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1474-L1504
[ "def", "edlimb", "(", "a", ",", "b", ",", "c", ",", "viewpt", ")", ":", "limb", "=", "stypes", ".", "Ellipse", "(", ")", "a", "=", "ctypes", ".", "c_double", "(", "a", ")", "b", "=", "ctypes", ".", "c_double", "(", "b", ")", "c", "=", "ctypes", ".", "c_double", "(", "c", ")", "viewpt", "=", "stypes", ".", "toDoubleVector", "(", "viewpt", ")", "libspice", ".", "edlimb_c", "(", "a", ",", "b", ",", "c", ",", "viewpt", ",", "ctypes", ".", "byref", "(", "limb", ")", ")", "return", "limb" ]
r case where an item can belong to multiple groups
def groupby_tags ( item_list , tags_list ) : groupid_to_items = defaultdict ( list ) for tags , item in zip ( tags_list , item_list ) : for tag in tags : groupid_to_items [ tag ] . append ( item ) return groupid_to_items
9,420
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1507-L1552
[ "def", "unindex_layers_with_issues", "(", "self", ",", "use_cache", "=", "False", ")", ":", "from", "hypermap", ".", "aggregator", ".", "models", "import", "Issue", ",", "Layer", ",", "Service", "from", "django", ".", "contrib", ".", "contenttypes", ".", "models", "import", "ContentType", "layer_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "Layer", ")", "service_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "Service", ")", "for", "issue", "in", "Issue", ".", "objects", ".", "filter", "(", "content_type__pk", "=", "layer_type", ".", "id", ")", ":", "unindex_layer", "(", "issue", ".", "content_object", ".", "id", ",", "use_cache", ")", "for", "issue", "in", "Issue", ".", "objects", ".", "filter", "(", "content_type__pk", "=", "service_type", ".", "id", ")", ":", "for", "layer", "in", "issue", ".", "content_object", ".", "layer_set", ".", "all", "(", ")", ":", "unindex_layer", "(", "layer", ".", "id", ",", "use_cache", ")" ]
Groups a list of items using the first element in each pair as the item and the second element as the groupid .
def group_pairs ( pair_list ) : # Initialize dict of lists groupid_to_items = defaultdict ( list ) # Insert each item into the correct group for item , groupid in pair_list : groupid_to_items [ groupid ] . append ( item ) return groupid_to_items
9,421
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1560-L1579
[ "def", "command_max_run_time", "(", "self", ",", "event", "=", "None", ")", ":", "try", ":", "max_run_time", "=", "self", ".", "max_run_time_var", ".", "get", "(", ")", "except", "ValueError", ":", "max_run_time", "=", "self", ".", "runtime_cfg", ".", "max_run_time", "self", ".", "runtime_cfg", ".", "max_run_time", "=", "max_run_time", "self", ".", "max_run_time_var", ".", "set", "(", "self", ".", "runtime_cfg", ".", "max_run_time", ")" ]
Groups a list of items by group id .
def group_items ( items , by = None , sorted_ = True ) : if by is not None : pairs = list ( zip ( by , items ) ) if sorted_ : # Sort by groupid for cache efficiency (does this even do anything?) # I forgot why this is needed? Determenism? try : pairs = sorted ( pairs , key = op . itemgetter ( 0 ) ) except TypeError : # Python 3 does not allow sorting mixed types pairs = sorted ( pairs , key = lambda tup : str ( tup [ 0 ] ) ) else : pairs = items # Initialize a dict of lists groupid_to_items = defaultdict ( list ) # Insert each item into the correct group for groupid , item in pairs : groupid_to_items [ groupid ] . append ( item ) return groupid_to_items
9,422
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1582-L1635
[ "def", "_launch_editor", "(", "starting_text", "=", "''", ")", ":", "# TODO: What is a reasonable default for windows? Does this approach even", "# make sense on windows?", "editor", "=", "os", ".", "environ", ".", "get", "(", "'EDITOR'", ",", "'vim'", ")", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "dirname", ":", "filename", "=", "pathlib", ".", "Path", "(", "dirname", ")", "/", "'metadata.yml'", "with", "filename", ".", "open", "(", "mode", "=", "'wt'", ")", "as", "handle", ":", "handle", ".", "write", "(", "starting_text", ")", "subprocess", ".", "call", "(", "[", "editor", ",", "filename", "]", ")", "with", "filename", ".", "open", "(", "mode", "=", "'rt'", ")", "as", "handle", ":", "text", "=", "handle", ".", "read", "(", ")", "return", "text" ]
Generalization of group_item . Convert a flast list of ids into a heirarchical dictionary .
def hierarchical_group_items ( item_list , groupids_list ) : # Construct a defaultdict type with the appropriate number of levels num_groups = len ( groupids_list ) leaf_type = partial ( defaultdict , list ) if num_groups > 1 : node_type = leaf_type for _ in range ( len ( groupids_list ) - 2 ) : node_type = partial ( defaultdict , node_type ) root_type = node_type elif num_groups == 1 : root_type = list else : raise ValueError ( 'must suply groupids' ) tree = defaultdict ( root_type ) # groupid_tuple_list = list ( zip ( * groupids_list ) ) for groupid_tuple , item in zip ( groupid_tuple_list , item_list ) : node = tree for groupid in groupid_tuple : node = node [ groupid ] node . append ( item ) return tree
9,423
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1638-L1719
[ "def", "main", "(", ")", ":", "cmd_args", "=", "TagCubeCLI", ".", "parse_args", "(", ")", "try", ":", "tagcube_cli", "=", "TagCubeCLI", ".", "from_cmd_args", "(", "cmd_args", ")", "except", "ValueError", ",", "ve", ":", "# We get here when there are no credentials configured", "print", "'%s'", "%", "ve", "sys", ".", "exit", "(", "1", ")", "try", ":", "sys", ".", "exit", "(", "tagcube_cli", ".", "run", "(", ")", ")", "except", "ValueError", ",", "ve", ":", "# We get here when the configured credentials had some issue (invalid)", "# or there was some error (such as invalid profile name) with the params", "print", "'%s'", "%", "ve", "sys", ".", "exit", "(", "2", ")" ]
node is a dict tree like structure with leaves of type list
def hierarchical_map_vals ( func , node , max_depth = None , depth = 0 ) : #if not isinstance(node, dict): if not hasattr ( node , 'items' ) : return func ( node ) elif max_depth is not None and depth >= max_depth : #return func(node) return map_dict_vals ( func , node ) #return {key: func(val) for key, val in six.iteritems(node)} else : # recursion #return {key: hierarchical_map_vals(func, val, max_depth, depth + 1) for key, val in six.iteritems(node)} #keyval_list = [(key, hierarchical_map_vals(func, val, max_depth, depth + 1)) for key, val in six.iteritems(node)] keyval_list = [ ( key , hierarchical_map_vals ( func , val , max_depth , depth + 1 ) ) for key , val in node . items ( ) ] if isinstance ( node , OrderedDict ) : return OrderedDict ( keyval_list ) else : return dict ( keyval_list )
9,424
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1750-L1821
[ "def", "_compute_metadata_from_readers", "(", "self", ")", ":", "mda", "=", "{", "'sensor'", ":", "self", ".", "_get_sensor_names", "(", ")", "}", "# overwrite the request start/end times with actual loaded data limits", "if", "self", ".", "readers", ":", "mda", "[", "'start_time'", "]", "=", "min", "(", "x", ".", "start_time", "for", "x", "in", "self", ".", "readers", ".", "values", "(", ")", ")", "mda", "[", "'end_time'", "]", "=", "max", "(", "x", ".", "end_time", "for", "x", "in", "self", ".", "readers", ".", "values", "(", ")", ")", "return", "mda" ]
sorts a dictionary by its values or its keys
def sort_dict ( dict_ , part = 'keys' , key = None , reverse = False ) : if part == 'keys' : index = 0 elif part in { 'vals' , 'values' } : index = 1 else : raise ValueError ( 'Unknown method part=%r' % ( part , ) ) if key is None : _key = op . itemgetter ( index ) else : def _key ( item ) : return key ( item [ index ] ) sorted_items = sorted ( six . iteritems ( dict_ ) , key = _key , reverse = reverse ) sorted_dict = OrderedDict ( sorted_items ) return sorted_dict
9,425
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L1955-L2003
[ "def", "to_csr", "(", "self", ")", ":", "self", ".", "_X_train", "=", "csr_matrix", "(", "self", ".", "_X_train", ")", "self", ".", "_X_test", "=", "csr_matrix", "(", "self", ".", "_X_test", ")" ]
r Reorders items in a dictionary according to a custom key order
def order_dict_by ( dict_ , key_order ) : dict_keys = set ( dict_ . keys ( ) ) other_keys = dict_keys - set ( key_order ) key_order = it . chain ( key_order , other_keys ) sorted_dict = OrderedDict ( ( key , dict_ [ key ] ) for key in key_order if key in dict_keys ) return sorted_dict
9,426
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L2006-L2038
[ "def", "watchdog_handler", "(", "self", ")", ":", "_LOGGING", ".", "debug", "(", "'%s Watchdog expired. Resetting connection.'", ",", "self", ".", "name", ")", "self", ".", "watchdog", ".", "stop", "(", ")", "self", ".", "reset_thrd", ".", "set", "(", ")" ]
change to iteritems ordered
def iteritems_sorted ( dict_ ) : if isinstance ( dict_ , OrderedDict ) : return six . iteritems ( dict_ ) else : return iter ( sorted ( six . iteritems ( dict_ ) ) )
9,427
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L2041-L2046
[ "def", "send_msg_to_clients", "(", "client_ids", ",", "msg", ",", "error", "=", "False", ")", ":", "if", "error", ":", "stream", "=", "\"stderr\"", "else", ":", "stream", "=", "\"stdout\"", "response", "=", "[", "{", "\"message\"", ":", "None", ",", "\"type\"", ":", "\"console\"", ",", "\"payload\"", ":", "msg", ",", "\"stream\"", ":", "stream", "}", "]", "for", "client_id", "in", "client_ids", ":", "logger", ".", "info", "(", "\"emiting message to websocket client id \"", "+", "client_id", ")", "socketio", ".", "emit", "(", "\"gdb_response\"", ",", "response", ",", "namespace", "=", "\"/gdb_listener\"", ",", "room", "=", "client_id", ")" ]
Flattens only values in a heirarchical dictionary keys are nested .
def flatten_dict_vals ( dict_ ) : if isinstance ( dict_ , dict ) : return dict ( [ ( ( key , augkey ) , augval ) for key , val in dict_ . items ( ) for augkey , augval in flatten_dict_vals ( val ) . items ( ) ] ) else : return { None : dict_ }
9,428
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L2054-L2065
[ "def", "fromimportunreg", "(", "cls", ",", "bundle", ",", "cid", ",", "rsid", ",", "import_ref", ",", "exception", ",", "endpoint", ")", ":", "# type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ImportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent", "return", "RemoteServiceAdminEvent", "(", "typ", "=", "RemoteServiceAdminEvent", ".", "IMPORT_UNREGISTRATION", ",", "bundle", "=", "bundle", ",", "cid", "=", "cid", ",", "rsid", "=", "rsid", ",", "import_ref", "=", "import_ref", ",", "exception", "=", "exception", ",", "endpoint", "=", "endpoint", ",", ")" ]
r Returns if depth of list is at least depth
def depth_atleast ( list_ , depth ) : if depth == 0 : return True else : try : return all ( [ depth_atleast ( item , depth - 1 ) for item in list_ ] ) except TypeError : return False
9,429
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L2096-L2125
[ "def", "construct_error_message", "(", "driver_id", ",", "error_type", ",", "message", ",", "timestamp", ")", ":", "builder", "=", "flatbuffers", ".", "Builder", "(", "0", ")", "driver_offset", "=", "builder", ".", "CreateString", "(", "driver_id", ".", "binary", "(", ")", ")", "error_type_offset", "=", "builder", ".", "CreateString", "(", "error_type", ")", "message_offset", "=", "builder", ".", "CreateString", "(", "message", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataStart", "(", "builder", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddDriverId", "(", "builder", ",", "driver_offset", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddType", "(", "builder", ",", "error_type_offset", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddErrorMessage", "(", "builder", ",", "message_offset", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddTimestamp", "(", "builder", ",", "timestamp", ")", "error_data_offset", "=", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataEnd", "(", "builder", ")", "builder", ".", "Finish", "(", "error_data_offset", ")", "return", "bytes", "(", "builder", ".", "Output", "(", ")", ")" ]
Returns column nr on which to split PSM table . Chooses from flags given via bioset and splitcol
def get_splitcolnr ( header , bioset , splitcol ) : if bioset : return header . index ( mzidtsvdata . HEADER_SETNAME ) elif splitcol is not None : return splitcol - 1 else : raise RuntimeError ( 'Must specify either --bioset or --splitcol' )
9,430
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/splitmerge.py#L14-L22
[ "def", "_recreate_list_with_indices", "(", "indices1", ",", "values1", ",", "indices2", ",", "values2", ")", ":", "# Test if indices are continuous", "list_indices", "=", "sorted", "(", "indices1", "+", "indices2", ")", "for", "i", ",", "index", "in", "enumerate", "(", "list_indices", ")", ":", "if", "i", "!=", "index", ":", "raise", "CraftAiInternalError", "(", "\"The agents's indices are not continuous\"", ")", "full_list", "=", "[", "None", "]", "*", "(", "len", "(", "indices1", ")", "+", "len", "(", "indices2", ")", ")", "for", "i", ",", "index", "in", "enumerate", "(", "indices1", ")", ":", "full_list", "[", "index", "]", "=", "values1", "[", "i", "]", "for", "i", ",", "index", "in", "enumerate", "(", "indices2", ")", ":", "full_list", "[", "index", "]", "=", "values2", "[", "i", "]", "return", "full_list" ]
Loops PSMs and outputs dictionaries passed to writer . Dictionaries contain the PSMs and info to which split pool the respective PSM belongs
def generate_psms_split ( fn , oldheader , bioset , splitcol ) : try : splitcolnr = get_splitcolnr ( oldheader , bioset , splitcol ) except IndexError : raise RuntimeError ( 'Cannot find bioset header column in ' 'input file {}, though --bioset has ' 'been passed' . format ( fn ) ) for psm in tsvreader . generate_tsv_psms ( fn , oldheader ) : yield { 'psm' : psm , 'split_pool' : psm [ oldheader [ splitcolnr ] ] }
9,431
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/splitmerge.py#L25-L38
[ "def", "compare", "(", "self", ",", "other", ",", "t_threshold", "=", "1e-3", ")", ":", "return", "compute_rmsd", "(", "self", ".", "t", ",", "other", ".", "t", ")", "<", "t_threshold" ]
Returns a randomly ordered list of the integers between min and max
def rnumlistwithoutreplacement ( min , max ) : if checkquota ( ) < 1 : raise Exception ( "Your www.random.org quota has already run out." ) requestparam = build_request_parameterNR ( min , max ) request = urllib . request . Request ( requestparam ) request . add_header ( 'User-Agent' , 'randomwrapy/0.1 very alpha' ) opener = urllib . request . build_opener ( ) numlist = opener . open ( request ) . read ( ) return numlist . split ( )
9,432
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/randomwrap.py#L54-L63
[ "def", "_ParseKeysFromFindSpecs", "(", "self", ",", "parser_mediator", ",", "win_registry", ",", "find_specs", ")", ":", "searcher", "=", "dfwinreg_registry_searcher", ".", "WinRegistrySearcher", "(", "win_registry", ")", "for", "registry_key_path", "in", "iter", "(", "searcher", ".", "Find", "(", "find_specs", "=", "find_specs", ")", ")", ":", "if", "parser_mediator", ".", "abort", ":", "break", "registry_key", "=", "searcher", ".", "GetKeyByPath", "(", "registry_key_path", ")", "self", ".", "_ParseKey", "(", "parser_mediator", ",", "registry_key", ")" ]
Returns a list of howmany integers with a maximum value = max . The minimum value defaults to zero .
def rnumlistwithreplacement ( howmany , max , min = 0 ) : if checkquota ( ) < 1 : raise Exception ( "Your www.random.org quota has already run out." ) requestparam = build_request_parameterWR ( howmany , min , max ) request = urllib . request . Request ( requestparam ) request . add_header ( 'User-Agent' , 'randomwrapy/0.1 very alpha' ) opener = urllib . request . build_opener ( ) numlist = opener . open ( request ) . read ( ) return numlist . split ( )
9,433
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/randomwrap.py#L75-L85
[ "def", "flush_all", "(", "self", ")", ":", "for", "queue_name", "in", "chain", "(", "self", ".", "queues", ",", "self", ".", "delay_queues", ")", ":", "self", ".", "flush", "(", "queue_name", ")" ]
r Weird function . Not very well written . Very special case - y
def num_fmt ( num , max_digits = None ) : if num is None : return 'None' def num_in_mag ( num , mag ) : return mag > num and num > ( - 1 * mag ) if max_digits is None : # TODO: generalize if num_in_mag ( num , 1 ) : if num_in_mag ( num , .1 ) : max_digits = 4 else : max_digits = 3 else : max_digits = 1 if util_type . is_float ( num ) : num_str = ( '%.' + str ( max_digits ) + 'f' ) % num # Handle trailing and leading zeros num_str = num_str . rstrip ( '0' ) . lstrip ( '0' ) if num_str . startswith ( '.' ) : num_str = '0' + num_str if num_str . endswith ( '.' ) : num_str = num_str + '0' return num_str elif util_type . is_int ( num ) : return int_comma_str ( num ) else : return '%r'
9,434
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_num.py#L82-L133
[ "def", "_apply_cached_indexes", "(", "self", ",", "cached_indexes", ",", "persist", "=", "False", ")", ":", "# cacheable_dict = {}", "for", "elt", "in", "[", "'valid_input_index'", ",", "'valid_output_index'", ",", "'index_array'", ",", "'distance_array'", "]", ":", "val", "=", "cached_indexes", "[", "elt", "]", "if", "isinstance", "(", "val", ",", "tuple", ")", ":", "val", "=", "cached_indexes", "[", "elt", "]", "[", "0", "]", "elif", "isinstance", "(", "val", ",", "np", ".", "ndarray", ")", ":", "val", "=", "da", ".", "from_array", "(", "val", ",", "chunks", "=", "CHUNK_SIZE", ")", "elif", "persist", "and", "isinstance", "(", "val", ",", "da", ".", "Array", ")", ":", "cached_indexes", "[", "elt", "]", "=", "val", "=", "val", ".", "persist", "(", ")", "setattr", "(", "self", ".", "resampler", ",", "elt", ",", "val", ")" ]
Load pickled features for train and test sets assuming they are saved in the features folder along with their column names .
def load_feature_lists ( self , feature_lists ) : column_names = [ ] feature_ranges = [ ] running_feature_count = 0 for list_id in feature_lists : feature_list_names = load_lines ( self . features_dir + 'X_train_{}.names' . format ( list_id ) ) column_names . extend ( feature_list_names ) start_index = running_feature_count end_index = running_feature_count + len ( feature_list_names ) - 1 running_feature_count += len ( feature_list_names ) feature_ranges . append ( [ list_id , start_index , end_index ] ) X_train = np . hstack ( [ load ( self . features_dir + 'X_train_{}.pickle' . format ( list_id ) ) for list_id in feature_lists ] ) X_test = np . hstack ( [ load ( self . features_dir + 'X_test_{}.pickle' . format ( list_id ) ) for list_id in feature_lists ] ) df_train = pd . DataFrame ( X_train , columns = column_names ) df_test = pd . DataFrame ( X_test , columns = column_names ) return df_train , df_test , feature_ranges
9,435
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/project.py#L89-L126
[ "def", "get_exchange_group_info", "(", "self", ",", "symprec", "=", "1e-2", ",", "angle_tolerance", "=", "5.0", ")", ":", "structure", "=", "self", ".", "get_structure_with_spin", "(", ")", "return", "structure", ".", "get_space_group_info", "(", "symprec", "=", "symprec", ",", "angle_tolerance", "=", "angle_tolerance", ")" ]
Save features for the training and test sets to disk along with their metadata .
def save_features ( self , train_features , test_features , feature_names , feature_list_id ) : self . save_feature_names ( feature_names , feature_list_id ) self . save_feature_list ( train_features , 'train' , feature_list_id ) self . save_feature_list ( test_features , 'test' , feature_list_id )
9,436
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/project.py#L128-L141
[ "def", "read", "(", "self", ",", "lpBaseAddress", ",", "nSize", ")", ":", "hProcess", "=", "self", ".", "get_handle", "(", "win32", ".", "PROCESS_VM_READ", "|", "win32", ".", "PROCESS_QUERY_INFORMATION", ")", "if", "not", "self", ".", "is_buffer", "(", "lpBaseAddress", ",", "nSize", ")", ":", "raise", "ctypes", ".", "WinError", "(", "win32", ".", "ERROR_INVALID_ADDRESS", ")", "data", "=", "win32", ".", "ReadProcessMemory", "(", "hProcess", ",", "lpBaseAddress", ",", "nSize", ")", "if", "len", "(", "data", ")", "!=", "nSize", ":", "raise", "ctypes", ".", "WinError", "(", ")", "return", "data" ]
Automatically discover the paths to various data folders in this project and compose a Project instance .
def discover ( ) : # Try ../data: we're most likely running a Jupyter notebook from the 'notebooks' directory candidate_path = os . path . abspath ( os . path . join ( os . curdir , os . pardir , 'data' ) ) if os . path . exists ( candidate_path ) : return Project ( os . path . abspath ( os . path . join ( candidate_path , os . pardir ) ) ) # Try ./data candidate_path = os . path . abspath ( os . path . join ( os . curdir , 'data' ) ) if os . path . exists ( candidate_path ) : return Project ( os . path . abspath ( os . curdir ) ) # Try ../../data candidate_path = os . path . abspath ( os . path . join ( os . curdir , os . pardir , 'data' ) ) if os . path . exists ( candidate_path ) : return Project ( os . path . abspath ( os . path . join ( candidate_path , os . pardir , os . pardir ) ) ) # Out of ideas at this point. raise ValueError ( 'Cannot discover the structure of the project. Make sure that the data directory exists' )
9,437
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/project.py#L170-L199
[ "def", "win32_refresh_window", "(", "cls", ")", ":", "# Get console handle", "handle", "=", "windll", ".", "kernel32", ".", "GetConsoleWindow", "(", ")", "RDW_INVALIDATE", "=", "0x0001", "windll", ".", "user32", ".", "RedrawWindow", "(", "handle", ",", "None", ",", "None", ",", "c_uint", "(", "RDW_INVALIDATE", ")", ")" ]
Creates the project infrastructure assuming the current directory is the project root . Typically used as a command - line entry point called by pygoose init .
def init ( ) : project = Project ( os . path . abspath ( os . getcwd ( ) ) ) paths_to_create = [ project . data_dir , project . notebooks_dir , project . aux_dir , project . features_dir , project . preprocessed_data_dir , project . submissions_dir , project . trained_model_dir , project . temp_dir , ] for path in paths_to_create : os . makedirs ( path , exist_ok = True )
9,438
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/project.py#L202-L221
[ "def", "update_qos_aggregated_configuration", "(", "self", ",", "qos_configuration", ",", "timeout", "=", "-", "1", ")", ":", "uri", "=", "\"{}{}\"", ".", "format", "(", "self", ".", "data", "[", "\"uri\"", "]", ",", "self", ".", "QOS_AGGREGATED_CONFIGURATION", ")", "return", "self", ".", "_helper", ".", "update", "(", "qos_configuration", ",", "uri", "=", "uri", ",", "timeout", "=", "timeout", ")" ]
List unique elements preserving order . Remember only the element just seen .
def unique_justseen ( iterable , key = None ) : # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B # unique_justseen('ABBCcAD', str.lower) --> A B C A D return imap ( next , imap ( operator . itemgetter ( 1 ) , groupby ( iterable , key ) ) )
9,439
https://github.com/tmr232/awesomelib/blob/69a63466a63679f9e2abac8a719853a5e527219c/awesome/iterator.py#L122-L126
[ "def", "_initialize_connection", "(", "api_key", ",", "app_key", ")", ":", "if", "api_key", "is", "None", ":", "raise", "SaltInvocationError", "(", "'api_key must be specified'", ")", "if", "app_key", "is", "None", ":", "raise", "SaltInvocationError", "(", "'app_key must be specified'", ")", "options", "=", "{", "'api_key'", ":", "api_key", ",", "'app_key'", ":", "app_key", "}", "datadog", ".", "initialize", "(", "*", "*", "options", ")" ]
finds module in sys . modules based on module name unless the module has already been found and is passed in
def _get_module ( module_name = None , module = None , register = True ) : if module is None and module_name is not None : try : module = sys . modules [ module_name ] except KeyError as ex : print ( ex ) raise KeyError ( ( 'module_name=%r must be loaded before ' + 'receiving injections' ) % module_name ) elif module is not None and module_name is None : pass else : raise ValueError ( 'module_name or module must be exclusively specified' ) if register is True : _add_injected_module ( module ) return module
9,440
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L86-L102
[ "def", "permissions", "(", "self", ")", ":", "can_read", "=", "self", ".", "_info", ".", "file", ".", "permissions", "&", "lib", ".", "GP_FILE_PERM_READ", "can_write", "=", "self", ".", "_info", ".", "file", ".", "permissions", "&", "lib", ".", "GP_FILE_PERM_DELETE", "return", "\"{0}{1}\"", ".", "format", "(", "\"r\"", "if", "can_read", "else", "\"-\"", ",", "\"w\"", "if", "can_write", "else", "\"-\"", ")" ]
Causes exceptions to be colored if not already
def inject_colored_exceptions ( ) : #COLORED_INJECTS = '--nocolorex' not in sys.argv #COLORED_INJECTS = '--colorex' in sys.argv # Ignore colored exceptions on win32 if VERBOSE : print ( '[inject] injecting colored exceptions' ) if not sys . platform . startswith ( 'win32' ) : if VERYVERBOSE : print ( '[inject] injecting colored exceptions' ) if '--noinject-color' in sys . argv : print ( 'Not injecting color' ) else : sys . excepthook = colored_pygments_excepthook else : if VERYVERBOSE : print ( '[inject] cannot inject colored exceptions' )
9,441
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L135-L166
[ "def", "guess_extension", "(", "amimetype", ",", "normalize", "=", "False", ")", ":", "ext", "=", "_mimes", ".", "guess_extension", "(", "amimetype", ")", "if", "ext", "and", "normalize", ":", "# Normalize some common magic mis-interpreation", "ext", "=", "{", "'.asc'", ":", "'.txt'", ",", "'.obj'", ":", "'.bin'", "}", ".", "get", "(", "ext", ",", "ext", ")", "from", "invenio", ".", "legacy", ".", "bibdocfile", ".", "api_normalizer", "import", "normalize_format", "return", "normalize_format", "(", "ext", ")", "return", "ext" ]
makes print functions to be injected into the module
def inject_print_functions ( module_name = None , module_prefix = '[???]' , DEBUG = False , module = None ) : module = _get_module ( module_name , module ) if SILENT : def print ( * args ) : """ silent builtins.print """ pass def printDBG ( * args ) : """ silent debug print """ pass def print_ ( * args ) : """ silent stdout.write """ pass else : if DEBUG_PRINT : # Turns on printing where a message came from def print ( * args ) : """ debugging logging builtins.print """ from utool . _internal . meta_util_dbg import get_caller_name calltag = '' . join ( ( '[caller:' , get_caller_name ( N = DEBUG_PRINT_N ) , ']' ) ) util_logging . _utool_print ( ) ( calltag , * args ) else : def print ( * args ) : """ logging builtins.print """ util_logging . _utool_print ( ) ( * args ) if __AGGROFLUSH__ : def print_ ( * args ) : """ aggressive logging stdout.write """ util_logging . _utool_write ( ) ( * args ) util_logging . _utool_flush ( ) ( ) else : def print_ ( * args ) : """ logging stdout.write """ util_logging . _utool_write ( ) ( * args ) # turn on module debugging with command line flags dotpos = module . __name__ . rfind ( '.' ) if dotpos == - 1 : module_name = module . __name__ else : module_name = module . __name__ [ dotpos + 1 : ] def _replchars ( str_ ) : return str_ . replace ( '_' , '-' ) . replace ( ']' , '' ) . replace ( '[' , '' ) flag1 = '--debug-%s' % _replchars ( module_name ) flag2 = '--debug-%s' % _replchars ( module_prefix ) DEBUG_FLAG = any ( [ flag in sys . argv for flag in [ flag1 , flag2 ] ] ) for curflag in ARGV_DEBUG_FLAGS : if curflag in module_prefix : DEBUG_FLAG = True if __DEBUG_ALL__ or DEBUG or DEBUG_FLAG : print ( 'INJECT_PRINT: %r == %r' % ( module_name , module_prefix ) ) def printDBG ( * args ) : """ debug logging print """ msg = ', ' . join ( map ( str , args ) ) util_logging . __UTOOL_PRINTDBG__ ( module_prefix + ' DEBUG ' + msg ) else : def printDBG ( * args ) : """ silent debug logging print """ pass #_inject_funcs(module, print, print_, printDBG) print_funcs = ( print , print_ , printDBG ) return print_funcs
9,442
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L207-L272
[ "def", "cache_url_config", "(", "cls", ",", "url", ",", "backend", "=", "None", ")", ":", "url", "=", "urlparse", "(", "url", ")", "if", "not", "isinstance", "(", "url", ",", "cls", ".", "URL_CLASS", ")", "else", "url", "location", "=", "url", ".", "netloc", ".", "split", "(", "','", ")", "if", "len", "(", "location", ")", "==", "1", ":", "location", "=", "location", "[", "0", "]", "config", "=", "{", "'BACKEND'", ":", "cls", ".", "CACHE_SCHEMES", "[", "url", ".", "scheme", "]", ",", "'LOCATION'", ":", "location", ",", "}", "# Add the drive to LOCATION", "if", "url", ".", "scheme", "==", "'filecache'", ":", "config", ".", "update", "(", "{", "'LOCATION'", ":", "url", ".", "netloc", "+", "url", ".", "path", ",", "}", ")", "if", "url", ".", "path", "and", "url", ".", "scheme", "in", "[", "'memcache'", ",", "'pymemcache'", "]", ":", "config", ".", "update", "(", "{", "'LOCATION'", ":", "'unix:'", "+", "url", ".", "path", ",", "}", ")", "elif", "url", ".", "scheme", ".", "startswith", "(", "'redis'", ")", ":", "if", "url", ".", "hostname", ":", "scheme", "=", "url", ".", "scheme", ".", "replace", "(", "'cache'", ",", "''", ")", "else", ":", "scheme", "=", "'unix'", "locations", "=", "[", "scheme", "+", "'://'", "+", "loc", "+", "url", ".", "path", "for", "loc", "in", "url", ".", "netloc", ".", "split", "(", "','", ")", "]", "config", "[", "'LOCATION'", "]", "=", "locations", "[", "0", "]", "if", "len", "(", "locations", ")", "==", "1", "else", "locations", "if", "url", ".", "query", ":", "config_options", "=", "{", "}", "for", "k", ",", "v", "in", "parse_qs", "(", "url", ".", "query", ")", ".", "items", "(", ")", ":", "opt", "=", "{", "k", ".", "upper", "(", ")", ":", "_cast", "(", "v", "[", "0", "]", ")", "}", "if", "k", ".", "upper", "(", ")", "in", "cls", ".", "_CACHE_BASE_OPTIONS", ":", "config", ".", "update", "(", "opt", ")", "else", ":", "config_options", ".", "update", "(", "opt", ")", "config", "[", "'OPTIONS'", "]", "=", "config_options", "if", "backend", ":", "config", "[", "'BACKEND'", "]", "=", "backend", "return", "config" ]
Injects dynamic module reloading
def make_module_reload_func ( module_name = None , module_prefix = '[???]' , module = None ) : module = _get_module ( module_name , module , register = False ) if module_name is None : module_name = str ( module . __name__ ) def rrr ( verbose = True ) : """ Dynamic module reloading """ if not __RELOAD_OK__ : raise Exception ( 'Reloading has been forced off' ) try : import imp if verbose and not QUIET : builtins . print ( 'RELOAD: ' + str ( module_prefix ) + ' __name__=' + module_name ) imp . reload ( module ) except Exception as ex : print ( ex ) print ( '%s Failed to reload' % module_prefix ) raise # this doesn't seem to set anything on import * #_inject_funcs(module, rrr) return rrr
9,443
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L298-L318
[ "def", "regex_chooser", "(", "alg", ")", ":", "if", "alg", "&", "ns", ".", "FLOAT", ":", "alg", "&=", "ns", ".", "FLOAT", "|", "ns", ".", "SIGNED", "|", "ns", ".", "NOEXP", "else", ":", "alg", "&=", "ns", ".", "INT", "|", "ns", ".", "SIGNED", "return", "{", "ns", ".", "INT", ":", "NumericalRegularExpressions", ".", "int_nosign", "(", ")", ",", "ns", ".", "FLOAT", ":", "NumericalRegularExpressions", ".", "float_nosign_exp", "(", ")", ",", "ns", ".", "INT", "|", "ns", ".", "SIGNED", ":", "NumericalRegularExpressions", ".", "int_sign", "(", ")", ",", "ns", ".", "FLOAT", "|", "ns", ".", "SIGNED", ":", "NumericalRegularExpressions", ".", "float_sign_exp", "(", ")", ",", "ns", ".", "FLOAT", "|", "ns", ".", "NOEXP", ":", "NumericalRegularExpressions", ".", "float_nosign_noexp", "(", ")", ",", "ns", ".", "FLOAT", "|", "ns", ".", "SIGNED", "|", "ns", ".", "NOEXP", ":", "NumericalRegularExpressions", ".", "float_sign_noexp", "(", ")", ",", "}", "[", "alg", "]" ]
Use in modules that do not have inject in them
def noinject ( module_name = None , module_prefix = '[???]' , DEBUG = False , module = None , N = 0 , via = None ) : if PRINT_INJECT_ORDER : from utool . _internal import meta_util_dbg callername = meta_util_dbg . get_caller_name ( N = N + 1 , strict = False ) lineno = meta_util_dbg . get_caller_lineno ( N = N + 1 , strict = False ) suff = ' via %s' % ( via , ) if via else '' fmtdict = dict ( N = N , lineno = lineno , callername = callername , modname = module_name , suff = suff ) msg = '[util_inject] N={N} {modname} is imported by {callername} at lineno={lineno}{suff}' . format ( * * fmtdict ) if DEBUG_SLOW_IMPORT : global PREV_MODNAME seconds = tt . toc ( ) import_times [ ( PREV_MODNAME , module_name ) ] = seconds PREV_MODNAME = module_name builtins . print ( msg ) if DEBUG_SLOW_IMPORT : tt . tic ( ) # builtins.print(elapsed) if EXIT_ON_INJECT_MODNAME == module_name : builtins . print ( '...exiting' ) assert False , 'exit in inject requested'
9,444
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L441-L470
[ "def", "_verify_options", "(", "options", ")", ":", "# sanity check all vals used for bitwise operations later", "bitwise_args", "=", "[", "(", "'level'", ",", "options", "[", "'level'", "]", ")", ",", "(", "'facility'", ",", "options", "[", "'facility'", "]", ")", "]", "bitwise_args", ".", "extend", "(", "[", "(", "'option'", ",", "x", ")", "for", "x", "in", "options", "[", "'options'", "]", "]", ")", "for", "opt_name", ",", "opt", "in", "bitwise_args", ":", "if", "not", "hasattr", "(", "syslog", ",", "opt", ")", ":", "log", ".", "error", "(", "'syslog has no attribute %s'", ",", "opt", ")", "return", "False", "if", "not", "isinstance", "(", "getattr", "(", "syslog", ",", "opt", ")", ",", "int", ")", ":", "log", ".", "error", "(", "'%s is not a valid syslog %s'", ",", "opt", ",", "opt_name", ")", "return", "False", "# Sanity check tag", "if", "'tag'", "in", "options", ":", "if", "not", "isinstance", "(", "options", "[", "'tag'", "]", ",", "six", ".", "string_types", ")", ":", "log", ".", "error", "(", "'tag must be a string'", ")", "return", "False", "if", "len", "(", "options", "[", "'tag'", "]", ")", ">", "32", ":", "log", ".", "error", "(", "'tag size is limited to 32 characters'", ")", "return", "False", "return", "True" ]
Injects your module with utool magic
def inject ( module_name = None , module_prefix = '[???]' , DEBUG = False , module = None , N = 1 ) : #noinject(module_name, module_prefix, DEBUG, module, N=1) noinject ( module_name , module_prefix , DEBUG , module , N = N ) module = _get_module ( module_name , module ) rrr = make_module_reload_func ( None , module_prefix , module ) profile_ = make_module_profile_func ( None , module_prefix , module ) print_funcs = inject_print_functions ( None , module_prefix , DEBUG , module ) ( print , print_ , printDBG ) = print_funcs return ( print , print_ , printDBG , rrr , profile_ )
9,445
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L473-L508
[ "def", "get_listing", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'listing'", ")", ":", "allEvents", "=", "self", ".", "get_allEvents", "(", ")", "openEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", "closedEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", "publicEvents", "=", "allEvents", ".", "instance_of", "(", "PublicEvent", ")", "allSeries", "=", "allEvents", ".", "instance_of", "(", "Series", ")", "self", ".", "listing", "=", "{", "'allEvents'", ":", "allEvents", ",", "'openEvents'", ":", "openEvents", ",", "'closedEvents'", ":", "closedEvents", ",", "'publicEvents'", ":", "publicEvents", ",", "'allSeries'", ":", "allSeries", ",", "'regOpenEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateEvents'", ":", "publicEvents", ".", "filter", "(", "publicevent__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'publicevent__category'", ")", ",", "'regOpenSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateSeries'", ":", "allSeries", ".", "filter", "(", "series__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'series__category'", ")", ",", "}", "return", "self", ".", "listing" ]
wrapper that depricates print_ and printDBG
def inject2 ( module_name = None , module_prefix = None , DEBUG = False , module = None , N = 1 ) : if module_prefix is None : module_prefix = '[%s]' % ( module_name , ) noinject ( module_name , module_prefix , DEBUG , module , N = N ) module = _get_module ( module_name , module ) rrr = make_module_reload_func ( None , module_prefix , module ) profile_ = make_module_profile_func ( None , module_prefix , module ) print = make_module_print_func ( module ) return print , rrr , profile_
9,446
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L511-L520
[ "def", "classify", "(", "self", ",", "txt", ")", ":", "ranks", "=", "[", "]", "for", "lang", ",", "score", "in", "langid", ".", "rank", "(", "txt", ")", ":", "if", "lang", "in", "self", ".", "preferred_languages", ":", "score", "+=", "self", ".", "preferred_factor", "ranks", ".", "append", "(", "(", "lang", ",", "score", ")", ")", "ranks", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ")", "return", "ranks", "[", "0", "]", "[", "0", "]" ]
Does autogeneration stuff
def inject_python_code2 ( fpath , patch_code , tag ) : import utool as ut text = ut . readfrom ( fpath ) start_tag = '# <%s>' % tag end_tag = '# </%s>' % tag new_text = ut . replace_between_tags ( text , patch_code , start_tag , end_tag ) ut . writeto ( fpath , new_text )
9,447
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L561-L568
[ "def", "clean_surface", "(", "surface", ",", "span", ")", ":", "surface", "=", "surface", ".", "replace", "(", "'-'", ",", "' '", ")", "no_start", "=", "[", "'and'", ",", "' '", "]", "no_end", "=", "[", "' and'", ",", "' '", "]", "found", "=", "True", "while", "found", ":", "found", "=", "False", "for", "word", "in", "no_start", ":", "if", "surface", ".", "lower", "(", ")", ".", "startswith", "(", "word", ")", ":", "surface", "=", "surface", "[", "len", "(", "word", ")", ":", "]", "span", "=", "(", "span", "[", "0", "]", "+", "len", "(", "word", ")", ",", "span", "[", "1", "]", ")", "found", "=", "True", "for", "word", "in", "no_end", ":", "if", "surface", ".", "lower", "(", ")", ".", "endswith", "(", "word", ")", ":", "surface", "=", "surface", "[", ":", "-", "len", "(", "word", ")", "]", "span", "=", "(", "span", "[", "0", "]", ",", "span", "[", "1", "]", "-", "len", "(", "word", ")", ")", "found", "=", "True", "if", "not", "surface", ":", "return", "None", ",", "None", "split", "=", "surface", ".", "lower", "(", ")", ".", "split", "(", ")", "if", "split", "[", "0", "]", "in", "[", "'one'", ",", "'a'", ",", "'an'", "]", "and", "len", "(", "split", ")", ">", "1", "and", "split", "[", "1", "]", "in", "r", ".", "UNITS", "+", "r", ".", "TENS", ":", "span", "=", "(", "span", "[", "0", "]", "+", "len", "(", "surface", ".", "split", "(", ")", "[", "0", "]", ")", "+", "1", ",", "span", "[", "1", "]", ")", "surface", "=", "' '", ".", "join", "(", "surface", ".", "split", "(", ")", "[", "1", ":", "]", ")", "return", "surface", ",", "span" ]
DEPRICATE puts code into files on disk
def inject_python_code ( fpath , patch_code , tag = None , inject_location = 'after_imports' ) : import utool as ut assert tag is not None , 'TAG MUST BE SPECIFIED IN INJECTED CODETEXT' text = ut . read_from ( fpath ) comment_start_tag = '# <util_inject:%s>' % tag comment_end_tag = '# </util_inject:%s>' % tag tagstart_txtpos = text . find ( comment_start_tag ) tagend_txtpos = text . find ( comment_end_tag ) text_lines = ut . split_python_text_into_lines ( text ) # split the file into two parts and inject code between them if tagstart_txtpos != - 1 or tagend_txtpos != - 1 : assert tagstart_txtpos != - 1 , 'both tags must not be found' assert tagend_txtpos != - 1 , 'both tags must not be found' for pos , line in enumerate ( text_lines ) : if line . startswith ( comment_start_tag ) : tagstart_pos = pos if line . startswith ( comment_end_tag ) : tagend_pos = pos part1 = text_lines [ 0 : tagstart_pos ] part2 = text_lines [ tagend_pos + 1 : ] else : if inject_location == 'after_imports' : first_nonimport_pos = 0 for line in text_lines : list_ = [ 'import ' , 'from ' , '#' , ' ' ] isvalid = ( len ( line ) == 0 or any ( line . startswith ( str_ ) for str_ in list_ ) ) if not isvalid : break first_nonimport_pos += 1 part1 = text_lines [ 0 : first_nonimport_pos ] part2 = text_lines [ first_nonimport_pos : ] else : raise AssertionError ( 'Unknown inject location' ) newtext = ( '\n' . join ( part1 + [ comment_start_tag ] ) + '\n' + patch_code + '\n' + '\n' . join ( [ comment_end_tag ] + part2 ) ) text_backup_fname = fpath + '.' + ut . get_timestamp ( ) + '.bak' ut . write_to ( text_backup_fname , text ) ut . write_to ( fpath , newtext )
9,448
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inject.py#L571-L622
[ "def", "get_resource_by_id", "(", "resource_id", ",", "api_version", ",", "extract_value", "=", "None", ")", ":", "ret", "=", "{", "}", "try", ":", "resconn", "=", "get_conn", "(", "client_type", "=", "'resource'", ")", "resource_query", "=", "resconn", ".", "resources", ".", "get_by_id", "(", "resource_id", "=", "resource_id", ",", "api_version", "=", "api_version", ")", "resource_dict", "=", "resource_query", ".", "as_dict", "(", ")", "if", "extract_value", "is", "not", "None", ":", "ret", "=", "resource_dict", "[", "extract_value", "]", "else", ":", "ret", "=", "resource_dict", "except", "CloudError", "as", "exc", ":", "__utils__", "[", "'azurearm.log_cloud_error'", "]", "(", "'resource'", ",", "exc", ".", "message", ")", "ret", "=", "{", "'Error'", ":", "exc", ".", "message", "}", "return", "ret" ]
Tries to make a nice type string for a value . Can also pass in a Printable parent object
def printableType ( val , name = None , parent = None ) : import numpy as np if parent is not None and hasattr ( parent , 'customPrintableType' ) : # Hack for non - trivial preference types _typestr = parent . customPrintableType ( name ) if _typestr is not None : return _typestr if isinstance ( val , np . ndarray ) : info = npArrInfo ( val ) _typestr = info . dtypestr elif isinstance ( val , object ) : _typestr = val . __class__ . __name__ else : _typestr = str ( type ( val ) ) _typestr = _typestr . replace ( 'type' , '' ) _typestr = re . sub ( '[\'><]' , '' , _typestr ) _typestr = re . sub ( ' *' , ' ' , _typestr ) _typestr = _typestr . strip ( ) return _typestr
9,449
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Printable.py#L96-L118
[ "def", "similarity", "(", "self", ",", "other", ":", "'Trigram'", ")", "->", "float", ":", "if", "not", "len", "(", "self", ".", "_trigrams", ")", "or", "not", "len", "(", "other", ".", "_trigrams", ")", ":", "return", "0", "count", "=", "float", "(", "len", "(", "self", ".", "_trigrams", "&", "other", ".", "_trigrams", ")", ")", "len1", "=", "float", "(", "len", "(", "self", ".", "_trigrams", ")", ")", "len2", "=", "float", "(", "len", "(", "other", ".", "_trigrams", ")", ")", "return", "count", "/", "(", "len1", "+", "len2", "-", "count", ")" ]
Very old way of doing pretty printing . Need to update and refactor . DEPRICATE
def printableVal ( val , type_bit = True , justlength = False ) : from utool import util_dev # Move to util_dev # NUMPY ARRAY import numpy as np if type ( val ) is np . ndarray : info = npArrInfo ( val ) if info . dtypestr . startswith ( 'bool' ) : _valstr = '{ shape:' + info . shapestr + ' bittotal: ' + info . bittotal + '}' # + '\n |_____' elif info . dtypestr . startswith ( 'float' ) : _valstr = util_dev . get_stats_str ( val ) else : _valstr = '{ shape:' + info . shapestr + ' mM:' + info . minmaxstr + ' }' # + '\n |_____' # String elif isinstance ( val , ( str , unicode ) ) : # NOQA _valstr = '\'%s\'' % val # List elif isinstance ( val , list ) : if justlength or len ( val ) > 30 : _valstr = 'len=' + str ( len ( val ) ) else : _valstr = '[ ' + ( ', \n ' . join ( [ str ( v ) for v in val ] ) ) + ' ]' # ??? isinstance(val, AbstractPrintable): elif hasattr ( val , 'get_printable' ) and type ( val ) != type : _valstr = val . get_printable ( type_bit = type_bit ) elif isinstance ( val , dict ) : _valstr = '{\n' for val_key in val . keys ( ) : val_val = val [ val_key ] _valstr += ' ' + str ( val_key ) + ' : ' + str ( val_val ) + '\n' _valstr += '}' else : _valstr = str ( val ) if _valstr . find ( '\n' ) > 0 : # Indent if necessary _valstr = _valstr . replace ( '\n' , '\n ' ) _valstr = '\n ' + _valstr _valstr = re . sub ( '\n *$' , '' , _valstr ) # Replace empty lines return _valstr
9,450
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Printable.py#L121-L163
[ "def", "get_job_ids", "(", "self", ")", ":", "if", "not", "self", ".", "parsed_response", ":", "return", "None", "try", ":", "job_ids", "=", "self", ".", "parsed_response", "[", "\"files\"", "]", "[", "\"results.xml\"", "]", "[", "\"job-ids\"", "]", "except", "KeyError", ":", "return", "None", "if", "not", "job_ids", "or", "job_ids", "==", "[", "0", "]", ":", "return", "None", "return", "job_ids" ]
OLD update and refactor
def npArrInfo ( arr ) : from utool . DynamicStruct import DynStruct info = DynStruct ( ) info . shapestr = '[' + ' x ' . join ( [ str ( x ) for x in arr . shape ] ) + ']' info . dtypestr = str ( arr . dtype ) if info . dtypestr == 'bool' : info . bittotal = 'T=%d, F=%d' % ( sum ( arr ) , sum ( 1 - arr ) ) elif info . dtypestr == 'object' : info . minmaxstr = 'NA' elif info . dtypestr [ 0 ] == '|' : info . minmaxstr = 'NA' else : if arr . size > 0 : info . minmaxstr = '(%r, %r)' % ( arr . min ( ) , arr . max ( ) ) else : info . minmaxstr = '(None)' return info
9,451
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Printable.py#L166-L185
[ "def", "main", "(", "self", ")", ":", "self", ".", "secret_finder", "(", ")", "self", ".", "parse_access_token", "(", ")", "self", ".", "get_session_token", "(", ")", "self", ".", "parse_session_token", "(", ")", "self", ".", "get_route", "(", ")", "self", ".", "download_profile", "(", ")", "self", ".", "find_loci", "(", ")", "self", ".", "download_loci", "(", ")" ]
Main function to calculate ratios for PSMs peptides proteins genes . Can do simple ratios median - of - ratios and median - centering normalization .
def get_isobaric_ratios ( psmfn , psmheader , channels , denom_channels , min_int , targetfn , accessioncol , normalize , normratiofn ) : psm_or_feat_ratios = get_psmratios ( psmfn , psmheader , channels , denom_channels , min_int , accessioncol ) if normalize and normratiofn : normheader = reader . get_tsv_header ( normratiofn ) normratios = get_ratios_from_fn ( normratiofn , normheader , channels ) ch_medians = get_medians ( channels , normratios , report = True ) outratios = calculate_normalized_ratios ( psm_or_feat_ratios , ch_medians , channels ) elif normalize : flatratios = [ [ feat [ ch ] for ch in channels ] for feat in psm_or_feat_ratios ] ch_medians = get_medians ( channels , flatratios , report = True ) outratios = calculate_normalized_ratios ( psm_or_feat_ratios , ch_medians , channels ) else : outratios = psm_or_feat_ratios # at this point, outratios look like: # [{ch1: 123, ch2: 456, ISOQUANTRATIO_FEAT_ACC: ENSG1244}, ] if accessioncol and targetfn : outratios = { x [ ISOQUANTRATIO_FEAT_ACC ] : x for x in outratios } return output_to_target_accession_table ( targetfn , outratios , channels ) elif not accessioncol and not targetfn : return paste_to_psmtable ( psmfn , psmheader , outratios ) elif accessioncol and not targetfn : # generate new table with accessions return ( { ( k if not k == ISOQUANTRATIO_FEAT_ACC else prottabledata . HEADER_ACCESSION ) : v for k , v in ratio . items ( ) } for ratio in outratios )
9,452
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/isonormalize.py#L13-L45
[ "def", "play_next", "(", "self", ",", "stream_url", "=", "None", ",", "offset", "=", "0", ",", "opaque_token", "=", "None", ")", ":", "directive", "=", "self", ".", "_play_directive", "(", "'REPLACE_ENQUEUED'", ")", "directive", "[", "'audioItem'", "]", "=", "self", ".", "_audio_item", "(", "stream_url", "=", "stream_url", ",", "offset", "=", "offset", ",", "opaque_token", "=", "opaque_token", ")", "self", ".", "_response", "[", "'directives'", "]", ".", "append", "(", "directive", ")", "return", "self" ]
Strips all undesirable characters out of potential file paths .
def sanitize ( value ) : value = unicodedata . normalize ( 'NFKD' , value ) value = value . strip ( ) value = re . sub ( '[^./\w\s-]' , '' , value ) value = re . sub ( '[-\s]+' , '-' , value ) return value
9,453
https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/files.py#L10-L18
[ "def", "add_grad", "(", "left", ",", "right", ")", ":", "# We assume that initial gradients are always identity WRT add_grad.", "# We also assume that only init_grad could have created None values.", "assert", "left", "is", "not", "None", "and", "right", "is", "not", "None", "left_type", "=", "type", "(", "left", ")", "right_type", "=", "type", "(", "right", ")", "if", "left_type", "is", "ZeroGradient", ":", "return", "right", "if", "right_type", "is", "ZeroGradient", ":", "return", "left", "return", "grad_adders", "[", "(", "left_type", ",", "right_type", ")", "]", "(", "left", ",", "right", ")" ]
Creates a directory yields to the caller and removes that directory if an exception is thrown .
def remove_on_exception ( dirname , remove = True ) : os . makedirs ( dirname ) try : yield except : if remove : shutil . rmtree ( dirname , ignore_errors = True ) raise
9,454
https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/files.py#L22-L31
[ "def", "setup_partitioning", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Setting up the enhanced partitioning system\"", ")", "# Add \"Create partition\" transition", "add_create_partition_transition", "(", "portal", ")", "# Add getAncestorsUIDs index in analyses catalog", "add_partitioning_indexes", "(", "portal", ")", "# Adds metadata columns for partitioning", "add_partitioning_metadata", "(", "portal", ")", "# Setup default ID formatting for partitions", "set_partitions_id_formatting", "(", "portal", ")" ]
Takes a MSGF + tsv and corresponding mzId adds percolatordata to tsv lines . Generator yields the lines . Multiple PSMs per scan can be delivered in which case rank is also reported .
def add_percolator_to_mzidtsv ( mzidfn , tsvfn , multipsm , oldheader ) : namespace = readers . get_mzid_namespace ( mzidfn ) try : xmlns = '{%s}' % namespace [ 'xmlns' ] except TypeError : xmlns = '' specfnids = readers . get_mzid_specfile_ids ( mzidfn , namespace ) mzidpepmap = { } for peptide in readers . generate_mzid_peptides ( mzidfn , namespace ) : pep_id , seq = readers . get_mzid_peptidedata ( peptide , xmlns ) mzidpepmap [ pep_id ] = seq mzidpercomap = { } for specid_data in readers . generate_mzid_spec_id_items ( mzidfn , namespace , xmlns , specfnids ) : scan , fn , pepid , spec_id = specid_data percodata = readers . get_specidentitem_percolator_data ( spec_id , xmlns ) try : mzidpercomap [ fn ] [ scan ] [ mzidpepmap [ pepid ] ] = percodata except KeyError : try : mzidpercomap [ fn ] [ scan ] = { mzidpepmap [ pepid ] : percodata } except KeyError : mzidpercomap [ fn ] = { scan : { mzidpepmap [ pepid ] : percodata } } for line in tsvreader . generate_tsv_psms ( tsvfn , oldheader ) : outline = { k : v for k , v in line . items ( ) } fn = line [ mzidtsvdata . HEADER_SPECFILE ] scan = line [ mzidtsvdata . HEADER_SCANNR ] seq = line [ mzidtsvdata . HEADER_PEPTIDE ] outline . update ( mzidpercomap [ fn ] [ scan ] [ seq ] ) yield outline
9,455
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/percolator.py#L6-L39
[ "def", "shared_like", "(", "param", ",", "suffix", ",", "init", "=", "0", ")", ":", "return", "theano", ".", "shared", "(", "np", ".", "zeros_like", "(", "param", ".", "get_value", "(", ")", ")", "+", "init", ",", "name", "=", "'{}_{}'", ".", "format", "(", "param", ".", "name", ",", "suffix", ")", ",", "broadcastable", "=", "param", ".", "broadcastable", ")" ]
Split the file into blocks along delimters and and put delimeters back in the list
def parse_rawprofile_blocks ( text ) : # The total time reported in the raw output is from pystone not kernprof # The pystone total time is actually the average time spent in the function delim = 'Total time: ' delim2 = 'Pystone time: ' #delim = 'File: ' profile_block_list = ut . regex_split ( '^' + delim , text ) for ix in range ( 1 , len ( profile_block_list ) ) : profile_block_list [ ix ] = delim2 + profile_block_list [ ix ] return profile_block_list
9,456
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_profile.py#L78-L91
[ "def", "similarity", "(", "self", ",", "other", ")", ":", "sim", "=", "self", ".", "Similarity", "(", ")", "total", "=", "0.0", "# Calculate similarity ratio for each attribute", "cname", "=", "self", ".", "__class__", ".", "__name__", "for", "aname", ",", "weight", "in", "self", ".", "attributes", ".", "items", "(", ")", ":", "attr1", "=", "getattr", "(", "self", ",", "aname", ",", "None", ")", "attr2", "=", "getattr", "(", "other", ",", "aname", ",", "None", ")", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ")", "# Similarity is ignored if None on both objects", "if", "attr1", "is", "None", "and", "attr2", "is", "None", ":", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ",", "result", "=", "\"attributes are both None\"", ")", "continue", "# Similarity is 0 if either attribute is non-Comparable", "if", "not", "all", "(", "(", "isinstance", "(", "attr1", ",", "Comparable", ")", ",", "isinstance", "(", "attr2", ",", "Comparable", ")", ")", ")", ":", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ",", "result", "=", "\"attributes not Comparable\"", ")", "total", "+=", "weight", "continue", "# Calculate similarity between the attributes", "attr_sim", "=", "(", "attr1", "%", "attr2", ")", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ",", "result", "=", "attr_sim", ")", "# Add the similarity to the total", "sim", "+=", "attr_sim", "*", "weight", "total", "+=", "weight", "# Scale the similarity so the total is 1.0", "if", "total", ":", "sim", "*=", "(", "1.0", "/", "total", ")", "return", "sim" ]
Build a map from times to line_profile blocks
def parse_timemap_from_blocks ( profile_block_list ) : prefix_list = [ ] timemap = ut . ddict ( list ) for ix in range ( len ( profile_block_list ) ) : block = profile_block_list [ ix ] total_time = get_block_totaltime ( block ) # Blocks without time go at the front of sorted output if total_time is None : prefix_list . append ( block ) # Blocks that are not run are not appended to output elif total_time != 0 : timemap [ total_time ] . append ( block ) return prefix_list , timemap
9,457
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_profile.py#L123-L138
[ "def", "_handle_properties", "(", "self", ",", "stmt", ":", "Statement", ",", "sctx", ":", "SchemaContext", ")", "->", "None", ":", "self", ".", "_handle_restrictions", "(", "stmt", ",", "sctx", ")" ]
Sorts the output from line profile by execution time Removes entries which were not run
def clean_line_profile_text ( text ) : # profile_block_list = parse_rawprofile_blocks ( text ) #profile_block_list = fix_rawprofile_blocks(profile_block_list) #--- # FIXME can be written much nicer prefix_list , timemap = parse_timemap_from_blocks ( profile_block_list ) # Sort the blocks by time sorted_lists = sorted ( six . iteritems ( timemap ) , key = operator . itemgetter ( 0 ) ) newlist = prefix_list [ : ] for key , val in sorted_lists : newlist . extend ( val ) # Rejoin output text output_text = '\n' . join ( newlist ) #--- # Hack in a profile summary summary_text = get_summary ( profile_block_list ) output_text = output_text return output_text , summary_text
9,458
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_profile.py#L191-L213
[ "def", "read_content", "(", "self", ")", ":", "if", "self", ".", "is_directory", "(", ")", ":", "self", ".", "url_connection", ".", "cwd", "(", "self", ".", "filename", ")", "self", ".", "files", "=", "self", ".", "get_files", "(", ")", "# XXX limit number of files?", "data", "=", "get_index_html", "(", "self", ".", "files", ")", "else", ":", "# download file in BINARY mode", "ftpcmd", "=", "\"RETR %s\"", "%", "self", ".", "filename", "buf", "=", "StringIO", "(", ")", "def", "stor_data", "(", "s", ")", ":", "\"\"\"Helper method storing given data\"\"\"", "# limit the download size", "if", "(", "buf", ".", "tell", "(", ")", "+", "len", "(", "s", ")", ")", ">", "self", ".", "max_size", ":", "raise", "LinkCheckerError", "(", "_", "(", "\"FTP file size too large\"", ")", ")", "buf", ".", "write", "(", "s", ")", "self", ".", "url_connection", ".", "retrbinary", "(", "ftpcmd", ",", "stor_data", ")", "data", "=", "buf", ".", "getvalue", "(", ")", "buf", ".", "close", "(", ")", "return", "data" ]
Reads a . lprof file and cleans it
def clean_lprof_file ( input_fname , output_fname = None ) : # Read the raw .lprof text dump text = ut . read_from ( input_fname ) # Sort and clean the text output_text = clean_line_profile_text ( text ) return output_text
9,459
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_profile.py#L216-L222
[ "def", "get_hash_as_int", "(", "*", "args", ",", "group", ":", "cmod", ".", "PairingGroup", "=", "None", ")", ":", "group", "=", "group", "if", "group", "else", "cmod", ".", "PairingGroup", "(", "PAIRING_GROUP", ")", "h_challenge", "=", "sha256", "(", ")", "serialedArgs", "=", "[", "group", ".", "serialize", "(", "arg", ")", "if", "isGroupElement", "(", "arg", ")", "else", "cmod", ".", "Conversion", ".", "IP2OS", "(", "arg", ")", "for", "arg", "in", "args", "]", "for", "arg", "in", "sorted", "(", "serialedArgs", ")", ":", "h_challenge", ".", "update", "(", "arg", ")", "return", "bytes_to_int", "(", "h_challenge", ".", "digest", "(", ")", ")" ]
Returns the weights for each class based on the frequencies of the samples .
def get_class_weights ( y , smooth_factor = 0 ) : from collections import Counter counter = Counter ( y ) if smooth_factor > 0 : p = max ( counter . values ( ) ) * smooth_factor for k in counter . keys ( ) : counter [ k ] += p majority = max ( counter . values ( ) ) return { cls : float ( majority / count ) for cls , count in counter . items ( ) }
9,460
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/keras.py#L4-L26
[ "def", "handle_query_error", "(", "msg", ",", "query", ",", "session", ",", "payload", "=", "None", ")", ":", "payload", "=", "payload", "or", "{", "}", "troubleshooting_link", "=", "config", "[", "'TROUBLESHOOTING_LINK'", "]", "query", ".", "error_message", "=", "msg", "query", ".", "status", "=", "QueryStatus", ".", "FAILED", "query", ".", "tmp_table_name", "=", "None", "session", ".", "commit", "(", ")", "payload", ".", "update", "(", "{", "'status'", ":", "query", ".", "status", ",", "'error'", ":", "msg", ",", "}", ")", "if", "troubleshooting_link", ":", "payload", "[", "'link'", "]", "=", "troubleshooting_link", "return", "payload" ]
Plots the learning history for a Keras model assuming the validation data was provided to the fit function .
def plot_loss_history ( history , figsize = ( 15 , 8 ) ) : plt . figure ( figsize = figsize ) plt . plot ( history . history [ "loss" ] ) plt . plot ( history . history [ "val_loss" ] ) plt . xlabel ( "# Epochs" ) plt . ylabel ( "Loss" ) plt . legend ( [ "Training" , "Validation" ] ) plt . title ( "Loss over time" ) plt . show ( )
9,461
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/keras.py#L29-L49
[ "def", "compose", "(", "self", ")", ":", "rr", "=", "self", ".", "__reagents", "+", "self", ".", "__reactants", "if", "rr", ":", "if", "not", "all", "(", "isinstance", "(", "x", ",", "(", "MoleculeContainer", ",", "CGRContainer", ")", ")", "for", "x", "in", "rr", ")", ":", "raise", "TypeError", "(", "'Queries not composable'", ")", "r", "=", "reduce", "(", "or_", ",", "rr", ")", "else", ":", "r", "=", "MoleculeContainer", "(", ")", "if", "self", ".", "__products", ":", "if", "not", "all", "(", "isinstance", "(", "x", ",", "(", "MoleculeContainer", ",", "CGRContainer", ")", ")", "for", "x", "in", "self", ".", "__products", ")", ":", "raise", "TypeError", "(", "'Queries not composable'", ")", "p", "=", "reduce", "(", "or_", ",", "self", ".", "__products", ")", "else", ":", "p", "=", "MoleculeContainer", "(", ")", "return", "r", "^", "p" ]
r iterates through iterable with a window size generalizeation of itertwo
def iter_window ( iterable , size = 2 , step = 1 , wrap = False ) : # it.tee may be slow, but works on all iterables iter_list = it . tee ( iterable , size ) if wrap : # Secondary iterables need to be cycled for wraparound iter_list = [ iter_list [ 0 ] ] + list ( map ( it . cycle , iter_list [ 1 : ] ) ) # Step each iterator the approprate number of times try : for count , iter_ in enumerate ( iter_list [ 1 : ] , start = 1 ) : for _ in range ( count ) : six . next ( iter_ ) except StopIteration : return iter ( ( ) ) else : _window_iter = zip ( * iter_list ) # Account for the step size window_iter = it . islice ( _window_iter , 0 , None , step ) return window_iter
9,462
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L89-L143
[ "def", "decode_consumer_metadata_response", "(", "cls", ",", "data", ")", ":", "(", "(", "correlation_id", ",", "error", ",", "nodeId", ")", ",", "cur", ")", "=", "relative_unpack", "(", "'>ihi'", ",", "data", ",", "0", ")", "(", "host", ",", "cur", ")", "=", "read_short_string", "(", "data", ",", "cur", ")", "(", "(", "port", ",", ")", ",", "cur", ")", "=", "relative_unpack", "(", "'>i'", ",", "data", ",", "cur", ")", "return", "kafka", ".", "structs", ".", "ConsumerMetadataResponse", "(", "error", ",", "nodeId", ",", "host", ",", "port", ")" ]
iter_compress - like numpy compress
def iter_compress ( item_iter , flag_iter ) : # TODO: Just use it.compress true_items = ( item for ( item , flag ) in zip ( item_iter , flag_iter ) if flag ) return true_items
9,463
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L232-L255
[ "def", "getAllowedReturnURLs", "(", "relying_party_url", ")", ":", "(", "rp_url_after_redirects", ",", "return_to_urls", ")", "=", "services", ".", "getServiceEndpoints", "(", "relying_party_url", ",", "_extractReturnURL", ")", "if", "rp_url_after_redirects", "!=", "relying_party_url", ":", "# Verification caused a redirect", "raise", "RealmVerificationRedirected", "(", "relying_party_url", ",", "rp_url_after_redirects", ")", "return", "return_to_urls" ]
r generates successive n - sized chunks from iterable .
def ichunks ( iterable , chunksize , bordermode = None ) : if bordermode is None : return ichunks_noborder ( iterable , chunksize ) elif bordermode == 'cycle' : return ichunks_cycle ( iterable , chunksize ) elif bordermode == 'replicate' : return ichunks_replicate ( iterable , chunksize ) else : raise ValueError ( 'unknown bordermode=%r' % ( bordermode , ) )
9,464
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L340-L411
[ "def", "set_volume", "(", "self", ",", "volume", ")", ":", "volume", "=", "min", "(", "max", "(", "0", ",", "volume", ")", ",", "1", ")", "self", ".", "logger", ".", "info", "(", "\"Receiver:setting volume to %.1f\"", ",", "volume", ")", "self", ".", "send_message", "(", "{", "MESSAGE_TYPE", ":", "'SET_VOLUME'", ",", "'volume'", ":", "{", "'level'", ":", "volume", "}", "}", ")", "return", "volume" ]
input must be a list .
def ichunks_list ( list_ , chunksize ) : return ( list_ [ ix : ix + chunksize ] for ix in range ( 0 , len ( list_ ) , chunksize ) )
9,465
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L458-L468
[ "def", "_compute_intra_event_alpha", "(", "self", ",", "C", ",", "vs30", ",", "pga1100", ")", ":", "alpha", "=", "np", ".", "zeros_like", "(", "vs30", ",", "dtype", "=", "float", ")", "idx", "=", "vs30", "<", "C", "[", "'k1'", "]", "if", "np", ".", "any", "(", "idx", ")", ":", "temp1", "=", "(", "pga1100", "[", "idx", "]", "+", "C", "[", "'c'", "]", "*", "(", "vs30", "[", "idx", "]", "/", "C", "[", "'k1'", "]", ")", "**", "C", "[", "'n'", "]", ")", "**", "-", "1.", "temp1", "=", "temp1", "-", "(", "(", "pga1100", "[", "idx", "]", "+", "C", "[", "'c'", "]", ")", "**", "-", "1.", ")", "alpha", "[", "idx", "]", "=", "C", "[", "'k2'", "]", "*", "pga1100", "[", "idx", "]", "*", "temp1", "return", "alpha" ]
r zip followed by flatten
def interleave ( args ) : arg_iters = list ( map ( iter , args ) ) cycle_iter = it . cycle ( arg_iters ) for iter_ in cycle_iter : yield six . next ( iter_ )
9,466
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L477-L505
[ "def", "validate_instance_dbname", "(", "self", ",", "dbname", ")", ":", "# 1-64 alphanumeric characters, cannot be a reserved MySQL word", "if", "re", ".", "match", "(", "'[\\w-]+$'", ",", "dbname", ")", "is", "not", "None", ":", "if", "len", "(", "dbname", ")", "<=", "41", "and", "len", "(", "dbname", ")", ">=", "1", ":", "if", "dbname", ".", "lower", "(", ")", "not", "in", "MYSQL_RESERVED_WORDS", ":", "return", "True", "return", "'*** Error: Database names must be 1-64 alphanumeric characters,\\\n cannot be a reserved MySQL word.'" ]
Yields num items from the cartesian product of items in a random order .
def random_product ( items , num = None , rng = None ) : import utool as ut rng = ut . ensure_rng ( rng , 'python' ) seen = set ( ) items = [ list ( g ) for g in items ] max_num = ut . prod ( map ( len , items ) ) if num is None : num = max_num if num > max_num : raise ValueError ( 'num exceedes maximum number of products' ) # TODO: make this more efficient when num is large if num > max_num // 2 : for prod in ut . shuffle ( list ( it . product ( * items ) ) , rng = rng ) : yield prod else : while len ( seen ) < num : # combo = tuple(sorted(rng.choice(items, size, replace=False))) idxs = tuple ( rng . randint ( 0 , len ( g ) - 1 ) for g in items ) if idxs not in seen : seen . add ( idxs ) prod = tuple ( g [ x ] for g , x in zip ( items , idxs ) ) yield prod
9,467
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L512-L549
[ "def", "getKeyName", "(", "username", ",", "date", ",", "blob_key", ")", ":", "sep", "=", "FileMetadata", ".", "__SEP", "return", "str", "(", "username", "+", "sep", "+", "str", "(", "date", ")", "+", "sep", "+", "blob_key", ")" ]
Yields num combinations of length size from items in random order
def random_combinations ( items , size , num = None , rng = None ) : import scipy . misc import numpy as np import utool as ut rng = ut . ensure_rng ( rng , impl = 'python' ) num_ = np . inf if num is None else num # Ensure we dont request more than is possible n_max = int ( scipy . misc . comb ( len ( items ) , size ) ) num_ = min ( n_max , num_ ) if num is not None and num_ > n_max // 2 : # If num is too big just generate all combinations and shuffle them combos = list ( it . combinations ( items , size ) ) rng . shuffle ( combos ) for combo in combos [ : num ] : yield combo else : # Otherwise yield randomly until we get something we havent seen items = list ( items ) combos = set ( ) while len ( combos ) < num_ : # combo = tuple(sorted(rng.choice(items, size, replace=False))) combo = tuple ( sorted ( rng . sample ( items , size ) ) ) if combo not in combos : # TODO: store indices instead of combo values combos . add ( combo ) yield combo
9,468
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L552-L616
[ "def", "getKeyName", "(", "username", ",", "date", ",", "blob_key", ")", ":", "sep", "=", "FileMetadata", ".", "__SEP", "return", "str", "(", "username", "+", "sep", "+", "str", "(", "date", ")", "+", "sep", "+", "blob_key", ")" ]
Parse a connection string and return the associated driver
def parse_dsn ( dsn_string ) : dsn = urlparse ( dsn_string ) scheme = dsn . scheme . split ( '+' ) [ 0 ] username = password = host = port = None host = dsn . netloc if '@' in host : username , host = host . split ( '@' ) if ':' in username : username , password = username . split ( ':' ) password = unquote ( password ) username = unquote ( username ) if ':' in host : host , port = host . split ( ':' ) port = int ( port ) database = dsn . path . split ( '?' ) [ 0 ] [ 1 : ] query = dsn . path . split ( '?' ) [ 1 ] if '?' in dsn . path else dsn . query kwargs = dict ( parse_qsl ( query , True ) ) if scheme == 'sqlite' : return SQLiteDriver , [ dsn . path ] , { } elif scheme == 'mysql' : kwargs [ 'user' ] = username or 'root' kwargs [ 'db' ] = database if port : kwargs [ 'port' ] = port if host : kwargs [ 'host' ] = host if password : kwargs [ 'passwd' ] = password return MySQLDriver , [ ] , kwargs elif scheme == 'postgresql' : kwargs [ 'user' ] = username or 'postgres' kwargs [ 'database' ] = database if port : kwargs [ 'port' ] = port if 'unix_socket' in kwargs : kwargs [ 'host' ] = kwargs . pop ( 'unix_socket' ) elif host : kwargs [ 'host' ] = host if password : kwargs [ 'password' ] = password return PostgreSQLDriver , [ ] , kwargs else : raise ValueError ( 'Unknown driver %s' % dsn_string )
9,469
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/__init__.py#L14-L57
[ "def", "add_otp_style", "(", "self", ",", "zip_odp", ",", "style_file", ")", ":", "style", "=", "zipwrap", ".", "Zippier", "(", "style_file", ")", "for", "picture_file", "in", "style", ".", "ls", "(", "\"Pictures\"", ")", ":", "zip_odp", ".", "write", "(", "picture_file", ",", "style", ".", "cat", "(", "picture_file", ",", "True", ")", ")", "xml_data", "=", "style", ".", "cat", "(", "\"styles.xml\"", ",", "False", ")", "# import pdb;pdb.set_trace()", "xml_data", "=", "self", ".", "override_styles", "(", "xml_data", ")", "zip_odp", ".", "write", "(", "\"styles.xml\"", ",", "xml_data", ")" ]
Prevent write actions on read - only tables .
def db_for_write ( self , model , * * hints ) : try : if model . sf_access == READ_ONLY : raise WriteNotSupportedError ( "%r is a read-only model." % model ) except AttributeError : pass return None
9,470
https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/db/router.py#L26-L39
[ "def", "list_supported_drivers", "(", ")", ":", "def", "convert_oslo_config", "(", "oslo_options", ")", ":", "options", "=", "[", "]", "for", "opt", "in", "oslo_options", ":", "tmp_dict", "=", "{", "k", ":", "str", "(", "v", ")", "for", "k", ",", "v", "in", "vars", "(", "opt", ")", ".", "items", "(", ")", "if", "not", "k", ".", "startswith", "(", "'_'", ")", "}", "options", ".", "append", "(", "tmp_dict", ")", "return", "options", "def", "list_drivers", "(", "queue", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "# Go to the parent directory directory where Cinder is installed", "os", ".", "chdir", "(", "utils", ".", "__file__", ".", "rsplit", "(", "os", ".", "sep", ",", "2", ")", "[", "0", "]", ")", "try", ":", "drivers", "=", "cinder_interface_util", ".", "get_volume_drivers", "(", ")", "mapping", "=", "{", "d", ".", "class_name", ":", "vars", "(", "d", ")", "for", "d", "in", "drivers", "}", "# Drivers contain class instances which are not serializable", "for", "driver", "in", "mapping", ".", "values", "(", ")", ":", "driver", ".", "pop", "(", "'cls'", ",", "None", ")", "if", "'driver_options'", "in", "driver", ":", "driver", "[", "'driver_options'", "]", "=", "convert_oslo_config", "(", "driver", "[", "'driver_options'", "]", ")", "finally", ":", "os", ".", "chdir", "(", "cwd", ")", "queue", ".", "put", "(", "mapping", ")", "# Use a different process to avoid having all driver classes loaded in", "# memory during our execution.", "queue", "=", "multiprocessing", ".", "Queue", "(", ")", "p", "=", "multiprocessing", ".", "Process", "(", "target", "=", "list_drivers", ",", "args", "=", "(", "queue", ",", ")", ")", "p", ".", "start", "(", ")", "result", "=", "queue", ".", "get", "(", ")", "p", ".", "join", "(", ")", "return", "result" ]
Loop over all plugins and invoke function hook with args and kwargs in each of them . If the plugin does not have the function it is skipped .
def run_hook ( self , hook , * args , * * kwargs ) : for plugin in self . raw_plugins : if hasattr ( plugin , hook ) : self . logger . debug ( 'Calling hook {0} in plugin {1}' . format ( hook , plugin . __name__ ) ) getattr ( plugin , hook ) ( * args , * * kwargs )
9,471
https://github.com/product-definition-center/pdc-client/blob/7236fd8b72e675ebb321bbe337289d9fbeb6119f/pdc_client/runner.py#L134-L143
[ "def", "OverwriteAndClose", "(", "self", ",", "compressed_data", ",", "size", ")", ":", "self", ".", "Set", "(", "self", ".", "Schema", ".", "CONTENT", "(", "compressed_data", ")", ")", "self", ".", "Set", "(", "self", ".", "Schema", ".", "SIZE", "(", "size", ")", ")", "super", "(", "AFF4MemoryStreamBase", ",", "self", ")", ".", "Close", "(", ")" ]
Writes header and generator of lines to tab separated file .
def write_tsv ( headerfields , features , outfn ) : with open ( outfn , 'w' ) as fp : write_tsv_line_from_list ( headerfields , fp ) for line in features : write_tsv_line_from_list ( [ str ( line [ field ] ) for field in headerfields ] , fp )
9,472
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/writers/tsv.py#L1-L12
[ "def", "rank", "(", "self", ")", ":", "rank", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXKVStoreGetRank", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "rank", ")", ")", ")", "return", "rank", ".", "value" ]
Utility method to convert list to tsv line with carriage return
def write_tsv_line_from_list ( linelist , outfp ) : line = '\t' . join ( linelist ) outfp . write ( line ) outfp . write ( '\n' )
9,473
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/writers/tsv.py#L15-L19
[ "def", "similarity", "(", "self", ",", "other", ")", ":", "sim", "=", "self", ".", "Similarity", "(", ")", "total", "=", "0.0", "# Calculate similarity ratio for each attribute", "cname", "=", "self", ".", "__class__", ".", "__name__", "for", "aname", ",", "weight", "in", "self", ".", "attributes", ".", "items", "(", ")", ":", "attr1", "=", "getattr", "(", "self", ",", "aname", ",", "None", ")", "attr2", "=", "getattr", "(", "other", ",", "aname", ",", "None", ")", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ")", "# Similarity is ignored if None on both objects", "if", "attr1", "is", "None", "and", "attr2", "is", "None", ":", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ",", "result", "=", "\"attributes are both None\"", ")", "continue", "# Similarity is 0 if either attribute is non-Comparable", "if", "not", "all", "(", "(", "isinstance", "(", "attr1", ",", "Comparable", ")", ",", "isinstance", "(", "attr2", ",", "Comparable", ")", ")", ")", ":", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ",", "result", "=", "\"attributes not Comparable\"", ")", "total", "+=", "weight", "continue", "# Calculate similarity between the attributes", "attr_sim", "=", "(", "attr1", "%", "attr2", ")", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ",", "result", "=", "attr_sim", ")", "# Add the similarity to the total", "sim", "+=", "attr_sim", "*", "weight", "total", "+=", "weight", "# Scale the similarity so the total is 1.0", "if", "total", ":", "sim", "*=", "(", "1.0", "/", "total", ")", "return", "sim" ]
r Replaces text between sentinal lines in a block of text .
def replace_between_tags ( text , repl_ , start_tag , end_tag = None ) : new_lines = [ ] editing = False lines = text . split ( '\n' ) for line in lines : if not editing : new_lines . append ( line ) if line . strip ( ) . startswith ( start_tag ) : new_lines . append ( repl_ ) editing = True if end_tag is not None and line . strip ( ) . startswith ( end_tag ) : editing = False new_lines . append ( line ) new_text = '\n' . join ( new_lines ) return new_text
9,474
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L75-L128
[ "def", "_set_status_self", "(", "self", ",", "key", "=", "JobDetails", ".", "topkey", ",", "status", "=", "JobStatus", ".", "unknown", ")", ":", "fullkey", "=", "JobDetails", ".", "make_fullkey", "(", "self", ".", "full_linkname", ",", "key", ")", "if", "fullkey", "in", "self", ".", "jobs", ":", "self", ".", "jobs", "[", "fullkey", "]", ".", "status", "=", "status", "if", "self", ".", "_job_archive", ":", "self", ".", "_job_archive", ".", "register_job", "(", "self", ".", "jobs", "[", "fullkey", "]", ")", "else", ":", "self", ".", "_register_self", "(", "'dummy.log'", ",", "key", ",", "status", ")" ]
r Format theta so it is interpretable in base 10
def theta_str ( theta , taustr = TAUSTR , fmtstr = '{coeff:,.1f}{taustr}' ) : coeff = theta / TAU theta_str = fmtstr . format ( coeff = coeff , taustr = taustr ) return theta_str
9,475
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L131-L161
[ "def", "Send", "(", "self", ",", "usb", ",", "timeout_ms", "=", "None", ")", ":", "usb", ".", "BulkWrite", "(", "self", ".", "Pack", "(", ")", ",", "timeout_ms", ")", "usb", ".", "BulkWrite", "(", "self", ".", "data", ",", "timeout_ms", ")" ]
r makes a string from an integer bounding box
def bbox_str ( bbox , pad = 4 , sep = ', ' ) : if bbox is None : return 'None' fmtstr = sep . join ( [ '%' + six . text_type ( pad ) + 'd' ] * 4 ) return '(' + fmtstr % tuple ( bbox ) + ')'
9,476
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L164-L169
[ "def", "configs", "(", "self", ")", ":", "run_path_pairs", "=", "list", "(", "self", ".", "run_paths", ".", "items", "(", ")", ")", "self", ".", "_append_plugin_asset_directories", "(", "run_path_pairs", ")", "# If there are no summary event files, the projector should still work,", "# treating the `logdir` as the model checkpoint directory.", "if", "not", "run_path_pairs", ":", "run_path_pairs", ".", "append", "(", "(", "'.'", ",", "self", ".", "logdir", ")", ")", "if", "(", "self", ".", "_run_paths_changed", "(", ")", "or", "_latest_checkpoints_changed", "(", "self", ".", "_configs", ",", "run_path_pairs", ")", ")", ":", "self", ".", "readers", "=", "{", "}", "self", ".", "_configs", ",", "self", ".", "config_fpaths", "=", "self", ".", "_read_latest_config_files", "(", "run_path_pairs", ")", "self", ".", "_augment_configs_with_checkpoint_info", "(", ")", "return", "self", ".", "_configs" ]
r makes a string from a list of integer verticies
def verts_str ( verts , pad = 1 ) : if verts is None : return 'None' fmtstr = ', ' . join ( [ '%' + six . text_type ( pad ) + 'd' + ', %' + six . text_type ( pad ) + 'd' ] * 1 ) return ', ' . join ( [ '(' + fmtstr % vert + ')' for vert in verts ] )
9,477
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L172-L178
[ "def", "to_csr", "(", "self", ")", ":", "self", ".", "_X_train", "=", "csr_matrix", "(", "self", ".", "_X_train", ")", "self", ".", "_X_test", "=", "csr_matrix", "(", "self", ".", "_X_test", ")" ]
removes all chars in char_list from str_
def remove_chars ( str_ , char_list ) : outstr = str_ [ : ] for char in char_list : outstr = outstr . replace ( char , '' ) return outstr
9,478
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L195-L218
[ "def", "getAssociation", "(", "self", ",", "server_url", ",", "handle", "=", "None", ")", ":", "if", "handle", "is", "None", ":", "handle", "=", "''", "# The filename with the empty handle is a prefix of all other", "# associations for the given server URL.", "filename", "=", "self", ".", "getAssociationFilename", "(", "server_url", ",", "handle", ")", "if", "handle", ":", "return", "self", ".", "_getAssociation", "(", "filename", ")", "else", ":", "association_files", "=", "os", ".", "listdir", "(", "self", ".", "association_dir", ")", "matching_files", "=", "[", "]", "# strip off the path to do the comparison", "name", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "for", "association_file", "in", "association_files", ":", "if", "association_file", ".", "startswith", "(", "name", ")", ":", "matching_files", ".", "append", "(", "association_file", ")", "matching_associations", "=", "[", "]", "# read the matching files and sort by time issued", "for", "name", "in", "matching_files", ":", "full_name", "=", "os", ".", "path", ".", "join", "(", "self", ".", "association_dir", ",", "name", ")", "association", "=", "self", ".", "_getAssociation", "(", "full_name", ")", "if", "association", "is", "not", "None", ":", "matching_associations", ".", "append", "(", "(", "association", ".", "issued", ",", "association", ")", ")", "matching_associations", ".", "sort", "(", ")", "# return the most recently issued one.", "if", "matching_associations", ":", "(", "_", ",", "assoc", ")", "=", "matching_associations", "[", "-", "1", "]", "return", "assoc", "else", ":", "return", "None" ]
r returns the number of preceding spaces
def get_minimum_indentation ( text ) : lines = text . split ( '\n' ) indentations = [ get_indentation ( line_ ) for line_ in lines if len ( line_ . strip ( ) ) > 0 ] if len ( indentations ) == 0 : return 0 return min ( indentations )
9,479
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L228-L255
[ "def", "write_image", "(", "filename", ",", "image", ")", ":", "data_format", "=", "get_data_format", "(", "filename", ")", "if", "data_format", "is", "MimeType", ".", "JPG", ":", "LOGGER", ".", "warning", "(", "'Warning: jpeg is a lossy format therefore saved data will be modified.'", ")", "return", "Image", ".", "fromarray", "(", "image", ")", ".", "save", "(", "filename", ")" ]
r Convineince indentjoin
def indentjoin ( strlist , indent = '\n ' , suffix = '' ) : indent_ = indent strlist = list ( strlist ) if len ( strlist ) == 0 : return '' return indent_ + indent_ . join ( [ six . text_type ( str_ ) + suffix for str_ in strlist ] )
9,480
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L357-L376
[ "def", "_get_exception_class_from_status_code", "(", "status_code", ")", ":", "if", "status_code", "==", "'100'", ":", "return", "None", "exc_class", "=", "STATUS_CODE_MAPPING", ".", "get", "(", "status_code", ")", "if", "not", "exc_class", ":", "# No status code match, return the \"I don't know wtf this is\"", "# exception class.", "return", "STATUS_CODE_MAPPING", "[", "'UNKNOWN'", "]", "else", ":", "# Match found, yay.", "return", "exc_class" ]
Removes the middle part of any string over maxlen characters .
def truncate_str ( str_ , maxlen = 110 , truncmsg = ' ~~~TRUNCATED~~~ ' ) : if NO_TRUNCATE : return str_ if maxlen is None or maxlen == - 1 or len ( str_ ) < maxlen : return str_ else : maxlen_ = maxlen - len ( truncmsg ) lowerb = int ( maxlen_ * .8 ) upperb = maxlen_ - lowerb tup = ( str_ [ : lowerb ] , truncmsg , str_ [ - upperb : ] ) return '' . join ( tup )
9,481
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L379-L392
[ "def", "get_bundle_by_id", "(", "self", ",", "bundle_id", ")", ":", "# type: (int) -> Union[Bundle, Framework]", "if", "bundle_id", "==", "0", ":", "# \"System bundle\"", "return", "self", "with", "self", ".", "__bundles_lock", ":", "if", "bundle_id", "not", "in", "self", ".", "__bundles", ":", "raise", "BundleException", "(", "\"Invalid bundle ID {0}\"", ".", "format", "(", "bundle_id", ")", ")", "return", "self", ".", "__bundles", "[", "bundle_id", "]" ]
alias for pack_into . has more up to date kwargs
def packstr ( instr , textwidth = 160 , breakchars = ' ' , break_words = True , newline_prefix = '' , indentation = '' , nlprefix = None , wordsep = ' ' , remove_newlines = True ) : if not isinstance ( instr , six . string_types ) : instr = repr ( instr ) if nlprefix is not None : newline_prefix = nlprefix str_ = pack_into ( instr , textwidth , breakchars , break_words , newline_prefix , wordsep , remove_newlines ) if indentation != '' : str_ = indent ( str_ , indentation ) return str_
9,482
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L468-L480
[ "def", "ReleaseFileObject", "(", "self", ",", "file_object", ")", ":", "identifier", ",", "cache_value", "=", "self", ".", "_file_object_cache", ".", "GetCacheValueByObject", "(", "file_object", ")", "if", "not", "identifier", ":", "raise", "RuntimeError", "(", "'Object not cached.'", ")", "if", "not", "cache_value", ":", "raise", "RuntimeError", "(", "'Invalid cache value.'", ")", "self", ".", "_file_object_cache", ".", "ReleaseObject", "(", "identifier", ")", "result", "=", "cache_value", ".", "IsDereferenced", "(", ")", "if", "result", ":", "self", ".", "_file_object_cache", ".", "RemoveObject", "(", "identifier", ")", "return", "result" ]
representing the number of bytes with the chosen unit
def byte_str ( nBytes , unit = 'bytes' , precision = 2 ) : #return (nBytes * ureg.byte).to(unit.upper()) if unit . lower ( ) . startswith ( 'b' ) : nUnit = nBytes elif unit . lower ( ) . startswith ( 'k' ) : nUnit = nBytes / ( 2.0 ** 10 ) elif unit . lower ( ) . startswith ( 'm' ) : nUnit = nBytes / ( 2.0 ** 20 ) elif unit . lower ( ) . startswith ( 'g' ) : nUnit = nBytes / ( 2.0 ** 30 ) elif unit . lower ( ) . startswith ( 't' ) : nUnit = nBytes / ( 2.0 ** 40 ) else : raise NotImplementedError ( 'unknown nBytes=%r unit=%r' % ( nBytes , unit ) ) return repr2 ( nUnit , precision = precision ) + ' ' + unit
9,483
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L671-L691
[ "def", "managed_reader", "(", "reader", ",", "catalog", "=", "None", ")", ":", "if", "catalog", "is", "None", ":", "catalog", "=", "SymbolTableCatalog", "(", ")", "ctx", "=", "_ManagedContext", "(", "catalog", ")", "symbol_trans", "=", "Transition", "(", "None", ",", "None", ")", "ion_event", "=", "None", "while", "True", ":", "if", "symbol_trans", ".", "delegate", "is", "not", "None", "and", "ion_event", "is", "not", "None", "and", "not", "ion_event", ".", "event_type", ".", "is_stream_signal", ":", "# We have a symbol processor active, do not yield to user.", "delegate", "=", "symbol_trans", ".", "delegate", "symbol_trans", "=", "delegate", ".", "send", "(", "Transition", "(", "ion_event", ",", "delegate", ")", ")", "if", "symbol_trans", ".", "delegate", "is", "None", ":", "# When the symbol processor terminates, the event is the context", "# and there is no delegate.", "ctx", "=", "symbol_trans", ".", "event", "data_event", "=", "NEXT_EVENT", "else", ":", "data_event", "=", "symbol_trans", ".", "event", "else", ":", "data_event", "=", "None", "if", "ion_event", "is", "not", "None", ":", "event_type", "=", "ion_event", ".", "event_type", "ion_type", "=", "ion_event", ".", "ion_type", "depth", "=", "ion_event", ".", "depth", "# System values only happen at the top-level", "if", "depth", "==", "0", ":", "if", "event_type", "is", "IonEventType", ".", "VERSION_MARKER", ":", "if", "ion_event", "!=", "ION_VERSION_MARKER_EVENT", ":", "raise", "IonException", "(", "'Invalid IVM: %s'", "%", "(", "ion_event", ",", ")", ")", "# Reset and swallow IVM", "ctx", "=", "_ManagedContext", "(", "ctx", ".", "catalog", ")", "data_event", "=", "NEXT_EVENT", "elif", "ion_type", "is", "IonType", ".", "SYMBOL", "and", "len", "(", "ion_event", ".", "annotations", ")", "==", "0", "and", "ion_event", ".", "value", "is", "not", "None", "and", "ctx", ".", "resolve", "(", "ion_event", ".", "value", ")", ".", "text", "==", "TEXT_ION_1_0", ":", "assert", "symbol_trans", ".", "delegate", "is", "None", "# A faux IVM is a NOP", "data_event", "=", "NEXT_EVENT", "elif", "event_type", "is", "IonEventType", ".", "CONTAINER_START", "and", "ion_type", "is", "IonType", ".", "STRUCT", "and", "ctx", ".", "has_symbol_table_annotation", "(", "ion_event", ".", "annotations", ")", ":", "assert", "symbol_trans", ".", "delegate", "is", "None", "# Activate a new symbol processor.", "delegate", "=", "_local_symbol_table_handler", "(", "ctx", ")", "symbol_trans", "=", "Transition", "(", "None", ",", "delegate", ")", "data_event", "=", "NEXT_EVENT", "if", "data_event", "is", "None", ":", "# No system processing or we have to get data, yield control.", "if", "ion_event", "is", "not", "None", ":", "ion_event", "=", "_managed_thunk_event", "(", "ctx", ",", "ion_event", ")", "data_event", "=", "yield", "ion_event", "ion_event", "=", "reader", ".", "send", "(", "data_event", ")" ]
string representation of function definition
def func_str ( func , args = [ ] , kwargs = { } , type_aliases = [ ] , packed = False , packkw = None , truncate = False ) : import utool as ut # if truncate: # truncatekw = {'maxlen': 20} # else: truncatekw = { } argrepr_list = ( [ ] if args is None else ut . get_itemstr_list ( args , nl = False , truncate = truncate , truncatekw = truncatekw ) ) kwrepr_list = ( [ ] if kwargs is None else ut . dict_itemstr_list ( kwargs , explicit = True , nl = False , truncate = truncate , truncatekw = truncatekw ) ) repr_list = argrepr_list + kwrepr_list argskwargs_str = ', ' . join ( repr_list ) _str = '%s(%s)' % ( meta_util_six . get_funcname ( func ) , argskwargs_str ) if packed : packkw_ = dict ( textwidth = 80 , nlprefix = ' ' , break_words = False ) if packkw is not None : packkw_ . update ( packkw_ ) _str = packstr ( _str , * * packkw_ ) return _str
9,484
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L720-L778
[ "def", "_timestamp_regulator", "(", "self", ")", ":", "unified_timestamps", "=", "_PrettyDefaultDict", "(", "list", ")", "staged_files", "=", "self", ".", "_list_audio_files", "(", "sub_dir", "=", "\"staging\"", ")", "for", "timestamp_basename", "in", "self", ".", "__timestamps_unregulated", ":", "if", "len", "(", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", ")", ">", "1", ":", "# File has been splitted", "timestamp_name", "=", "''", ".", "join", "(", "timestamp_basename", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "staged_splitted_files_of_timestamp", "=", "list", "(", "filter", "(", "lambda", "staged_file", ":", "(", "timestamp_name", "==", "staged_file", "[", ":", "-", "3", "]", "and", "all", "(", "[", "(", "x", "in", "set", "(", "map", "(", "str", ",", "range", "(", "10", ")", ")", ")", ")", "for", "x", "in", "staged_file", "[", "-", "3", ":", "]", "]", ")", ")", ",", "staged_files", ")", ")", "if", "len", "(", "staged_splitted_files_of_timestamp", ")", "==", "0", ":", "self", ".", "__errors", "[", "(", "time", "(", ")", ",", "timestamp_basename", ")", "]", "=", "{", "\"reason\"", ":", "\"Missing staged file\"", ",", "\"current_staged_files\"", ":", "staged_files", "}", "continue", "staged_splitted_files_of_timestamp", ".", "sort", "(", ")", "unified_timestamp", "=", "list", "(", ")", "for", "staging_digits", ",", "splitted_file", "in", "enumerate", "(", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", ")", ":", "prev_splits_sec", "=", "0", "if", "int", "(", "staging_digits", ")", "!=", "0", ":", "prev_splits_sec", "=", "self", ".", "_get_audio_duration_seconds", "(", "\"{}/staging/{}{:03d}\"", ".", "format", "(", "self", ".", "src_dir", ",", "timestamp_name", ",", "staging_digits", "-", "1", ")", ")", "for", "word_block", "in", "splitted_file", ":", "unified_timestamp", ".", "append", "(", "_WordBlock", "(", "word", "=", "word_block", ".", "word", ",", "start", "=", "round", "(", "word_block", ".", "start", "+", "prev_splits_sec", ",", "2", ")", ",", "end", "=", "round", "(", "word_block", ".", "end", "+", "prev_splits_sec", ",", "2", ")", ")", ")", "unified_timestamps", "[", "str", "(", "timestamp_basename", ")", "]", "+=", "unified_timestamp", "else", ":", "unified_timestamps", "[", "timestamp_basename", "]", "+=", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", "[", "0", "]", "self", ".", "__timestamps", ".", "update", "(", "unified_timestamps", ")", "self", ".", "__timestamps_unregulated", "=", "_PrettyDefaultDict", "(", "list", ")" ]
String of function definition signature
def func_defsig ( func , with_name = True ) : import inspect argspec = inspect . getargspec ( func ) ( args , varargs , varkw , defaults ) = argspec defsig = inspect . formatargspec ( * argspec ) if with_name : defsig = get_callable_name ( func ) + defsig return defsig
9,485
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L781-L809
[ "def", "_timestamp_regulator", "(", "self", ")", ":", "unified_timestamps", "=", "_PrettyDefaultDict", "(", "list", ")", "staged_files", "=", "self", ".", "_list_audio_files", "(", "sub_dir", "=", "\"staging\"", ")", "for", "timestamp_basename", "in", "self", ".", "__timestamps_unregulated", ":", "if", "len", "(", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", ")", ">", "1", ":", "# File has been splitted", "timestamp_name", "=", "''", ".", "join", "(", "timestamp_basename", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "staged_splitted_files_of_timestamp", "=", "list", "(", "filter", "(", "lambda", "staged_file", ":", "(", "timestamp_name", "==", "staged_file", "[", ":", "-", "3", "]", "and", "all", "(", "[", "(", "x", "in", "set", "(", "map", "(", "str", ",", "range", "(", "10", ")", ")", ")", ")", "for", "x", "in", "staged_file", "[", "-", "3", ":", "]", "]", ")", ")", ",", "staged_files", ")", ")", "if", "len", "(", "staged_splitted_files_of_timestamp", ")", "==", "0", ":", "self", ".", "__errors", "[", "(", "time", "(", ")", ",", "timestamp_basename", ")", "]", "=", "{", "\"reason\"", ":", "\"Missing staged file\"", ",", "\"current_staged_files\"", ":", "staged_files", "}", "continue", "staged_splitted_files_of_timestamp", ".", "sort", "(", ")", "unified_timestamp", "=", "list", "(", ")", "for", "staging_digits", ",", "splitted_file", "in", "enumerate", "(", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", ")", ":", "prev_splits_sec", "=", "0", "if", "int", "(", "staging_digits", ")", "!=", "0", ":", "prev_splits_sec", "=", "self", ".", "_get_audio_duration_seconds", "(", "\"{}/staging/{}{:03d}\"", ".", "format", "(", "self", ".", "src_dir", ",", "timestamp_name", ",", "staging_digits", "-", "1", ")", ")", "for", "word_block", "in", "splitted_file", ":", "unified_timestamp", ".", "append", "(", "_WordBlock", "(", "word", "=", "word_block", ".", "word", ",", "start", "=", "round", "(", "word_block", ".", "start", "+", "prev_splits_sec", ",", "2", ")", ",", "end", "=", "round", "(", "word_block", ".", "end", "+", "prev_splits_sec", ",", "2", ")", ")", ")", "unified_timestamps", "[", "str", "(", "timestamp_basename", ")", "]", "+=", "unified_timestamp", "else", ":", "unified_timestamps", "[", "timestamp_basename", "]", "+=", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", "[", "0", "]", "self", ".", "__timestamps", ".", "update", "(", "unified_timestamps", ")", "self", ".", "__timestamps_unregulated", "=", "_PrettyDefaultDict", "(", "list", ")" ]
String of function call signature
def func_callsig ( func , with_name = True ) : import inspect argspec = inspect . getargspec ( func ) ( args , varargs , varkw , defaults ) = argspec callsig = inspect . formatargspec ( * argspec [ 0 : 3 ] ) if with_name : callsig = get_callable_name ( func ) + callsig return callsig
9,486
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L812-L840
[ "def", "_index_audio_cmu", "(", "self", ",", "basename", "=", "None", ",", "replace_already_indexed", "=", "False", ")", ":", "self", ".", "_prepare_audio", "(", "basename", "=", "basename", ",", "replace_already_indexed", "=", "replace_already_indexed", ")", "for", "staging_audio_basename", "in", "self", ".", "_list_audio_files", "(", "sub_dir", "=", "\"staging\"", ")", ":", "original_audio_name", "=", "''", ".", "join", "(", "staging_audio_basename", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "[", ":", "-", "3", "]", "pocketsphinx_command", "=", "''", ".", "join", "(", "[", "\"pocketsphinx_continuous\"", ",", "\"-infile\"", ",", "str", "(", "\"{}/staging/{}\"", ".", "format", "(", "self", ".", "src_dir", ",", "staging_audio_basename", ")", ")", ",", "\"-time\"", ",", "\"yes\"", ",", "\"-logfn\"", ",", "\"/dev/null\"", "]", ")", "try", ":", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "\"Now indexing {}\"", ".", "format", "(", "staging_audio_basename", ")", ")", "output", "=", "subprocess", ".", "check_output", "(", "[", "\"pocketsphinx_continuous\"", ",", "\"-infile\"", ",", "str", "(", "\"{}/staging/{}\"", ".", "format", "(", "self", ".", "src_dir", ",", "staging_audio_basename", ")", ")", ",", "\"-time\"", ",", "\"yes\"", ",", "\"-logfn\"", ",", "\"/dev/null\"", "]", ",", "universal_newlines", "=", "True", ")", ".", "split", "(", "'\\n'", ")", "str_timestamps_with_sil_conf", "=", "list", "(", "map", "(", "lambda", "x", ":", "x", ".", "split", "(", "\" \"", ")", ",", "filter", "(", "None", ",", "output", "[", "1", ":", "]", ")", ")", ")", "# Timestamps are putted in a list of a single element. To match", "# Watson's output.", "self", ".", "__timestamps_unregulated", "[", "original_audio_name", "+", "\".wav\"", "]", "=", "[", "(", "self", ".", "_timestamp_extractor_cmu", "(", "staging_audio_basename", ",", "str_timestamps_with_sil_conf", ")", ")", "]", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "\"Done indexing {}\"", ".", "format", "(", "staging_audio_basename", ")", ")", "except", "OSError", "as", "e", ":", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "e", ",", "\"The command was: {}\"", ".", "format", "(", "pocketsphinx_command", ")", ")", "self", ".", "__errors", "[", "(", "time", "(", ")", ",", "staging_audio_basename", ")", "]", "=", "e", "self", ".", "_timestamp_regulator", "(", ")", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "\"Finished indexing procedure\"", ")" ]
suppress_small = False turns off scientific representation
def numpy_str ( arr , strvals = False , precision = None , pr = None , force_dtype = False , with_dtype = None , suppress_small = None , max_line_width = None , threshold = None , * * kwargs ) : # strvals = kwargs.get('strvals', False) itemsep = kwargs . get ( 'itemsep' , ' ' ) # precision = kwargs.get('precision', None) # suppress_small = kwargs.get('supress_small', None) # max_line_width = kwargs.get('max_line_width', None) # with_dtype = kwargs.get('with_dtype', False) newlines = kwargs . pop ( 'nl' , kwargs . pop ( 'newlines' , 1 ) ) data = arr # if with_dtype and strvals: # raise ValueError('cannot format with strvals and dtype') separator = ',' + itemsep if strvals : prefix = '' suffix = '' else : modname = type ( data ) . __module__ # substitute shorthand for numpy module names np_nice = 'np' modname = re . sub ( '\\bnumpy\\b' , np_nice , modname ) modname = re . sub ( '\\bma.core\\b' , 'ma' , modname ) class_name = type ( data ) . __name__ if class_name == 'ndarray' : class_name = 'array' prefix = modname + '.' + class_name + '(' if with_dtype : dtype_repr = data . dtype . name # dtype_repr = np.core.arrayprint.dtype_short_repr(data.dtype) suffix = ',{}dtype={}.{})' . format ( itemsep , np_nice , dtype_repr ) else : suffix = ')' if not strvals and data . size == 0 and data . shape != ( 0 , ) : # Special case for displaying empty data prefix = modname + '.empty(' body = repr ( tuple ( map ( int , data . shape ) ) ) else : body = np . array2string ( data , precision = precision , separator = separator , suppress_small = suppress_small , prefix = prefix , max_line_width = max_line_width ) if not newlines : # remove newlines if we need to body = re . sub ( '\n *' , '' , body ) formatted = prefix + body + suffix return formatted
9,487
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1112-L1170
[ "def", "wait_on_any", "(", "*", "events", ",", "*", "*", "kwargs", ")", ":", "timeout", "=", "kwargs", ".", "get", "(", "\"timeout\"", ")", "composite_event", "=", "threading", ".", "Event", "(", ")", "if", "any", "(", "[", "event", ".", "is_set", "(", ")", "for", "event", "in", "events", "]", ")", ":", "return", "def", "on_change", "(", ")", ":", "if", "any", "(", "[", "event", ".", "is_set", "(", ")", "for", "event", "in", "events", "]", ")", ":", "composite_event", ".", "set", "(", ")", "else", ":", "composite_event", ".", "clear", "(", ")", "def", "patch", "(", "original", ")", ":", "def", "patched", "(", ")", ":", "original", "(", ")", "on_change", "(", ")", "return", "patched", "for", "event", "in", "events", ":", "event", ".", "set", "=", "patch", "(", "event", ".", "set", ")", "event", ".", "clear", "=", "patch", "(", "event", ".", "clear", ")", "wait_on_event", "(", "composite_event", ",", "timeout", "=", "timeout", ")" ]
prints the list members when the list is small and the length when it is large
def list_str_summarized ( list_ , list_name , maxlen = 5 ) : if len ( list_ ) > maxlen : return 'len(%s)=%d' % ( list_name , len ( list_ ) ) else : return '%s=%r' % ( list_name , list_ )
9,488
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1251-L1259
[ "def", "swo_enable", "(", "self", ",", "cpu_speed", ",", "swo_speed", "=", "9600", ",", "port_mask", "=", "0x01", ")", ":", "if", "self", ".", "swo_enabled", "(", ")", ":", "self", ".", "swo_stop", "(", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_EnableTarget", "(", "cpu_speed", ",", "swo_speed", ",", "enums", ".", "JLinkSWOInterfaces", ".", "UART", ",", "port_mask", ")", "if", "res", "!=", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "self", ".", "_swo_enabled", "=", "True", "return", "None" ]
used by recrusive functions to specify which level to turn a bool on in counting down yeilds True True ... False conting up yeilds False False False ... True
def _rectify_countdown_or_bool ( count_or_bool ) : if count_or_bool is True or count_or_bool is False : count_or_bool_ = count_or_bool elif isinstance ( count_or_bool , int ) : if count_or_bool == 0 : return 0 sign_ = math . copysign ( 1 , count_or_bool ) count_or_bool_ = int ( count_or_bool - sign_ ) #if count_or_bool_ == 0: # return sign_ == 1 else : count_or_bool_ = False return count_or_bool_
9,489
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1266-L1310
[ "def", "update_cache_for_instance", "(", "model_name", ",", "instance_pk", ",", "instance", "=", "None", ",", "version", "=", "None", ")", ":", "cache", "=", "SampleCache", "(", ")", "invalid", "=", "cache", ".", "update_instance", "(", "model_name", ",", "instance_pk", ",", "instance", ",", "version", ")", "for", "invalid_name", ",", "invalid_pk", ",", "invalid_version", "in", "invalid", ":", "update_cache_for_instance", ".", "delay", "(", "invalid_name", ",", "invalid_pk", ",", "version", "=", "invalid_version", ")" ]
Attempt to replace repr more configurable pretty version that works the same in both 2 and 3
def repr2 ( obj_ , * * kwargs ) : kwargs [ 'nl' ] = kwargs . pop ( 'nl' , kwargs . pop ( 'newlines' , False ) ) val_str = _make_valstr ( * * kwargs ) return val_str ( obj_ )
9,490
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1317-L1324
[ "def", "cancel", "(", "self", ")", ":", "self", ".", "event", ".", "clear", "(", ")", "if", "self", ".", "__timer", "is", "not", "None", ":", "self", ".", "__timer", ".", "cancel", "(", ")" ]
hack for json reprs
def repr2_json ( obj_ , * * kwargs ) : import utool as ut kwargs [ 'trailing_sep' ] = False json_str = ut . repr2 ( obj_ , * * kwargs ) json_str = str ( json_str . replace ( '\'' , '"' ) ) json_str = json_str . replace ( '(' , '[' ) json_str = json_str . replace ( ')' , ']' ) json_str = json_str . replace ( 'None' , 'null' ) return json_str
9,491
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1327-L1336
[ "def", "parseReaderConfig", "(", "self", ",", "confdict", ")", ":", "logger", ".", "debug", "(", "'parseReaderConfig input: %s'", ",", "confdict", ")", "conf", "=", "{", "}", "for", "k", ",", "v", "in", "confdict", ".", "items", "(", ")", ":", "if", "not", "k", ".", "startswith", "(", "'Parameter'", ")", ":", "continue", "ty", "=", "v", "[", "'Type'", "]", "data", "=", "v", "[", "'Data'", "]", "vendor", "=", "None", "subtype", "=", "None", "try", ":", "vendor", ",", "subtype", "=", "v", "[", "'Vendor'", "]", ",", "v", "[", "'Subtype'", "]", "except", "KeyError", ":", "pass", "if", "ty", "==", "1023", ":", "if", "vendor", "==", "25882", "and", "subtype", "==", "37", ":", "tempc", "=", "struct", ".", "unpack", "(", "'!H'", ",", "data", ")", "[", "0", "]", "conf", ".", "update", "(", "temperature", "=", "tempc", ")", "else", ":", "conf", "[", "ty", "]", "=", "data", "return", "conf" ]
r Makes a pretty list string
def list_str ( list_ , * * listkw ) : import utool as ut newlines = listkw . pop ( 'nl' , listkw . pop ( 'newlines' , 1 ) ) packed = listkw . pop ( 'packed' , False ) truncate = listkw . pop ( 'truncate' , False ) listkw [ 'nl' ] = _rectify_countdown_or_bool ( newlines ) listkw [ 'truncate' ] = _rectify_countdown_or_bool ( truncate ) listkw [ 'packed' ] = _rectify_countdown_or_bool ( packed ) nobraces = listkw . pop ( 'nobr' , listkw . pop ( 'nobraces' , False ) ) itemsep = listkw . get ( 'itemsep' , ' ' ) # Doesn't actually put in trailing comma if on same line trailing_sep = listkw . get ( 'trailing_sep' , True ) with_comma = True itemstr_list = get_itemstr_list ( list_ , * * listkw ) is_tuple = isinstance ( list_ , tuple ) is_set = isinstance ( list_ , ( set , frozenset , ut . oset ) ) is_onetup = isinstance ( list_ , ( tuple ) ) and len ( list_ ) <= 1 if nobraces : lbr , rbr = '' , '' elif is_tuple : lbr , rbr = '(' , ')' elif is_set : lbr , rbr = '{' , '}' else : lbr , rbr = '[' , ']' if len ( itemstr_list ) == 0 : newlines = False if newlines is not False and ( newlines is True or newlines > 0 ) : sep = ',\n' if with_comma else '\n' if nobraces : body_str = sep . join ( itemstr_list ) if trailing_sep : body_str += ',' retstr = body_str else : if packed : # DEPRICATE? joinstr = sep + itemsep * len ( lbr ) body_str = joinstr . join ( [ itemstr for itemstr in itemstr_list ] ) if trailing_sep : body_str += ',' braced_body_str = ( lbr + '' + body_str + '' + rbr ) else : body_str = sep . join ( [ ut . indent ( itemstr ) for itemstr in itemstr_list ] ) if trailing_sep : body_str += ',' braced_body_str = ( lbr + '\n' + body_str + '\n' + rbr ) retstr = braced_body_str else : sep = ',' + itemsep if with_comma else itemsep body_str = sep . join ( itemstr_list ) if is_onetup : body_str += ',' retstr = ( lbr + body_str + rbr ) # TODO: rectify with dict_truncate do_truncate = truncate is not False and ( truncate is True or truncate == 0 ) if do_truncate : truncatekw = listkw . get ( 'truncatekw' , { } ) retstr = truncate_str ( retstr , * * truncatekw ) return retstr
9,492
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1582-L1694
[ "def", "__execute_sext", "(", "self", ",", "instr", ")", ":", "op0_size", "=", "instr", ".", "operands", "[", "0", "]", ".", "size", "op2_size", "=", "instr", ".", "operands", "[", "2", "]", ".", "size", "op0_val", "=", "self", ".", "read_operand", "(", "instr", ".", "operands", "[", "0", "]", ")", "op0_msb", "=", "extract_sign_bit", "(", "op0_val", ",", "op0_size", ")", "op2_mask", "=", "(", "2", "**", "op2_size", "-", "1", ")", "&", "~", "(", "2", "**", "op0_size", "-", "1", ")", "if", "op0_msb", "==", "1", "else", "0x0", "op2_val", "=", "op0_val", "|", "op2_mask", "self", ".", "write_operand", "(", "instr", ".", "operands", "[", "2", "]", ",", "op2_val", ")", "return", "None" ]
Horizontally concatenates strings reprs preserving indentation
def horiz_string ( * args , * * kwargs ) : import unicodedata precision = kwargs . get ( 'precision' , None ) sep = kwargs . get ( 'sep' , '' ) if len ( args ) == 1 and not isinstance ( args [ 0 ] , six . string_types ) : val_list = args [ 0 ] else : val_list = args val_list = [ unicodedata . normalize ( 'NFC' , ensure_unicode ( val ) ) for val in val_list ] all_lines = [ ] hpos = 0 # for each value in the list or args for sx in range ( len ( val_list ) ) : # Ensure value is a string val = val_list [ sx ] str_ = None if precision is not None : # Hack in numpy precision if util_type . HAVE_NUMPY : try : if isinstance ( val , np . ndarray ) : str_ = np . array_str ( val , precision = precision , suppress_small = True ) except ImportError : pass if str_ is None : str_ = six . text_type ( val_list [ sx ] ) # continue with formating lines = str_ . split ( '\n' ) line_diff = len ( lines ) - len ( all_lines ) # Vertical padding if line_diff > 0 : all_lines += [ ' ' * hpos ] * line_diff # Add strings for lx , line in enumerate ( lines ) : all_lines [ lx ] += line hpos = max ( hpos , len ( all_lines [ lx ] ) ) # Horizontal padding for lx in range ( len ( all_lines ) ) : hpos_diff = hpos - len ( all_lines [ lx ] ) all_lines [ lx ] += ' ' * hpos_diff + sep all_lines = [ line . rstrip ( ' ' ) for line in all_lines ] ret = '\n' . join ( all_lines ) return ret
9,493
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1795-L1879
[ "def", "download_feed_posts", "(", "self", ",", "max_count", ":", "int", "=", "None", ",", "fast_update", ":", "bool", "=", "False", ",", "post_filter", ":", "Optional", "[", "Callable", "[", "[", "Post", "]", ",", "bool", "]", "]", "=", "None", ")", "->", "None", ":", "self", ".", "context", ".", "log", "(", "\"Retrieving pictures from your feed...\"", ")", "count", "=", "1", "for", "post", "in", "self", ".", "get_feed_posts", "(", ")", ":", "if", "max_count", "is", "not", "None", "and", "count", ">", "max_count", ":", "break", "name", "=", "post", ".", "owner_username", "if", "post_filter", "is", "not", "None", "and", "not", "post_filter", "(", "post", ")", ":", "self", ".", "context", ".", "log", "(", "\"<pic by %s skipped>\"", "%", "name", ",", "flush", "=", "True", ")", "continue", "self", ".", "context", ".", "log", "(", "\"[%3i] %s \"", "%", "(", "count", ",", "name", ")", ",", "end", "=", "\"\"", ",", "flush", "=", "True", ")", "count", "+=", "1", "with", "self", ".", "context", ".", "error_catcher", "(", "'Download feed'", ")", ":", "downloaded", "=", "self", ".", "download_post", "(", "post", ",", "target", "=", "':feed'", ")", "if", "fast_update", "and", "not", "downloaded", ":", "break" ]
r gets substring between two sentianl strings
def str_between ( str_ , startstr , endstr ) : if startstr is None : startpos = 0 else : startpos = str_ . find ( startstr ) + len ( startstr ) if endstr is None : endpos = None else : endpos = str_ . find ( endstr ) if endpos == - 1 : endpos = None newstr = str_ [ startpos : endpos ] return newstr
9,494
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1885-L1910
[ "def", "catalogFactory", "(", "name", ",", "*", "*", "kwargs", ")", ":", "fn", "=", "lambda", "member", ":", "inspect", ".", "isclass", "(", "member", ")", "and", "member", ".", "__module__", "==", "__name__", "catalogs", "=", "odict", "(", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "fn", ")", ")", "if", "name", "not", "in", "list", "(", "catalogs", ".", "keys", "(", ")", ")", ":", "msg", "=", "\"%s not found in catalogs:\\n %s\"", "%", "(", "name", ",", "list", "(", "kernels", ".", "keys", "(", ")", ")", ")", "logger", ".", "error", "(", "msg", ")", "msg", "=", "\"Unrecognized catalog: %s\"", "%", "name", "raise", "Exception", "(", "msg", ")", "return", "catalogs", "[", "name", "]", "(", "*", "*", "kwargs", ")" ]
Works on must functionlike objects including str which has no func_name
def get_callable_name ( func ) : try : return meta_util_six . get_funcname ( func ) except AttributeError : if isinstance ( func , type ) : return repr ( func ) . replace ( '<type \'' , '' ) . replace ( '\'>' , '' ) elif hasattr ( func , '__name__' ) : return func . __name__ else : raise NotImplementedError ( ( 'cannot get func_name of func=%r' 'type(func)=%r' ) % ( func , type ( func ) ) )
9,495
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1913-L1942
[ "def", "from_manifest", "(", "app", ",", "filename", ",", "raw", "=", "False", ",", "*", "*", "kwargs", ")", ":", "cfg", "=", "current_app", ".", "config", "if", "current_app", ".", "config", ".", "get", "(", "'TESTING'", ")", ":", "return", "# Do not spend time here when testing", "path", "=", "_manifests", "[", "app", "]", "[", "filename", "]", "if", "not", "raw", "and", "cfg", ".", "get", "(", "'CDN_DOMAIN'", ")", "and", "not", "cfg", ".", "get", "(", "'CDN_DEBUG'", ")", ":", "scheme", "=", "'https'", "if", "cfg", ".", "get", "(", "'CDN_HTTPS'", ")", "else", "request", ".", "scheme", "prefix", "=", "'{}://'", ".", "format", "(", "scheme", ")", "if", "not", "path", ".", "startswith", "(", "'/'", ")", ":", "# CDN_DOMAIN has no trailing slash", "path", "=", "'/'", "+", "path", "return", "''", ".", "join", "(", "(", "prefix", ",", "cfg", "[", "'CDN_DOMAIN'", "]", ",", "path", ")", ")", "elif", "not", "raw", "and", "kwargs", ".", "get", "(", "'external'", ",", "False", ")", ":", "if", "path", ".", "startswith", "(", "'/'", ")", ":", "# request.host_url has a trailing slash", "path", "=", "path", "[", "1", ":", "]", "return", "''", ".", "join", "(", "(", "request", ".", "host_url", ",", "path", ")", ")", "return", "path" ]
r Performs multiple replace functions foreach item in search_list and repl_list .
def multi_replace ( str_ , search_list , repl_list ) : if isinstance ( repl_list , six . string_types ) : repl_list_ = [ repl_list ] * len ( search_list ) else : repl_list_ = repl_list newstr = str_ assert len ( search_list ) == len ( repl_list_ ) , 'bad lens' for search , repl in zip ( search_list , repl_list_ ) : newstr = newstr . replace ( search , repl ) return newstr
9,496
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L2213-L2248
[ "def", "_handle_relation_harness", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "tokens", ":", "Union", "[", "ParseResults", ",", "Dict", "]", ")", "->", "ParseResults", ":", "if", "not", "self", ".", "control_parser", ".", "citation", ":", "raise", "MissingCitationException", "(", "self", ".", "get_line_number", "(", ")", ",", "line", ",", "position", ")", "if", "not", "self", ".", "control_parser", ".", "evidence", ":", "raise", "MissingSupportWarning", "(", "self", ".", "get_line_number", "(", ")", ",", "line", ",", "position", ")", "missing_required_annotations", "=", "self", ".", "control_parser", ".", "get_missing_required_annotations", "(", ")", "if", "missing_required_annotations", ":", "raise", "MissingAnnotationWarning", "(", "self", ".", "get_line_number", "(", ")", ",", "line", ",", "position", ",", "missing_required_annotations", ")", "self", ".", "_handle_relation", "(", "tokens", ")", "return", "tokens" ]
r Heuristically changes a word to its plural form if num is not 1
def pluralize ( wordtext , num = 2 , plural_suffix = 's' ) : if num == 1 : return wordtext else : if wordtext . endswith ( '\'s' ) : return wordtext [ : - 2 ] + 's\'' else : return wordtext + plural_suffix return ( wordtext + plural_suffix ) if num != 1 else wordtext
9,497
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L2251-L2281
[ "def", "dump", "(", "self", ")", ":", "return", "{", "u'storage_data'", ":", "[", "x", ".", "asdict", "(", ")", "for", "x", "in", "self", ".", "storage_data", "]", ",", "u'streaming_data'", ":", "[", "x", ".", "asdict", "(", ")", "for", "x", "in", "self", ".", "streaming_data", "]", "}" ]
r Heuristically generates an english phrase relating to the quantity of something . This is useful for writing user messages .
def quantstr ( typestr , num , plural_suffix = 's' ) : return six . text_type ( num ) + ' ' + pluralize ( typestr , num , plural_suffix )
9,498
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L2284-L2314
[ "def", "Process", "(", "self", ",", "parser_mediator", ",", "registry_key", ",", "*", "*", "kwargs", ")", ":", "if", "registry_key", "is", "None", ":", "raise", "ValueError", "(", "'Windows Registry key is not set.'", ")", "# This will raise if unhandled keyword arguments are passed.", "super", "(", "WindowsRegistryPlugin", ",", "self", ")", ".", "Process", "(", "parser_mediator", ",", "*", "*", "kwargs", ")", "self", ".", "ExtractEvents", "(", "parser_mediator", ",", "registry_key", ",", "*", "*", "kwargs", ")" ]
puts text inside a visual ascii block
def msgblock ( key , text , side = '|' ) : blocked_text = '' . join ( [ ' + --- ' , key , ' ---\n' ] + [ ' ' + side + ' ' + line + '\n' for line in text . split ( '\n' ) ] + [ ' L ___ ' , key , ' ___\n' ] ) return blocked_text
9,499
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L2317-L2324
[ "def", "symlink_bundles", "(", "self", ",", "app", ",", "bundle_dir", ")", ":", "for", "bundle_counter", ",", "bundle", "in", "enumerate", "(", "app", ".", "bundles", ")", ":", "count", "=", "0", "for", "path", ",", "relpath", "in", "bundle", ".", "filemap", ".", "items", "(", ")", ":", "bundle_path", "=", "os", ".", "path", ".", "join", "(", "bundle_dir", ",", "relpath", ")", "count", "+=", "1", "if", "os", ".", "path", ".", "exists", "(", "bundle_path", ")", ":", "continue", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "safe_mkdir", "(", "os", ".", "path", ".", "dirname", "(", "bundle_path", ")", ")", "os", ".", "symlink", "(", "path", ",", "bundle_path", ")", "elif", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "safe_mkdir", "(", "bundle_path", ")", "if", "count", "==", "0", ":", "raise", "TargetDefinitionException", "(", "app", ".", "target", ",", "'Bundle index {} of \"bundles\" field '", "'does not match any files.'", ".", "format", "(", "bundle_counter", ")", ")" ]